body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have made a carousel with sections and animated background images. How can I make the code better and more reusable? It's now working with a width of only 3 sections.</p>
<pre><code>$(function () {
var state = 0;
var background = $(".selection-carousel .carousel-image"),
buttonLeft = $(".selection-carousel .carousel-left"),
buttonRight = $(".selection-carousel .carousel-right"),
imageWidth = 1000,
imageWidthMin = -1000,
reelSize = 3,
imageSum = $('.selection-carousel img').size(),
maxPos = (imageSum - reelSize) * imageWidth;
$(".selection-carousel section").hide();
$(".selection-carousel section:first").show();
$(".selection-carousel section:first").append(' <div class="steam"></div> ');
// If ie8 than use drop shadow fallback
if ($("html").hasClass("ie8")) {
$(".selection-carousel section:first h2, .selection-carousel section:first p").dropShadow({ left: 0, top: 0, opacity: 0.6, blur: 3 });
}
buttonLeft.hide();
buttonRight.click(function (e) {
e.preventDefault();
var trigger = $('class'),
maxPos = (imageSum - reelSize) * -imageWidthMin,
image_reelPosition = (trigger === 'carousel-right') ? -imageWidth : imageWidth,
reel_currentPosition = $('.carousel-image').css('left').replace('px', ''),
pos = reel_currentPosition - image_reelPosition;
$(".selection-carousel section:visible .steam").remove();
if ($(background).is(':animated')) {
$(background).is(':animated').stop();
}
background.animate({ left: "-=1000px" }, 1100, function () {
$(".selection-carousel section:visible").fadeOut(300, function () {
$(this).next().fadeIn(600, function () {
if ($("html").hasClass("textshadow")) {
$(this).append(' <div class="steam"></div> ');
createSteam();
}
if ($("html").hasClass("no-textshadow")) {
$("h2", this).dropShadow({ left: 0, top: 0, opacity: 0.6, blur: 3 });
$("p", this).dropShadow({ left: 0, top: 0, opacity: 0.6, blur: 3 });
}
});
});
});
state++;
checkstate();
});
buttonLeft.click(function (e) {
e.preventDefault();
var trigger = $('class'),
maxPos = (imageSum - reelSize) * -imageWidthMin,
image_reelPosition = (trigger === 'carousel-right') ? -imageWidth : imageWidth,
reel_currentPosition = $('.carousel-image').css('left').replace('px', ''),
pos = reel_currentPosition - image_reelPosition;
$(".selection-carousel section:visible .steam").remove();
if ($(background).is(':animated')) {
$(background).is(':animated').stop();
}
background.animate({ left: "+=1000px" }, 1100, function () {
$(".selection-carousel section:visible").hide().prev().fadeIn(600, function () {
if ($("html").hasClass("textshadow")) {
$(this).append(' <div class="steam"></div> ');
createSteam();
}
$(".dropShadow").remove();
if ($("html").hasClass("no-textshadow")) {
$("h2", this).dropShadow({ left: 0, top: 0, opacity: 0.6, blur: 3 });
$("p", this).dropShadow({ left: 0, top: 0, opacity: 0.6, blur: 3 });
}
});
});
state--;
checkstate();
});
function checkstate () {
if (state == 0) {
if ($(".carousel-left").is(':visible'))
if ($("html").hasClass("textshadow")) {
$(".carousel-left").fadeOut(600);
} else {
$(".carousel-left").hide();
}
}
else if (state == 1) {
if ($(".carousel-left").is(':hidden'))
if ($("html").hasClass("textshadow")) {
$(".carousel-left").fadeIn('slow');
} else {
$(".carousel-left").show();
}
if ($(".carousel-right").is(':hidden'))
if ($("html").hasClass("textshadow")) {
$(".carousel-right").fadeIn(600);
} else {
$(".carousel-right").show();
}
}
else {
if ($(".carousel-right").is(':visible'))
if ($("html").hasClass("textshadow")) {
$(".carousel-right").fadeOut(600);
} else {
$(".carousel-right").hide();
}
}
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T08:51:33.730",
"Id": "8628",
"Score": "1",
"body": "In terms of readability, you can move the repeating part of your code to a separate function, and call it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T10:10:45.853",
"Id": "8629",
"Score": "1",
"body": "You can't optimise javascript code without knowing your HTML structure"
}
] |
[
{
"body": "<p>Some small tips could be:</p>\n\n<p>Use the jquery plugin strcture for extending it with options, create/destroy/next/prev functions. See: <a href=\"http://www.queness.com/post/112/a-really-simple-jquery-plugin-tutorial\" rel=\"nofollow\">http://www.queness.com/post/112/a-really-simple-jquery-plugin-tutorial</a></p>\n\n<p>Don't overuse selectors</p>\n\n<pre><code>var background = $(\".selection-carousel .carousel-image\"),\n buttonLeft = $(\".selection-carousel .carousel-left\"),\n buttonRight = $(\".selection-carousel .carousel-right\"),\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>var selector = $('.selection-carousel'),\n background = selector.children('.carousel-left'),\n buttonLeft = selector.children('.carousel-left'),\n buttonRight = selector.children('.carousel-right'),\n</code></pre>\n\n<p>Everytime you make it search the entire DOM, it makes it slower/heavier to use.\n(Your checksate also overuse it).</p>\n\n<p>Make some methods for the plugin, so you can create the carousel, destroy it, or send navigations functions (next/prev/gotoId).</p>\n\n<p>Just some small tips :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T09:15:47.397",
"Id": "5713",
"ParentId": "5712",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T08:48:19.870",
"Id": "5712",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "Carousel with sections and animated background images"
}
|
5712
|
<p>This is my code. I am having a file, whose first line's second word contains a number. Let this number is <code>$u</code>. 2nd line is empty, and from third line, I am given with two numbers separated by a space in each line where let first number is <code>$c</code> and second is <code>$w</code>. Now I need to figure out the minimum <code>$b</code> where <code>$b</code> for a line is <code>ceil($u / $w) * $c</code>. Is there anyway I can optimize my code. </p>
<pre><code><?php
$f = file($argv[1]);
list(, $u) = explode(" ", $f[0]);
list($c, $w) = explode(" ", $f[2]);
$b = ceil($u / $w) * $c;
unset($f[0], $f[1], $f[2]);
foreach($f as $l)
{
list($c, $w) = explode(" ", $l);
$b = min($b, ceil($u / $w) * $c);
}
echo "$b\n";
exit;
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T03:05:11.063",
"Id": "8651",
"Score": "9",
"body": "Computers are quick, people are slow. Maintenance time is huge when you have to work out what each variable is. Name your variables: $f = $file, $u = $firstLineNumber (or whatever that number really means), etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T15:24:47.030",
"Id": "8673",
"Score": "0",
"body": "I want to make computer fast not human. The question is how can I make it better for computers not humans."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T17:14:33.007",
"Id": "8679",
"Score": "2",
"body": "Sourabh: It won't be any slower if you use longer and readable variable names ;-) It helps a lot for the humans who try answering the question :) @Paul: I'd upvote your comment if you write it as an answer..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T08:29:05.513",
"Id": "8703",
"Score": "1",
"body": "If you want to optimize it like that, you should strip out all linebreaks, because then the interpreter will only have to interpret one line. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T08:29:56.680",
"Id": "8704",
"Score": "2",
"body": "Also, there are no \"levels\"...\"next level\" doesn't mean anything."
}
] |
[
{
"body": "<p>I guess my comment really was an answer in a philosophical way. So here is the answer:</p>\n\n<p>Use names for your variables that have meaning.</p>\n\n<p>There are lots of advantages to naming your variables well. Many people have looked at this question only with a very abstract idea of what you are trying to do. This makes it difficult to find improvements. If people know exactly what you are trying to do then they can work out clever ways to achieve that.</p>\n\n<p>As palacsint said: 'It won't be any slower if you use longer and readable variable names' but it may well be faster when people understand it and can see how to improve it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T03:16:38.163",
"Id": "5748",
"ParentId": "5718",
"Score": "4"
}
},
{
"body": "<p>I'm not a PHP guru, so the following is more or less just some general idea.</p>\n\n<p>Maybe don't read the whole file in one step. These questions (and comments) could be relevant: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/3496614/php-reading-large-text-files\">PHP Reading Large Text Files</a></li>\n<li><a href=\"https://stackoverflow.com/questions/7706529/fastest-way-to-read-a-csv-file\">Fastest way to read a csv file</a></li>\n</ul>\n\n<p>I wouldn't not think that reading the file line-by-line will make it significantly faster but it may worth a try. (Except if the file is bigger than the size of the free memory.) Since you just do some very simple string parsing and math operations inside the for loop I could imagine it's actually slower than the posted version.</p>\n\n<p>I could imagine that freeing these small memory areas also could slow the running with minimal gain:</p>\n\n<pre><code>unset($f[0], $f[1], $f[2]);\n</code></pre>\n\n<p>(If you omit it don't forget to skip the first 3 items inside the <code>foreach</code>.)</p>\n\n<p>Changing the double quotes may have some performance benefit especially inside the <code>foreach</code> loop. (<a href=\"https://stackoverflow.com/questions/482202/is-there-a-performance-benefit-single-quote-vs-double-quote-in-php\">Is there a performance benefit single quote vs double quote in php?</a>)</p>\n\n<p><a href=\"http://www.php.net/manual/en/control-structures.foreach.php#92116\" rel=\"nofollow noreferrer\">Using references in the foreach</a> also could have some benefit.</p>\n\n<p>Anyway, you should measure the costs of these (and other) changes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T04:52:03.483",
"Id": "5749",
"ParentId": "5718",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:41:33.390",
"Id": "5718",
"Score": "2",
"Tags": [
"php"
],
"Title": "Finding the minimum ratio out of many lines of input"
}
|
5718
|
<p>I am not so much used to OOP designing, So I took one of the very commonly used interview question , "Designing the Elevator System". Below is the prototype.</p>
<p>I would like to get some feedback on the design like </p>
<ul>
<li>Best practices which will have a particular aspect</li>
<li>Flexibility in the code</li>
<li>Some important generic feature missing</li>
<li>Areas to concentrate to write better code and design</li>
</ul>
<p>I know that these kind of things have no finite answer or just one answer but I would like to know my required areas of improvement.</p>
<h3>Original Design:</h3>
<pre><code>class elevator{
private:
//The Lift box the elevator controls
liftbox box;
//The total number of levels
const int LEVEL;
//The request for various floors
set<int> req;
//Triggers the search to move to the next floor if required
void moveLiftToNext();
//Instructs the lift box to move to that floor
void moveLiftTo(int);
public:
//Adds request to the queue
void addRequest(int);
//Gets the total levels the box can move
int getLevel();
//For Emergency
void setEmergency();
void unsetEmergency();
};
class liftbox{
private:
dailpad pad;
elevator ele;
int currLevel; //Current position
bool direction; //True - up ; False- Down
public:
//Instruction to move the box to certain level
void Move(int x){
if(x < 0 || x >= ele.getLevel())
return; //invalid number
//Move the lift
//update direction and currLevel
}
//returns the current level. Used by Elevator
int getCurrLevel();
//returns the current direction of movement.Used by Elevator
int getDirection();
void setEmergency(){
//Do the required
ele.setEmergency();
}
void unsetEmergency(){
ele.unsetEmergency();
}
//can passed to the elevator
void addRequest(int);
};
class dailpad{
private:
//Some DS to represent the dailpad
//Lift box is belongs to
liftbox box;
public:
void recieveCommand(int x){
//Depending on the value we can do the following
box.setEmergency();
//or
box.unsetEmergency();
//or
box.addRequest(x);
}
};
</code></pre>
<h3>Updated Design:</h3>
<pre><code>class elevator{
private:
//The Lift box the elevator controls
liftboxControlUnit & mLiftBoxCtrlUnit;
//constructor
elevator(int Level=1, int NoOfBanks =1 );
//Destructor
~elevator();
//Triggers the search to move to the next floor if required
void moveLiftToNext();
public:
//Adds request to the queue
void addRequest(int FloorNumber){
//Add the request to the queue. The single button outside the elevator door
mLiftBoxCtrlUnit.addRequest(FloorNumber);
}
//For Emergency. Should be accessible to everyone !
void setEmergency();
void unsetEmergency();
};
typedef enum Direction{
UP,
DOWN
}direction;
class liftboxControlUnit{
private:
//The request for various floors
set<int> mRequestQueue;
//The various banks for the whole system
vector<Bank> mBanks;
//The total number of levels. Remains the same for one building
const int mTotalLevel;
//Instruction to move the box to certain level
void processRequest(){
//Do the logic to move the box.
}
//can passed to the elevator
void addRequest(int x){
mRequestQueue.insert(x);
}
//Can be set by elevator class
void setEmergency(){
//Do the required
//Set Emergency on all Banks
}
void unsetEmergency(){
//UnsetEmegency on all banks
}
void emergencyListener(){
//Listen to all the banks if emergency has been set
}
void BankFreeListener(){
//Listen to the banks if any is free
//If so then
processRequest();
}
public:
//Constructor
liftboxControlUnit(int TotalLevels, int NoOfBanks): mTotalLevel(TotalLevels){
for(int i=0 ; i lessthan NoOfBanks; ++ i)
mBanks.push_back(Bank(0,UP));
}
friend class elevator;
};
class Bank{
private:
//The dailpad inside the bank
dailpad & mpad;
//Current Location
int mPresentLevel;
//Current direction of movement
direction mDirection;
//Currently moving
bool mEngaged;
//Manipulate the bank
void move(int NoOfMoves){
setEngaged();
//Move the elevator
unsetEngaged();
}
//getters
int getPresentLevel() const;
int getDirection() const;
//setters
void setPresentLevel(int);
void setDirection(direction);
//Manipulate the engaged flag
bool isEngaged() const;
bool setEngaged();
bool unsetEngaged();
//For emergency
void reset();
//Dailpad Listener
void dailpadListener(){
}
public:
Bank(int StartingLevel, direction Direction): mPresentLevel(StartingLevel),
mDirection(Direction),
mEngaged(false),
mpad()
{
}
//For emergency . Should be available for all.
void SetEmergency();
void UnsetEmergency();
bool isEmergency();
friend class liftboxControlUnit;
};
class dailpad{
private:
//Some DS to represent the state . probably a 2D Array.
void renderDisplay();
public:
//Constructor
dailpad();
void getCommand(int x){
//Depending on the value we can do the following
//Make necessary changes to the display
renderDisplay();
}
friend class Bank;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T11:57:35.820",
"Id": "8662",
"Score": "1",
"body": "Before I comment/look at the code. I would like to point out that the `elevator design` interview question is more about design than actual coding. It is designed to see if you understand how different parts in a complex system can interact with each other."
}
] |
[
{
"body": "<ul>\n<li><p>Dial pads usually also reflect back the set of requests which are already registered (which makes those buttons light-up). This means there could be way to telling all button pads - once activity happens on outside dial pads as well. </p></li>\n<li><p>Number of requests are always more than one - usually so it deserves a sorted link list. </p></li>\n<li><p>the levels:<br>\nconst int LEVEL; : this should have been a property of Box rather than elevator.</p></li>\n<li><p>in general, if you are referring to dial pad for inside the elevator pad. For both it is better that it is abstracted as a child of elevator rather than lift box. </p></li>\n<li><p>where do you put the list of destinations upward and down-word - and who manages the algorithm to follow? </p></li>\n</ul>\n\n<p>Overall this is good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T04:30:00.243",
"Id": "8658",
"Score": "0",
"body": "Few justifications.\n\nFirst comment: Yes, I gave it a thought but some reason left it. Can have a _displaymethod_ to manipulate the display. \nSecond, I had a set of ints, the ints went missing due to formatting. Sets will take the same space as Linked list but also faster than Linked list . Also it gives faster computation of the next level to go after , it services the current level.\nThird, height is constant factor for only the building but the same liftbox can be placed in any building.\nFourth, Could you please explain more ?\nFifth, the logic will be in elevator::moveLiftToNext() . Thankyou"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T03:47:47.223",
"Id": "5728",
"ParentId": "5723",
"Score": "0"
}
},
{
"body": "<h3>First the C++ code:</h3>\n<pre><code>class elevator{\n liftbox box;\n\nclass liftbox{\n elevator ele;\n</code></pre>\n<p>This is not going to work as you expect it.<br />\nEach class contains an object of the other type means that both will have completely different objects. If you want them to refer back to each other in some sort of parent child relationship then one of them needs to be a reference or pointer to the parent.</p>\n<pre><code>const int LEVEL;\n</code></pre>\n<p>Traditional all caps is reserved for macros. Break the tradition at your own cost.</p>\n<pre><code>int getCurrLevel();\nint getDirection();\n</code></pre>\n<p>Methods that return information about the state of the object without actually changing the state should be marked const.</p>\n<pre><code>public/private\n</code></pre>\n<p>I am not sure I agree with some of the decisions about making methods public. I think very few objects should get to interact with these systems sometimes friendship can help in limitting access. (Now friendship increases coupling with the friend, but if it decreases the external public interface it will decrease coupling with objects that have no rights to modify the object). Anyway I would expect to see a justification as to why methods are public. If anybody should be able to call them fine. If nobody but another object should call them you need to make a better case.</p>\n<h3>Design</h3>\n<p>Looking at it from a design perspective.</p>\n<p>Not sure I see the distinction between an elevator/liftbox</p>\n<p>In big buildings some lifts do not go to all floors.</p>\n<p>One of the things about elevators is that they usually come in banks and do not operate independently. For really big building multiple banks will be combined but will work independently (unless there is some major emergency). How are you going to organize your code so that multiple lifts(sorry elevators) can work together. Also I want to see how you can decouple the elevator object from bank control logic. (ie I don't expect to see all the control logic in the bank, I would like to see control logic in the elevator but decision logic in bank). But if their are multiple banks to coordinate I want the logic for a higher level control.</p>\n<p>The real meat of this problem is how to de-couple the objects from each other. What patterns do you think are being used here.</p>\n<h2>Updated Code:</h2>\n<p>Not sure you understand a bank of elevators work (based on the code).</p>\n<blockquote>\n<p>A bank is a group of 2 or more elevators that work together to serve a set of floors.</p>\n</blockquote>\n<p>I still do not see the pattern you are using to decouple the elevators from the Bank.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T19:49:21.753",
"Id": "8681",
"Score": "0",
"body": "Thank you for the feedback. I have updated the design . Please give your comments on the modifications please. About the first comment true, the design is screwed ! Is there a prototype or a standard way to establish a parent - child relationship . Could you provide an example ? I have performed some decoupling , Let me know how better I can do it !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T19:52:54.043",
"Id": "8682",
"Score": "0",
"body": "@bsoundra: Don;t edit your file like that. If you change things drastically then peoples answer do not match up to the question and it becomes hard to vote on them. If you have major modifications edit your question and **ADD** a new section with the updated design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T19:58:39.683",
"Id": "8683",
"Score": "0",
"body": "Thanks . I too was editing parallelly. I will this in mind the next time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T20:12:48.307",
"Id": "8684",
"Score": "0",
"body": "I did not understand the bank concept prior. In the current Design - elevator - the whole system, liftboxControlUnit - the controller, Bank - each lift box. The bank concept can be incorporated by adding the resrictions as a part of the Bank (i.e. the lift box). Would it be a bad idea ? Considering this design idea, is there any place that needs decoupling ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T20:18:48.037",
"Id": "8685",
"Score": "0",
"body": "When you say a pattern , are you expecting a design pattern ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T21:22:24.120",
"Id": "8689",
"Score": "0",
"body": "@bsoundra: A `design pattern` name is just a way of easily [communicating well known patterns](http://programmers.stackexchange.com/questions/70877/are-design-patterns-really-essential-nowadays/70893#70893). If you know the name fine, but if not just explain how you would de-cople them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T21:44:24.373",
"Id": "8691",
"Score": "0",
"body": "Ok . I got it. Design Patterns help in faster communication. But from your above comment, I see that you suggest there is still a place that can handle a decoupling. Is there one ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T21:58:58.143",
"Id": "8692",
"Score": "0",
"body": "@bsoundra: When I am asking the question I am looking for some form of description of decoupling. But the question is designed to be open-ended so there are lots of ways a candidate can get marks. But suggestions about decoupling the elevators from the control systems by using the Observer pattern would be a good start. Additionally mentioning that Control systems could be an even based system that respond to events from elevators and keypads is another thing that could be done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T00:38:58.710",
"Id": "8694",
"Score": "0",
"body": "As far as the decoupling goes, I think I understood you. There is just not one answer. Secondly, I introduced the listener in the Bank class and liftboxControlUnit . But I did not specifically mention it . I will mark this answer as answer .But I would like to know if making Parent class a friend of Child class and marking a child class object a reference member variable , a good practice . Thank you again."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T12:24:21.450",
"Id": "5733",
"ParentId": "5723",
"Score": "5"
}
},
{
"body": "<p>I agree with the points made by Loki Astari. I would like to add a few.</p>\n\n<ol>\n<li>Instead of the <code>liftbox</code> asking the <code>elevator</code> for the total number of levels, the lift box could be given the total number in it's constructor (that is, if the <code>liftbox</code> is to be created by the <code>elevator</code>).</li>\n<li>It's not a major point, but the use of a <code>boolean</code> to specify the direction isn't the easiest to read. I would be tempted to replace it with an <code>enum</code> that would allow the options of up or down. This would be much easier to read and would remove the need for the comment to explain it.</li>\n<li>With regards to naming of variables, I would strongly advise you use meaningful names, and try to avoid abbreviations where possible. If someone was reading over this code and it was in a larger scale program, reading a reference to <code>ele</code> might be misinterpreted depending on the context of the rest of the code being read. <code>ele</code> probably isn't the best of examples, particularly for this question, but it's something that should be considered for future programs.</li>\n<li>Lastly, similarly to point 3, I would recommend differentiating between your local and global variables. For example, in some coding standards, programmers prefix their global variables with an underscore (e.g. <code>_currLevel</code>). I write my global variables in PasCal case, prefixed with the 'm' character, to signify that they are member variables (e.g. mCurrLevel). It is good to try and adopt similar naming conventions, as it really helps in making code easier to read.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T17:22:19.643",
"Id": "8680",
"Score": "0",
"body": "for a +1 modify point 4 (taking this into consideration http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T13:29:33.617",
"Id": "5734",
"ParentId": "5723",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5733",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T02:59:21.557",
"Id": "5723",
"Score": "4",
"Tags": [
"c++",
"object-oriented"
],
"Title": "OOP elevator design evaluation"
}
|
5723
|
<p>TO DO</p>
<ul>
<li>exception handling</li>
<li>merge with dynamic arrary</li>
</ul>
<p>*SO Bug here--remove this line and Control K will not work</p>
<pre><code>/*
Added in comments from Jerry, Ed and Loki
This code borrows from from http://cslibrary.stanford.edu/
C++ Version - lnode, lnode_reverse, lnode_push, lnode_print, lnode_count
*/
#include "c_arclib.cpp"
template <class T1> class sl_list
{
private:
class node_1
{
public:
T1 data;
node_1 *next;
node_1(T1 data, node_1 *next = NULL) : data(data), next(next) {}
};
node_1 *head;
int count;
public:
sl_list() : count(0), head(NULL){}
void push(int data)
{
node_1 *newNode = new node_1(data, head);
++count;
head = newNode;
}
void print()
{
node_1 *current=head;
while (current != NULL)
{
cout << current->data << endl;
current = current->next;
}
}
void reverse()
{
node_1 *previous, *current, *future;
previous=NULL;
current=head;
future=head;
while(current!=NULL)
{
future=current->next;
current->next=previous;
previous=current;
current=future;
}
head=previous;
}
void break_heap()
{
int i=0;
while(1)
{
i++;
push(1);
}
}
};
/*
C Version - lnode, lnode_reverse, lnode_push, lnode_print, lnode_count
*/
typedef struct node_type
{
int data;
struct node_type* next;
} lnode_type;
struct lnode
{
int data;
struct lnode* next;
};
void lnode_reverse(struct lnode*& head)
{
struct lnode *previous, *current, *future;
previous=NULL;
current=head;
future=head;
while(current!=NULL)
{
future=current->next;
current->next=previous;
previous=current;
current=future;
}
head=previous;
}
void lnode_push(struct lnode*& head, int data)
{
struct lnode* newNode = new lnode;
newNode->data = data;
newNode->next = head;
head = newNode;
}
void lnode_print(struct lnode* current)
{
while (current != NULL)
{
cout << current->data;
current = current->next;
}
}
int lnode_count(struct lnode* current)
{
int count = 0;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
void break_heap()
{
struct lnode* head = NULL;
int i=0;
while(1)
{
i++;
lnode_push(head,1);
}
}
int main()
{
sl_list<int> list1;
list1.push(10);
list1.push(20);
list1.push(30);
list1.push(40);
list1.push(50);
list1.push(60);
list1.print();
list1.reverse();
list1.print();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T07:48:00.807",
"Id": "8744",
"Score": "0",
"body": "what's the `break_heap` method for? It sounds malicious and it's public too!"
}
] |
[
{
"body": "<pre><code>/* C++ Version - lnode, lnode_reverse, lnode_push, lnode_print, lnode_count\n I need node_type turned into a templated class..How does one do this?\n*/\ntypedef struct node_type \n { \n int data; \n struct node_type* next; \n } lnode_type;\n</code></pre>\n\n<p>Turning it into a template is pretty straightforward:</p>\n\n<pre><code>template <class T>\nclass node_type { \n T data;\n node_type *next;\n};\n</code></pre>\n\n<p>Note that the <code>typedef</code> isn't really necessary (or desirable) in C++. You normally just want to use <code>class whatever</code>, and then the body of the class definition. This makes <code>whatever</code> usable as a name by itself, just about like the typedef would in C.</p>\n\n<p>There's one other thing we probably want to do though: the whole basic idea of a linked-list node is really just an implementation detail of the linked list, so we really want to make the node type a nested class inside of the linked-list class:</p>\n\n<pre><code>template <class T>\nclass sl_list {\n\n struct node {\n T data;\n node *next;\n } head;\n\npublic:\n // Other stuff here.\n};\n</code></pre>\n\n<p>From there, we want to write the functions that work with the data type to use <code>T</code> instead of <code>int</code>. For example, instead of your <code>push(int)</code>, you might write something like this:</p>\n\n<pre><code>void push(T data) {\n ++count; // prefer pre-increment when you don't need the old value.\n node* newNode = new node; \n newNode->data = data;\n newNode->next = head;\n head = newNode; \n}\n</code></pre>\n\n<p>We might prefer to add a ctor to the node class/struct, something like this:</p>\n\n<pre><code>node(T data, node *next = NULL) : data(data), next(next) {}\n</code></pre>\n\n<p>With that, <code>push</code> becomes something like this:</p>\n\n<pre><code>void push(T data) { \n node *newNode = new node(data, head);\n ++count;\n head = newNode;\n}\n</code></pre>\n\n<p>[Edit2: Note that, as recommended by @LokiAstari, I've also moved the <code>++count</code> to <em>after</em> allocating the new node. This way if the attempted allocation fails (and <code>new</code> throws an exception), <code>count</code> will <em>not</em> be incremented, so it retains the correct values. If and only if the allocation succeeds, it's incremented to reflect the new node having been added to the list. ]</p>\n\n<p>[Edit: and <code>node</code> would look roughly like this:</p>\n\n<pre><code> struct node {\n T data;\n node *next;\n\n node(T data, node *next = NULL) : data(data), next(next) {} \n } head;\n</code></pre>\n\n<p>]</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T04:09:56.177",
"Id": "8656",
"Score": "0",
"body": "Thanks...everything made sense except these lines: \nWe might prefer to add a ctor to the node class/struct, something like this:\nnode(T data, node *next = NULL) : data(data), next(next) {}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T12:33:39.957",
"Id": "8663",
"Score": "3",
"body": "The one thing I would add is exception safety. No operation that modify the object should be performed until all exception dangerous code has completed. Thus in push(), the ++count should be moved after the call to new. If new throw the state of the object is left in an inconsistent state."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T13:17:45.627",
"Id": "8665",
"Score": "0",
"body": "@LokiAstari: Good point. Done."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T03:47:31.683",
"Id": "5727",
"ParentId": "5724",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "5727",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T03:11:41.960",
"Id": "5724",
"Score": "4",
"Tags": [
"c++",
"c"
],
"Title": "Single Linked List - Improvements - 1 - not complete"
}
|
5724
|
<p>Feel free to critique this database wrapper which is written as a code example for employers or clients.</p>
<pre><code><?php
class Database {
static function getInstance()
{
if (self::$instance == NULL) {
self::$instance = new Database();
}
return self::$instance;
}
public function connect()
{
/*
if dbConnection already exists, do not
make another one.
*/
if (is_resource($this->dbConnection))
{
return true;
}
$conn = $this->createDbConnection();
if (!$conn){
trigger_error("Error Connecting to Database", E_USER_NOTICE);
}
$this->dbConnection = $conn;
$result = mysql_select_db($this->database_name, $conn);
if (!$result){
trigger_error("Error Selecting Database", E_USER_NOTICE);
}
}//endfunction
public function closeConnection()
{
/*
mysql documentation says closing a connection
isn't nessesary since the connection is closed
at the end of the script.
*/
mysql_close($this->dbConnection);
}
public function executeQuery($query)
{
$this->query_result = mysql_query($query);
if (!$this->query_result){
trigger_error("Error Executing Database Query", E_USER_NOTICE);
}
}
public function getRow(){
return mysql_fetch_array($this->query_result);
}
private function createDbConnection()
{
if ($_SERVER["SERVER_NAME"] == "website.com") {
$this->database_name = 'databasename';
return mysql_connect('localhost', 'username', 'password');
//$msdb = mysql_connect("localhost", "root", "");
//mysql_select_db("test", $msdb) or die(mysql_error());
}
}
private $dbConnection;
private $query_result;
private $database_name;
static private $instance = NULL;
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>I'm going to be harsh, maybe you will disagree with my assessment, or maybe it will help you get a job.</p>\n\n<p>I don't understand why everyone wants to make a singleton database class. Singleton is evil. Now you are limited to a single database object (should we all rejoice?). Interestingly your connection can be managed to connect to different databases using closeConnection and connect (but only 1 at a time). What is the point of this?</p>\n\n<p>If you really must make it a singleton - do it right. Stop people calling constructing, cloning or getting another from unserialize:</p>\n\n<pre><code>private function __construct();\nprivate function __clone();\nprivate function __wakeup();\n</code></pre>\n\n<p>See the singleton pattern <a href=\"http://php.net/manual/en/language.oop5.patterns.php\" rel=\"nofollow\">here</a>.</p>\n\n<p>I am not impressed by your choice of mysql when you could have chosen PDO or at least mysqli (mysql improved). PDO in my opinion is the best which allows you to connect to non-mysql databases too.</p>\n\n<p>You have hard-coded values spread throughout your code.</p>\n\n<p>Your object properties appear at the end of your class rather than the start. Personally I like to see them at the start as they tend to be used throughout the methods. Seeing them at the start of the class gives me an idea of the object that is created by the class.</p>\n\n<p>I prefer exceptions rather than errors when I have serious database problems.</p>\n\n<p>Your indentation is not completely consistent. You use the beautiful Allman style once and have extra spacing in createDbConnection.</p>\n\n<p>// endfunction should not be a comment.</p>\n\n<p>Provide a comment for each method. If a method does not do enough to even be commented on does it even deserve to exist?</p>\n\n<p>For pure php I would advise not ending your file with ?>. Extra spacing (such as carriage returns) after this causes output which messes up header function calls.</p>\n\n<p>I think less is more when it comes to example code. I'm not looking through any of the other code on your site. I think a very good database class alone should be enough example code. However, to be very good it must really encapsulate the ideas of a database, be well commented and standalone (loosely coupled). It should also be consistent in its interface and structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T23:33:39.230",
"Id": "5907",
"ParentId": "5725",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "5907",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T03:24:41.370",
"Id": "5725",
"Score": "3",
"Tags": [
"php",
"singleton"
],
"Title": "Singleton wrapper"
}
|
5725
|
<p>Here are the 3 files that make up my MVC. The two view files containing the HTML are not included.</p>
<p>Any advice on how to improve this so it is usable by others.</p>
<p>It is meant to be a light-weight alternative to heavier libraries.</p>
<p>Thanks!</p>
<pre><code><?php // index.php
/*
When the user hits reload button on browser
*/
include 'arche_control.php';
$controller = new controller_reload();
$controller->reload();
?>
<?php //model.php
/*
Used to decouple super global variables
Gateway file for Ajax and File Uploads
*/
include 'arche_control.php';
if(isset($_FILES['ufile']['tmp_name']))
{
$controller = new controller_file();
}
elseif(isset($_POST['a']))
{
$controller = new controller_ajax($_POST['a']);
}
?>
<?php // mvc.php
/****************************************************************
Light MVC Framework - copyright 2011 ArcdeV, Inc.
Note the modules are broken up using commented sections not files
as is common
*****************************************************************/
session::start();
/****************************************************************
CREDENTIALS
*****************************************************************/
define('DB_USER', 'archemar_1');
define('DB_PASS', 'A*99');
define('DB_HOST', 'localhost');
define('DB_DATABASE', 'archemar_1');
/****************************************************************
MODEL CLASSES
one_db, database, post, session, validate, signin, signup,
signout, bookmark, tweet, table_maintain, upload, import
****************************************************************/
/*one_db*/
class one_db
{
protected static $db;
private function __construct()
{
self::$db=new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
}
public static function get()
{
if(self::$db==NULL)
{
new self();
}
return self::$db;
}
}
/*database*/
class database extends one_db
{
function __construct()
{
one_db::get();
}
public function query($query)
{
return one_db::$db->query($query);
}
private function ref_arr(&$arr) // will need this later.
{
$refs = array();
foreach($arr as $key => $value)
{
$refs[$key] = &$arr[$key];
}
return $refs;
}
}
/*post*/
class post extends database
{
public $_protected_arr=array();
protected function __construct()
{
parent::__construct();
$this->protect();
}
protected function protect()
{
foreach($_POST as $key=>$value)
{
/* magic_quotes issue
$this->_protected_arr[$key]=mysqli_real_escape_string($value);
*/
$this->_protected_arr[$key]=$value;
}
}
}
/*session*/
class session
{
public static function start()
{
session_start();
}
public static function activate($a,$b)
{
$_SESSION['email']=$a;
$_SESSION['name']=$b;
}
public static function deactivate()
{
unset($_SESSION['email']);
unset($_SESSION['name']);
}
public static function active()
{
return isset($_SESSION['email']);
}
public static function finish()
{
$_SESSION=array();
if(session_id() != "" || isset($_COOKIE[session_name()]))
{
setcookie(session_name(),'',time()-2592000,'/');
}
session_destroy();
}
}
/*validate*/
class validate
{
private $input;
function __construct($input_arg)
{
$this->input=$input_arg;
}
function empty_user()
{
if((int)!in_array('',$this->input,TRUE)) return 1;
return 0;
}
function name()
{
if(preg_match('/^[a-zA-Z-\.\s]{1,60}$/',$this->input['name'])) return 1;
return 0;
}
function email()
{
if(preg_match('/^[a-zA-Z0-9._s-]{1,256}+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$this->input['email'])) return 1;
return 0;
}
function pass()
{
if(preg_match('/.{6,40}/',$this->input['pass'])) return 1;
return 0;
}
}
/*signin*/
class signin extends post
{
function __construct()
{
parent::__construct();
$this->invoke();
}
function invoke()
{
$obj=new validate($this->_protected_arr);
if($obj->empty_user())
{
if($obj->email())
{
if($obj->pass())
{
if(self::validate())
{
self::activate_session();
$control=new controller_control();
$control->send('pass');
}
else
{
new view_message('validate');
}
}
else
{
new view_message('pass');
}
}
else
{
new view_message('email');
}
}
else
{
new view_message('empty');
}
}
private function validate()
{
$email=$this->_protected_arr['email'];
$pass=$this->_protected_arr['pass'];
$query="SELECT pass FROM cr WHERE email='$email'";
$row=mysqli_fetch_row(database::query($query));
$pass=crypt($pass, $row[0]);
$query="SELECT email,pass FROM cr WHERE email='$email' AND pass='$pass'";
if(mysqli_num_rows(database::query($query))!=0)
{
return 1;
}
else
{
return 0;
}
}
private function activate_session()
{
$email=$this->_protected_arr['email'];
$res_arr=mysqli_fetch_assoc(database::query("SELECT flname FROM cr WHERE email='$email'"));
$flname=$res_arr['flname'];
session::activate($email,$flname);
}
}
/*signup*/
class signup extends post
{
function __construct()
{
parent::__construct();
$this->invoke();
}
private function invoke()
{
$obj=new validate($this->_protected_arr);
if($obj->empty_user())
{
if($obj->name())
{
if($obj->email())
{
if($obj->pass())
{
if(self::taken())
{
self::insert_data();
$control=new controller_control();
$control->send('pass');
}
else
{
new view_message('taken');
}
}
else
{
new view_message('pass');
}
}
else
{
new view_message('email');
}
}
else
{
new view_message('name');
}
}
else
{
new view_message('empty');
}
}
private function taken()
{
$email=$this->_protected_arr['email'];
$query="SELECT * FROM cr WHERE email='$email'";
if(mysqli_num_rows(database::query($query)))
{
return 0;
}
else
{
return 1;
}
}
private function insert_data()
{
$flname=$this->_protected_arr['name'];
$email=$this->_protected_arr['email'];
$pass=crypt($this->_protected_arr['pass']);
database::query("INSERT INTO cr VALUES ('$flname', '$email', '$pass')");
database::query("INSERT INTO bo VALUES ('Facebook','http://www.facebook.com','','$email')");
session::activate($email, $flname);
}
}
/*signout*/
class signout
{
function __construct()
{
session::finish();
}
}
/*bookmark*/
class bookmark extends post
{
function __construct($type)
{
parent::__construct();
if($type=='insert')
{
database::query("INSERT INTO bo VALUES ('{$this->_protected_arr["f3a"]}', '{$this->_protected_arr["f3b"]}', '', '$_SESSION[email]')");
$control=new controller_control();
$control->send('pass');
}
else if($type=='delete')
{
database::query("DELETE FROM bo WHERE name='{$this->_protected_arr[a1]}' AND email='$_SESSION[email]' LIMIT 1");
$control=new controller_control();
$control->send('pass');
}
}
}
/*tweet*/
class tweet extends post
{
private $time;
function __construct()
{
$this->time=time();
parent::__construct();
$this->invoke();
}
private function invoke()
{
$this->insert();
$this->send_aml();
}
private function insert()
{
$email=$_SESSION['email'];
$flname=$_SESSION['name'];
$message=$this->_protected_arr['f4b'];
database::query("INSERT INTO tw VALUES ('$this->time','$flname','$message','$email')");
}
private function send_aml()
{
$query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7");
$control=new controller_control();
$aml_string = $control->add('pass');
$iter=0;
while($a=mysqli_fetch_assoc($query_return))
{
if($iter!=0)
{
$aml_string = $aml_string . "||";
}
$iter++;
$aml_string = $aml_string . $a['email'] . "|" . $a['fname'] . "|" . $this->time . "|" . $a['time'] . "|" . $a['message'];
}
echo $aml_string;
}
}
/*table_maintain*/
class table_maintain extends database
{
public function delete($table_type)
{
database::query("DROP TABLE $table_type");
echo "Table '$table_type' deleted \n";
}
private function create($name, $query)
{
database::query("CREATE TABLE $name($query)");
echo "Table '$name' created <br>";
}
public function make($type)
{
switch ($type)
{
case "te":
$this->create('te', 'id INT NOT NULL AUTO_INCREMENT, address VARCHAR(60), date DATE, PRIMARY KEY(id)');
break;
case "cr":
self::create('cr', 'flname VARCHAR(60), email VARCHAR(321), pass VARCHAR(40), INDEX(email(6))');
break;
case "bo":
self::create('bo', 'name VARCHAR(64), url VARCHAR(256), dom VARCHAR(256), email VARCHAR(64)');
break;
case "tw":
self::create('tw', 'time INT, fname VARCHAR(32), message VARCHAR(128), email VARCHAR(64)');
break;
case "co":
self::create('co', 'name VARCHAR(32), number VARCHAR(32), email VARCHAR(32), address VARCHAR(32), web VARCHAR(32), web VARCHAR(32), notes VARCHAR(128), tag VARCHAR(3)');
break;
}
}
}
/*upload*/
class upload
{
private $w, $h, $tw, $th, $max1=50, $max2=20;
private $path1="images/generic_large.jpg", $path2="images/generic_small.jpg";
private $src=NULL;
function __construct()
{
$this->invoke();
}
private function invoke()
{
$email=$_SESSION['email'];
$path3="pictures/$email.jpg";
$path4="pictures/$email-1.jpg";
if(move_uploaded_file($_FILES['ufile']['tmp_name'], $path3))
{
if($this->get_image($path3))
{
list($this->w,$this->h)=getimagesize($path3);
$this->tw=$this->w;$this->th=$this->h;
$this->resize_move($this->max1,$path3);
$this->resize_move($this->max2,$path4);
imagedestroy($this->src);
}
}
else
{
copy($this->path1, $path3);
copy($this->path2, $path4);
}
}
private function get_image($path)
{
$a=TRUE;
switch($_FILES['ufile']['type'])
{
case "image/gif":
$this->src = imagecreatefromgif($path);
break;
case "image/jpeg":
case "image/pjpeg":
$this->src = imagecreatefromjpeg($path);
break;
case "image/png":
$this->src = imagecreatefrompng($path);
break;
default:
$a = FALSE;
break;
}
return $a;
$type_creators = array(
'image/gif' => 'imagecreatefromgif',
'image/pjpeg' => 'imagecreatefromjpeg',
'image/jpeg' => 'imagecreatefromjpeg',
'image/png' => 'imagecreatefrompng');
$img_type = $_FILES['ufile']['type'];
if(array_key_exists($img_type, $type_creators))
{
$this->src = $type_creators[$img_type]($path);
return true;
}
return false;
}
private function resize_move($max, $path)
{
if($this->w > $this->h && $max < $this->w)
{
$this->th = $max / $this->w * $this->h;
$this->tw = $max;
}
elseif($this->h > $this->w && $ax < $this->h)
{
$this->tw = $max / $this->h * $this->w;
$this->th = $max;
}
elseif($max < $this->w)
{
$this->tw=$this->th=$max;
}
$a = imagecreatetruecolor($this->tw, $this->th);
imagecopyresampled($a, $this->src, 0, 0, 0, 0, $this->tw, $this->th, $this->w, $this->h);
imagejpeg($a, $path);
imagedestroy($a);
}
}
/*import*/
class import extends database
{
protected function __construct($file_name)
{
parent::__construct();
$this->ie($file_name);
}
function ie($file_name)
{
$lines = file('ie.htm');
foreach ($lines as $line)
{
if(preg_match("/(https?:\/\/.+?)\"(.+)\" >(.+)\./", "$line", $matches))
{
//('bo', $matches[3], $matches[1] );
}
}
}
}
/****************************************************************
VIEW MODULE
view, view_database, view_message
view_arche_1 (external), view_arche_2 (external) - these are
primarily html files
****************************************************************/
/*view*/
class view extends database
{
}
/*view_db*/
class view_db extends view
{
function __construct($type)
{
parent::__construct();
$this->invoke($type);
}
private function invoke($type)
{
switch ($type)
{
case "bookmarks":
$this->html_bookmarks();
break;
case "tweets":
$this->html_tweets();
break;
default:
throw new Exception('Invalid View Type');
break;
}
}
private function html_bookmarks()
{
$email = $_SESSION['email'];
$query_return = database::query("SELECT * FROM bo WHERE email='$email' ORDER BY name ASC");
$html_string='';
while ($ass_array = mysqli_fetch_assoc($query_return))
{
$fav=$this->favicon($ass_array['url']);
$html_string = $html_string . "<img name='bo_im' class='c' src='$fav' onerror='i_bm_err(this)'><a target='_blank' name='a1' class='b' href = $ass_array[url]>$ass_array[name]</a>";
}
echo $html_string;
}
private function html_tweets()
{
$query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7");
$time = time();
$html_string='';
while ($a = mysqli_fetch_assoc($query_return))
{
$html_string = $html_string . "<div class='Bb2b'><img class='a' src='pictures/$a[email].jpg' alt=''/><a class='a' href='javascript:void(0)'>$a[fname] posted <script type='text/javascript'>document.write(v0($time,$a[time]))</script></a><br/><p class='c'>$a[message]</p></div>";
}
echo $html_string;
}
private function favicon($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))
{
return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico';
}
return false;
}
}
class view_message extends view
{
function __construct($type)
{
$this->invoke($type);
}
private function invoke($type)
{
$this->message($type);
}
private function message($type)
{
$type_message = array(
'empty' => '<si_f>Please complete all fields.',
'name'=> '<su_f>Only letters or dashes for the name field.',
'email' => '<si_f>Please enter a valid email.',
'taken' => '<si_f>Sorry that email is taken.',
'pass' => '<si_f>Please enter a valid password, 6-40 characters.',
'validate' => '<si_f>Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password.');
echo $type_message[$type];
}
}
/****************************************************************
CONTROLLER MODULE - controller_file, controller_ajax,
controller_reload, controller_database, controller_control
****************************************************************/
/*controller_reload*/
class controller_reload
{
public $model;
public function __construct()
{
}
public function reload()
{
if(session::active())
{
include 'arche_view_2.php';
}
else
{
include 'arche_view_1.php';
}
}
public function reload_header()
{
$uri = 'http://' . $_SERVER['HTTP_HOST'] ;
header('Location: '.$uri);
}
}
/*controller_ajax*/
class controller_ajax
{
public $model;
function __construct($type)
{
$this->invoke($type);
}
function invoke($type)
{
if(isset($type))
{
switch($type)
{
case '0':
$this->model = new signin();
break;
case '1':
$this->model = new signup();
break;
case '2':
$this->model = new signout();
$controller=new controller_reload();
$controller->reload_header();
break;
case '3':
$this->model = new bookmark('insert');
break;
case '3a':
$this->model = new bookmark('delete');
break;
case '4':
$this->model = new tweet();
break;
default:
throw new Exception('Invalid Model Type');
break;
}
}
}
}
/*controller_database*/
class controller_database
{
private $model;
function __construct($type)
{
$this->invoke($type);
}
function invoke($type)
{
switch($type)
{
case 'bookmarks':
$this->model = new view_db($type);
break;
case 'tweets':
$this->model = new view_db($type);
break;
default:
throw new Exception('Invalid View Type');
break;
}
}
}
/*controller_file*/
class controller_file
{
public $model;
function __construct()
{
$this->invoke();
}
function invoke()
{
$this->model=new upload();
$controller=new controller_reload();
$controller->reload_header();
}
}
/*controller_control*/
class controller_control
{
private $type_array = array(
'pass' => '<xx_p>',
'fail' => '<xx_f>');
function add($type)
{
return $this->type_array[$type];
}
function send($type)
{
echo $this->type_array[$type];
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Some random thoughts:</p>\n\n<p>1, You should put your database connection informations (and other settings) to a <code>config.php</code>.</p>\n\n<p>2, Using inheritance to share code generally isn't a good idea: <a href=\"https://stackoverflow.com/questions/3294348/what-are-the-disadvantages-of-using-inheritance-as-a-way-of-reusing-code\">What are the disadvantages of using inheritance as a way of reusing code?</a></p>\n\n<p>3, Instead of the magic number <code>2592000</code> use a named constant.</p>\n\n<p>4, I'd write the <code>invoke()</code> method in this way:</p>\n\n<pre><code>function invoke() {\n $obj=new validate($this->_protected_arr);\n if(!$obj->empty_user()) {\n new view_message('empty');\n return;\n }\n\n if(!$obj->email()) {\n new view_message('email');\n return;\n }\n\n if(!$obj->pass()) {\n new view_message('pass');\n return;\n }\n ...\n}\n</code></pre>\n\n<p>It's much easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T16:59:56.707",
"Id": "8890",
"Score": "2",
"body": "2. Depends on the circumstances. It's acceptable to use inheritance to share functionality if a `tweet` is, indeed, a `post` (for example); one shouldn't need to write similar code twice. But a `post` is not a `database`, and trying to say it is one will lead to trouble. Like, say, a tweet accidentally being passed in as a database."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T20:40:44.053",
"Id": "8901",
"Score": "0",
"body": "I agree. It's worth reading *Item 16: Favor composition over inheritance* from *Effective Java Second Edition*."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T23:18:50.393",
"Id": "5844",
"ParentId": "5729",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>This code seems to require changes based on whether magic quotes are enabled. Moreover, it's currently assuming that magic quotes <em>are</em> enabled. One should be encouraging the elimination of magic quotes from this earth, not depending on them.</p></li>\n<li><p>This rather hard-to-decipher code contains no comments. I'm usually against lots of comments, but i'm even more against code whose intent is not self-evident. Pick one or the other. (Allow me to cast my vote here in favor of making the code readable enough that you don't need comments.)</p></li>\n<li><p>Who told you two-char table names were acceptable? Names should be descriptive. You seem to be aware that there's no two-char limit on name lengths; use that to make life easier for the poor schmuck who ends up working on this code later (which could be you in 6 months). I should not need documentation to look through your stuff and see what it does. Particularly considering you haven't provided any. :P</p></li>\n<li><p>A <code>post</code> is a <code>database</code>? No. A <code>view</code> is a <code>database</code>? Even more strongly, <strong><em>no</em></strong>. (You've claimed this is MVC; you should know that in MVC, views should <em>never even have</em> direct access to the db. That's the model's job.) Use inheritance to say something \"is a\" something-else, not just because it's handy to say <code>parent::__construct()</code> to set up the DB.</p></li>\n<li><p>BTW, that's another thing. The constructor's job is to set up an object. No more, no less. <code>new something()</code> should return me a new something -- <em>that i will use</em>. No more, no less. It should not have side effects outside of setting up the instance in question. Setting some magic global 3 layers up in the inheritance tree? <em>Hell</em> no. You should never have a naked <code>new something();</code>; if you want an object, then you should be using it (storing it, calling functions on it, etc). If you don't, then <em>quit abusing constructors</em>. Hell, if everything is going to be init'ing the database anyway, then just say <code>database::get()</code> at the beginning of the code and spare yourself all the unnecessary inheritance.</p></li>\n<li><p>What's up with the odd tags in the strings in <code>view_message::message</code>, <code>controller_control::$type_array</code>, ? You know that's not valid HTML. If that's meant to be interpreted by JS or something, use a standard format like JSON.</p></li>\n<li><p>Stylewise, your indents and naming scheme suck. It's almost universal convention that class names start with an uppercase letter. And i've seen precisely two people in my life who align braces like that -- neither of whom i'd ever let touch any code i'll ever be working on. It always looks to me like someone misplaced their braces. Google \"php coding style\" and read up on conventions -- almost all recommend 4 space indents, and K&R, OTBS, or Allman style braces. If you intend to release this code to the world, you'd better stick to common conventions. (The only plus is, at least you're consistent about it.)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:55:38.673",
"Id": "8992",
"Score": "0",
"body": "Great Advice. Although not set in stone, I'd recommend Zend's coding standard. Who better than the makers of the language to follow for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:53:09.310",
"Id": "9222",
"Score": "0",
"body": "magic quotes is set by my serverice provider...I can not change this..I can however use bound queries as opposed to escaping..this is on my todo list"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:53:49.730",
"Id": "9223",
"Score": "0",
"body": "I will make the code more readable....likewise with the table names"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:58:25.573",
"Id": "9224",
"Score": "0",
"body": "I'm going to change the comments from MVC to MV...as I do not follow the MVC pattern..it would add small in-efficiencies...and I can not see a benefit in adhering to it...I will provide a UML like diagram so it is easy to understand on the spot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:59:46.700",
"Id": "9225",
"Score": "0",
"body": "I belive contstructors can be more abstact...I learned this from quantlib.org...though I don't have a strong opinion on this I will consider more to the return type necessity"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T19:00:39.693",
"Id": "9226",
"Score": "0",
"body": "All my posts work with the database...so in my case ...a post is a database...thought I changed the name from post to post_to_database...to differentiated"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T21:28:05.240",
"Id": "9228",
"Score": "0",
"body": "Re: magic quotes: if you can't put `php_flag magic_quotes_gpc off` in .htaccess or specify a custom php.ini, and the host won't change it for you, then you need a new web host. No host that's worth a damn enables that unless a customer requires it, and even then they'd either enable it only for that one site or give the customer a way to set it themselves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T22:08:27.547",
"Id": "9230",
"Score": "0",
"body": "Re: constructors: Constructors have a specific purpose. They are not and can not be \"abstract\"; their entire purpose is to initialize the object that was just allocated. That's it. The code at quantlib.org does not appear to contradict that. There's nothing wrong with parent constructors; it's just parent constructors that have *global side effects* that are evil."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T22:21:01.290",
"Id": "9231",
"Score": "0",
"body": "Re: inheritance: All your posts might *use* the database. They might *have* a database. But if a post *is* a database, then $some_post->query($sql) would make sense -- and it doesn't. See http://en.wikipedia.org/wiki/Solid_(object-oriented_design) -- and especially note SRP and LSP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T02:50:57.140",
"Id": "9322",
"Score": "0",
"body": "O.K...I get it...it's just not good practice...and I will shape it to the MVC pattern..I'v decoupled my view and model again...completely now..and also...I will follow the OO design rule...as is good practice...thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T01:43:47.930",
"Id": "9386",
"Score": "0",
"body": "I thought about simply insantiating a databse from with in POST..that way I would not have to extend it...my code would basically not change at all and I could not extend post from database...but"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T01:45:06.433",
"Id": "9387",
"Score": "0",
"body": "I'm choosing to break the principle b.c. it makes more since to see post extends databse..then to have new database created from with in POST...I realize I'm breaking a principle or practice...but just changing the syntax to conform to a principle is not important..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T01:48:25.480",
"Id": "9388",
"Score": "0",
"body": "my way is more explicit...you don't have to look in the code to see the relation...I realize the principle I'm breaking....some what...but once again..these are some what abstract concepts what is a database...?...data...what is data...anything...what is a POST...a way to submit data...definitely worth considering...but linear inheritance is a good jump from pure functional programming...the less complexity the better...for now....so I don't want to add internal instantiations of my database and one_db class...I want it explicity...even if it breaks a principle somewhat"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:34:04.397",
"Id": "9397",
"Score": "0",
"body": "Extending something you shouldn't extend isn't explicit -- it's convoluted. There are much cleaner ways to do init the DB. For example, you could do the same thing by saying, in `database::query`, `one_db::get();` -- the DB would init itself as soon as you needed it, and you wouldn't have this wacky inheritance tree, and it's more explicit than abusing constructors the way you're doing."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T18:19:53.847",
"Id": "5854",
"ParentId": "5729",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "5854",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T03:59:13.587",
"Id": "5729",
"Score": "1",
"Tags": [
"php"
],
"Title": "mvc improvment - 0 - to_do"
}
|
5729
|
<p>I'm experimenting with moving shapes in JavaScript with a <code>canvas</code> tag.</p>
<p>I have one half circle (only stroked) which rotates on set intervals.</p>
<p>I've written the code so many more can be added. I can give starting rotations and a lot of other handy parameters.</p>
<p>I've tried this with twelve circles and it looks exactly like I want. Problem is, the animation slows down and the framerate goes down quite fast. And it uses heaps and heaps of memory. Any ideas on how to optimize this code to not consume so much?</p>
<p>Demo: <a href="http://jsfiddle.net/xaddict/fLE8z/" rel="nofollow">http://jsfiddle.net/xaddict/fLE8z/</a></p>
<p>JS code:</p>
<pre><code>var kin;
var canvas;
var context;
var pi = Math.PI;
var linearSpeed = 0.5*pi; // pixels / second
var linearDistEachFrame;
var myCircle;
function Circle(x, y, rot, radius, borderWidth, strokestyle){
this.x = x;this.y = y;
this.radius = radius;
this.borderWidth = borderWidth;
this.rot = rot
this.goalrot = rot;
this.strokestyle = strokestyle;
}
function randomizeThis(object){
object.goalrot += pi;
}
function updateCircle(object){
if(object.goalrot > object.rot){ //if goal rotation is bigger than current rotation
object.rot += linearDistEachFrame;
}else{ // if goal rotation is equal or smaller than current
if(object.goalrot >= 2* pi){object.goalrot -= 2* pi;}
object.rot = object.goalrot;
}
}
function drawCircle(object){
context.beginPath();
context.arc(object.x, object.y, object.radius, object.rot, object.rot+pi, false);
context.fillStyle = "none"; context.fill();
context.lineCap = "round";
context.lineWidth = object.borderWidth;
context.strokeStyle = object.strokestyle;context.stroke();
}
function drawCirc(context,x,y,radius,clip){
context.beginPath();
context.arc(x,y,radius, 0, 2*pi, false);
if(clip == true){context.clip();}
}
window.onload = function(){
kin = new Kinetic_2d("canvas");
canvas = kin.getCanvas();
context = kin.getContext();
myCircle = new Circle(421,320,1.0*pi, 153, 12,"#FAA61A");//FAA61A
kin.setDrawStage(function(){
//update
linearDistEachFrame = linearSpeed * kin.getTimeInterval() / 1000;
updateCircle(myCircle);
//clear
kin.clear();
//draw
context.save();
drawCirc(context,281,222,58,true);
drawCircle(myCircle);
context.restore();
});
kin.startAnimation();
setTimeout(function(){randomizeThis(myCircle);setInterval("randomizeThis(myCircle)",4000);clearTimeout(this);},6000);
};
</code></pre>
<p>Thanks for all help!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T05:40:55.713",
"Id": "32072",
"Score": "0",
"body": "You may be interested to know that your code performs differently between Firefox and Chrome. The statement `context.fillStyle = \"none\";` should instead be `context.fillStyle = \"rgba(0,0,0,0)\";`."
}
] |
[
{
"body": "<p>There is no need to recalculate the <code>linearDistEachFrame</code> during each update. You may want to precompute <code>2 * Math.PI</code> as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T08:01:26.847",
"Id": "8701",
"Score": "0",
"body": "I've changed the Math.PI part so now there is a variable 'pi' which is set. Where would you place linearDistEachFrame? Doesn't it change every frame?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T08:04:56.170",
"Id": "8702",
"Score": "0",
"body": "I've changed the fiddle to use linear distance as a global variable: http://jsfiddle.net/xaddict/fLE8z/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T05:13:22.140",
"Id": "5750",
"ParentId": "5731",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T09:53:33.403",
"Id": "5731",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"performance",
"html5"
],
"Title": "JavaScript canvas animation slowing down and hogging memory"
}
|
5731
|
<p>I'm an absolute beginner in PHP OOP in search of the "Holy Grail" of connecting to MySQL database once and reusing this connection for the whole site.</p>
<p><strong>classes/db.php</strong></p>
<pre><code><?php
define('SERVER', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', 'password');
define('DATABASE', 'cms');
class DB {
function __construct(){
$connection = @mysql_connect(SERVER, USERNAME, PASSWORD) or die('Connection error -> ' . mysql_error());
mysql_select_db(DATABASE, $connection) or die('Database error -> ' . mysql_error());
}
}
?>
</code></pre>
<p><strong>classes/users.php</strong></p>
<pre><code><?php
class Users {
function __construct(){
$db = new DB();
}
public function read(){
$query = mysql_query("select use_id, use_name, use_email FROM users");
while ($row = mysql_fetch_array($query)){
$data[] = $row;
}
return $data;
}
}
?>
</code></pre>
<p><strong>users.php</strong></p>
<pre><code><?php require_once('classes/db.php'); ?>
<?php require_once('classes/users.php'); ?>
<?php
$Users = new Users();
$users = $Users->read();
?>
<?php
if ($users) {
echo '<ul>';
foreach($users as $user){
echo '<li><a href="mailto:' . $user['use_email'] . '">' . $user['use_name'] . '</a></li>';
}
echo '</ul>';
}
?>
</code></pre>
<p>My doubts are mostly on the <code>Users</code> class part:</p>
<pre><code>function __construct(){
$db = new DB();
}
</code></pre>
<p>It seems to be an easy way to have the connection available, but I read somewhere that instantiate the db connection in the constructor is a bad idea. Can you explain why, and if there's a better way to have the db connection easily available in every class that needs it?</p>
<p>I read a similar question <a href="https://codereview.stackexchange.com/questions/1/database-connection-in-in-constructor-destructor">here</a>, but I can't understand the abstraction/holding reference/singleton suggestion from the accepted answer, and the lack of a full practical example doesn't help me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T12:57:38.040",
"Id": "8664",
"Score": "1",
"body": "If possible, you should be using the [PDO](http://php.net/manual/en/book.pdo.php) or [mysqli](http://php.net/manual/en/book.mysqli.php) extensions to avoid possible [SQL injections](http://littlebobbytables.com/)."
}
] |
[
{
"body": "<p>A better practice is passing a created <code>DB</code> instance to the <code>Users</code> class. Imagine that you have a <code>Products</code> class, an <code>Orders</code> class etc. Will all of their constructors create a separate MySQL connection? It doesn't look a good idea since all of them could use the same database connection. </p>\n\n<pre><code>class Users {\n private $db;\n\n public function __construct($db) {\n $this->db = $db;\n }\n\n ....\n}\n\nclass Products {\n private $db;\n\n public function __construct($db) {\n $this->db = $db;\n }\n\n ....\n}\n\n$db = new DB();\n$users = new Users($db);\n$products = new Products($db);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T16:02:16.107",
"Id": "8713",
"Score": "0",
"body": "Thanks a lot, this solution seems easy to understand and implement! The last part of your post is not much clear to me (\"If the type of the constructor parameter is an interface...\"), please can you provide an example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T20:44:26.283",
"Id": "8733",
"Score": "0",
"body": "Good point :-). I've deleted this paragraph, it looks inappropriate in your case since the `Users` class use a lot of mysql functions. Here you can find a simple mocking example: http://java.dzone.com/news/a-simple-manual-mock-example"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T17:07:13.673",
"Id": "5742",
"ParentId": "5732",
"Score": "3"
}
},
{
"body": "<p>The thing is that it'd be ideal not to have to make a connection to the DB everytime \nyou want to query something, instead you make the connection only once through a\nsingleton class \"connexion\", and by doing that you have only one connection,\nbecause there'd exist only one instnace of the class connection</p>\n\n<p>But having only one connection is not good either because sharing the same connection\nby multiple users can slow things down. In my opinion it'd be ok to have a number\nof available connections and use only those, not making a new connection everytime \nyou want to query something, I guess this is called \"connection pooling\".\nMaybe you can implement a singleton class with an array of a fixed number of connections\nto the database available, say 20 so to speak.</p>\n\n<p>But it depends on the configuration of the server running the php script\nit can be multithreaded or multiprocess.\nHere it's explained: <a href=\"http://www.zerigo.com/article/apache_multi-threaded_vs_multi-process_pre-forked\" rel=\"nofollow\">Apache: multi-threaded vs multi-process (pre-forked)</a>\nIf your server is configured as multiprocess, it's the same to make the connection in the\nconstructor of your class or in a different class.</p>\n\n<p>if your server is configured as multithreaded it's better to have a singleton class.\nBut I also read that php is not multithreaded safe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T16:16:50.470",
"Id": "8715",
"Score": "0",
"body": "Thanks, now I understand! At the moment I'm on IIS 7.5, so it's PHP thread safe"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T17:07:43.073",
"Id": "5743",
"ParentId": "5732",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5742",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T11:25:01.753",
"Id": "5732",
"Score": "5",
"Tags": [
"php",
"beginner",
"object-oriented",
"mysql",
"constructor"
],
"Title": "MySQL database connection in the constructor"
}
|
5732
|
<p>For the last few day I tried to figure out how to work with MySQL and PDO. Although I've tried to read a lot about the subject, there are still a lot of things I don't understand.</p>
<p>Because of this lack of knowledge, I can't really judge this code (or other example code on-line) on its safety and logic, and therefore was hoping I could get some feedback on it.</p>
<p>The class makes a connection and returns a query:</p>
<pre><code>class Connection
{
private $username = "xxxx";
private $password = "xxxx";
private $dsn = "mysql:host=host;dbname=name_db";
private $sql;
private $DBH;
function setSQL($sql){
$this->sql = $sql; //if $sql is not set it troughs an error at PDOException
}
public function query()
{
//the connection will get established here if it hasn't been already
if (is_null($this->DBH))
try {
$this->DBH = new PDO( $this->dsn, $this->username, $this->password );
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//query
$result = $this->DBH->prepare($this->sql);
$result->execute();
return $result->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo "I'm afraid I can't do that1.";
//file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
//clear connection and variables
function __destruct(){
$this->DBH = null;
}
}
</code></pre>
<p>Using the class:</p>
<pre><code>$sql = "SELECT * from stock WHERE id = 302";
$test = new Connection();
$test->setSQL($sql);
echo $test->query();
</code></pre>
|
[] |
[
{
"body": "<p>Two issues:</p>\n\n<p>1) I would place the code to open the connection in the constructor. </p>\n\n<p>2) You want to look into parametrized prepared statements.</p>\n\n<p>You want to send a query like:</p>\n\n<pre><code>SELECT * from stock WHERE id = ?\n</code></pre>\n\n<p>Then send an array of parmeteters:</p>\n\n<pre><code>array(302)\n</code></pre>\n\n<p>This will prevent SQL injection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:19:02.787",
"Id": "8668",
"Score": "0",
"body": "I see the logic in there, but how do you deal with the different query's you need? like: SELECT stock.size people.age from sizes LEFT JOIN people ON stock.id = people.id?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:26:34.520",
"Id": "8669",
"Score": "0",
"body": "Well you can have queries as complex as you wish but the user parameters will ultimately become ?'s. You can also create a query builder where you can say $test->leftjoin(table) and build up SQL. This will slow you down a bit though if the server is getting a lot of hits."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:05:47.260",
"Id": "5736",
"ParentId": "5735",
"Score": "0"
}
},
{
"body": "<p>1) When using PDO, you want to get the benefits of automatic parameter escaping. \nBy wrapping your PDO class you are limiting it's functionality. Check out this question for a better example:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/6366661/php-pdo-parameterised-query-for-mysql\">https://stackoverflow.com/questions/6366661/php-pdo-parameterised-query-for-mysql</a></p>\n\n<p>2) Every time you run a query you are making a new PDO instance. It might be better to have an application resource pool that you can call to get a preconfigured db handle. </p>\n\n<p>3) You wrote some sql to be able to fetch a stock by ID, that should probably be functionality that is reusable.</p>\n\n<p>combining 1 & 2 & 3 .. code would probably look better as something like this:</p>\n\n<pre><code>class ApplicationResourcePool \n{\n static var $_dbHandle;\n\n private static $_dbConfig = array(\n 'dsn' => '',\n 'username' => '',\n 'password' => '',\n\n );\n public static getDbHandle(){\n if(self::$_dbHandle == null){\n self::$_dbHandle = new PDO(\n self::$_dbConfig['dsn'] , \n self::$_dbConfig['username'], \n self::$_dbConfig['password'] \n );\n }\n return self::$_dbHandle;\n }\n\n}\n\nclass StockMapper\n{\n protected $_dbh; \n public __construct($dbh = null)\n {\n if($dbh == null){\n $this->_dbh = ApplicationResourcePool::getDbHandle();\n } else {\n $this->_dbh = $dbh;\n }\n\n }\n public getStockById($stockId){\n\n $sth=$this->_dbh->prepare(\"SELECT * from stock WHERE id = :stockId\"); \n $sth->bindParam(\":stockId\", $stockId);\n $sth->execute();\n $result = $sth->fetch(PDO::FETCH_ASSOC);\n return $result[0];\n }\n}\n</code></pre>\n\n<p>your codeBlock then becomes:</p>\n\n<pre><code>$stockMapper = new StockMapper();\n$stockData = $stockMapper->getStockById('302');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:42:15.017",
"Id": "8670",
"Score": "0",
"body": "perfect!, that seems like a more logic and better way to handle this. Would you have any advice how to handle the PDOException in this example? Would you add it as a function('s) to getStockById?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T19:04:04.207",
"Id": "8671",
"Score": "0",
"body": "I'd probably log the exception in a logger and in turn throw another exception that my outer code could catch. Your outer code shouldn't need to know that the stock mapper is internally using a DB or PDO as it's data storage/retrieval."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T19:05:55.313",
"Id": "8672",
"Score": "0",
"body": "The one other thing I would probably do is create a \"Stock\" class that my mapper could populate with the data array from the database. Then I get a first class object instead of a PHP array as a return value."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:26:54.113",
"Id": "5737",
"ParentId": "5735",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T18:00:19.093",
"Id": "5735",
"Score": "4",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "PDO (MySQL) connection and query class, safety and logic"
}
|
5735
|
<p>In building any new application I end up using something similar to this data access type code. I know it well, and it works well. But in the act of wanting to try something new on a new project I thought I could review it again and maybe simplify it more, or move it into an ORM. I've been looking at <a href="http://code.google.com/p/dapper-dot-net/" rel="nofollow">Dapper</a>, though I know there are a whole host of ORM's. </p>
<p>This is code to retrieve a List of any sort of data. Something thats completed often in my code.<br>
"Business" code</p>
<pre><code>public class MyClassA
{
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
// Many other properties
internal static MyClassA BuildPostsFromRow(DataRow dr)
{
MyClassA _myclass = new MyClassA();
_myclass.Id = (int)dr["ContentId"];
/* Many other properties */
_myclass.CreatedDate = (DateTime)dr["CreatedDate"];
return _myclass;
}
public List<Post> ListRecentForInstance(int id)
{
DataAccess _da = new DataAccess();
return _da.ListForInstance(id);
}
}
</code></pre>
<p>My actual Data access</p>
<pre><code>public class DataAccess
{
public readonly string Con = ConfigurationManager.ConnectionStrings["MyDb"].ToString();
public List<MyClassA> ListForInstance(int instanceId)
{
var _sql = @"
SELECT Id,
CreatedDate,
...other data
FROM MyData
WHERE InstanceId = @instanceId
";
SqlParameter[] _params = new SqlParameter[1];
_params[0] = new SqlParameter("@instanceId", SqlDbType.Int) { Value = instanceId };
return DataHelper.ExecuteQuery(Con, _sql, _params).Tables[0].AsEnumerable()
//MyClassA.BuildPostsFromRow can also be split out to be inline rather and
// calling another method but I'm reusing the BuildPostsFromRow method for now
.Select(row => MyClassA.BuildPostsFromRow(row))
.ToList();
}
}
public class DataHelper
{
// A few other similar methods to wrap up data access code and sql logging
// only the DataAccess class calls these methods
public static DataSet ExecuteQuery(string connection, string sql, params SqlParameter[] paramsToCommand)
{
using (DataSet ds = new DataSet())
{
using (SqlConnection _con = new SqlConnection(connection))
{
if (_con.State == ConnectionState.Closed)
_con.Open();
using (SqlCommand _cmd = new SqlCommand(sql, _con))
{
AttachParameters(_cmd, paramsToCommand);
using (SqlDataAdapter adapter = new SqlDataAdapter(_cmd))
{
adapter.Fill(ds);
}
}
}
return ds;
}
}
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
if (command == null)
throw new ArgumentNullException("command");
if (commandParameters != null)
{
foreach (SqlParameter p in commandParameters)
{
if (p != null)
{
if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && (p.Value == null))
p.Value = DBNull.Value;
command.Parameters.Add(p);
}
}
}
}
}
</code></pre>
<p>Yes I'm sure everyone thinks "oh great another DAL". But I'm really wanting some change. I'd really like some pointers on how to move away from this model and slip into something more modern. </p>
<p>Edit:<br>
In the thought of testing, I spent today figuring out Linq 2 Sql and Dapper. I really want something to work, I really do. So here is my app, as short and sweet and full of nothing as it is:</p>
<pre><code>class Program
{
public static readonly string connectionString =
@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\Database1.mdf;Integrated Security=True;User Instance=True";
public static SqlConnection GetOpenConnection()
{
var connection = new SqlConnection(connectionString);
if (connection.State != ConnectionState.Open)
connection.Open();
return connection;
}
SqlConnection connection = GetOpenConnection();
static void Main(string[] args)
{
// Added as it was taking time the first time to connect the db to the instance
using (var connection = new SqlConnection(connectionString))
{
if (connection.State != ConnectionState.Open)
connection.Open();
}
Stopwatch sw1 = new Stopwatch();
sw1.Start();
int i = 0;
// Linq2Sql
for (i = 0; i <= 100; i++)
{
CoreClassesDataContext _dc = new CoreClassesDataContext();
var _posts = (from p in _dc.Posts
select p).ToList();
foreach (var item in _posts)
{
int id = item.Id;
}
_dc.Dispose();
}
sw1.Stop();
Console.WriteLine("Linq 2 Sql");
Console.WriteLine(sw1.ElapsedMilliseconds);
sw1.Reset();
sw1.Start();
// Dapper
for (i = 0; i <= 100; i++)
{
Program _p = new Program();
var data = _p.connection.Query<Post>("select Id, PostContent from Post").ToList();
foreach (var item in data)
{
int id = item.Id;
}
}
sw1.Stop();
Console.WriteLine("Dapper");
Console.WriteLine(sw1.ElapsedMilliseconds);
sw1.Restart();
// Plain ol ADO
for (i = 0; i <= 100; i++)
{
Data _d = new Data();
foreach (var item in _d.BuildList())
{
int id = item.Id;
}
}
sw1.Stop();
Console.WriteLine("DAL");
Console.WriteLine(sw1.ElapsedMilliseconds);
Console.ReadKey();
}
class Data
{
public List<Post> BuildList()
{
var _sql = "select Id, PostContent from Post";
return DataHelper.ExecuteQuery(connectionString, _sql).Tables[0].AsEnumerable()
.Select(row => new Post { Id = (int)row["Id"],
PostContent = (string)row["PostContent"]
}).ToList();
}
}
class Post
{
public int Id { get; set; }
public string PostContent { get; set; }
}
}
</code></pre>
<p>After many, many runs, it almost always works out like this or close to:</p>
<pre><code>Linq 2 Sql
205
Dapper
394
DAL
105
</code></pre>
<p>I thought part of an ORM was to help with speed? So why is my dead simple, hand crafted DAL beating the pants off both? Am I doing something wrong? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T08:41:04.953",
"Id": "8788",
"Score": "0",
"body": "In this small solution, speed is not going to be an issue. It's easy to get picky when it comes to performance, but in this case it doesnt matter. And Dapper should be one of the fastest ORM's out there according to: http://www.eggheadcafe.com/tutorials/ado/72379bea-41ab-4370-9484-aec017d083b3/net-microorms--dapper-petapoco-and-more.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T10:53:06.030",
"Id": "8792",
"Score": "0",
"body": "Who's saying this is going to be a small solution? I know I didn't. The application usage is pretty wide. I'm using similar patterns with both personal work (MS SQL) like my example. As well as at work in MySQL with many millions of rows of data. This is why I was looking at things like Dapper, one implementation, many database types. I also work with Oracle at work along with MySQL in the same application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T11:01:00.283",
"Id": "8793",
"Score": "0",
"body": "Performance is also very critical for me, not so much the time it takes to write all the data access. As a company, we don't do TDD. So while it would be nice to be able to someday, its not important to the powers that be at this time. I'd even wager a bet that my senior dev doesn't even know what it is. I'm just trying to find something that's ***really*** fast, not too complex, and maybe just maybe be able to run tests against."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T11:21:29.037",
"Id": "8794",
"Score": "0",
"body": "Im sure LINQ-TO-SQL will do: http://blog.stackoverflow.com/2008/09/what-was-stack-overflow-built-with/"
}
] |
[
{
"body": "<p>Your headline question is in two parts. </p>\n\n<p>Taking the first part, \"How to simplify\", I'd say that you shouldn't bother trying. All of that effort is already in other frameworks, whether they are small helpers like Dapper or fully-featured ORMs like NHibernate. The world, as you've realised, has moved on.</p>\n\n<p>To answer the second part, \"shift it into an ORM\", I'd suggest that is not possible. Taking the example of EF code first or Fluent NHibernate (preferably with AutoMapping), you start from your POCOs that model your domain, in the case of your code above, a single 'Post' class. The rest of the code is already in the framework.</p>\n\n<p>My advice on how to pick up a modern model, as you put it, would be to do a learning exercise. Put aside the codebase you have for a while and look at creating a small application for yourself that uses EF code first or Fluent NHibernate with Automapping. You could even see how easy it is to branch/refactor and use the other ORM - a great way to learn the essentials.</p>\n\n<p>UPDATE: hopefully this implementation of a rough PostRepository with Fluent NHibernate Automapping will encourage you in your studies. There are holes in the following but you could probably get it working. Use NuGet to fetch Fluent NHibernate.</p>\n\n<pre><code>public static class Configuration\n{\n public static FluentConfiguration GetConfiguration(string connectionString)\n {\n var executingAssembly = Assembly.GetExecutingAssembly();\n\n var configuration =\n Fluently.Configure()\n .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))\n .Mappings(\n m =>\n m.AutoMappings.Add(\n AutoMap.Assemblies(new AutomappingConfiguration(), executingAssembly)\n .IgnoreBase<Entity>())\n .ExposeConfiguration(BuildSchema);\n\n return configuration;\n }\n\n // Set SchemaScript to True to see the generated DDL.\n // Set SchemaExport to True to build the database.\n private static void BuildSchema(NHibernate.Cfg.Configuration configuration)\n {\n new SchemaExport(configuration)\n .SetOutputFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"schema.sql\"))\n .Create(Properties.Settings.Default.SchemaScript, Properties.Settings.Default.SchemaExport);\n }\n}\n</code></pre>\n\n<p>The following class allows you to specify the namespace of your entity (i.e. the 'Post' model).</p>\n\n<pre><code>public class AutomappingConfiguration : DefaultAutomappingConfiguration\n{\n public override bool ShouldMap(Type type)\n {\n return type.Namespace == \"MyPostProject.Entities\";\n }\n}\n</code></pre>\n\n<p>NHibernate likes everything to have an identity. Here's a base class for that. Everything needs to be virtual so NHibernate can create proxies to your model objects.</p>\n\n<pre><code>public abstract class Entity\n{\n public virtual int Id { get; protected internal set; }\n}\n</code></pre>\n\n<p>Here's a basic Post entity.</p>\n\n<pre><code>public class Post : Entity\n{\n public virtual string Content { get; set; }\n}\n</code></pre>\n\n<p>A base repository class that uses the Session as its Unit of Work.</p>\n\n<pre><code>public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity\n{\n protected readonly ISession Session;\n\n protected Repository(ISessionSource sessionSource)\n {\n this.Session = sessionSource.CreateSession();\n }\n\n public virtual void SaveOrUpdate(TEntity entity)\n {\n this.Session.SaveOrUpdate(entity);\n this.Session.Flush();\n }\n\n public virtual TEntity GetById(int id)\n {\n return this.Session.Get<TEntity>(id);\n }\n\n public virtual IEnumerable<TEntity> GetAll()\n {\n return this.Session.CreateCriteria<TEntity>().List<TEntity>();\n }\n}\n</code></pre>\n\n<p>The PostRepository.</p>\n\n<pre><code>public class PostRepository : Repository<Post>, IDeletionRepository<Post>, IPostRepository\n{\n public PostRepository(ISessionSource sessionSource) : base(sessionSource)\n {\n }\n\n public void Delete(Post post)\n {\n this.Session.Delete(post);\n this.Session.Flush();\n }\n}\n</code></pre>\n\n<p>A persistence test that checks your mappings are correct.</p>\n\n<pre><code>using Configuration = MyPostProject.Configuration;\n\n[TestClass]\npublic class PersistenceSpecificationTests\n{\n private ISession session;\n\n [TestInitialize]\n public void SetUp()\n {\n var sessionSource = new SessionSource(Configuration.GetConfiguration(\"Data Source =.; Initial Catalog =Post; Integrated Security=True;\"));\n session = sessionSource.CreateSession();\n }\n\n [TestMethod]\n public void CanMapPost()\n {\n using (var transaction = session.BeginTransaction())\n {\n new PersistenceSpecification<Post>(session)\n .CheckProperty(m => m.Content, \"Lorum ipsum\")\n .VerifyTheMappings();\n\n transaction.Rollback();\n }\n }\n}\n</code></pre>\n\n<p>Create a dummy post (use an Object Mother generator like NBuilder or AutoFixture) and try to exercise your repository.</p>\n\n<pre><code> [TestMethod]\n public void ShouldSaveUser()\n {\n using (var transaction = session.BeginTransaction())\n {\n session.Save(dummyPost);\n transaction.Rollback();\n }\n }\n</code></pre>\n\n<p>There's a lot more besides with Fluent NHibernate's Overrides, that let you set up small changes to the default automapping if required, and Conventions, that pretty up your DDL. Your repository should also be able to take specifications (criteria to search on).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T20:09:57.573",
"Id": "8722",
"Score": "0",
"body": "My main problem is that this model is dead simple. It's just very time consuming to hand write all the SQL. When I look at EF I see major complexities. Maybe I just need to find the right example, covering a common goal or problem, that is not over engineered. I'm able to learn and adapt, but it has to make sense to me, and so far I haven't found the right example or tutorial."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T09:40:00.857",
"Id": "8745",
"Score": "0",
"body": "I can't point you to a perfect tutorial, I'm afraid, and my own implementation is more complicated, but I'll edit my answer to show a rough PostRepository with Fluent NHibernate Automapping."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T10:43:15.887",
"Id": "8751",
"Score": "1",
"body": "If NHibernate feels too much overkill, you should definitely utilize LINQ-TO-SQL. Perfect for a smaller scenario."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T13:35:23.057",
"Id": "8757",
"Score": "0",
"body": "@Mattias That's a really sensible suggestion - wish I'd thought of that! Mark up your entity with attributes, one line to create your data context and you're away. The queries even _look_ like SQL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T16:44:53.707",
"Id": "8762",
"Score": "0",
"body": "Very nice! I will give this a whirl soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T16:45:27.017",
"Id": "8763",
"Score": "0",
"body": "@Mattias, maybe post an answer eh?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T15:59:09.090",
"Id": "5762",
"ParentId": "5744",
"Score": "3"
}
},
{
"body": "<p>If NHibernate feels too much overkill, you should definitely utilize LINQ-TO-SQL. Perfect for a smaller scenario.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T17:28:56.877",
"Id": "5785",
"ParentId": "5744",
"Score": "2"
}
},
{
"body": "<p>I'm a BIG fan of Entity Framework. I generally use database first and then update my data model from the tables I select. I then use linq with lambdas expressions. With this, combination, I can write some pretty concise code and no SQL. I have to recommend giving it a try.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/data/gg685489\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/data/gg685489</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T01:48:53.090",
"Id": "5826",
"ParentId": "5744",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5762",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T20:54:40.223",
"Id": "5744",
"Score": "4",
"Tags": [
"c#",
"design-patterns"
],
"Title": "How to simplify my data access or shift it into an ORM"
}
|
5744
|
<p>This is primarily a container for quicksort and mergesort:</p>
<pre><code>#include "c_arclib.cpp"
template <class T> class dynamic_array
{
private:
T* array;
T* scratch;
public:
int size;
dynamic_array(int sizein)
{
size=sizein;
array = new T[size]();
}
void print_array()
{
for (int i = 0; i < size; i++) cout << array[i] << endl;
}
void merge_recurse(int left, int right)
{
if(right == left + 1)
{
return;
}
else
{
int i = 0;
int length = right - left;
int midpoint_distance = length/2;
int l = left, r = left + midpoint_distance;
merge_recurse(left, left + midpoint_distance);
merge_recurse(left + midpoint_distance, right);
for(i = 0; i < length; i++)
{
if((l < (left + midpoint_distance)) && (r == right || array[l] > array[r]))
{
scratch[i] = array[l];
l++;
}
else
{
scratch[i] = array[r];
r++;
}
}
for(i = left; i < right; i++)
{
array[i] = scratch[i - left];
}
}
}
int merge_sort()
{
scratch = new T[size]();
if(scratch != NULL)
{
merge_recurse(0, size);
return 1;
}
else
{
return 0;
}
}
void quick_recurse(int left, int right)
{
int l = left, r = right, tmp;
int pivot = array[(left + right) / 2];
while (l <= r)
{
while (array[l] < pivot)l++;
while (array[r] > pivot)r--;
if (l <= r)
{
tmp = array[l];
array[l] = array[r];
array[r] = tmp;
l++;
r--;
}
}
if (left < r)quick_recurse(left, r);
if (l < right)quick_recurse(l, right);
}
void quick_sort()
{
quick_recurse(0,size);
}
void rand_to_array()
{
srand(time(NULL));
int* k;
for (k = array; k != array + size; ++k)
{
*k=rand();
}
}
};
int main()
{
dynamic_array<int> d1(10);
cout << d1.size;
d1.print_array();
d1.rand_to_array();
d1.print_array();
d1.merge_sort();
d1.print_array();
}
</code></pre>
|
[] |
[
{
"body": "<p>My first comment is its named badly.</p>\n\n<p>dynamic_array implies that I can use [] operator on it and get a value out.</p>\n\n<p>You have owned RAW pointers in your structure.</p>\n\n<pre><code>private:\n T* array;\n T* scratch;\n</code></pre>\n\n<p>First this means you need to look up RAII to make sure these members are correctly deleted.</p>\n\n<p>Second you you need to look up the rule of three (or 5 in C++11) to make sure they are copied correctly.</p>\n\n<p>You have owned RAW pointers in your structure. This means you need to correctly manage the object as a resource. This means constructions/destruction/copy (creation and assignment) need to be taken care of correctly.</p>\n\n<p>Either do this manually or use a standard container that will do it for you. I suggest a standard container.</p>\n\n<pre><code>void print_array()\n {\n for (int i = 0; i < size; i++) cout << array[i] << endl;\n }\n</code></pre>\n\n<p>If you are going to write print_array at least write it so that it can use alternative stream (not just std::cout). Then write the output operator.</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& stream, dynamic_array const& data)\n{\n data.print_array(stream); // After you fix print_array\n return stream;\n}\n</code></pre>\n\n<p>Also note that a method that access data but does not modify the state of the object should be marked const. So the signature should be: <code>void print_array() const</code></p>\n\n<p>Are the following members really part of the array?</p>\n\n<pre><code>void merge_recurse(int left, int right)\nint merge_sort()\nvoid quick_recurse(int left, int right)\n</code></pre>\n\n<p>OK. Lets assume they are for now.<br>\nThen <code>void merge_recurse(int left, int right)</code> should be a private member. There should be no reason to call this from externally.</p>\n\n<pre><code> scratch = new T[size]();\n if(scratch != NULL)\n</code></pre>\n\n<p>scratch will <strong>Never</strong> be NULL.</p>\n\n<p>I think merge (in merge_recurse) is easier to write than you are making it:</p>\n\n<pre><code> int index = 0;\n int l = left;\n int r = midpoint;\n while((l < midpoint) && (r < right))\n {\n scratch[index++] = (array[l] > array[r]))\n ? array[l++]\n : array[r++];\n }\n // One of the two ranges is empty.\n // copy the other into the destination.\n while(l < midpoint)\n {\n scratch[index++] = array[l++];\n }\n while(r < right)\n {\n scratch[index++] = array[r++];\n }\n</code></pre>\n\n<p>You should only call srand() once in an application:</p>\n\n<pre><code>void rand_to_array()\n {\n srand(time(NULL));\n</code></pre>\n\n<p>By putting srand() inside the structure you are opening it up to be called multiple times. Call it once just after main() then don't call it again.</p>\n\n<p>When you can use the standard tools:</p>\n\n<pre><code> tmp = array[l];\n array[l] = array[r];\n array[r] = tmp;\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code> std::swap(array[l], array[r]);\n</code></pre>\n\n<p>I am relatively sure these two are wrong:</p>\n\n<pre><code> while (l <= r)\n if (l <= r) \n</code></pre>\n\n<p>They should be:</p>\n\n<pre><code> while (l < r)\n if (l < r) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T01:14:11.193",
"Id": "8695",
"Score": "0",
"body": "+1 but I must disagree with the bit about using a standard container. The OP is reimplementing a poor man's version of vector. Of course, he should normally use a vector, but if reimplementing vector for learning purposes it would be silly to use vector or another standard container to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T16:11:31.223",
"Id": "8714",
"Score": "0",
"body": "@WinstonEwert: I was not sure if his goal was a poor man vector or just a structure so that he could practice sorting with. My advice design the class for **one** particular use. Thus in the case use a standard container to hold the data and implement the sorting here. If this is a poor man's vector then fine but in that case my advice would be to factor out the sorting stuff into its own class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T16:47:50.677",
"Id": "8827",
"Score": "0",
"body": "Posted New Code. Thank you, I re-wrote merge_sort alltogether and implemented some of your changes. This is a class so I can practice sorting and interview...but I'm also curious that b.c. I \"own\" it..maybe I can beat Vector in performance for special cases....there is still alot of work to to do on this..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T16:52:13.930",
"Id": "8828",
"Score": "0",
"body": "You raised so many questions I do not think I have time to answer them...particularly the issue with raw pointers...how can I verify their destruction?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T17:33:09.933",
"Id": "8832",
"Score": "0",
"body": "@Chris Aaker: You will not beat vector in any situation. If you find that you have written code that is faster than vector then you have forgotten to do something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T17:35:05.513",
"Id": "8833",
"Score": "0",
"body": "@Chris Aaker: This is why you should not have RAW pointers in your class. RAW pointers should be wrapped inside a smart pointer (or containers) to allow for correct copying and destruction. The exception to this rule are smart pointers and containers. If you write these then you need to make sure that you obey the rule of three (look it up) this will mkae sure you correctly copy and delete any RAW pointers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T17:35:49.680",
"Id": "8834",
"Score": "0",
"body": "@ChrisAaker: When you say you posted new code. I hope you mean in a new question. This question should be left in its original state or any new code **appended** to the bottom. If we do not maintain the questions then the answers become disjoint from the question and new people will not be able to learn much. I find the best solution is to post a new question and put links between the questions then you maintain a linked history. If you have overwritten the code then please revert and create a new question."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T00:18:27.923",
"Id": "5746",
"ParentId": "5745",
"Score": "3"
}
},
{
"body": "<p>This is just a review regarding coding style. Because... your code is impossible to read. And because of the poor coding style alone, you will get less replies whenever you post it to sites like this one.</p>\n\n<p>At a very minimum, you should keep empty rows between every function declaration, or the program look like one big goo. Including empty rows here and there inside the function bodies as well, to indicate which sections of code that belong together.</p>\n\n<p>You should also consider changing indention style to something more conventional. The most common form by far is not to indent the braces, but indent the contents between them. Another less common but acceptable style is to indent the braces <em>and</em> then indent the contents between them. </p>\n\n<p>Here is an example of what your code would look like, using one of the most common styles:</p>\n\n<pre><code>#include \"c_arclib.cpp\"\n\n// space here\n\ntemplate <class T> // template specification is most often put on a row of its own\nclass dynamic_array\n{\n private:\n T* array;\n T* scratch;\n\n // space here, private and public dont belong together\n\n public:\n int size;\n\n dynamic_array (int sizein)\n {\n size=sizein;\n array = new T[size]();\n }\n\n // space between all functions!!!\n\n void print_array ()\n {\n for (int i = 0; i < size; i++) // always use braces to avoid bugs!\n { \n cout << array[i] << endl;\n }\n }\n\n void merge_recurse (int left, int right)\n {\n if(right == left + 1)\n {\n return;\n }\n else\n {\n int i = 0;\n int length = right - left;\n int midpoint_distance = length/2;\n int l = left, r = left + midpoint_distance;\n\n // space here, end of variable declarations\n\n merge_recurse(left, left + midpoint_distance);\n merge_recurse(left + midpoint_distance, right);\n\n for(i = 0; i < length; i++)\n {\n /* The if statement would really benefit from getting split up in several\n statements. Replace the bool variable names below with something meaningful. \n (I haven't bothered to look at what your code actually does). */\n\n bool less_midpoint = l < (left + midpoint_distance);\n bool equal = r == right;\n bool larger = array[l] > array[r];\n\n if(less_midpoint && (equal || larger))\n {\n scratch[i] = array[l];\n l++;\n }\n else\n {\n scratch[i] = array[r];\n r++;\n }\n }\n\n for(i = left; i < right; i++)\n {\n array[i] = scratch[i - left];\n }\n } // else /* <- Write \"else\" or similar in a comment to indicate to what\n code a brace belongs to inside a complex, long nested code */\n } // merge_recurse\n\n int merge_sort ()\n {\n scratch = new T[size]();\n if(scratch != NULL)\n {\n merge_recurse(0, size);\n return 1;\n }\n else\n {\n return 0;\n }\n }\n\n void quick_recurse (int left, int right) \n { \n int l = left, r = right, tmp;\n int pivot = array[(left + right) / 2];\n\n while (l <= r)\n {\n while (array[l] < pivot) // always use braces to avoid bugs!\n {\n l++;\n }\n while (array[r] > pivot) // always use braces to avoid bugs!\n {\n r--;\n }\n\n if (l <= r) \n {\n tmp = array[l];\n array[l] = array[r];\n array[r] = tmp;\n l++;\n r--;\n }\n } // while (l <= r)\n\n if (left < r)\n {\n quick_recurse(left, r);\n }\n if (l < right)\n {\n quick_recurse(l, right);\n }\n } \n\n void quick_sort ()\n {\n quick_recurse(0,size);\n }\n\n void rand_to_array ()\n {\n srand(time(NULL));\n int* k;\n\n for (k = array; k != array + size; ++k) \n { \n *k=rand(); \n } \n }\n};\n\nint main()\n{\n dynamic_array<int> d1(10);\n cout << d1.size;\n d1.print_array();\n d1.rand_to_array();\n d1.print_array();\n d1.merge_sort();\n d1.print_array();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T16:37:43.230",
"Id": "8826",
"Score": "0",
"body": "I agree your code looks nicer...I get tired of scrolling so I bunch it togther too much....screen is too small"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T07:38:58.020",
"Id": "8850",
"Score": "0",
"body": "@Chris Aaker: You should get yourself a modern or semi-modern IDE, so that you can jump directly to a specific function in the source code without any scrolling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T01:59:39.850",
"Id": "9601",
"Score": "0",
"body": "I'm finally updating my style to the Zend PHP Style..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T12:48:03.563",
"Id": "5803",
"ParentId": "5745",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-01T23:20:40.290",
"Id": "5745",
"Score": "7",
"Tags": [
"c++",
"array"
],
"Title": "Dynamic array container"
}
|
5745
|
<p><pre>
class BencodeObject:</p>
<code>def __init__(self,filename):
with open(filename,'rb') as diskbytes:
self.loads(diskbytes)
def _isdictionary(self,bits): return(bits == b"d")
def _isnumber(self,bits): return(bits > b"/" and bits < b":")
def _iscolon(self,bits): return(bits == b":")
def _isint(self,bits): return(bits == b"i")
def _islist(self,bits): return(bits == b"l")
def _isend(self,bits): return(bits == b"e")
def _isnull(self,bits): return(bits == b"")
def loads(self,bcbuffer):
tokens = []
null = b""
numbuffer = null # a buffer for storing number bytes
last = []
while True:
atom = bcbuffer.read(1)
if self._isdictionary(atom): last.append(atom)
elif self._isnumber(atom):
numbuffer += atom
elif self._iscolon(atom):
tokens.append(bcbuffer.read(int(numbuffer)))
numbuffer = null
elif self._isint(atom): last.append(atom)
elif self._islist(atom): last.append(atom)
elif self._isend(atom):
char = last.pop()
if self._isint(char):
tokens.append(int(numbuffer))
numbuffer = null
else: break
self.bytestrings = tokens
self.trackerURL = str(self.bytestrings[1],"utf-8")
</code></pre>
<p>Looking for whatever input I can get.</p>
|
[] |
[
{
"body": "<pre><code>class BencodeObject:\n</code></pre>\n\n<p>Putting object inside Class names is generally not a good idea, because it doesn't tell me anything. </p>\n\n<pre><code>def __init__(self,filename):\n with open(filename,'rb') as diskbytes:\n self.loads(diskbytes)\n\ndef _isdictionary(self,bits): return(bits == b\"d\")\n</code></pre>\n\n<p>There is no need for the parens around the expression. They just clutter things</p>\n\n<pre><code>def _isnumber(self,bits): return(bits > b\"/\" and bits < b\":\")\n</code></pre>\n\n<p>That's a confusing way to express this. Instead use <code>bits >= b'0' and bits <= '9'</code> </p>\n\n<pre><code>def _iscolon(self,bits): return(bits == b\":\")\ndef _isint(self,bits): return(bits == b\"i\")\ndef _islist(self,bits): return(bits == b\"l\")\ndef _isend(self,bits): return(bits == b\"e\")\ndef _isnull(self,bits): return(bits == b\"\")\n</code></pre>\n\n<p>Its not clear how useful these functions are. You call them once, and calling them isn't shorter then just checking the string for equality in the first place. Also the pythons style guide recommends using underscores_to_seperate_words. As it is I keep reading isend as i send.</p>\n\n<pre><code>def loads(self,bcbuffer):\n tokens = []\n null = b\"\"\n numbuffer = null # a buffer for storing number bytes\n</code></pre>\n\n<p>I'm not sure a constant for an empty string is neccessary. If you insist I suggest it should be a global constant.</p>\n\n<pre><code> last = []\n</code></pre>\n\n<p>Last suggests, well, last. But this is more of a stack. I think it could have a better name</p>\n\n<pre><code> while True:\n atom = bcbuffer.read(1)\n if self._isdictionary(atom): last.append(atom)\n</code></pre>\n\n<p>Mixing between on-the-same-line, and on-the-next lines within a string of if-elifs looks ugly and makes it harder to read. I'm generally not a fan of putting the body on the same line as the if expression. But it really doesn't work when you mix both styles.</p>\n\n<pre><code> elif self._isnumber(atom): \n numbuffer += atom\n elif self._iscolon(atom): \n tokens.append(bcbuffer.read(int(numbuffer)))\n numbuffer = null \n elif self._isint(atom): last.append(atom)\n elif self._islist(atom): last.append(atom)\n</code></pre>\n\n<p>You <code>last.append(atom)</code> a lot. Consider <code>or</code> to combine the conditions</p>\n\n<pre><code> elif self._isend(atom): \n char = last.pop()\n if self._isint(char):\n tokens.append(int(numbuffer))\n numbuffer = null\n else: break\n</code></pre>\n\n<p>You don't distinguish between finding invalid characters and the end of the file. In both case you just quit. I'd recommend throwing an exception if you find an invalid character.</p>\n\n<pre><code> self.bytestrings = tokens\n</code></pre>\n\n<p>But the tokens also include numbers. So storing them in bytestrings is kinda odd.</p>\n\n<pre><code> self.trackerURL = str(self.bytestrings[1],\"utf-8\")\n</code></pre>\n\n<p>Your loop follows the common pattern of building data structures over several iterations of the loop and then consuming them. Don't do that. It ends up being hard to follow the logic of the function because I've got to figure out what happens over several iterations of the loop. Instead, each iteration of the loop should handle a logical unit.</p>\n\n<p>Here is how I'd approach the problem:</p>\n\n<pre><code>def read_number(bcbuffer, terminator):\n read_byte = lambda: bcbuffer.read(1)\n bytes_iter = iter(read_byte, terminator)\n text = ''.join(bytes_iter)\n return int(text)\n\n\ndef parse_tokens(self, bcbuffer):\n tokens = []\n\n while True:\n atom = bcbuffer.read()\n if atom == b'i':\n tokens.append( read_number(bcbuffer, b'e') )\n elif atom >= b'0' and atom <= b'9':\n length = read_number(bcbuffer, b':')\n tokens.append( bcbuffer.read(length) )\n elif atom in b\"lde\":\n pass # ignore the structure which we don't care about\n elif atom == b'':\n break\n else:\n raise IOError('Did not expect %s' % atom)\n\n return tokens\n</code></pre>\n\n<p>Notice that I don't have a collection of variables to store partial results. Because each iteration of the loop handles a single \"token\" I don't need to store data other then my result across the iterations. It is also much clearer, I think, what is going on in the parsing.</p>\n\n<p>I've not tested this code in anyway, use at own risk. I've ignored the possiblity of invalid bencodes. read_number will end up in an infinite loop if it cannot find the terminator. non-digits before the terminator will cause int to throw a ValueError. Various methods to handle those exist. I'd probably wrap file.read() to throw an exception when trying to read past the end of the file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T17:50:44.493",
"Id": "8765",
"Score": "0",
"body": "Can you elaborate a little more on the “class name” comment at the top? Perhaps I am missing some Pythonic OOP concept. Or just being a dumb dumb. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T18:22:53.750",
"Id": "8766",
"Score": "1",
"body": "@veryfoolish, Your class's name is BencodeObject. Everything in python is an object. So its kinda useless to point that out in your class name. A better class named might be BencodeExtractor. My point is just that Object is a useless word that means almost nothing. So don't put it in your class names"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T14:43:01.757",
"Id": "5758",
"ParentId": "5751",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T06:55:18.020",
"Id": "5751",
"Score": "3",
"Tags": [
"python"
],
"Title": "Bencode “Parser” in Python 3"
}
|
5751
|
<p>I know that there are many similar questions, but I don't understand most of those questions because I'm not sure if I know what a factory method pattern is.</p>
<p>So, after reading many examples over the web, I came up with the following simple classes.</p>
<p>Am I doing it correctly? If so...any improvements I can add?</p>
<pre><code>abstract class Driveable
{
abstract public function start();
abstract public function stop();
}
class CoupeDriveable extends Driveable
{
public function start()
{
}
public function stop()
{
}
}
class MotorcycleDriveable extends Driveable
{
public function start()
{
}
public function stop()
{
}
}
class SedanDriveable extends Driveable
{
public function start()
{
}
public function stop()
{
}
}
class DriveableFactory
{
static public function create($numberOfPeople){
if( $numberOfPeople == 1 )
{
return new MotorcycleDriveable;
}
elseif( $numberOfPeople == 2 )
{
return new CoupleDriveable;
}
elseif( $numberOfPeople >= 3 && $numberOfPeople < 4)
{
return SedanDriveable;
}
}
}
class App
{
static public function getDriveableMachine($numberOfPeople)
{
return DriveableFactory::create($numberOfPeople);
}
}
$DriveableMachine = App::getDriveableMachine(2);
$DriveableMachine->start();
</code></pre>
<p><strong>Update</strong>: <em>according to palacsint and serghei's valueable advices, I've updated my code.</em></p>
<pre><code>abstract class DriveableFactory
{
static public function create($numberOfPeople);
}
class CarDriveableFactory extends DriveableFactory
{
static public function create($numberOfPeople){
$products = array
(
1=>"MotorcycleDriveable",
2=>"CoupeDriveable",
3=>"SedanDriveable",
4=>"SedanDriveable"
);
if( isset( $products[$numberOfPeople] ) )
{
return new $products[$numberOfPeople];
}
else
{
throw new Exception("unable to find a suitable drivable car");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T04:45:10.353",
"Id": "49289",
"Score": "0",
"body": "Now your `create` function returns a string instead of an object. Was this for the sake of simplication? You got the Factory Method right though."
}
] |
[
{
"body": "<p>I think is good implementation but you can reduce the multiple if else conditions\nI don't know the PHP I can write you as I implement in C# code\nin C# there is specific type Dictionary that represent key value pair collection and if in PHP exist some similar you can use it look at the foolwing code</p>\n\n<pre><code> private Driveable Create(int numberOfPeople)\n {\n Dictionary<int, Driveable> registerDriveable = new Dictionary<int, Driveable>();\n registerDriveable.Add(1, new MotorcycleDriveable());\n registerDriveable.Add(2, new CoupeDriveable());\n registerDriveable.Add(3, new SedanDriveable());\n registerDriveable.Add(4, new SedanDriveable());\n // and then find in dictionary by key\n\n //this code return the new CoupeDriveable()\n Driveable driveable = registerDriveable[numberOfPeople];\n return driveable;\n }\n</code></pre>\n\n<p>benefit of this solutions is when you will add anther type of Driveable you don't need to add additional if else\nonly one line</p>\n\n<pre><code>registerDriveable.Add(10, new BusDriveable());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T11:14:42.003",
"Id": "8705",
"Score": "1",
"body": "+1, it's also a good point, but it's worth notice that if creating the `Driveable` objects is slow the `else if` could be better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T10:37:46.883",
"Id": "5755",
"ParentId": "5752",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>The essence of the Factory method Pattern is to \"Define an interface\n for creating an object, but let the subclasses decide which class to\n instantiate. The Factory method lets a class defer instantiation to\n subclasses.\"</p>\n</blockquote>\n\n<p>If you insist on the above <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern#Definition\">GoF definition</a> there are two issues. </p>\n\n<p>First, you should create a <code>DriveableFactory</code> interface and rename your <code>DriveableFactory</code> to (for example) <code>CarDriveableFactory</code>.</p>\n\n<pre><code>abstract class DriveableFactory\n{\n static public function create($numberOfPeople);\n}\n\nclass CarDriveableFactory extends DriveableFactory\n{\n static public function create($numberOfPeople) { ... }\n}\n</code></pre>\n\n<p>But your code is fine, if you don't need (don't have a reason) the abstract <code>DriveableFactory</code> interface do NOT add it to the code.</p>\n\n<p>The second issue is that the <code>create</code> method should not be <code>static</code>. If it's <code>static</code> subclasses cannot override the <code>create</code> method.</p>\n\n<p>Finally, the <code>App</code> class looks unnecessary. So, I'd write something like this:</p>\n\n<pre><code>DriveableFactory factory = new CarDriveableFactory();\n$DriveableMachine = factory->getDriveableMachine(2);\n$DriveableMachine->start();\n</code></pre>\n\n<p>Some small improvements:</p>\n\n<p><code>3.5</code> is an allowed value? And <code>3.1415</code>? If not consider changing </p>\n\n<pre><code>else if( $numberOfPeople >= 3 && $numberOfPeople < 4)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>else if($numberOfPeople == 3 || $numberOfPeople == 4)\n</code></pre>\n\n<p>In the last line of the <code>create()</code> method I would throw an <code>IllegalArgumentException</code> (or a similar one in PHP) with the message <code>\"invalid value: \" . $numberOfPeople</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T17:17:22.313",
"Id": "8892",
"Score": "2",
"body": "Isn't this the Abstract Factory Pattern, and not the factory method pattern?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T04:43:28.413",
"Id": "49288",
"Score": "0",
"body": "@simao: you are correct, the moment palacsint extended a factory to anther factory, this became an example of Abstract Factory Pattern. Factory Method would have created classes that inherits from a factory that has static methods to return one type of subclass."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T11:12:08.590",
"Id": "5756",
"ParentId": "5752",
"Score": "7"
}
},
{
"body": "<p>As simao pointed out in a comment, this is an example of the <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow\">Factory Pattern</a>--not the <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow\">Factory <em>Method</em> Pattern</a>. In fact, you usually subclass the factory to determine the class to instantiate rather than making that determination based on a parameter. Perhaps this example mixes in the <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow\">Builder Pattern</a> or another whose name I'm forgetting at the moment.</p>\n\n<p>The factory pattern defines an interface for creating instances where the concrete implementations define how to create those instances and what dependencies they require. Interfaces are used here because the factory's <code>create</code> method is called by other classes.</p>\n\n<p>While related, the factory method pattern differs in that an abstract class defines a protected <code>create</code> method that is called by the concrete subclasses--never externally. You can always replace the method-based pattern with an external factory to increase flexibility.</p>\n\n<p>Here's a simple example of using the factory method pattern:</p>\n\n<p><strong>Abstract Factory</strong></p>\n\n<pre><code>abstract class Race\n{\n private $racers = array();\n\n public function __construct($numRacers) {\n for ($i = 0; $i < $numRacers; $i++) {\n $this->racers[] = $this->createRacer($i);\n }\n }\n\n protected abstract function createRacer($racerNum);\n\n public function startRace() { ... use $this->racers ... }\n}\n</code></pre>\n\n<p><strong>Concrete Factory Implementations</strong></p>\n\n<pre><code>class MotorcycleRace extends Race\n{\n protected function createRacer($racerNum) {\n return new MotorcycleRacer($racerNum);\n }\n}\n\nclass DragsterRace extends Race\n{\n protected function createRacer($racerNum) {\n return new DragsterRacer($racerNum);\n }\n}\n\nclass FormulaOneRace extends Race\n{\n protected function createRacer($racerNum) {\n return new FormulaOneRacer($racerNum);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-14T05:21:33.813",
"Id": "23896",
"ParentId": "5752",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "5756",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T07:36:27.887",
"Id": "5752",
"Score": "10",
"Tags": [
"php",
"design-patterns",
"factory-method"
],
"Title": "Is this correct factory method pattern?"
}
|
5752
|
<p>In a WPF application I have the following event handler for <code>PreviewTextInput</code> event in <code>ComboBox</code> control. The main purpose of this code is to select an item in <code>ComboBox</code> via pressing a letter key. There is duplicated logic in this code and I want it removed.</p>
<pre><code>private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var comboBox = sender as ComboBox;
if (!comboBox.IsDropDownOpen)
{
return;
}
if (!comboBox.IsEditable || !comboBox.IsReadOnly)
{
return;
}
foreach (var item in comboBox.Items)
{
if (item == null)
{
continue;
}
var textSearch = TextSearch.GetTextPath(comboBox);
var stringItem = item as string;
if (stringItem != null)
{
if (stringItem.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
{
SelectItemInComboBox(comboBox, item);
break;
}
continue;
}
var dependencyObjItem = item as DependencyObject;
if (dependencyObjItem != null)
{
var textMember = TextSearch.GetText(dependencyObjItem);
if (!string.IsNullOrEmpty(textMember))
{
var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);
var textValue = selectorFunc(dependencyObjItem);
if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
{
SelectItemInComboBox(comboBox, item);
break;
}
continue;
}
}
if (!string.IsNullOrEmpty(textSearch))
{
var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);
var textValue = selectorFunc(item);
if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
{
SelectItemInComboBox(comboBox, item);
break;
}
}
}
e.Handled = true;
}
private void SelectItemInComboBox(ComboBox comboBox, object item)
{
var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
comboBoxItem.IsSelected = true;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>I prefer a simple cast over <code>as</code> when I don't expect an object to be of any other type. If you do expect this, use <code>as</code> and be sure to check for <code>null</code>.</p>\n\n<p><code>var comboBox = (ComboBox)sender;</code></p></li>\n<li><p>When it makes sense to group code together do so.</p>\n\n<p><code>if (!comboBox.IsDropDownOpen || !combobox.IsEditable || !combobox.IsReadOnly)</code></p></li>\n<li><p>Try to use LINQ where possible.</p></li>\n<li><p>Place variables close to where they are being used. (<code>textSearch</code>)</p></li>\n<li><p>Don't overuse <code>var</code>. This is subjective, and there <a href=\"https://softwareengineering.stackexchange.com/questions/42863/c-explicitly-defining-variable-data-types-vs-using-the-keyword-var/42893#42893\">are several discussion about it</a>. (also see comments in the code underneath)</p></li>\n<li><p>Using <code>continue</code> can make it more difficult to get an overview of the code. In some occasions it is useful, but look at the code below to see how you could replace it with normal <code>if else</code> conditions instead.</p></li>\n<li><p>Identify redundant code, see what you can eliminate and what you can't. You might have to introduce new intermediate variables. (e.g. <code>textToCompare</code>)</p></li>\n</ol>\n\n<p>Here is the complete reworked example:</p>\n\n<pre><code>private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)\n{\n var comboBox = (ComboBox)sender;\n if (!comboBox.IsDropDownOpen || !combobox.IsEditable || !combobox.IsReadOnly)\n {\n return;\n }\n\n foreach (var item in comboBox.Items.Where( i => i != null ))\n { \n string textToCompare = null;\n\n if (item is string)\n {\n textToCompare = (string)item;\n }\n else if (item is DependencyObject)\n {\n DependencyObject dependencyObjItem = (DependencyObject)item;\n\n string textMember = TextSearch.GetText(dependencyObjItem);\n if (!string.IsNullOrEmpty(textMember))\n {\n // From this sample, I don't know what the following type is!\n // I wouldn't use var here.\n var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);\n textToCompare = selectorFunc(dependencyObjItem);\n }\n }\n else\n {\n string textSearch = TextSearch.GetTextPath(comboBox);\n if (!string.IsNullOrEmpty(textSearch))\n {\n var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);\n textToCompare = selectorFunc(item);\n }\n }\n\n if (textToCompare != null && textToCompare.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))\n {\n SelectItemInComboBox(comboBox, item);\n break;\n }\n }\n\n e.Handled = true;\n}\n\nprivate void SelectItemInComboBox(ComboBox comboBox, object item)\n{\n var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;\n comboBoxItem.IsSelected = true;\n}\n</code></pre>\n\n<p>I will leave it up to you as an exercise whether you can further eliminate the duplicate code from <code>selectorFunc</code>, and whether it would be useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T20:11:40.223",
"Id": "8723",
"Score": "0",
"body": "`break` could of course be replaced with a `while` statement. But in this case I don't see the problem with it as the `break` statement is near the end of the `for`, clearly indicating an early out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T10:53:38.557",
"Id": "8752",
"Score": "3",
"body": "As a minor subtle (again subjective) side note. If `SelectItemInComboBox` is [only called from one place](http://whathecode.wordpress.com/2010/12/07/function-hell/), I wouldn't separate it in a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T11:03:44.807",
"Id": "8753",
"Score": "0",
"body": "@Steven Jeuris Thank you for good answer, I can answer for you comment in code // From this sample, I don't know what the following type is!//I wouldn't use var here var selectorFunc - will be a type of Func<object,object>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T11:13:10.317",
"Id": "8755",
"Score": "0",
"body": "and this var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch); textToCompare = selectorFunc(item); I've extracted in method to remove duplication ."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T16:13:57.103",
"Id": "5763",
"ParentId": "5754",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "5763",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T10:04:53.290",
"Id": "5754",
"Score": "7",
"Tags": [
"c#",
"event-handling"
],
"Title": "Even handler for text input preview"
}
|
5754
|
<p>I needed to write a function which would 'error diffuse' floating values to integers:</p>
<pre><code>errorDiffuse :: Double -> Int -> Double -> [Int]
errorDiffuse _ 0 _ = []
errorDiffuse v num err = tv : errorDiffuse v (num - 1) (err + v - fromIntegral tv)
where tv = truncate (v + err)
</code></pre>
<p>So that, for example:</p>
<pre><code>errorDiffuse 1.4 10 0 => [1,1,2,1,1,2,1,2,1,1]
</code></pre>
<p>(i.e., the function produces a list of <code>num</code> integers, each of which is the ceiling or floor of <code>v</code>, starting with a given error value (zero in this case)).</p>
<p><strong>Is there a better way to write this sort of <code>for</code> loop? What's the higher-order function I ought to be thinking in terms of?</strong></p>
|
[] |
[
{
"body": "<p>First I'd get rid of the dependency on <code>num</code>, since that's just a counter,\nand you can use <code>take num</code> on an infinite list of <code>errorDiffuses</code>:</p>\n\n<pre><code>errorDiffuses :: Double -> Double -> [Int]\nerrorDiffuses v err = tv : errorDiffuses v (err + v - fromIntegral tv)\n where\n tv = truncate (v + err)\n</code></pre>\n\n<p>So we have:</p>\n\n<pre><code>errorDiffuse' :: Double -> Int -> Double -> [Int]\nerrorDiffuse' v num err = take num $ errorDiffuses v err\n</code></pre>\n\n<p>Then I'd think about generating the list of <code>errorDiffuses</code> differently.\nSince we're trying to generate a list, that makes me think of <code>unfolds</code>,\nwhich you can find in Data.List:</p>\n\n<pre><code>unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\n</code></pre>\n\n<p>The unfold takes a function that, given a seed, produces the next\nvalue in the outputted list, along with a new seed. The function\nstarts with an intitial seed, and keeps using those seeds, adding to the\nlist until the function returns <code>Nothing</code>.</p>\n\n<p>The function we're looking for is the following:</p>\n\n<pre><code>nextErrorDiffuse :: Double -> Double -> Maybe (Int, Double)\nnextErrorDiffuse v err = Just (tv, err + v - fromIntegral tv)\n where\n tv = truncate (v + err)\n</code></pre>\n\n<p>Our list is infinite, so we always return a <code>Just</code> value. The value that is output at each stage is <code>tv</code>, and the next \"seed\" is given by <code>err + v - fromIntegral tv</code>.</p>\n\n<p>Putting things together we have:</p>\n\n<pre><code>errorDiffuse'' :: Double -> Int -> Double -> [Int]\nerrorDiffuse'' v num err = take num $ unfoldr (nextErrorDiffuse v) err\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T16:34:26.127",
"Id": "8716",
"Score": "0",
"body": "Fantastic, thankyou! I don't think `unfoldr` is in my mental toolkit yet but it was exactly the sort of thing I was thinking of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T16:37:28.073",
"Id": "8718",
"Score": "0",
"body": "Glad I could help :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T20:03:17.133",
"Id": "9795",
"Score": "0",
"body": "`unfoldr` is a great tool to add to your toolkit. Whenever you need to produce a list from some seed value(s), `unfoldr` should come to mind."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T15:45:07.013",
"Id": "5761",
"ParentId": "5757",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-02T14:12:46.817",
"Id": "5757",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Haskell function to error-diffuse a floating value to a list of integers"
}
|
5757
|
<p>I'm learning to Jinja2 and what's important in this case isn't speed but i18n translations and functionality. With Python 2.7, Jinja2 and not Django seems to preferred way to go, so I'm rewriting much of my project to use Jinja2 templates. We already had plenty of translations in .mo and .po files and wanted to keep use of those and we also want to make use of django's translation package. I found a way to use the Django translation libraries with Jinja2.</p>
<p>Could you review this code and comment if I can use it this way? My SDK is Google App Engine.</p>
<pre><code>import jinja2
from django.utils import translation
from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
class DjangoTranslator(object):
def __init__(self):
self.gettext = gettext
self.ngettext = ngettext
self.ugettext = ugettext
self.ungettext = ungettext
from jinja2 import Environment, FileSystemLoader
class DjangoEnvironment(jinja2.Environment):
def get_translator(self, context):
return DjangoTranslator()
jinja_environment = DjangoEnvironment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
jinja_environment.install_gettext_translations(translation)
</code></pre>
|
[] |
[
{
"body": "<p>I don't know jinja but I can give a few generic python pointers:</p>\n\n<ol>\n<li>Generally, its considered best to put all imports at the top of the file not scattered throughout</li>\n<li>Rather then importing a bunch of stuff to use once, use <code>self.gettext = translation.gettext</code> etc</li>\n<li>Why empty lines after class, but nowhere else? I'd but a blank line before the start of a class and not inside.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T04:51:11.723",
"Id": "8742",
"Score": "0",
"body": "Thanks. I'm still learning conventions and how to code python so I didn't totally know how to do it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T20:38:57.897",
"Id": "5769",
"ParentId": "5767",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5769",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T19:48:00.347",
"Id": "5767",
"Score": "3",
"Tags": [
"python",
"python-2.x",
"django",
"google-app-engine",
"i18n"
],
"Title": "i18n translator using Jinja2"
}
|
5767
|
<p>I'm creating a design database for an autoparts store (this is a project school). For the moment, I'm not sure if the relationship model especially in <code>MODEL</code>, <code>MAKE</code>, <code>BRAND</code> is correct (I really have no experience about this area).</p>
<p>I'm not an expert in this area, so I need some help.</p>
<pre><code>create database AutoParts2
use AutoParts2
go
create table Make
(
MakeID int not null identity(1,1),
Name varchar(50) not null,
constraint PK_Make primary key (MakeID)
)
create table Model
(
ModelID int not null identity(1,1),
MakeID int not null,
Name varchar(50) not null,
constraint PK_Model primary key (ModelID),
constraint FK_Model_Make foreign key (MakeID)
references Make(MakeID)
)
create table [Year]
(
YearID tinyint not null identity(1,1),
Name char(4) not null,
constraint PK_Year primary key (YearID)
)
create table Model2Year
(
Model2YearID int not null identity(1,1),
ModelID int not null,
YearID tinyint not null,
constraint PK_Model2Year primary key (Model2YearID),
constraint FK_Model2Year_Model foreign key (ModelID)
references Model(ModelID),
constraint FK_Model2Year_Year foreign key (YearID)
references [Year](YearID)
)
create table Category
(
CategoryID tinyint not null identity(1,1),
Name varchar(30) not null,
constraint PK_Category primary key (CategoryID)
)
create table Subcategory
(
SubcategoryID tinyint not null identity(1,1),
CategoryID tinyint not null,
Name varchar(30) not null,
constraint PK_Subcategory primary key (SubcategoryID),
constraint FK_Subcategory_Category foreign key (SubcategoryID)
references Category(CategoryID)
)
create table Model2Year2Category
(
Model2Year2CategoryID int not null identity(1,1),
Model2YearID int not null,
CategoryID tinyint not null,
constraint PK_Model2Year2Category primary key (Model2Year2CategoryID),
constraint FK_Model2Year2Category_Model2Year foreign key (Model2YearID)
references Model2Year(Model2YearID),
constraint FK_Model2Year2Category_Category foreign key (CategoryID)
references Category(CategoryID)
)
create table Brand
(
BrandID int not null identity(1,1),
Name varchar(50) not null,
constraint PK_Brand primary key (BrandID)
)
create table Brand2Subcategory
(
Brand2SubcategoryID int not null identity(1,1),
BrandID int not null,
SubcategoryID int not null,
constraint PK_Brand2Subcategory primary key (Brand2SubcategoryID),
constraint FK_Brand2Subcategory_Brand foreign key (BrandID)
references Brand(BrandID),
constraint FK_Brand2Subcategory_Subcategory foreign key (SubcategoryID)
references Subcategory(SubcategoryID)
)
create table Part
(
PartID int not null identity(1,1),
Name varchar(50) not null,
BrandID int not null,
PartNumber varchar(50) not null,
Description varchar(200),
constraint PK_Part primary key (PartID),
constraint FK_Part_Brand foreign key (BrandID)
references Brand(BrandID)
)
create table Model2Year2Part
(
Model2Year2PartID int not null identity(1,1),
Model2YearID int not null,
PartID int not null,
constraint PK_Model2Year2Part primary key (Model2Year2PartID),
constraint FK_Model2Year2Part_Model2Year foreign key (Model2YearID)
references Model2Year(Model2YearID),
constraint FK_Model2Year2Part_Part foreign key (PartID)
references Part(PartID)
)
create table Brand2Subcategory2Part
(
Brand2Subcategory2PartID int not null identity(1,1),
Brand2SubcategoryID int not null,
PartID int not null,
constraint PK_Brand2Subcategory2Part primary key (Brand2Subcategory2PartID),
constraint FK_Brand2Subcategory2Part_Brand2Subcategory foreign key (Brand2SubcategoryID)
references Brand2Subcategory(Brand2SubcategoryID),
constraint FK_Brand2Subcategory2Part_Part foreign key (PartID)
references Part(PartID)
)
</code></pre>
|
[] |
[
{
"body": "<p>You have all the tables you need and you have the many-to-many relationships correct, I think. </p>\n\n<p>I'd suggest that you add a Parent field to Category and then create a hierarchy of categories instead of having a Category table with a single Subcategory table.</p>\n\n<pre><code>create table Category(\n CategoryId int not null identity(1,1),\n ParentCategoryId int null,\n CategoryName nvarchar(100) not null,\n primary key (CategoryId))\n</code></pre>\n\n<p>As a point of style, I'd name the many-to-many tables with underscores instead of numbers, i.e. <code>Model_Year_Part</code>.</p>\n\n<p>Note that I used nvarchar instead of varchar.</p>\n\n<p>If you ask a question on StackExchange for a school project, don't forget the citation if you use the answers! It's okay to ask but never to plagiarise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T16:29:41.307",
"Id": "8761",
"Score": "0",
"body": "Yes, the initial design seems mostly there, although he _may_ want to add at least one more unique constraint on `Part` - `[BrandId, PartNumber]`. And yeah, the `2`s as seperators is confusing - what if there was a table named `Model2` (for whatever bizarre reason...)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T11:10:08.357",
"Id": "5781",
"ParentId": "5770",
"Score": "4"
}
},
{
"body": "<p>I'd consider the following things:</p>\n\n<ul>\n<li><p>Are you sure that you need the <code>Year</code> table? You could store the year in the <code>Model2Year</code> table directly.</p></li>\n<li><p>I would omit the <code>Model2Year.Model2YearID</code> attribute. Instead of this I'd use a compound primary key <code>(ModelID, Year)</code> or <code>(ModelID, YearID)</code>.</p></li>\n<li><p>Is it possible that, for example, a specific model is in <code>categoryX</code> in 1999 and it's in <code>categoryY</code> in 2000? If not, connect the <code>Model</code> and the <code>Category</code> table with a <code>model_to_category</code> helper table (<code>(ModelId, CategoryId)</code> is the primary key) instead of the current <code>Model2Year2Category</code> table.</p></li>\n</ul>\n\n<p>It's not obvious what you store in these tables. Provide some example for every table and I'll update this answer. For example, does <code>Category</code> store car categories or part categories?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T18:04:35.900",
"Id": "5786",
"ParentId": "5770",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T21:05:27.143",
"Id": "5770",
"Score": "3",
"Tags": [
"sql",
"sql-server"
],
"Title": "Relationship design for auto parts store database"
}
|
5770
|
<p><a href="https://i.stack.imgur.com/Y5AZJ.png" rel="nofollow noreferrer">This is the result of the code it has extra option tags no idea why.</a></p>
<p>I have no idea why It produces the extra option box. </p>
<p>Below is the result of the query. Correct number of rows correct response...</p>
<pre><code> ParentID Parent
1 Pipe
2 Valve
3 Control Valve
4 Pump
5 Chamber
6 Meter
7 Check
8 Distribution Pipe
</code></pre>
<p>This is some php that makes the dropdown:</p>
<pre><code>$qry = "select distinct ParentID, Parent from tbl
where ChildID = '0' and Parent is not null";
$parentRslt = mysql_query($qry);
$count = mysql_num_rows($parentRslt);
$opt7 = null;
for($m=0;$m<$count;$m++)
{
$var = mysql_result($parentRslt,$m,'ParentID');
$name = mysql_result($parentRslt,$m,'Parent');
$var = trim($var);
$name = trim($name);
$opt7.="<option value='$var'>$m $name<option>";
}
$form = "
<form method='post'>
Network Action: <input type='text' name='child' />
<select name='parentID'>
$opt7
</select>
<input type='submit' name='submit' value='submit' /></form>";
return $form;
</code></pre>
|
[] |
[
{
"body": "<p>You should close the <code>option</code> tag. Change</p>\n\n<pre><code>$opt7.=\"<option value='$var'>$m $name<option>\";\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$opt7.=\"<option value='$var'>$m $name</option>\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T21:59:15.193",
"Id": "8734",
"Score": "2",
"body": "I cant believe I overlooked that. thanks so much Palacsint."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T21:48:55.453",
"Id": "5772",
"ParentId": "5771",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5772",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T21:35:19.077",
"Id": "5771",
"Score": "1",
"Tags": [
"php",
"javascript",
"mysql",
"html"
],
"Title": "<select> has extra blank <option>'s and I have no idea why. please help me get them out"
}
|
5771
|
<p><code>CustomDialog</code> is the parent abstract class for <code>OkExclamationDialog</code> and <code>ExclamationDialog</code> with abstract method <code>displayDialog()</code> being overriden.</p>
<p>Does this fall into a design pattern? Can this design be improved upon?</p>
<p><code>JudgeButton</code> controls the other classes.</p>
<pre><code>public class JudgeButton {
private int typeCode;
private void initialise(){
setTypeCode();
if(typeCode == 0){
c = new ExclamationDialog("Episode not started");
c.displayDialog();
}
else if(typeCode == 1){
c = new OkExclamationDialog("Episode Finished, you will now be redirected");
c.displayDialog();
}
}
private void setTypeCode(){
wrapperJsonObject = Utils.getCurrentWrapperJsonObjectFromServer();
jsonObject = wrapperJsonObject.getJsonObject();
NextRatingsScreen n = new NextRatingsScreen(jsonObject);
RatingsCountDownTime r = new RatingsCountDownTime();
if(!n.isEpisodeStarted()){
typeCode = 0;
}
else if(!n.isPerformanceStarted()){
typeCode = 1;
}
}
}
public class OkExclamationDialog extends CustomDialog{
public OkExclamationDialog(String text) {
super(text);
}
public void displayDialog() {
DialogType dialogType = new DialogType();
DialogBuilder dialogBuilder = new DialogBuilder();
AbstractDialogFactory abstractDialogFactory = dialogType.getDialogType(DialogEnum.EXCLAMATION_DIALOG);
Dialog nextScreen = dialogBuilder.buildDialog(abstractDialogFactory, super.getText());
int result = nextScreen.doModal();
ScreenController.displayNextScreenFadeTransition(nextScreen);
if(result==Dialog.OK)
{
ScreenController.displayNextScreenFadeTransition(new ContestantsScreen());
}
}
}
public class ExclamationDialog extends CustomDialog{
public ExclamationDialog(String text) {
super(text);
}
public void displayDialog() {
DialogType dialogType = new DialogType();
DialogBuilder dialogBuilder = new DialogBuilder();
AbstractDialogFactory abstractDialogFactory = dialogType.getDialogType(DialogEnum.EXCLAMATION_DIALOG);
Dialog nextScreen = dialogBuilder.buildDialog(abstractDialogFactory, super.getText());
ScreenController.displayNextScreenFadeTransition(nextScreen);
}
}
public abstract class CustomDialog {
private String text;
public CustomDialog(String text){
this.text = text;
}
public String getText(){
return this.text;
}
public abstract void displayDialog();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T23:57:04.150",
"Id": "8738",
"Score": "0",
"body": "What happened to your code? Did you not grab all of it when you cut and pasted it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T00:03:50.403",
"Id": "8739",
"Score": "0",
"body": "I've added more code, will this suffice ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T19:47:35.037",
"Id": "8769",
"Score": "0",
"body": "The variable `r` is never used, so just `new RatingsCountDownTime();` should be sufficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T01:42:25.873",
"Id": "73050",
"Score": "0",
"body": "You cold use decorator pattern here is example http://www.dofactory.com/Patterns/PatternDecorator.aspx"
}
] |
[
{
"body": "<p>The <code>initialise</code> reminds me a factory but it's not exactly a factory. It's fine if you don't use the same if-elseif structure in your code elsewhere. If you do pull out it to a factory class.</p>\n\n<p>Just some idea:</p>\n\n<p>1, Consider using an <code>enum</code> instead of the integer <code>typeCode</code> (eliminate magic numbers).</p>\n\n<p>2, Maybe you should throw an <code>IllegalStateException</code> in the end of the <code>initialise</code> method with a message <code>\"Invalid typecode\"</code>.</p>\n\n<p>3, The same is true for the <code>setTypeCode()</code> method. Or set explicitly <code>typeCode</code> to <code>0</code> in the last line of the method if <code>0</code> is a valid value. (This is the implicit default value of the <code>private int typeCode</code> field.)</p>\n\n<p>4, I'd rename the <code>setTypeCode()</code> to <code>calculateTypeCode()</code> which would return a <code>TypeCode</code> enum. Now it's more or less temporal coupling.</p>\n\n<p>5, You should create a new <code>getNextScreen()</code> method in the <code>CustomDialog</code> class with the first four line of the <code>displayDialog()</code> method. Then call the <code>getNextScreen()</code> from the <code>displayDialog()</code> methods. It would remove some code duplication.</p>\n\n<pre><code>// CustomDialog class code\npublic Dialog createNextScreen() {\n DialogType dialogType = new DialogType();\n DialogBuilder dialogBuilder = new DialogBuilder();\n AbstractDialogFactory abstractDialogFactory = \n dialogType.getDialogType(DialogEnum.EXCLAMATION_DIALOG);\n Dialog nextScreen = dialogBuilder.buildDialog(abstractDialogFactory, text);\n return nextScreen;\n}\n</code></pre>\n\n\n\n<pre><code>// OkExclamationDialog, ExclamationDialog class code\npublic void displayDialog() {\n Dialog nextScreen = getNextScreen();\n ...\n ScreenController.displayNextScreenFadeTransition(nextScreen);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T19:38:28.823",
"Id": "5789",
"ParentId": "5775",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5789",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T23:45:35.183",
"Id": "5775",
"Score": "6",
"Tags": [
"java",
"design-patterns"
],
"Title": "Does this code fall into a design pattern?"
}
|
5775
|
<p>I wrote this without much thought:</p>
<pre><code>(defn- tail-cmd
"Construct a tail cmd"
[file n & ignore-patterns]
(clojure.string/join
" | "
(flatten [(format "tail -n %s -f %s" (or n 200) file)
(map #(format "grep --line-buffered -v \"%s\"" %)
ignore-patterns)])))
</code></pre>
<p>On further thought, I'm not sure if it can simplified further. Can it be?</p>
|
[] |
[
{
"body": "<p>You may or may not consider this simpler:</p>\n\n<pre><code>(defn tail-cmd-2\n \"Construct a tail cmd\"\n [file n & ignore-patterns]\n (str \"cat \"\n file\n \" | \"\n (apply str (map #(format \"grep -v \\\"%s\\\" | \" %) ignore-patterns))\n \"tail -f \"\n (if n (str \"-n \" n))))\n</code></pre>\n\n<p>Or if you're willing to use the non-standard clojure.core.strint library, you can do the following.</p>\n\n<pre><code>(defn tail-cmd-5\n \"Construct a tail cmd\"\n [file n & ignore-patterns]\n (let [greps (apply str (for [p ignore-patterns] (format \"grep -v \\\"%s\\\" | \" p)))\n minus-n (if n (str \"-n \" n))]\n (<< \"cat ~{file} | ~{greps} tail -f ~{minus-n}\")))\n</code></pre>\n\n<p>Here's the library source:\n<a href=\"https://github.com/clojure/core.incubator\" rel=\"nofollow\">https://github.com/clojure/core.incubator</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T20:18:19.160",
"Id": "8771",
"Score": "0",
"body": "Yes, it is subjective .. but I do like the fact that both `join` and `flatten` have been obviated in your code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T19:26:32.377",
"Id": "5788",
"ParentId": "5777",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T03:58:35.517",
"Id": "5777",
"Score": "5",
"Tags": [
"strings",
"clojure"
],
"Title": "Constructing a tail cmd"
}
|
5777
|
<p>It's my first stab at TCP/IP and honestly I'm just starting out on C# also, so any comments on the design, method, etc are more than welcome.</p>
<p>Basically I wanted to create a listening thread and someday a sending thread, that can handle listen/send heartbeat message and also other messages.</p>
<p>Once it retrieve the message, it will update some value back into the main execution program.</p>
<pre><code>public virtual void StartReceivingThread()
{
Thread thrReceive = new Thread(Receive);
try
{
if (!bIsActive && Connect())
{
//NOTE: exception thrown by a thread can only be captured by that thread itself
//start a listen thread
//wait until heartbeat message is accepted
thrReceive.Name = "thr" + serviceType.Name;
thrReceive.Start();
bIsActive = true;
//wait to get the heartbeat message
for (int i = 0; i < maxRetry; i++)
{
Thread.Sleep(maxTimeOutValue);
if (bIsReceivingHeartbeat)
break;
}
//if nothing happens close the connection and try again
if (!bIsReceivingHeartbeat)
{
bIsActive = false;
CleanUp();
logger.Info("Closing receiver thread - " + thrReceive.Name);
}
else
{
logger.Info("Starting receiver thread - " + thrReceive.Name);
}
}
}
catch(Exception ex)
{
logger.Error(ex);
}
//finally
//{
// logger.Info("Exiting receiver thread - " + thrReceive.Name);
//}
}
public void CleanUp()
{
if (client != null)
{
client.Close();
}
}
public virtual void Receive()
{
string eventMessage = string.Empty;
int bytesRcvd = 0;
int totalBytesRcvd = 0;
byte[] byteBuffer = new byte[maxBufferSize];
NetworkStream listenStream;
try
{
if (client.Connected)
{
listenStream = client.GetStream();
}
else
{
return;
}
while (true)
{
//message that is slot in from the object will get sent here.
if (!string.IsNullOrEmpty(MessageToSend))
{
Send(MessageToSend);
MessageToSend = string.Empty;
}
// must convert it back and look for the delimiter, cannot wait for the three heartbeat to pass
string leftoverMsg = string.Empty;
bytesRcvd = listenStream.Read(byteBuffer, totalBytesRcvd, maxBufferSize - totalBytesRcvd);
totalBytesRcvd += bytesRcvd;
//if more than heart beat size, can process to see if it's a heartbeat and proceed to send
if (totalBytesRcvd > msgHeartbeatSize)
{
eventMessage = Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd);
ProcessMessage(eventMessage, ref leftoverMsg, ref totalBytesRcvd, ref byteBuffer);
}
}
}
catch (ThreadAbortException thEx)
{
//do nothing as main thread has aborted and waiting to close
logger.Info(Thread.CurrentThread.Name + " is stopped. ");
}
catch (Exception exce)
{
bIsActive = false;
logger.Error(exce);
CleanUp();
}
finally
{
logger.Info(String.Format("Thread {0} Exiting. ", Thread.CurrentThread.Name));
}
}
public void Send(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append(Char.STX);
sb.Append(msg);
sb.Append(Char.ETX);
try
{
string message = sb.ToString();
byte[] byteBuffer = Encoding.ASCII.GetBytes(message);
//use a different stream to prevent blocking?
NetworkStream sendNetStream = client.GetStream();
sendNetStream.Write(byteBuffer, 0, byteBuffer.Length);
sendNetStream.Flush(); //clear buffer straight without waiting for the write buffer to fill up.
//simplify the heart beat message for logging
if (simpleHeartbeatMsg.ToLower().Contains("on")
&& message.Contains("fnxheartbeatack"))
{
message = "heartbeat message.";
}
logger.Info("Sending to - xml: " + Char.GetNonFormattedString(message));
}
catch (Exception ex)
{
bIsActive = false;
CleanUp();
sb = null;
throw ex;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A few things come to mind when reading this...</p>\n\n<ul>\n<li>Set your thread priority. Remember that spawned threads do not follow the priority of the host process. So you need to decide what level this should be relative to other priorities</li>\n<li>This is going to be a foreground thread, is that really what you want here. In other words, when the host process comes down, should this thread hang the process until your abort it? Consider the background option</li>\n<li>Using a Spin-Wait pattern with Sleep may not be the best way to go. Consider using a Monitor.Pulse/Wait pattern, you could even set a Wait timeout if needed.</li>\n<li>If the <code>logger</code> is Log4Net, make sure to use the <code>if (logger.IsInfoEnabled())</code> pattern which is recommended by the project owner. This will offset some internal expenses.</li>\n<li>The <code>Cleanup()</code> method is not visible in your post, but this is called inside the <code>catch</code> block. Make sure this cannot throw an exception also</li>\n<li>Pretty much all your code is inside a try-catch block. In doing so, none of it will be eligible for JIT Optimizations. Depending on your performance needs, that could be a problem. Move the insides of the <code>try</code> section into seperate methods</li>\n<li>Given your use of the StringBuilder it will cost 2 or 3 times more then just doing an <code>x+y</code> or <code>string.concat(x, y)</code>. Write a performance test around these and your will see what I mean </li>\n<li>Using <code>ToUpper()</code> vs <code>ToLower()</code> is more performant</li>\n<li>Your not Closing or Disposing your <code>NetworkStream</code></li>\n</ul>\n\n<p>Hope this helps</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-16T20:36:48.233",
"Id": "6924",
"ParentId": "5778",
"Score": "3"
}
},
{
"body": "<p>One thing about the heartbeat timeout on the receiving end. Sleeping and polling is generally an indicator that you're not doing asynchronous I/O correctly. In this case, you're better off starting a countdown timer and resetting it every time you receive a heartbeat. If the timer expires, that indicates a timeout. It'll be more accurate and allow for better threading practices. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T04:52:11.487",
"Id": "49387",
"ParentId": "5778",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T07:04:11.357",
"Id": "5778",
"Score": "2",
"Tags": [
"c#",
"beginner",
"multithreading",
"networking",
"tcp"
],
"Title": "TCP/IP sending and receiving threads"
}
|
5778
|
<p>I have fair concept in a programming (learner) but not an expert to refactor code at the highest level. I am trying to read a huge (100MB-2GB) XML file and parse necessary element (attributes) from a file into MySQLdb. The code is working perfectly as I have tested in small file sizes. But, unfortunately when I got big size today (400MB-900MB), it's taking unexpected time. </p>
<p>Currently, I am diving into List Comprehension, <code>generator()</code>, <code>lambda()</code> and list reduction techniques.</p>
<p>Not to make more lines of code, but I have eliminated 3 or 4 elements from my list (taglist) from here. But, the structure of the code for rest of the eliminated elements are the same.</p>
<p>I am using: Python 2.7, lxml, MySQL (1.2.3)</p>
<pre><code>import os, sys
import stat
import getpass
import MySQLdb
from lxml import etree
import datetime, time
import dbconfig as config
# All global variables set
#Namespace which is default in every mzML file
#taglist=['mzML','sourceFile','software','dataProcessing','instrumentConfiguration','selectedIon']
taglist=['mzML','sourceFile']
NS="{http://psi.hupo.org/ms/mzml}"
def fast_iter(context, func,args=[],kwargs={}):
# fast_iter is useful if we need to free memory while iterating through a
# very large XML file.
#http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
# Author: Liza Daly
for event, elem in context:
func(elem,*args, **kwargs)
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
del context
def process_element(elt):
# global mzml_pk, sf_cv_fk,softw_fk_ID, softw_cv_fk_ID
# Processing first element (mzML) and it's attributes (id, version, accession)
# version attribute is required AND id & accession are optional
if elt.tag==NS+taglist[0]:
L= elt.keys()
L1=['id','version','accession']
# Checking whether element attributes (items L1) exist in a mzml element attributes (L)
if L1[0] in L:
mzmlID = elt.attrib['id']
else:
mzmlID = "-"
if L1[1] in L:
mzml_version = elt.attrib['version']
else:
mzml_version = "-"
if L1[2] in L:
mzml_accession = elt.attrib['accession']
else:
mzml_accession = "-"
exp_id_fk = exp_PK
sql = """INSERT INTO pmass_mzml (mzml_id,accession,version,exp_id)
VALUES (%s, %s, %s, %s)"""
try:
# Execute the SQL command
config.cursor.execute(sql,(mzmlID,mzml_accession,mzml_version,exp_id_fk))
# Commit your changes in the database
config.conn.commit()
#mzml_pk= cursor.lastrowid
except Exception as err:
# logger.error(err)
# Rollback in case there is any error
config.conn.rollback()
global mzml_pk
mzml_pk = config.cursor.lastrowid
# Processing second element (sourceFile) which has attributes (id, name and location)
# SourceFile attributes id, name and location are required
# Further, sourceFile has child element (cvParam) and attributes (cvRef, name, accession, value)
# cvParam attributes: cvRef, name, accession are Required and value optional
elif elt.tag==NS+taglist[1]:
sf_keys = elt.keys()
sf_need = ['id','name','location']
if sf_need[0] in sf_keys:
sf_id = elt.attrib['id']
else:
sf_id, "-"
if sf_need[1] in sf_keys:
sf_name = elt.attrib['name']
else:
sf_name, "-"
if sf_need[2] in sf_keys:
sf_location = elt.attrib['location']
else:
sf_location = "-"
global sf_fk
sf_fk = mzml_pk
#print "Insert values into django sourceFile class data model"
sql = """INSERT INTO pmass_source_file (sf_id,name,location,mzml_fk_id)
VALUES (%s, %s, %s, %s)"""
try:
# Execute the SQL command
config.cursor.execute(sql,(sf_id,sf_name,sf_location,sf_fk))
# Commit your changes in the database
config.conn.commit()
except Exception as err:
# logger.error(err)
# Rollback in case there is any error
config.conn.rollback()
#sf_pk = cursor.lastrowid
global sf_cv_fk
sf_cv_fk= config.cursor.lastrowid
for child in elt.getchildren():
sf_child_keys =child.keys()
sf_child_need = ['cvRef','name','accession','value']
if sf_child_need[0] in sf_child_keys:
sf_cv_cvref = child.attrib['cvRef']
else:
sf_cv_cvref = "-"
if sf_child_need[1] in sf_child_keys:
sf_cv_name = child.attrib['name']
else:
sf_cv_name = "-"
if sf_child_need[2] in sf_child_keys:
sf_cv_accession = child.attrib['accession']
else:
sf_cv_accession = "-"
if sf_child_need[3] in sf_child_keys :
if len(child.get('value'))>0:
sf_cv_value = child.attrib['value']
else:
sf_cv_value = "-"
else:
sf_cv_value = "-"
sql = """INSERT INTO pmass_source_file_cv (ref, accession,name,value,sf_fk_id)
VALUES (%s, %s, %s, %s, %s)"""
try:
# Execute the SQL command
config.cursor.execute(sql,(sf_cv_cvref,sf_cv_accession,sf_cv_name,sf_cv_value,sf_cv_fk))
# Commit your changes in the database
config.conn.commit()
except Exception as err:
# logger.error(err)
# Rollback in case there is any error
config.conn.rollback()
</code></pre>
<p>I haven't pasted the rest of the code for other elements because it's more than 300 lines, but of the same concept.</p>
<pre><code>def convert_bytes(bytes):
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fTB' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fGB' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 1048576
size = '%.2fMB' % megabytes
elif bytes >= 1024:
kilobytes = bytes / 1024
size = '%.2fKB' % kilobytes
else:
size = '%.2fb' % bytes
return size
def main():
global EXP_PK
# Start time counter
begin=time.clock()
# Reading file from the configured directory
file_dir = r'D:\files\111102_CA2.mzML'
# Reactor so it will read all new files from configured directory
file_name = os.path.basename(file_dir)
# File name and extension
(name, ext) = os.path.splitext(file_name)
user= getpass.getuser()
exp_name = name
exp_type= ext[1:]
exp_created_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(file_dir)))
exp_modi_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(file_dir)))
exp_uploaddate= datetime.date.today()
exp_uptime = str(datetime.datetime.now())[10:19]
exp_size = convert_bytes(os.path.getsize(file_dir))
#exp_located = r'C:\Users\Thaman\Documents\My Dropbox\Files\small1.mzML'
exp_located = r'C:\My Documents\Dropbox\Files\plgs_example.mzML'
#exp_located =r'D:\files\111102_CA2.mzML'
sql = """INSERT INTO pmass_experiment (user,filename,filetype,createddate,modifieddate,uploaddate,time,size,located)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""
try:
# Execute the SQL command
config.cursor.execute(sql,(user,exp_name,exp_type,exp_created_time,exp_modi_time,exp_uploaddate,exp_uptime,exp_size,exp_located))
# Commit your changes in the database
config.conn.commit()
except:
#logger.error(err)
# Rollback in case there is any error
config.conn.rollback()
global exp_PK
exp_PK = config.cursor.lastrowid
#Reading elements from file
for intag in range(len(taglist)):
context= etree.iterparse(file_dir,events=("end",),tag=NS+taglist[intag])
fast_iter(context, process_element)
tend= time.clock()
print "\n\nTIME TAKEN TO COMPLETE JOB", tend-begin
if __name__ == '__main__':
main()
</code></pre>
<p><strong>Problem according to me:</strong></p>
<ul>
<li>I am sure my approach towards using too much <code>if</code> and <code>for</code> expression is a problem but haven't figure out the solution.</li>
<li>400 MB file is still and taking more than 1 hr.</li>
</ul>
<p><strong>Reviewing:</strong> Pythonic, memory friendly, speed optimization, structure</p>
<p>If someone wants the file, I can share it on Dropbox.</p>
|
[] |
[
{
"body": "<pre><code>import os, sys\nimport stat\nimport getpass\nimport MySQLdb\nfrom lxml import etree\nimport datetime, time\nimport dbconfig as config\n</code></pre>\n\n<p>They python style guide recommends one import per line. I'd also probably group things together i.e. standard library imports then 3rd party imports/ then app imports. But that doesn't really matter much</p>\n\n<pre><code># All global variables set\n #Namespace which is default in every mzML file\n\ntaglist=['mzML','sourceFile']\nNS=\"{http://psi.hupo.org/ms/mzml}\"\n</code></pre>\n\n<p>For global constants, the python style guide recommends ALL_CAPS. I recommend not using NS, instead spell it out NAMESPACE</p>\n\n<pre><code>def fast_iter(context, func,args=[],kwargs={}):\n</code></pre>\n\n<p>Taking variable arguments as a list and dict are odd, any reason you didn't take them as *args and **kwargs?</p>\n\n<pre><code> # fast_iter is useful if we need to free memory while iterating through a\n # very large XML file.\n #http://www.ibm.com/developerworks/xml/library/x-hiperfparse/\n # Author: Liza Daly\n\n for event, elem in context:\n func(elem,*args, **kwargs)\n</code></pre>\n\n<p>Using a yield to make this a generator rather then calling a function would probable be better.</p>\n\n<pre><code> elem.clear()\n while elem.getprevious() is not None:\n del elem.getparent()[0]\n del context\n</code></pre>\n\n<p>There is no point in deleting local names at the end of the function. When the function ends all the names will be deleted anyways.</p>\n\n<pre><code>def process_element(elt):\n</code></pre>\n\n<p>I recommend not using short abbreviations like elt unless they are really common.</p>\n\n<pre><code> # global mzml_pk, sf_cv_fk,softw_fk_ID, softw_cv_fk_ID\n # Processing first element (mzML) and it's attributes (id, version, accession)\n # version attribute is required AND id & accession are optional\n if elt.tag==NS+taglist[0]:\n\n L= elt.keys()\n L1=['id','version','accession']\n\n # Checking whether element attributes (items L1) exist in a mzml element attributes (L)\n if L1[0] in L:\n</code></pre>\n\n<p>You haven't helped anything by storing 'id' L1[0] and then fetching it again. Just use 'id' here.</p>\n\n<pre><code> mzmlID = elt.attrib['id']\n else:\n mzmlID = \"-\"\n</code></pre>\n\n<p>You should be able to do something like mzmlID = el.attrib.get('id', '-') to replace this whole if/else block.</p>\n\n<pre><code> if L1[1] in L:\n mzml_version = elt.attrib['version']\n else:\n mzml_version = \"-\"\n if L1[2] in L:\n mzml_accession = elt.attrib['accession']\n else:\n mzml_accession = \"-\"\n\n exp_id_fk = exp_PK\n\n sql = \"\"\"INSERT INTO pmass_mzml (mzml_id,accession,version,exp_id)\n VALUES (%s, %s, %s, %s)\"\"\"\n try:\n # Execute the SQL command\n config.cursor.execute(sql,(mzmlID,mzml_accession,mzml_version,exp_id_fk))\n # Commit your changes in the database\n config.conn.commit()\n\n #mzml_pk= cursor.lastrowid\n</code></pre>\n\n<p>Don't leave dead code in comments</p>\n\n<pre><code> except Exception as err:\n # logger.error(err)\n # Rollback in case there is any error\n config.conn.rollback()\n</code></pre>\n\n<p>Don't just ignore errors that happen. If you expect an error to occur, you should check to make sure exactly the error you wanted was caught. Otherwise you should re-raise or at least log the error.</p>\n\n<p>You might also look into with statments and context managers. Amongst other things, they make transactions easier to work with.</p>\n\n<pre><code> global mzml_pk\n mzml_pk = config.cursor.lastrowid\n</code></pre>\n\n<p>avoid use of global variables. Use return values/object attributes/pretty much anything before using a global variable.</p>\n\n<pre><code> # Processing second element (sourceFile) which has attributes (id, name and location)\n # SourceFile attributes id, name and location are required\n # Further, sourceFile has child element (cvParam) and attributes (cvRef, name, accession, value)\n # cvParam attributes: cvRef, name, accession are Required and value optional\n</code></pre>\n\n<p>Right about now, this function is way too long. You should break it up into several functions.</p>\n\n<pre><code> elif elt.tag==NS+taglist[1]:\n sf_keys = elt.keys()\n sf_need = ['id','name','location']\n if sf_need[0] in sf_keys:\n sf_id = elt.attrib['id']\n else:\n sf_id, \"-\"\n if sf_need[1] in sf_keys:\n sf_name = elt.attrib['name']\n else:\n sf_name, \"-\"\n if sf_need[2] in sf_keys:\n sf_location = elt.attrib['location']\n else:\n sf_location = \"-\"\n global sf_fk\n sf_fk = mzml_pk\n #print \"Insert values into django sourceFile class data model\"\n\n sql = \"\"\"INSERT INTO pmass_source_file (sf_id,name,location,mzml_fk_id)\n VALUES (%s, %s, %s, %s)\"\"\"\n try:\n # Execute the SQL command\n config.cursor.execute(sql,(sf_id,sf_name,sf_location,sf_fk))\n # Commit your changes in the database\n config.conn.commit()\n\n except Exception as err:\n # logger.error(err)\n # Rollback in case there is any error\n config.conn.rollback()\n #sf_pk = cursor.lastrowid\n global sf_cv_fk\n sf_cv_fk= config.cursor.lastrowid\n</code></pre>\n\n<p>Deja vu... You should see if you can refactor the simiairites between any two very similiar pieces of code like this.</p>\n\n<pre><code> for child in elt.getchildren():\n sf_child_keys =child.keys()\n sf_child_need = ['cvRef','name','accession','value']\n\n if sf_child_need[0] in sf_child_keys:\n sf_cv_cvref = child.attrib['cvRef']\n else:\n sf_cv_cvref = \"-\"\n if sf_child_need[1] in sf_child_keys:\n sf_cv_name = child.attrib['name']\n else:\n sf_cv_name = \"-\"\n if sf_child_need[2] in sf_child_keys:\n sf_cv_accession = child.attrib['accession']\n else:\n sf_cv_accession = \"-\"\n if sf_child_need[3] in sf_child_keys :\n if len(child.get('value'))>0:\n sf_cv_value = child.attrib['value']\n else:\n sf_cv_value = \"-\"\n else:\n sf_cv_value = \"-\"\n\n sql = \"\"\"INSERT INTO pmass_source_file_cv (ref, accession,name,value,sf_fk_id)\n VALUES (%s, %s, %s, %s, %s)\"\"\"\n try:\n # Execute the SQL command\n config.cursor.execute(sql,(sf_cv_cvref,sf_cv_accession,sf_cv_name,sf_cv_value,sf_cv_fk))\n # Commit your changes in the database\n config.conn.commit()\n except Exception as err:\n # logger.error(err)\n # Rollback in case there is any error\n config.conn.rollback()\n\n# **Rest of the codes I have pasted because it's more then 300 lines but same concept reading other element**\n</code></pre>\n\n<p>You've got lots of repeating sections which is obnoxious to deal with. I'd try something like. You should pull any common elements into a function or perhaps but all the different elements in a big list/dictionary and pull data from there</p>\n\n<pre><code>def convert_bytes(bytes):\n</code></pre>\n\n<p>This function doesn't really convert bytes, it formats the count of bytes. The name could be better.</p>\n\n<pre><code> bytes = float(bytes)\n</code></pre>\n\n<p>Why are you converting bytes to a float? I presume you don't have fractional bits</p>\n\n<pre><code> if bytes >= 1099511627776:\n terabytes = bytes / 1099511627776\n size = '%.2fTB' % terabytes\n elif bytes >= 1073741824:\n gigabytes = bytes / 1073741824\n size = '%.2fGB' % gigabytes\n elif bytes >= 1048576:\n megabytes = bytes / 1048576\n size = '%.2fMB' % megabytes\n elif bytes >= 1024:\n kilobytes = bytes / 1024\n size = '%.2fKB' % kilobytes\n else:\n size = '%.2fb' % bytes\n return size\n</code></pre>\n\n<p>The code repeats the same idea several times, I'd use a data-based approach</p>\n\n<pre><code>UNITS = [ \n (1024**4, 'TB'),\n (1024**3, 'GB'),\n (1024**2, 'MB'),\n (1024**1, 'KB'),\n (1024**0, 'b')\n]\n\ndef convert_bytes(bytes):\n for size, unit in UNITS:\n if bytes > size:\n return '%d%s' % (bytes / size, unit)\n\n\n\ndef main():\n global EXP_PK\n # Start time counter\n begin=time.clock()\n\n # Reading file from the configured directory\n file_dir = r'D:\\files\\111102_CA2.mzML'\n</code></pre>\n\n<p>That's not a directory... </p>\n\n<pre><code> # Reactor so it will read all new files from configured directory\n file_name = os.path.basename(file_dir)\n</code></pre>\n\n<p>Reactor? Did you mean refactor? Because that's not what that means either. Really, I can't heads or tails out of your comment</p>\n\n<pre><code> # File name and extension\n (name, ext) = os.path.splitext(file_name)\n user= getpass.getuser()\n exp_name = name\n exp_type= ext[1:]\n</code></pre>\n\n<p>A comment explaining why you are stripping off the first character of the extension might be nice.</p>\n\n<pre><code> exp_created_time = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime(os.path.getctime(file_dir)))\n exp_modi_time = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime(os.path.getmtime(file_dir)))\n exp_uploaddate= datetime.date.today()\n exp_uptime = str(datetime.datetime.now())[10:19]\n exp_size = convert_bytes(os.path.getsize(file_dir))\n #exp_located = r'C:\\Users\\Thaman\\Documents\\My Dropbox\\Files\\small1.mzML'\n exp_located = r'C:\\My Documents\\Dropbox\\Files\\plgs_example.mzML'\n #exp_located =r'D:\\files\\111102_CA2.mzML'\n\n sql = \"\"\"INSERT INTO pmass_experiment (user,filename,filetype,createddate,modifieddate,uploaddate,time,size,located)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\n try:\n # Execute the SQL command\n config.cursor.execute(sql,(user,exp_name,exp_type,exp_created_time,exp_modi_time,exp_uploaddate,exp_uptime,exp_size,exp_located))\n # Commit your changes in the database\n config.conn.commit()\n except:\n #logger.error(err)\n # Rollback in case there is any error\n config.conn.rollback()\n global exp_PK\n exp_PK = config.cursor.lastrowid\n</code></pre>\n\n<p>You have this basic piece of code over and over again. That's a very big hint you should move it into a function and reuse it.</p>\n\n<pre><code> #Reading elements from file\n for intag in range(len(taglist)):\n</code></pre>\n\n<p>Just use <code>for tag in taglist:</code> You aren't using the index, so there is no reason to use range</p>\n\n<pre><code> context= etree.iterparse(file_dir,events=(\"end\",),tag=NS+taglist[intag])\n fast_iter(context, process_element)\n\n tend= time.clock()\n print \"\\n\\nTIME TAKEN TO COMPLETE JOB\", tend-begin\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>You should do something like this in order to handle the different tag types. It'll be faster and clearer then what you are doing.</p>\n\n<pre><code>def process_foo_tag(element):\n fetch element from foo\n insert into database\n\ndef process_bar_tag(element):\n fetch elements for bar tag\n insert into database\n\nTAGS = {\n 'bar' : process_bar_tag,\n 'foo' : process_foo_tag\n}\n\ndef process_element(element):\n TAGS[element.tag](element)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T19:44:39.140",
"Id": "8768",
"Score": "0",
"body": "Can you give me the hints in achieving parsing speed from above line of codes. I genuinely admire your review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T20:17:28.817",
"Id": "8770",
"Score": "0",
"body": "@thchand, for performance: don't commit after every statement. Commit at the end. Don't have a long chain of if-statements to decide what to do with a tag. Use a dictionary instead, have the keys be tag names and values functions to call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T20:34:12.557",
"Id": "8772",
"Score": "0",
"body": "Commit every statement? You mean query commit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T20:35:58.797",
"Id": "8773",
"Score": "0",
"body": "I mean every SQL statement. You don't need to commit for call to cursor.execute() just once at the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T21:09:20.313",
"Id": "8775",
"Score": "0",
"body": "Is it good idea to set default list like i did for all needed tag and loop in context= etree.iterparse(file_dir,events=(\"end\",),tag=NS+taglist[intag]). This is the one I have most doubt. I am trying to follow your tips regarding long chain of if-statement of deciding tag"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T21:11:16.303",
"Id": "8776",
"Score": "0",
"body": "I called cursor.execute() in every statement so element attributes value will be stored in database and get primary key which should be use in another table of database"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T21:57:58.647",
"Id": "8777",
"Score": "0",
"body": "@tchand calling cursor.execute() is correct. Calling conn.commit() for every cursor.execute() is incorrect. You should probably only call con.commit() once at the very end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T21:59:15.120",
"Id": "8778",
"Score": "0",
"body": "@tchand, if I understand you correctly, you should use a dictionary not a list. I'll add a little section to my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T07:35:42.483",
"Id": "8787",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1726/discussion-between-thchand-and-winston-ewert)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T15:12:57.617",
"Id": "5783",
"ParentId": "5782",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T14:39:05.263",
"Id": "5782",
"Score": "3",
"Tags": [
"python",
"parsing",
"xml",
"python-2.x",
"io"
],
"Title": "Reading a large XML file and parsing necessary elements into MySQLdb"
}
|
5782
|
<p>How does this look for basic image rotation? What is there to be improved here?</p>
<pre><code><p>
<img src='images/rotation/dsc_0052.jpg' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/bilde1.jpg' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/bilde2.jpg' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/bilde3.jpg' id='rotateImg3' style='display:none;' alt='image rotation' />
<img src='images/rotation/bilde4.jpg' id='rotateImg4' style='display:none;' alt='image rotation' />
<img src='images/rotation/dsc_0043.jpg' id='rotateImg5' style='display:none;' alt='image rotation' />
</p>
<script type='text/javascript'>
var rotation = function () {
var currentImage;
var count = function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString()))
x++;
return x;
} ();
var hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
document.getElementById('rotateImg' + i.toString()).style.display = 'none';
}
};
var showImage = function (number) {
document.getElementById('rotateImg' + number.toString()).style.display = 'block';
};
var fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval("rotation.advanceRotation()", 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
}
return fn;
} ();
rotation.setupRotation();
</script>
</code></pre>
|
[] |
[
{
"body": "<p>Three things I noticed:</p>\n\n<p><strong>1. Looking through the document with DOM methods is a slow process.</strong> There's often no way around it, and it won't crash anything here, but try to minimize it when you can. From page 183 of Stoyan Stefanov's <em>JavaScript Patterns</em>:</p>\n\n<blockquote>\n <p>DOM access is expensive; it's the most common bottleneck when it comes\n to JavaScript performance. This is because the DOM is usually\n implemented separately from the JavaScript engine...</p>\n \n <p>The bottom line is that DOM access should be reduced to a minimum.\n This means:</p>\n \n <ul>\n <li>Avoiding DOM access in loops</li>\n <li>Assigning DOM references to local variables and working with the locals</li>\n <li>Using selectors API where available</li>\n <li>Caching the length when iterating over HTML collections</li>\n </ul>\n</blockquote>\n\n<p>I've done that here. I created one extra variable named <code>images</code> and assigned it an empty array. Then, using your counting function, I store the image references in it.</p>\n\n<pre><code>var currentImage,\n images = [],\n\n ...\n\n count = (function () { \n // Figure out how many images we have on the rotation \n var x = 0;\n while (document.getElementById('rotateImg' + (x + 1).toString())) {\n images[x] = document.getElementById('rotateImg' + x.toString());\n x++;\n }\n return images.length;\n }()),\n</code></pre>\n\n<p>(If you're able to change the HTML, you can avoid the loop altogether and collect these images in one line. Just add an <code>id</code> to the element that contains them...</p>\n\n<pre><code><p id=\"container\">\n <img src='images/rotation/dsc_0052.jpg' id='rotateImg0' alt='image rotation' />\n ...\n</p>\n</code></pre>\n\n<p>...and collect them with...</p>\n\n<pre><code>var images = document.getElementById(\"container\").getElementsByTagName(\"img\");\n</code></pre>\n\n<p>But this doesn't help you if you can't change the markup.)</p>\n\n<p>Now you can run <code>hideImage</code> and <code>showImages</code> on the array instead of having to walk the DOM every time. </p>\n\n<p><strong>2. When the first argument to <code>setInterval</code> is a string, the browser runs <code>eval()</code> -- an implementation of the JavaScript compiler -- on it before firing.</strong> That's also expensive and unnecessary here. From page 111 of Douglas Crockford's <em>JavaScript: The Good Parts</em>:</p>\n\n<blockquote>\n <p>The browser provides <code>setTimeout</code> and <code>setInterval</code> functions that can\n take string arguments or function arguments. When given string\n arguments, <code>setTimeout</code> and <code>setInterval</code> act as <code>eval</code>. The string\n argument form also should be avoided.</p>\n</blockquote>\n\n<p>Getting rid of the quotes and the closing parentheses makes it a plain old function reference, which works fine.</p>\n\n<p>So I changed this:</p>\n\n<pre><code>var interval = setInterval(\"rotation.advanceRotation()\", 4000);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>var interval = setInterval(rotation.advanceRotation, 4000);\n</code></pre>\n\n<p><strong>3. Not crucial here. You can do all your variable declaration with one <code>var</code> statement per function.</strong> This reduces the chances of your variables being overwritten or unavailable due to hoisting. From <em>JavaScript Patterns</em> again:</p>\n\n<blockquote>\n <p>JavaScript enables you to have multiple var statements anywhere in a\n function, and they all act as if the variables were declared at the\n top of the function... This can lead to logical errors when you use a\n variable and then declare it further in the function.</p>\n</blockquote>\n\n<p>So I took out the multiple <code>var</code> statements and declared them all at the top of the outer function.</p>\n\n<p>The final code:</p>\n\n<pre><code><html lang=\"en\">\n <head>\n <title>Rice Flour Cookies' image rotation test</title>\n\n </head>\n\n <body>\n <p> \n <img src='images/rotation/dsc_0052.jpg' id='rotateImg0' alt='image rotation' />\n <img src='images/rotation/bilde1.jpg' id='rotateImg1' style='display:none;' alt='image rotation' />\n <img src='images/rotation/bilde2.jpg' id='rotateImg2' style='display:none;' alt='image rotation' />\n <img src='images/rotation/bilde3.jpg' id='rotateImg3' style='display:none;' alt='image rotation' />\n <img src='images/rotation/bilde4.jpg' id='rotateImg4' style='display:none;' alt='image rotation' />\n <img src='images/rotation/dsc_0043.jpg' id='rotateImg5' style='display:none;' alt='image rotation' /> \n </p>\n </body>\n</html>\n\n<script type='text/javascript'>\n var rotation = function () {\n var currentImage,\n images = [],\n count,\n hideImages,\n showImage,\n fn;\n\n count = (function () { \n // Figure out how many images we have on the rotation \n var x = 0;\n while (document.getElementById('rotateImg' + (x + 1).toString())) {\n images[x] = document.getElementById('rotateImg' + x.toString());\n x++;\n }\n return images.length;\n })();\n\n hideImages = function () {\n // Hide all the images \n for (var i = 0; i < count; i++) {\n images[i].style.display = 'none';\n }\n };\n\n showImage = function (number) {\n images[number].style.display = 'block';\n };\n\n fn = {};\n fn.setupRotation = function () {\n // Show the first image\n currentImage = 0;\n showImage(currentImage);\n\n // Start the rotation\n var interval = setInterval(rotation.advanceRotation, 4000);\n };\n\n fn.advanceRotation = function () {\n if (currentImage + 1 == count)\n currentImage = 0;\n else\n currentImage++;\n hideImages();\n showImage(currentImage);\n };\n\n return fn;\n } ();\n\n rotation.setupRotation(); \n</script>\n</code></pre>\n\n<p>And you can see it at work here:\n<a href=\"http://james.da.ydrea.ms/riceflourcookies/rotate.html\" rel=\"nofollow\">http://james.da.ydrea.ms/riceflourcookies/rotate.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T17:17:45.493",
"Id": "8893",
"Score": "0",
"body": "Thanks, I have implemented most of what you suggest on my (private) site. It works very well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T05:02:54.437",
"Id": "5827",
"ParentId": "5784",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5827",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-03T15:58:20.580",
"Id": "5784",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "JavaScript Code for image rotation on a web page"
}
|
5784
|
<p>I am starting to learn Ruby. </p>
<p>This is pretty much the first thing I have coded. It's very simple; it's a prime number calculator. Since this is my first Ruby code, I would like some review on the following:</p>
<ol>
<li>Adherence to Ruby standards</li>
<li>Is it done in the Ruby way (the way a Rubyist would have coded it)?</li>
<li>Adherence to Ruby naming conventions</li>
</ol>
<p>What I am <em>not</em> looking for is a review on the prime number algorithm. I know there are more efficient ones out there. </p>
<hr>
<p>File: <code>prime_numbers.rb</code></p>
<pre><code>class PrimeNumber
def is_prime_kata(number)
if number == 1 then return false end
max = Math.sqrt(number)
(2..max).any? do |i|
if number % i == 0 then return false end
end
true
end
end
</code></pre>
<hr>
<p>File: <code>prime_numbers_test.rb</code></p>
<pre><code>require 'test/unit'
require 'set'
require_relative 'prime_numbers.rb'
class PrimeNumberTest < Test::Unit::TestCase
def test_is_prime
primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
primeNumber = PrimeNumber.new
for i in primeNumbers
result = primeNumber.is_prime_kata(i)
assert_equal(true, result)
end
primeNumbersSet = Set.new(primeNumbers)
allNumbersSet = Set.new(1..100)
nonPrimeNumbersSet = allNumbersSet - primeNumbersSet
for i in nonPrimeNumbersSet
result = primeNumber.is_prime_kata(i)
assert_equal(false, result)
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T19:35:03.323",
"Id": "9838",
"Score": "0",
"body": "first advice: 2-space indentation."
}
] |
[
{
"body": "<p>Minor things. I will leave your actual questions to proper "Rubyists". :)</p>\n<h2>defensive programming</h2>\n<p>I would change the first condition to</p>\n<pre><code>return false if number <= 1\n</code></pre>\n<p>0 is not a prime number, and negative numbers aren't either.<br />\nMaybe I would also adapt the test to check these cases.</p>\n<h2>brevity</h2>\n<pre><code>if <condition> then <statement> end\n</code></pre>\n<p>can be written</p>\n<pre><code><statement> if <condition>\n</code></pre>\n<p>, so you could write</p>\n<pre><code>return false if number == 1\n</code></pre>\n<p>and</p>\n<pre><code>return false if number % i == 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T12:23:29.367",
"Id": "8796",
"Score": "0",
"body": "Thank you, this is exactly the kind of input I was looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T13:18:10.813",
"Id": "8799",
"Score": "0",
"body": "I understand. But please note that I am just a beginner in Ruby as well. (Just an older beginner.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T09:49:03.150",
"Id": "5798",
"ParentId": "5792",
"Score": "2"
}
},
{
"body": "<p>Aiming at your questions, your naming conventions are good. However, in your test you tend to switch between <code>camelCase</code> and <code>words_separated_by_underscores</code>. I would suggest sticking to one or the other (we tend to use underscores). Your algorithm looks good and taking ANeves suggestions will make it look more \"Ruby\"ish.</p>\n\n<p>However, I am going to suggest a much more efficient way of generating your prime numbers and none prime numbers in your Test. Instead of typing each prime number between 1 and 100 by hand into an Array, you could use the <a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select\" rel=\"nofollow\">Array#Select</a> method. It takes in an Enumerator, runs a given block against each item passed in, and returns an Array of only the items that return true. </p>\n\n<pre><code>prime_numbers = (1..100).select {|num| num.prime?}\n</code></pre>\n\n<p>This will given you the same Array you got by typing it all in manually. You can do the same for the none prime numbers.</p>\n\n<pre><code>non_prime_numbers = (1..100).select {|num| num unless num.prime?}\n</code></pre>\n\n<p>This'll return <code>num</code> only if it is not prime.</p>\n\n<p>It'll save you a lot of typing and it will look more \"Ruby\"ish. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:59:33.723",
"Id": "5948",
"ParentId": "5792",
"Score": "3"
}
},
{
"body": "<p>I'd write:</p>\n\n<pre><code>class PrimeNumber\n def is_prime_kata(number)\n return false if number == 1 \n max = Math.sqrt(number) \n (2..max).all? { |x| number % x != 0 }\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T19:34:26.317",
"Id": "6336",
"ParentId": "5792",
"Score": "0"
}
},
{
"body": "<p>Per your request, I suggest:</p>\n\n<p>File: <code>prime_numbers.rb</code></p>\n\n<pre><code>class PrimeNumbers\n def self.prime_kata? number\n n=number.floor\n return false if n < 2\n max=Math.sqrt(n).floor\n (2..max).none?{|k| 0==n % k}\n end\nend\n</code></pre>\n\n<p>File: <code>prime_numbers_test.rb</code></p>\n\n<pre><code>require 'mathn'\nrequire 'test/unit'\nrequire_relative 'prime_numbers'\n\nclass PrimeNumbersTest < Test::Unit::TestCase\n LIMIT=100\n def test_is_prime_or_not\n primes=Prime.each(LIMIT).to_a\n non_primes = (0.. LIMIT).to_a - primes\n non_primes.each{|k| assert ! (PrimeNumbers.prime_kata? k)}\n primes. each{|k| assert PrimeNumbers.prime_kata? k }\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T23:06:50.650",
"Id": "8171",
"ParentId": "5792",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5798",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:40:07.870",
"Id": "5792",
"Score": "4",
"Tags": [
"ruby",
"primes"
],
"Title": "Prime number calculator"
}
|
5792
|
<p>I'm looking for the most concise regex that matches one or two 4-digit years in any the following setups:</p>
<ul>
<li>year </li>
<li>year-</li>
<li>-year</li>
<li>year-year</li>
</ul>
<p>I can't think of anything slicker than this:</p>
<pre><code>[\\-]?\d{4}|\d{4}\[\\-](\d{4})?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:49:48.250",
"Id": "8780",
"Score": "0",
"body": "Do you really need the \"\\\" before the \"-\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T02:08:48.330",
"Id": "8781",
"Score": "0",
"body": "@asoundmove: In a character set, yes. But the character set itself is redundant (as it contains only a single character)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-12T16:03:36.393",
"Id": "49612",
"Score": "0",
"body": "@codesparkle: won't adding the double slash mean that we could match: \\2005 ... that's not really ideal. We should only match -2005"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T19:21:29.683",
"Id": "117846",
"Score": "0",
"body": "By our current requirements, this question would be off-topic for Code Review, since it lacks a programming language tag and is therefore hypothetical code. (This question predates the existence of the rule.)"
}
] |
[
{
"body": "<p>If you first removed all \"-\" characters you could make it</p>\n\n<pre><code>(\\d{4}){1,2}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>(\\d{4}|\\d{8})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:33:44.033",
"Id": "8782",
"Score": "3",
"body": "If it doesn't have to work, I can make the regex zero characters long ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T06:18:57.687",
"Id": "12922",
"Score": "0",
"body": "and if we didn't have computer's we wouldn't have a job. So it all works out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T00:42:11.003",
"Id": "5795",
"ParentId": "5794",
"Score": "1"
}
},
{
"body": "<p>This is a somewhat difficult one because regular expressions inherently lack memory, so you can't tell on the back whether the front existed, so I don't think one can get better than the one you wrote for that particular set. If you wanted to allow some sort of variant, you could potentially find a better one. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:07:28.280",
"Id": "8783",
"Score": "1",
"body": "You don't need the full power of memory. You can also determine whether there is any year first, via lookaround. And if that part matches, you proceed with the easy (but by itself insufficient) shortcut of making both years optional. For example `(?=.*\\d)\\d{4}?-\\d{4}?` or even (abusing the fact the following pattern has only one false positive, a single dash) `(?=..)\\d{4}-\\d{4}`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:20:45.923",
"Id": "8784",
"Score": "0",
"body": "@delnan I don't believe theoretical regexes have lookahead/behind (possibly behind), and/because that does require additional memory (to keep the original expression while analyzing the pre-condition)[If I'm wrong about that, please provide a citation]. If he were doing this in a language which allows such a construct, yes, that should work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:27:19.237",
"Id": "8785",
"Score": "0",
"body": "I don't think it requires additional memory, at least not if one looks ahead by a fixed number of character. You can try the lookaround, then adjust your string position pointer to be back where you started the lookaround, or you simply don't consume characters (use a seperate counter). I don't know a nice way to encode that in a DFA or NFA though, maybe that's why it's not part of regular expression theory. Either way, it's certainly available in pretty much every language that has a serious regex implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T01:48:48.963",
"Id": "8786",
"Score": "0",
"body": "@delnan: in the question you missed the requirement that you could have a year without a hyphen."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T00:52:31.807",
"Id": "5796",
"ParentId": "5794",
"Score": "3"
}
},
{
"body": "<p>I am assuming you prefer the longest match. That is, if the input line is:</p>\n\n<pre><code>xyzzy 2000-2010 xyzzy\n</code></pre>\n\n<p>then matching <code>2000</code> or <code>2010</code> or <code>2000-</code> or <code>-2010</code> is not what you want, even though these would be valid matches the way you have stated the problem.</p>\n\n<p>In Perl 5.10 and later, you can reduce the pattern to 20 characters:</p>\n\n<pre><code>(\\d{4})-(?1)?|-?(?1)\n</code></pre>\n\n<p>Let's break this down.</p>\n\n<pre><code>(\\d{4}) # match a year and capture the pattern\n- # match a hyphen\n(?1)? # match a year again if possible\n | # OR,\n-? # match an initial hyphen if possible\n(?1) # match a year\n</code></pre>\n\n<p>Things get more complicated if you prefer to match two years even in cases such as:</p>\n\n<pre><code>xyzzy -2000-2010 xyzzy\n</code></pre>\n\n<p>See: <a href=\"http://perldoc.perl.org/perlretut.html#Recursive-patterns\" rel=\"nofollow\">http://perldoc.perl.org/perlretut.html#Recursive-patterns</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T23:33:03.967",
"Id": "5875",
"ParentId": "5794",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5875",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T00:18:48.470",
"Id": "5794",
"Score": "2",
"Tags": [
"regex"
],
"Title": "Best Regular Expression for a one or two values optionally divided by a certain character"
}
|
5794
|
<p>What can I do better?</p>
<pre><code>$(function () {
"use strict";
/*
* Header text. Vergroot de tekst door op lees meer te klikken
*/
var heading = $(".header .text h2").height(),
firstP = $(".header p:first").height(),
areaSmall = heading + firstP,
areaBig = $(".header .text").height(),
box = $(".header .text"),
readmore = $('.header .text a[title*="meer"]'),
closeBox = $('.header .text a[title*="Sluit"]');
$(".header .text").css({ height: areaSmall });
readmore.click(function () {
$(".header .text").animate({ height: areaBig }, 1000, "easeInQuart", function () {
$(".header .text p").css({ visibility: "visible" });
});
});
closeBox.click(function () {
$(".header .text").animate({ height: areaSmall }, 1000, "easeOutQuart", function () {
$(".header .text p").css({ visibility: "hidden" });
$(".header .text p:first").css({ visibility: "visible" });
});
});
});
</code></pre>
|
[] |
[
{
"body": "<p>I am not sure of what you want to be better but, for better code legibility and maintainability I would say that you should replace all your string constants with variables:</p>\n\n<pre><code>var headerClassId = \".header\";\nvar textClassId = \".text\";\nvar aTextValueThatMeansSomething = \"easeInQuart\"; \n</code></pre>\n\n<p>Do the same with all other constants:</p>\n\n<pre><code>var aVariableNameThatMeansSomething = 1000;\n...\n$(headerClassId +\" \"+textClassId).animate({ height: areaBig },\n aVariableNameThatMeansSomething , aTextValueThatMeansSomething, function ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T19:18:04.583",
"Id": "8899",
"Score": "0",
"body": "This really doesn't do much for legibility. `headerClassId +\" \"+textClassId` is less readable to me than `\".header .text\"` -- for one thing, because it requires that i know the value and intent of `headerClassId` and `textClassId`. (Not to mention, `*ClassId` is a rather crappy name -- is it a class, or an id, or both? \"Either\" is a bad answer.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T14:05:26.303",
"Id": "5807",
"ParentId": "5802",
"Score": "1"
}
},
{
"body": "<p>You have lots of calls to <code>$(\".header .text\")</code>, which you can replace with calls to <code>box</code>:</p>\n\n<pre><code>var areaBig = box.height();\n</code></pre>\n\n<p>Similarly, you can simplify calls to selectors within <code>box</code>, such as:</p>\n\n<pre><code>// Better than: readmore = $('.header .text a[title*=\"meer\"]')\nvar readmore = box.find('a[title*=\"meer\"]');\n\n// Better than: $(\".header .text\").animate(...\nbox.animate({ height: areaBig }, 1000, \"easeInQuart\", function () {\n box.find(\"p\").css({ visibility: \"visible\" });\n});\n</code></pre>\n\n<p>These changes will not only make the code easier to read but also increase execution speed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T19:12:07.557",
"Id": "8898",
"Score": "1",
"body": "Just make sure that the definition of `box` comes first, or at least before any code that intends to use it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T15:16:14.923",
"Id": "5808",
"ParentId": "5802",
"Score": "2"
}
},
{
"body": "<p>I would:</p>\n\n<ul>\n<li>call heights <code>height</code>s (or <code>\"ht\"</code>), as in areaSmall</li>\n<li>name jQuery object to start with <code>$</code>, and use them for elements I reference multiple times</li>\n<li>don't change names of things (header !== heading)</li>\n<li>don't create variables that are only used once</li>\n<li>remove unused variables (<code>box</code>) </li>\n</ul>\n\n<p>Here's one take...</p>\n\n<pre><code>var $header = $('.header'),\n $text = $('.text', $header),\n $p = $('p', $text),\n areaSmallHt = $(\"h2\", $text).height() + $(\"p:first\", $header).height(),\n textHt = $text.height();\n\n$text.css({ height: areaSmallHt });\n\n$('a[title*=\"meer\"]', $text).click(function () {\n $text.animate({ height: textHt }, 1000, \"easeInQuart\", function () {\n $p.css({ visibility: \"visible\" });\n });\n});\n\n$('a[title*=\"Sluit\"]', $text).click(function () {\n $text.animate({ height: areaSmallHt }, 1000, \"easeOutQuart\", function () {\n $p.css({ visibility: \"hidden\" });\n $(\"p:first\", $text).css({ visibility: \"visible\" });\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-05T05:17:13.530",
"Id": "5818",
"ParentId": "5802",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T12:22:33.603",
"Id": "5802",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Increasing visible text with on-click \"read more\""
}
|
5802
|
<p>I have been developing Javascript for few months, and, as a former Java developer, needed a simple way to perform class inheritance.</p>
<p>My needs are:</p>
<ul>
<li>having private members not accessible (encapsulation),</li>
<li>to make inheritance simple,</li>
<li>to avoid 'new' keywords bugs,</li>
<li>to let the superclass methods accessible using the this.super property.</li>
</ul>
<p>The purpose of this request is to indicate me if the solution I developped should be applied into my project or if there are some misbehaviour risks by using it, and if you have remarks on how to enhance it.</p>
<p>My code is below, thank you for your reviews.</p>
<pre><code>/**
* Allows to retrieve the global object (used to test if the 'new' keyword is needed)
*/
function getGlobal(){
return (function(){
return this;
}).call(null);
}
if (typeof Object.extend !== 'function') {
Object.extend = function (object, superClassConstructor, superConstructorArgs) {
//Inherits from the super object
superClassConstructor.apply(object, superConstructorArgs);
//make this.super allow to access to inherited object original functions
object.super = {};
for (var property in object){
object.super[property] = object[property];
}
};
}
//The superclass
function SuperClass(options){
//Make sure we will not alter global object
if (this === getGlobal()){
throw new Error("Constructor cannot be called as a function (new keyword should not be omitted)");
}
//Use of jshashtable-2.1:
var attributes = new Hashtable();
for (var key in options){
attributes.put(key, options[key]);
}
this.setValue = function(key, value){
if(value != null){
attributes.put(key, value);
}
else{
attributes.remove(key);
}
};
this.getValue = function(key){
return attributes.get(key);
};
}
/**
* Inheriting class
*/
function ProjectModel(projectId) {
//Make sure we will not alter global object
if (this === getGlobal()){
throw new Error("Constructor cannot be called as a function (new keyword should not be omitted)");
}
//extends SuperClass
Object.extend(this, SuperClass, [{
id:projectId,
'one':1,
'two':"2"
}]);
this.myType = "ProjectNumber";
//Overriding a function
this.getValue = function(key){
return this.myType + ":" + this.super.getValue(key);
};
}
var project = new ProjectModel(123);
alert(project.getValue('one')); //this displays 'ProjectNumber:123'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:15:35.457",
"Id": "8856",
"Score": "0",
"body": "I do not agree: I do not try to do like Java, I try to do OOP. This means encapsulation and encapsulation is not possible without private attributes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:28:09.933",
"Id": "8857",
"Score": "0",
"body": "To create private attributes/methods in JavaScript, just use local variables in the constructor; they will be bound in the public methods of the object, without being exposed to other objects. `/*constructor*/ function counter() { var cnt=0; this.getNext()={return cnt++;};}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:29:59.550",
"Id": "8858",
"Score": "0",
"body": "Have you looked at the way existing JavaScript libraries do this? E.g. Look at [dojo.declare](http://dojotoolkit.org/reference-guide/dojo/declare.html). Or consider simply consider using it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:31:29.947",
"Id": "8859",
"Score": "0",
"body": "Thank you ammoQ, I already knew this: my goal here was to allow inheritance from a class that has private attributes and to add new private attributes to the subclass (without seeing superclass' private attributes)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:37:07.163",
"Id": "8860",
"Score": "0",
"body": "@MarkJ: yes, it seems that it is something like dojo.declare that I was trying to do. Thank you for this, I will try it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:21:21.733",
"Id": "8861",
"Score": "4",
"body": "@lauhub you don't need \"private\" that's not what encapsulation is about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:35:11.113",
"Id": "8862",
"Score": "0",
"body": "@Raynos: I do know what I need and, as far as I know, using \"private\" or not-accessible members is a way to deal with encapsulation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:36:49.220",
"Id": "8863",
"Score": "5",
"body": "@lauhub but you don't need \"privates\". They are slow, ugly and a pain in the ass. If you going to use \"privates\" then give up on OO and use closures everywhere. State bound in closures is actually quite elegant but you shouldn't be emulating OO using it. closures (functional programming) and inheritance (OO programming) are parallel constructs pick one or the other because any combination of the two is ugly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:44:41.867",
"Id": "8864",
"Score": "0",
"body": "@Raynos: thank you but I do not agree with this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T21:13:48.820",
"Id": "8902",
"Score": "0",
"body": "Encapsulation is quite possible without private variables. The most basic point of encapsulation is that you make it possible to work with an object without knowing anything about its innards. Not necessarily that the innards are hidden behind some kind of codewall. We're all adults here, and should be able to follow a simple guideline like \"don't mess with properties directly; call functions that mess with the properties for you\". Python, Perl, JS, etc get by just fine without private properties. That you see some need for them is evidence of a C++ or Java mindset."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:30:22.093",
"Id": "8906",
"Score": "1",
"body": "@cHao: I work with non IT engineers since 10 years (mechanical engineers, scientific researchers) who modify or code some stuffs. And all I have to say is, although they are very efficient into their fields, they are not able to follow some IT rules only because they are more interested into their fields than in IT. My job is to support them. My question was: \"is my code correct and how to enhance it ?\", it was not \"what is your opinion about software development ?\" Thank you to all the people who understand that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T03:59:14.183",
"Id": "8948",
"Score": "1",
"body": "If they can't follow a simple rule, then they have no business touching code. Period. They wouldn't tolerate you coming in and scribbling on their plans/graphs/whatever they use; if your work is any less worthy of respect, crap like this is why. And the answer to your question is \"No, because the very idea is flawed. Javascript does not have classes. It does not have private variables. It is not Java, and you can not turn it into Java, because the two languages are fundamentally different. The more you try, the more gotchas you'll run into. That way lies madness. You've been warned.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T08:59:35.633",
"Id": "8953",
"Score": "0",
"body": "@cHao: about business of people: you are not the one who decides about who do what. About private variable etc: a link (from D. Crockford, I think you know him as you know javascript): [link](http://javascript.crockford.com/private.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T13:13:16.980",
"Id": "8957",
"Score": "0",
"body": "Know him? Yes. Take every word he says as gospel? Not on your life. Everything he and anyone else says should be evaluated on its own merits. And in this case, private variables are rather incompatible with the idea of prototypal inheritance (which is another of his big ones, and one i can agree with). Even he has said \"I now see my early attempts to support the classical model in JavaScript as a mistake\" ([link](http://www.crockford.com/javascript/inheritance.html), at the bottom of the page)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T13:47:34.980",
"Id": "8960",
"Score": "0",
"body": "No need to follow your link: I already did it. And evaluated myself what is good for me without imposing it to anyone else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T02:52:03.410",
"Id": "9056",
"Score": "0",
"body": "\"Without imposing it to anyone else\", you say? Did you forget those engineers and researchers you feel the need to treat like spoiled brats who'll destroy anything that isn't bolted down and locked up? They are allegedly the whole reason for this monstrosity, after all..."
}
] |
[
{
"body": "<p>It's generally a bad idea to try writing code in one language as if it were a different language. </p>\n\n<p>Don't fight your tool; use it as it was designed. JavaScript has prototype-based OO rather than class-based OO, so use it like that.</p>\n\n<p>Read \"Javascript - the Good Parts\" and learn to write actually good JavaScript rather than \"Java in JavaScript\" (for which other developers working with your code will hate and/or mock you).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:23:35.587",
"Id": "8865",
"Score": "0",
"body": "Thank you for your answer.\n\nBut OOP means encapsulation and encapsulation means nothing without private attributes.\n\nI do not fight, I just currently think that it is possible to have a simple way to do this without falling into traps (none of the solutions I found was simple nor efficient enough)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:36:14.510",
"Id": "8866",
"Score": "6",
"body": "@lauhub so you've asserted, twice. But no, encapsulation does *not* mean private variables, as any programmer in Python (for example) will tell you. Again, please drop the Java mindset when you're not using Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:43:17.763",
"Id": "8867",
"Score": "1",
"body": "@DanielRoseman: encapsulation means information hiding. From what I know from Python, a variable is private only if it is prefixed with __.\nProblem: it is not possible always to trust developpers will not do forbidden access to private members. This is an observation from my experience programming with other languages (actually I did not write a line of Java code since 6 years)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T11:45:06.780",
"Id": "8868",
"Score": "1",
"body": "@lauhub: You're right that encapsulation is important, and your code seems to use the generally accepted way to implement it in JavaScript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:01:32.570",
"Id": "8869",
"Score": "6",
"body": "`it is not possible always to trust developpers` -- then NO amount of encapsulation is sufficient!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:11:37.867",
"Id": "8870",
"Score": "0",
"body": "@greengit: it is not sufficient, it is a higher security level. And this is not the subject of this topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:22:30.267",
"Id": "8871",
"Score": "4",
"body": "@lauhub \"it is not possible always to trust developpers\" Fire your developers. Stop writing ugly ass code to deal with incompetent team mates. We really need to get over this problem, the solution is not becoming a turtle fortress in your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:27:39.877",
"Id": "8872",
"Score": "0",
"body": "@raynos: thank you for my ugly ass code. And you will learn that, sometimes, developpers are customers that you cannot fire.\n\nActually, I decided to fire myself from these kind of projects, but I still have to eat, this is my human condition ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:10:58.127",
"Id": "8873",
"Score": "0",
"body": "@lauhub: mind you, in many languages that support private members, it is trivial to access them anyway, via reflection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:19:17.737",
"Id": "8874",
"Score": "0",
"body": "@NemanjaTrifunovic: I know reflection, but I also know that developpers who ignore trivial encapsulation rules also ignore what reflection is. So this is a protection shield."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:23:44.710",
"Id": "8875",
"Score": "1",
"body": "@lauhub: Are they also ignorant enough to replace keywords \"private\" with \"public\"? The bottom line is: you really can't use language features to fix broken development process; if someone doesn't like encapsulation, they will break it. Just don't sweat over things like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:31:06.677",
"Id": "8876",
"Score": "0",
"body": "@NemanjaTrifunovic: I can use language feature because I furnish an API to some users who will not be able to break my encapsulation. And I also can control if a member is private or not with code control tools."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:43:03.020",
"Id": "8877",
"Score": "1",
"body": "@lauhub why does it matter if they break encapsulation. If _they_ break it, then it's _their_ problem. Not yours"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:44:32.957",
"Id": "8878",
"Score": "3",
"body": "\"it is not possible always to trust developpers\" A bit of a tangent, but this mindset is something that has always bugged me about Java. The entire language is infused with the sense that you are being talked down to, versus languages like Python that give you a sense of being respected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T14:00:23.630",
"Id": "8879",
"Score": "0",
"body": "@jhocking: my need is not to have a discussion about which is the best programming language and why. My need is to prevent _javascript_ developpers (who are human) to make errors by simple and easy to apply coding rules."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T14:17:23.633",
"Id": "8884",
"Score": "2",
"body": "@lauhub prevent developers from making errors is really easy. Write unit tests, make sure unit tests pass before you commit any code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T17:02:05.063",
"Id": "8891",
"Score": "0",
"body": "@Raynos: _prevent developers from making errors is really easy_ well, in a real world this kind of assertion is not always true, especially when you have to learn programmers what is a unit test. Actually my need was not philosophy nor orthodoxy rules about software development as anyone here has a different philosophy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T17:25:52.073",
"Id": "8894",
"Score": "0",
"body": "@lauhub you don't have unit tests? :( I feel sorry for you and your team. Maybe you should get a better job"
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T10:15:38.780",
"Id": "5850",
"ParentId": "5806",
"Score": "15"
}
},
{
"body": "<p>No, it's wrong. JavaScript inheritance is really easy.</p>\n\n<pre><code>var SomeKlass = {\n ...\n};\n\nvar someInstance = Object.create(SomeKlass);\n</code></pre>\n\n<p>For a more complete example / conversion of your code see <a href=\"http://jsfiddle.net/vKTnc/4/\" rel=\"nofollow noreferrer\">the following example</a></p>\n\n<blockquote>\n <p>to make inheritance simple,</p>\n</blockquote>\n\n<p>Can't be any simpler, to inherit any object call <code>Object.create</code> on it.</p>\n\n<blockquote>\n <p>to avoid 'new' keywords bugs,</p>\n</blockquote>\n\n<p>You don't use <code>new</code> anymore so that problem dissappeared</p>\n\n<blockquote>\n <p>to let the superclass methods accessible using the this.super property.</p>\n</blockquote>\n\n<p>Emulating <code>super</code> with elegant syntax is a <a href=\"https://stackoverflow.com/q/8032566/419970\">seriously non trivial problem</a></p>\n\n<p>The best mechanism I've seen is function replacement with either setting <code>this.$super</code> to a sensible value before and after or recompiling the function to reference a super object. Both of those solutions are ugly, I'd recommend just referencing the super object directly by name.</p>\n\n<blockquote>\n <p>having private members not accessible (encapsulation),</p>\n</blockquote>\n\n<p>You can't do non accessible private members in JavaScript using prototypical OO. You can use closures, but that's not prototypical OO and that does not work with prototypical OO.</p>\n\n<p>I recommend you use pseudo internal properties prefixed with <code>_</code> and shoot any developer who uses it.</p>\n\n<p>Alternatively you can use namespaces. <a href=\"http://jsfiddle.net/9QmPf/4/\" rel=\"nofollow noreferrer\">Live Example</a>.</p>\n\n<pre><code>var SuperClass = (function () {\n // Name shim : https://gist.github.com/1344853\n var privates = Name();\n\n return {\n constructor: function (options) {\n privates(this).attributes = options;\n },\n setValue: function (key, value) {\n if (value) {\n privates(this).attributes[key] = value; \n } else {\n delete privates(this).attributes[key];\n }\n },\n getValue: function (key) {\n return privates(this).attributes[key];\n }\n };\n})();\n\n\n// Object.make : https://github.com/Raynos/pd#pd.make\nvar ProjectModel = Object.make(SuperClass, {\n constructor: function (projectId) {\n SuperClass.constructor.call(this, {\n id: projectId,\n one: 1,\n two: \"2\" \n });\n this.myType = \"ProjectModel\";\n },\n getValue: function (key) {\n return this.myType + \":\" + SuperClass.getValue.apply(this, arguments);\n }\n});\n\nvar project = Object.create(ProjectModel);\nproject.constructor(123);\nalert(project.getValue('one')); //this displays 'ProjectNumber:123'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:22:04.880",
"Id": "8880",
"Score": "0",
"body": "Thank you for your solution: I already tried it and it does not fulfill my first need (private members). You are out of the scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:23:03.997",
"Id": "8881",
"Score": "0",
"body": "@lauhub what? `Name` fulfills private members in a very elegant way and it actually works with prototypical OO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:26:48.977",
"Id": "8882",
"Score": "0",
"body": "Sorry, I did not have noticed you had changed your code. Your first version did not use Name and I agree that it is an elegant way to do that.\n\nThank you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T14:02:57.357",
"Id": "8883",
"Score": "0",
"body": "I have only a remark: if I need to create a private member, I have to write `privates(this).myVariable`.\n\nThis is not as simple as `var myVariable` and I usually declare more that a single private member."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T14:18:10.997",
"Id": "8885",
"Score": "0",
"body": "I would cache privates, so `var _ = privates(this)` and then `_.myVariable = ...` so it's actually one less character. However you get the massive advantage of people to access private variables outside of the constructor scope as long as you have a reference to `privates`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T12:34:58.037",
"Id": "5851",
"ParentId": "5806",
"Score": "6"
}
},
{
"body": "<p>Taking into account remarks and suggestions, here is an enhanced version of my initial code: it works and fulfills my needs.</p>\n\n<pre><code>/**\n* Allows to retrieve the global object\n*/\nfunction getGlobal(){\n return (function(){\n return this;\n }).call(null);\n}\nfunction getFunctionName(fonction){\n var nom = fonction.toString();\n nom = nom.substr('function '.length);\n nom = nom.substr(0, nom.indexOf('('));\n return nom;\n} \nif (typeof Object.extend !== 'function') {\n Object.extend = function (object, objectConstructor, superClassConstructor, superConstructorArgs) {\n //To stop if new keyword was not used\n if (object === getGlobal()){ \n throw new Error(\"Constructor should always be called with new keyword.\");\n }\n //Check arguments:\n if(objectConstructor === undefined){throw new Error(\"Missing argument: objectConstructor\");} \n if(superClassConstructor === undefined){throw new Error(\"Missing argument: superClassConstructor\");} \n if(superConstructorArgs === undefined){throw new Error(\"Missing argument: superConstructorArgs\");} \n\n //Calls super class' constructor, apply it to new object:\n superClassConstructor.apply(object, superConstructorArgs);\n\n //Create a super class \"mirror\" object\n var superProperties = {};\n //At this point, the new object will only have super object properties\n //Copies each property:\n for (var property in object){\n superProperties[property] = object[property];\n }\n //Set it to new object:\n object.super = superProperties;\n\n //put super class name into a property\n if(object.super.className === undefined){\n object.super.className = getFunctionName(superClassConstructor);\n }\n //Set className for object\n var className = getFunctionName(objectConstructor);\n object.className = className;\n //Set constructor for object\n object.constructor = objectConstructor;\n };\n}\n//The superclass\nfunction SuperClass(options){\n //Inherits from object:\n Object.extend(this, arguments.callee, Object, [{}]);\n\n //Use of jshashtable-2.1:\n var attributes = new Hashtable();\n\n for (var key in options){\n attributes.put(key, options[key]);\n }\n\n this.setValue = function(key, value){\n if(value != null){\n attributes.put(key, value);\n }\n else{\n attributes.remove(key);\n }\n };\n\n this.getValue = function(key){\n return attributes.get(key);\n };\n}\n\n/**\n* Inheriting class\n*/\nfunction ProjectModel(projectId) {\n //extends SuperClass\n Object.extend(this, arguments.callee, SuperClass, [{\n id:projectId,\n 'one':1,\n 'two':\"2\"\n }]);\n\n this.myType = \"ProjectNumber\";\n //Overriding a function\n this.getValue = function(key){\n return this.myType + \":\" + this.super.getValue(key);\n };\n}\n\nvar project = new ProjectModel(123);\nalert(project.getValue('one'));\n//At this point, project will have:\n// - a className property set to \"ProjectModel\"\n// - a super property which will contain:\n// --> className set to \"SuperClass\"\n// --> setValue and getValue functions from SuperClass\n// --> a super property set to Object parent class \n// (with a className property set to \"Object\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T14:45:02.540",
"Id": "9286",
"Score": "0",
"body": "Actually, the first thing I found that does not work with this is instanceof function: it does not work with super classes. A work around is to do SubClass.prototype = new SuperClass() after SubClass declaration."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T09:52:15.473",
"Id": "5886",
"ParentId": "5806",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5850",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-04T13:43:40.187",
"Id": "5806",
"Score": "7",
"Tags": [
"javascript",
"extension-methods"
],
"Title": "Javascript inheritance: is my solution correct?"
}
|
5806
|
<p>I want to review the URL routing for my appengine webapp:</p>
<pre><code>routes = [
(r'/', CyberFazeHandler),
(r'/vi/(eyes|mouth|nose)', CyberFazeHandler),
(r'/realtime', RealtimeHandler),
(r'/task/refresh-user/(.*)', RefreshUserHandler),
('/ai', FileUploadFormHandler),
('/serve/([^/]+)?', ServeHandler),
('/upload', FileUploadHandler),
('/generate_upload_url', GenerateUploadUrlHandler),
('/file/([0-9]+)', FileInfoHandler),
('/file/set/([0-9]+)', SetCategoryHandler),
('/file/([0-9]+)/download', FileDownloadHandler),
('/file/([0-9]+)/success', AjaxSuccessHandler),
]
app = webapp2.WSGIApplication(routes,
debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'
))
</code></pre>
<p>Does it look alright to you? Can you recommend an improvement? Should I use the <code>'r</code> prefix to my regexes?</p>
|
[] |
[
{
"body": "<p>Have you considered using <a href=\"http://webapp-improved.appspot.com/api/webapp2.html#webapp2.Route\">named Route templates</a> instead of capturing regular expressions? It could make the code more readable. Consider</p>\n\n<pre><code>Route(\"/task/refresh-user/<username>\", RefreshUserHandler)\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>(r'/task/refresh-user/(.*)', RefreshUserHandler)\n</code></pre>\n\n<p>for example. (Of course, I don't know what kwargs <code>RefreshUser</code> actually wants, but you can change the angle-bracketed part to the appropriate name.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T09:37:21.320",
"Id": "9060",
"Score": "1",
"body": "Thanks! The suggestion would definitely have the advantages of improving readibility and maintainability."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T04:37:18.133",
"Id": "5914",
"ParentId": "5817",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "5914",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-05T04:36:22.323",
"Id": "5817",
"Score": "6",
"Tags": [
"python",
"regex",
"google-app-engine"
],
"Title": "Regexes for Google App Engine"
}
|
5817
|
<p>I have the following code which works but seems like it could be improved. I'm not sure if I'm using <code>event.stopPropagation()</code> correctly or if it is the best solution.</p>
<p>The elements are loaded via AJAX and so need to have <code>.on()</code> (previously <code>.live()</code>, which is now deprecated in jQuery 1.7).</p>
<p>I've used the example given <a href="https://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element/153047#153047">here</a> as a basis.</p>
<pre><code>$('html').on('click', '.poster:not(.active) .image-effect', function (event) {
var obj = $(this).parent();
// If there are no .close spans
if (obj.find('.close').length === 0) {
// Add the close element by javascript to remain semantic
obj.find('.quick-view').append('<span class="close">&times;</span>');
}
// Close any open Quick Views
closeQuickView();
// Add the active class (controls opacity)
obj.addClass('active');
// Fade in the Quick View
obj.find('.quick-view').fadeIn(200, 'easeInOutQuint');
event.preventDefault();
event.stopPropagation();
});
$('html').on('click', '.active', function () {
return false;
});
$('html').on('click', '.close', function () {
closeQuickView();
});
$('html').on('click', '.quick-view', function (event) {
event.stopPropagation();
});
// Close the QuickView with a button
$('html').on('click', function () {
closeQuickView();
});
function closeQuickView() {
$('.poster').removeClass('active');
$('.quick-view').fadeOut(200, 'easeInOutQuint');
}
</code></pre>
<p>For some reason clicking the document isn't working in Chrome (the <code>closeQuickView</code> is not being called) which may be an indicator that the code is not functioning 100%.</p>
<p>My markup is as follows:</p>
<pre><code><figure class="grid_2 box poster">
<a class="image-effect" href="#">
<img class="colour" src="path/to/image" />
<img class="bw" src="path/to/image" />
</a>
<div class="quick-view">
Content
</div>
</figure>
</code></pre>
<p>Is this the right way to approach the scenario? Are there any conflicting functions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-05T19:17:43.010",
"Id": "8813",
"Score": "0",
"body": "Actually, you are not using `on` instead of `live`, but instead of `delegate`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T14:34:45.630",
"Id": "8825",
"Score": "0",
"body": "Oh, really? Ok. I got a little confused as the .on() function in 1.7 seems to do the job of a few things."
}
] |
[
{
"body": "<p>It did work in my Chrome. However, I felt your code was confusing with all those handlers. Let me suggest the following:</p>\n\n<pre><code>$('html').on('click', '.poster', function(e) {\n\n var target = $(e.target);\n var poster = $(this); \n\n if (!poster.hasClass('active')) {\n closeQuickView();\n poster.addClass('active').find('.quick-view').fadeIn(200);\n }\n if (target.hasClass('quick-view') || target.hasClass('image-effect')) e.stopPropagation(); // prevent bubbling and thus closeClickView call below\n});\n\n$('html').on('click', closeQuickView);\n</code></pre>\n\n<p>This way, it's more concise and hopefully clearer what's handling what.</p>\n\n<p>PS: I threw out the conditional '.close' appendage here, nothing wrong with having it in the vanilla HTML I'd say. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T10:34:32.113",
"Id": "8954",
"Score": "0",
"body": "I understand it but would not have been able to write it as succinctly. The reason for appending the spans was to maintain semantic code. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T02:13:29.977",
"Id": "5878",
"ParentId": "5821",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5878",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-05T17:13:55.067",
"Id": "5821",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"html5"
],
"Title": "Using jQuery 1.7 .on() and event.stopPropagation to close boxes when clicking in document body"
}
|
5821
|
<p>I have multiple form validation checks around my site so I decided to write them as functions to simplify the process of creating the validation pages, here is a snippet for an understanding of what I'm doing.</p>
<pre><code>// Declare regex variables
$regex_email = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$regex_password = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).*$/";
// Declare validation functions
function checkEmail($regex, $email) {
if (!preg_match($regex, $email)) {
$error = "The format of that Email Address is invalid";
$solution = "Please go back and <a href=\"javascript:history.go(-1)\">try again</a>";
}
return array($error, $solution);
}
function checkPassword($regex, $password) {
if (!preg_match($regex, $password)) {
$error = "Your Passwords does not meet our requirements";
$solution = "Please go back and <a href=\"javascript:history.go(-1)\">try again</a>";
}
return array($error, $solution);
}
</code></pre>
<p>I was hoping that when I come to validate it I could simply use:</p>
<pre><code>// Values for $email and $password are fetched from `$_POST` before hand...
// Validate form
list ($error, $solution) = checkEmail($regex_email, $email);
list ($error, $solution) = checkPassword($regex_password, $password);
// Display error
echo("Error:<br />".$error."<br />Solution:<br />".$solution."");
</code></pre>
<p>But alas, it doesn't work and no errors at all are displayed and I'm having to do error checks after each one like this:</p>
<pre><code>// Validate form
list ($error, $solution) = checkEmail($regex_email, $email);
if (!$error) {
list ($error, $solution) = checkPassword($regex_password, $password);
}
// Display error
echo("Error:<br />".$error."<br />Solution:<br />".$solution."");
</code></pre>
<p>I don't mind doing it like this, but when I have say 10+ <code>check*VALUE*</code> functions being called, each one wrapped in an <code>if statement</code> within an <code>if statement</code> and so on, it looks a little messy, I wasn't sure if there was a different approach which would work more like the first way I tried without all the <code>if statement</code>'s.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T18:32:56.790",
"Id": "9267",
"Score": "0",
"body": "Javascript in your backlinks. Just give them a class and hook the javascript into that class, so that if you ever want to change the behavior, you can change it in the js instead of everywhere in the php code."
}
] |
[
{
"body": "<p>This might not be what you are looking for but I recently wrote this code to validate my forms.</p>\n\n<p>As you might notice I define the data to be validated in the $validate array. Then some loops run through them and show the proper errors. If no errors are found, it sends the form.</p>\n\n<p>With some modifications, you could probably use something similar. Hope it helps.</p>\n\n<pre><code><?php\n\n # post data collection\n $name = \"Full name\";\n $email = \"a@b.c\";\n $age = \"193\";\n $x = \"s\";\n $y = \"s\";\n\n # select data that needs validation\n $validate = array(\n 'required' => array($name, $email, $x, $y),\n 'validEmail' => array($email),\n 'validNumber' => array($age),\n 'validAlpha' => array($name)\n );\n\n # error messages\n $errorsMsgs = array(\n 'required' => 'Please fill out all required fields.',\n 'validEmail' => 'is an invalid email address.',\n 'validNumber' => 'is an invalid number.',\n 'validAlpha' => 'contains invalid characters. This field only accepts letters and spaces.'\n );\n\n $errorMarkup = \"<h1>We found a few errors :-(</h1><h2>Please fix these errors and try again</h2><ol>\";\n $successMarkup = \"<h1>Success!</h1><h2>Your form was sent successfully.</h2>\";\n $backMarkup = \"<a href=\\\"\" . $_SERVER['HTTP_REFERER'] . \"\\\">Back to form</a>\";\n\n # begin state\n $valid = true;\n\n # loop through fields of error types\n foreach ($validate as $type => $fields) {\n # loop through values of fields to be tested\n foreach ($fields as $value) {\n # throw error if value is required and not entered\n if ($type === 'required' && strlen($value) === 0) {\n $errorMarkup .= \"<li>$errorsMsgs[$type]</li>\";\n $valid = false;\n break;\n }\n else if (\n $type === 'validEmail' && !filter_var($value, FILTER_VALIDATE_EMAIL) ||\n $type === 'validNumber' && !preg_match('/^[0-9 ]+$/', $value) ||\n $type === 'validAlpha' && !preg_match('/^[a-zA-Z ]+$/', $value)\n ) {\n if (strlen($value) === 0) {break;} # skip check if value is not entered\n $errorMarkup .= \"<li>\\\"$value\\\" $errorsMsgs[$type]</li>\";\n $valid = false;\n continue;\n }\n }\n }\n\n if ($valid) {\n # email form\n $body = $successMarkup . $backMarkup;\n $title = \"Form sent\";\n } else {\n $body = $errorMarkup . \"</ol>\" . $backMarkup;\n $title = \"Form errors\";\n }\n\n # write html ouput\n echo \"<!DOCTYPE html><head><title>$title</title><style type=\\\"text/css\\\">body{margin:100px;font:16px/1.5 sans-serif;color:#111}h1{font-size:32px;margin:0;font-weight:bold}h2{font-size:18px;margin:0 0 20px 0}ol,li{list-style-position:inside;padding-left:0;margin-left:0}</style></head><body>$body</body></html>\";\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T17:12:14.897",
"Id": "8831",
"Score": "1",
"body": "Thank you for the example kht! I was hoping to stick to the approach I've taken since it works well with everything I've got so far. But it's good to have a working alternative! +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T16:09:34.140",
"Id": "5835",
"ParentId": "5830",
"Score": "3"
}
},
{
"body": "<p>I'd do the following:</p>\n\n<pre><code>function checkEmail($errors, $email) {\n $regex_email = \"/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,5}$/\";\n if (!preg_match($regex_email, $email)) {\n array_push($errors, \"The format of that Email Address is invalid\");\n array_push($solutions, \"Please go back and <a ...>try again</a>\");\n }\n return array($errors, $solution);\n}\n\n$errors = array();\n$solutions = array();\nlist ($errors, $solutions) = checkEmail($errors, $solutions, $email);\n// ...\n\nif (count($errors) > 0) {\n // TODO: print the errors\n}\n</code></pre>\n\n<p>Consider declaring the <code>$regex_mail</code> variable inside the <code>checkEmail</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T10:52:16.413",
"Id": "8853",
"Score": "0",
"body": "I'm not at my computer with all my files to test this out, but from reading it, would that list ALL the errors or just the first one it detects? I was hoping to just display the first error it says, rather than a big list, but I'm sure I can figure that out with something. Thanks for the heads up on the position of the regex variables declarations too! If I get it working I'll be back to mark it as top answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T22:39:19.523",
"Id": "5841",
"ParentId": "5830",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5841",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T11:34:31.247",
"Id": "5830",
"Score": "3",
"Tags": [
"php",
"array",
"form"
],
"Title": "PHP Validation with functions and list()"
}
|
5830
|
<p>This is a switch statement in JavaScript. I have a feeling that it can be done in a shorter way.</p>
<pre><code>switch(n.length){
case 1:
n = '00000' + n;
break;
case 2:
n = '0000' + n;
break;
case 3:
n = '000' + n;
break;
case 4:
n = '00' + n;
break;
case 5:
n = '0' + n;
break;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T20:00:28.267",
"Id": "8838",
"Score": "0",
"body": "I'm curious what this is being used for. It's pretty non-general."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T23:57:59.993",
"Id": "8845",
"Score": "0",
"body": "@HackSaw I believe it's used for left-padding a number. There's a better padding function out there as well: [click me](http://sajjadhossain.com/2008/10/31/javascript-string-trimming-and-padding/)"
}
] |
[
{
"body": "<pre><code>function foobar(n)\n{\n var zeroes = \"000000\";\n return zeroes.substr(n.length) + n.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T12:42:38.127",
"Id": "8820",
"Score": "0",
"body": "ps: there's a small error in the code, it should be: `zeroes.substr(n.length) + n.toString();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T13:07:23.597",
"Id": "8823",
"Score": "0",
"body": "Then why you don't use n.length in your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T13:12:14.603",
"Id": "8824",
"Score": "0",
"body": "lol sorry, the same mistake is in my code :) anyway thank you, I just needed the idea"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T22:53:39.543",
"Id": "8842",
"Score": "12",
"body": "You don’t need the variable. The name `zeroes` doesn’t add any meaning, so `\"000000\".substr(n.length)` is just as clear, and more succinct."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T12:29:29.603",
"Id": "5833",
"ParentId": "5831",
"Score": "22"
}
},
{
"body": "<p>Well, the value of <code>n</code> is known in each case, so you can just put it in the string:</p>\n\n<pre><code>switch(n) {\n case 1:\n n = '000001';\n break;\n case 2:\n n = '00002';\n break;\n case 3:\n n = '0003';\n break;\n case 4:\n n = '004';\n break;\n case 5:\n n = '05';\n break;\n}\n</code></pre>\n\n<p>If <code>n</code> can only have one of these values, you can use it as index in an array:</p>\n\n<pre><code>n = ['000001','00002','0003','004','05'][n - 1];\n</code></pre>\n\n<h3>Edit:</h3>\n\n<p>With the edited code (using <code>n.length</code> in the switch), it would be:</p>\n\n<pre><code>n = ['00000','0000','000','00','0'][n.length - 1] + n;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T13:16:24.570",
"Id": "5834",
"ParentId": "5831",
"Score": "7"
}
},
{
"body": "<p>It seems you're trying to implement part of the functionality of printf.\nUse one of the existing implementations, e.g. <a href=\"http://www.diveintojavascript.com/projects/javascript-sprintf\">dive.into.javascripts sprintf</a>\nto do the zero-padding:</p>\n\n<pre><code>n = sprintf(\"%06d\", n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T18:46:38.033",
"Id": "7495",
"ParentId": "5831",
"Score": "6"
}
},
{
"body": "<p>Currently the other answers do not provide a robust way of doing this. They either use magic numbers or create long strings of zeroes manually. So I am adding this answer as a reference for anyone visiting this question in the future.</p>\n\n<p>We can create the padding by joining an empty array together. I have provided two options: straight code or a function for reuse.</p>\n\n<p>Straight Code:</p>\n\n<pre><code>var desiredLength = 6;\n\nif (n.length < desiredLength) {\n n = Array(desiredLength - n.length + 1).join(\"0\") + n;\n}\n</code></pre>\n\n<p>Function:</p>\n\n<pre><code>function padTo(length, str, ch) {\n if (str.length < length) {\n return Array(length - str.length + 1).join(ch) + str;\n }\n\n return str;\n} \n\n// Usage\npadTo(6, \"3\", \"0\")); // 000003\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T04:37:16.830",
"Id": "8643",
"ParentId": "5831",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5833",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T11:58:14.513",
"Id": "5831",
"Score": "8",
"Tags": [
"javascript",
"formatting"
],
"Title": "Zero-padding a number to have six digits"
}
|
5831
|
<p>How can I write this shorter?</p>
<pre><code>$('#pietra_svg #p1_4 polygon#p1').click(function() {
$('#apla_p1').fadeIn("slow");
return false;
});
$('#pietra_svg #p1_4 polygon#p2').click(function() {
$('#apla_p2').fadeIn("slow");
return false;
});
$('#pietra_svg #p1_4 polygon#p3').click(function() {
$('#apla_p3').fadeIn("slow");
return false;
});
$('#pietra_svg #p1_4 polygon#p4').click(function() {
$('#apla_p4').fadeIn("slow");
return false;
});
$('#pietra_svg #p5 polygon#a').click(function() {
$('#apla_p5').fadeIn("slow");
return false;
});
$('#pietra_svg #p5 polygon#b').click(function() {
$('#apla_p5').fadeIn("slow");
return false;
});
$('.close').click(function() {
$('.apla').fadeOut("slow");
return false;
});
</code></pre>
|
[] |
[
{
"body": "<p>You can use an array in a similar way here. Just leave the last one, as it doesn't fit the same pattern.</p>\n\n<pre><code>$.each(\n [\n { poly: 'p1', id: '#apla_p1' },\n { poly: 'p2', id: '#apla_p2' },\n { poly: 'p3', id: '#apla_p3' },\n { poly: 'p4', id: '#apla_p4' },\n { poly: 'a', id: '#apla_p5' },\n { poly: 'b', id: '#apla_p5' }\n ],\n function(o){\n var id = o.id; // copy to closure\n $('#pietra_svg #p1_4 polygon#' + o.poly).click(function() {\n $(id).fadeIn(\"slow\");\n return false;\n });\n }\n);\n\n$('.close').click(function() {\n $('.apla').fadeOut(\"slow\");\n return false;\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T14:55:56.650",
"Id": "5852",
"ParentId": "5848",
"Score": "3"
}
},
{
"body": "<p>There are lots of id's you shouldn't use, if #p1 is unique (as it should), <code>$('#p1')</code> should be the same as <code>$('#pietra_svg #p1_4 polygon#p1')</code>. You should try to <strong>review your svg tags</strong>,</p>\n\n<p>You can also <strong>cache the root of the query</strong>, saving a lot of time searching the dom:</p>\n\n<pre><code>var pietra = $('#pietra_svg')\n</code></pre>\n\n<p>and then </p>\n\n<pre><code>pietra.find('#p1_4 polygon#p1')\n</code></pre>\n\n<p>Also, for the first four elements you may <strong>bind them once</strong>, and with the clicked element id, find element to fade:</p>\n\n<pre><code>pietra.find('#p1_4 polygon').click(function() {\n $('#apla_' + this.id).fadeIn(\"slow\");\n return false;\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T14:52:52.833",
"Id": "57687",
"ParentId": "5848",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "5852",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T13:58:38.320",
"Id": "5848",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"event-handling"
],
"Title": "Click handlers for SVG polygons"
}
|
5848
|
<p>This is a sample exercise tutorial that would be used to test understanding of how simple classes communicate/message and are designed.</p>
<p>Tester class</p>
<pre><code>public class GuessingGameTester {
public static void main(String[] args){
//create a new game
GuessingGame g1 = new GuessingGame();
//call the start method
g1.startGame();
}
}
</code></pre>
<p>Player class</p>
<pre><code>public class GuessingGamePlayer {
boolean areTheyRight = false;
//player random guess
int getPlayerGuess(){
return (int) (Math.random()* 20);
}
}
</code></pre>
<p>Game class</p>
<pre><code>public class GuessingGame {
private int numberToGuess;
private boolean keepPlaying;
private int round;
//constructor
GuessingGame(){
//create a random number for players to guess
numberToGuess = (int) (Math.random() * 20);//cast to int
keepPlaying = true;
round = 1;
}
void startGame(){
//create 3 players to play
GuessingGamePlayer p1 = new GuessingGamePlayer();
GuessingGamePlayer p2 = new GuessingGamePlayer();
GuessingGamePlayer p3 = new GuessingGamePlayer();
System.out.println("The number to guess is : " + numberToGuess);
//giving 100 attemps for the computer to guess the correct number
while(keepPlaying && round <= 100){
//get their guess
int p1guess = p1.getPlayerGuess();
int p2guess = p2.getPlayerGuess();
int p3guess = p3.getPlayerGuess();
System.out.println("round " + round);
System.out.println("p1 guessed: " + p1guess);
System.out.println("p2 guessed: " + p2guess);
System.out.println("p3 guessed: " + p3guess);
System.out.println("\n");
if(p1guess == numberToGuess){
p1.areTheyRight = true;
keepPlaying = false;
}else if(p2guess == numberToGuess){
p2.areTheyRight = true;
keepPlaying = false;
}else if(p3guess == numberToGuess){
p3.areTheyRight = true;
keepPlaying = false;
}
round ++;
}//end while
//game over - echo who guessed the correct num and the round
System.out.println("\n");
if(p1.areTheyRight){
System.out.println("p1 guessed the correct number during round " + round);
}else if(p2.areTheyRight){
System.out.println("p2 guessed the correct number during round " + round);
}else{
System.out.println("p3 guessed the correct number during round " + round);
}
}//end startGame
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T18:04:45.767",
"Id": "8895",
"Score": "1",
"body": "So is this for a tutorial you're writing and you want to make sure new programmers should understand it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T05:24:55.207",
"Id": "9109",
"Score": "0",
"body": "Or this a cleverly worded homework problem :) (kidding)"
}
] |
[
{
"body": "<p>A couple observations:</p>\n\n<ol>\n<li>If none of them guess the number before the number of rounds runs out, you will print that p3 guessed in round 101.</li>\n<li>If more than one guessed correctly in the last round, you'll only credit one of them.</li>\n<li>I see no reason to keep instance variables, especially for <code>keepPlaying</code>, it will prevent the game from being played properly if started a second time unless no one guessed the first game.</li>\n<li>At the end you print 2 blank lines (3 newlines: one with \"p3 guessed...\", one because of the \"\\n\", and one because that last is a <code>println</code>, not a <code>print</code> or <code>printf</code>. I think that's a bit excessive.</li>\n</ol>\n\n<p>Perhaps you could use instance variables to set the maximum number instead of 20 (as a magic number), and pass the number of rounds to play as an argument to the <code>startGame</code> method. You could even, once you get more advanced, change it to pass in the players as an array, and then add in subclasses with different methods of guessing. You could also return the number/index of the winner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T18:23:29.893",
"Id": "5855",
"ParentId": "5853",
"Score": "2"
}
},
{
"body": "<p>I'd add only a couple of minor things.</p>\n\n<p>The comments are more trouble than they're worth. I understand it's a tutorial, but if they're going to be in there, they should do more--right now they don't add value. Since it's a learning exercise, use those comments to teach them something, including terminology.</p>\n\n<pre><code>// Create a new GuessingGame instance to represent the current game.\n// Begin playing by calling the startGame() method.\n</code></pre>\n\n<p>But I'd leave them out altogether, and have the corresponding text/lecture do the describing; you will achieve more by writing or talking about them outside of the code.</p>\n\n<p>Secondly, I'd consider keeping the players in an array or a list. If not now, then in \"part two\". This simplifies the code conceptually, because you can directly represent \"for each player, check their guess\" in code. If not in \"part one\", then I'd at least move the guess-getting into another method--you only need to return a boolean, the players hold whether or not it's a right guess.</p>\n\n<p>(IMO the player shouldn't maintain that state, rather the game should.)</p>\n\n<p>Next, I'd refactor more; the <code>startGame</code> does more than starts the game. Either refactor, or rename. Right now, <code>startGame</code> starts, plays, and ends the game. By refactoring, the code becomes more story-like, at the cost of more methods. But good methods should be tightly focused and easy to reason about.</p>\n\n<p>On a more theoretical level, the end conditions as implemented makes a certain assumption about the nature of the game. Asking if anyone can spot a potential \"gotcha\" with the current implementation might be a good \"extra credit\" problem.</p>\n\n<p>In real life, what would happen if two players both guessed correctly? In the current implementation, the players are always checked in numerical order. In real life, a typical game would be either who guessed the fastest (which I supposed the player order could be said to represent), or multiple players could win, or...?</p>\n\n<p>To put that into \"real life\" terms, let's say the guesses are access control votes, or search result weightings, etc. In those cases, a tie <em>does</em> matter. So instead of having a single winner, there would be a collection of \"winners\". How to decide if there should be a single winner, or a group, depends on the nature of the game.</p>\n\n<p>Lastly, I'd make some of the things more configurable, although perhaps with reasonable defaults. This also mirrors real life a bit more accurately, and I tend towards adding a bit of complexity early, since it can be ignored.</p>\n\n<p>Some of my suggestions are more appropriate for a \"second round\" implementation, while some make sense for what you have now. Pick and choose, or ignore them all :) I've appended everything in a single blob.</p>\n\n<pre><code>public class GuessingGameTester {\n\n public static void main(String[] args){\n GuessingGame game = new GuessingGame();\n game.startGame();\n }\n\n}\n\n\npublic class GuessingGamePlayer {\n\n private int playerNumber;\n\n public GuessingGamePlayer(int playerNumber) {\n this.playerNumber = playerNumber;\n }\n\n int getGuess(){\n return new Random().nextInt(GuessingGame.MAX_GUESSING_NUMBER) + 1;\n }\n\n @Override\n public String toString() {\n return \"Player \" + playerNumber;\n }\n\n}\n\n\npublic class GuessingGame {\n\n private int numberToGuess;\n private int roundsToPlay;\n private int numberOfPlayers;\n private List<GuessingGamePlayer> players;\n\n public static int MAX_GUESSING_NUMBER = 20;\n\n public GuessingGame() {\n init(100, 3);\n }\n\n public GuessingGame(int roundsToPlay, int numberOfPlayers) {\n init(roundsToPlay, numberOfPlayers);\n }\n\n public void init(int numberOfRounds, int numberOfPlayers) {\n this.roundsToPlay = numberOfRounds;\n this.numberOfPlayers = numberOfPlayers;\n\n numberToGuess = new Random().nextInt(MAX_GUESSING_NUMBER) + 1;\n\n initPlayers();\n }\n\n public void initPlayers() {\n players = new ArrayList<GuessingGamePlayer>();\n for (int i = 0; i < numberOfPlayers; i++) {\n players.add(new GuessingGamePlayer(i+1));\n }\n }\n\n public void startGame() {\n int currentRound = 0;\n GuessingGamePlayer correctGuesser = null;\n System.out.println(\"The number to guess is: \" + numberToGuess);\n\n while((correctGuesser == null) && (currentRound <= roundsToPlay)) {\n ++currentRound;\n System.out.println(\"\\nRound \" + currentRound);\n\n for (GuessingGamePlayer player : players) {\n int playerGuess = player.getGuess();\n System.out.println(\" \" + player + \" guessed \" + playerGuess);\n if (playerGuess == numberToGuess) {\n correctGuesser = player;\n }\n }\n }\n\n System.out.println();\n\n if (correctGuesser == null) {\n System.out.println(\"Nobody guessed the right number!\");\n } else {\n System.out.println(correctGuesser + \" guessed the number in round \" + currentRound);\n }\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:56:13.653",
"Id": "8969",
"Score": "0",
"body": "thanks for thoughtful articulation. Most of your recommendations will be used in the next version. A lot of what you suggest, has not been presented yet, so I cant use in this example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:54:43.360",
"Id": "8977",
"Score": "0",
"body": "specifically, at this point, I have not yet presented imports, constructors, lists, arrays, parameters/arguments. The primary goal of the tutorial is to demo simple class construction with a hopefully interesting example. I do like how you made it configurable and refactored the startGame() method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:57:19.287",
"Id": "8979",
"Score": "0",
"body": "@jamesTheProgrammer Well, you already have a constructor, so it's too late ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T19:20:49.653",
"Id": "9004",
"Score": "0",
"body": "guilty...I'll try to sneak that one by"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T19:22:11.170",
"Id": "9005",
"Score": "0",
"body": "@jamesTheProgrammer \"Pay no attention to this code for now\" usually works. Just try explaining what `public static void main(String[] args)` means :/ I just hold off and say \"assume magic for now; we'll get there.\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:23:34.833",
"Id": "5859",
"ParentId": "5853",
"Score": "4"
}
},
{
"body": "<p>Ive updated the classes based on feedback. Some of the good feedback can't be used in this example, because the content has not been presented. Here is the revised code: block.</p>\n\n<pre><code>public class GuessingGameTester {\n\n public static void main(String[] args){\n //create a new game object\n GuessingGame game = new GuessingGame();\n //call the startGame method on the game object\n game.startGame(); \n } \n}\n\n\npublic class GuessingGamePlayer {\n\n GuessingGamePlayer(){};\n boolean areTheyRight = false;\n\n //player random guess\n int getPlayerGuess(){\n return (int) (Math.random()* 15); \n }\n}\n\n\npublic class GuessingGame {\n\n private int numberToGuess;\n private boolean keepPlaying;\n private int round;\n\n //create 3 player objects\n private GuessingGamePlayer p1 = new GuessingGamePlayer();\n private GuessingGamePlayer p2 = new GuessingGamePlayer();\n private GuessingGamePlayer p3 = new GuessingGamePlayer();\n\n private int player1Guess;\n private int player2Guess;\n private int player3Guess;\n\n //constructor\n GuessingGame(){\n //return the players random guess\n numberToGuess = (int) (Math.random() * 15);//cast to int, random function returns double \n round = 1;\n }\n\n void startGame(){\n keepPlaying = true;\n System.out.println(\"The number to guess is : \" + numberToGuess);\n displayGuesses();\n displayGameEndingInfo(); \n }//end startGame\n\n void displayGuesses(){\n // 20 attemps for the computer to guess the correct number\n while(keepPlaying && round <= 20){\n\n getPlayerGuesses();\n\n System.out.println(\"Round \" + round);\n System.out.println(\"Player 1 guessed: \" + player1Guess);\n System.out.println(\"Player 2 guessed: \" + player2Guess);\n System.out.println(\"Player 3 guessed: \" + player3Guess);\n\n System.out.println(\"\\n\");\n\n if(player1Guess == numberToGuess){\n p1.areTheyRight = true;\n keepPlaying = false;\n break;\n }else if(player2Guess == numberToGuess){\n p2.areTheyRight = true;\n keepPlaying = false;\n break;\n }else if(player3Guess == numberToGuess){\n p3.areTheyRight = true;\n keepPlaying = false;\n break;\n }\n\n round ++;\n }//end while\n }//end displayGuesses\n\n void getPlayerGuesses(){\n //get the guess from each player object and assign to pxguess variable\n player1Guess = p1.getPlayerGuess();\n player2Guess = p2.getPlayerGuess();\n player3Guess = p3.getPlayerGuess();\n }\n\n void displayGameEndingInfo(){\n //game over - echo who guessed the correct num and the round\n System.out.println(\"\\n\");\n if(p1.areTheyRight){\n System.out.println(\"p1 guessed the correct number during round \" + round); \n }else if(p2.areTheyRight){\n System.out.println(\"p2 guessed the correct number during round \" + round); \n }else{\n System.out.println(\"p3 guessed the correct number during round \" + round); \n }\n }//end displayGameEndingInfo\n\n }//end class GuessingGame\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T20:40:36.327",
"Id": "5903",
"ParentId": "5853",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "5859",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T17:23:01.230",
"Id": "5853",
"Score": "3",
"Tags": [
"java",
"number-guessing-game"
],
"Title": "Three-player number-guessing game"
}
|
5853
|
<p>This is my first attempt ever to build a <code>Vector2</code> class. I scoured the net for anything that might make this class more efficient but know I'm to the point where I'm ready to share. This way I can get advice on how I can improve it further. I wanted to do this before I make my <code>Vector3</code> and <code>Vector4</code> class.</p>
<p><strong>Vector2.h</strong></p>
<pre><code>//VECTOR2 H
#ifndef VECTOR2_H
#define VECTOR2_H
//INCLUDES
#include <math.h>
//DEFINE TYPES
typedef float float32;
//VECTOR2 CLASS
class Vector2
{
public:
//MEMBERS
float32 x;
float32 y;
//CONSTRUCTORS
Vector2(void);
Vector2(float32 xValue, float32 yValue);
Vector2(const Vector2 & v);
Vector2(const Vector2 * v);
//DECONSTRUCTOR
~Vector2(void);
//METHODS
void Set(float32 xValue, float32 yValue);
float32 Length() const;
float32 LengthSquared() const;
float32 Distance(const Vector2 & v) const;
float32 DistanceSquared(const Vector2 & v) const;
float32 Dot(const Vector2 & v) const;
float32 Cross(const Vector2 & v) const;
Vector2 & Normal();
Vector2 & Normalize();
//ASSINGMENT AND EQUALITY OPERATIONS
inline Vector2 & Vector2::operator = (const Vector2 & v) { x = v.x; y = v.y; return *this; }
inline Vector2 & Vector2::operator = (const float32 & f) { x = f; y = f; return *this; }
inline Vector2 & Vector2::operator - (void) { x = -x; y = -y; return *this; }
inline bool Vector2::operator == (const Vector2 & v) const { return (x == v.x) && (y == v.y); }
inline bool Vector2::operator != (const Vector2 & v) const { return (x != v.x) || (y != v.y); }
//VECTOR2 TO VECTOR2 OPERATIONS
inline const Vector2 Vector2::operator + (const Vector2 & v) const { return Vector2(x + v.x, y + v.y); }
inline const Vector2 Vector2::operator - (const Vector2 & v) const { return Vector2(x - v.x, y - v.y); }
inline const Vector2 Vector2::operator * (const Vector2 & v) const { return Vector2(x * v.x, y * v.y); }
inline const Vector2 Vector2::operator / (const Vector2 & v) const { return Vector2(x / v.x, y / v.y); }
//VECTOR2 TO THIS OPERATIONS
inline Vector2 & Vector2::operator += (const Vector2 & v) { x += v.x; y += v.y; return *this; }
inline Vector2 & Vector2::operator -= (const Vector2 & v) { x -= v.x; y -= v.y; return *this; }
inline Vector2 & Vector2::operator *= (const Vector2 & v) { x *= v.x; y *= v.y; return *this; }
inline Vector2 & Vector2::operator /= (const Vector2 & v) { x /= v.x; y /= v.y; return *this; }
//SCALER TO VECTOR2 OPERATIONS
inline const Vector2 Vector2::operator + (float32 v) const { return Vector2(x + v, y + v); }
inline const Vector2 Vector2::operator - (float32 v) const { return Vector2(x - v, y - v); }
inline const Vector2 Vector2::operator * (float32 v) const { return Vector2(x * v, y * v); }
inline const Vector2 Vector2::operator / (float32 v) const { return Vector2(x / v, y / v); }
//SCALER TO THIS OPERATIONS
inline Vector2 & Vector2::operator += (float32 v) { x += v; y += v; return *this; }
inline Vector2 & Vector2::operator -= (float32 v) { x -= v; y -= v; return *this; }
inline Vector2 & Vector2::operator *= (float32 v) { x *= v; y *= v; return *this; }
inline Vector2 & Vector2::operator /= (float32 v) { x /= v; y /= v; return *this; }
};
#endif
//ENDFILE
</code></pre>
<p><strong>Vector2.cpp</strong></p>
<pre><code>//VECTOR2 CPP
#include "Vector2.h"
//CONSTRUCTORS
Vector2::Vector2(void) : x(0), y(0) { }
Vector2::Vector2(float32 xValue, float32 yValue) : x(xValue), y(yValue) { }
Vector2::Vector2(const Vector2 & v) : x(v.x), y(v.y) { }
Vector2::Vector2(const Vector2 * v) : x(v->x), y(v->y) { }
//DECONSTRUCTOR
Vector2::~Vector2(void) { }
//METHODS
void Vector2::Set(float32 xValue, float32 yValue) { x = xValue; y = yValue; }
float32 Vector2::Length() const { return sqrt(x * x + y * y); }
float32 Vector2::LengthSquared() const { return x * x + y * y; }
float32 Vector2::Distance(const Vector2 & v) const { return sqrt(((x - v.x) * (x - v.x)) + ((y - v.y) * (y - v.y))); }
float32 Vector2::DistanceSquared(const Vector2 & v) const { return ((x - v.x) * (x - v.x)) + ((y - v.y) * (y - v.y)); }
float32 Vector2::Dot(const Vector2 & v) const { return x * v.x + y * v.y; }
float32 Vector2::Cross(const Vector2 & v) const { return x * v.y + y * v.x; }
Vector2 & Vector2::Normal() { Set(-y, x); return *this; }
Vector2 & Vector2::Normalize()
{
if(Length() != 0)
{
float32 length = LengthSquared();
x /= length; y /= length;
return *this;
}
x = y = 0;
return *this;
}
//ENDFILE
</code></pre>
<p><strong>First Edit:</strong></p>
<p>Changed <code>Cross</code> to <code>OrthoVector</code>:</p>
<pre><code>Vector2 & Vector2::Ortho() { Set(-y, x); return *this; }
</code></pre>
<p>Changed <code>Normal</code> code to actually get the normal of the vector:</p>
<pre><code>Vector2 & Vector2::Normal() { float32 len = Length(); Set(x / len, y / len); return *this; }
</code></pre>
<p><strong>Second Edit:</strong></p>
<p>Changed the normal code again to check for division by zero:</p>
<pre><code>Vector2 & Vector2::Normal()
{
if(Length() != 0)
{
float32 len = Length();
x /= len; y /= len;
return *this;
}
x = y = 0;
return *this;
}
</code></pre>
<p>Got rid of my Pointer Constructor and my Empty Deconstructor as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:08:23.630",
"Id": "8903",
"Score": "0",
"body": "Cross product is meaningless in the context that you have created it in for 2d vectors. If you are going for the orthogonal vector, it is simply \"(x, y) -> (y, -x)\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:11:38.250",
"Id": "8904",
"Score": "0",
"body": "Define \"better\". Do you want fast? Usable? Safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:27:27.513",
"Id": "8905",
"Score": "0",
"body": "faster and more usable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T19:50:28.680",
"Id": "88465",
"Score": "0",
"body": "Note that revising the code in the question, even as an addendum, is [no longer accepted practice on Code Review](http://meta.codereview.stackexchange.com/q/1763). However, since this is an old question, we'll let it stand."
}
] |
[
{
"body": "<p>Cross product is meaningless in the context that you have created it in for 2d vectors. If you are going for the orthogonal vector, it is simply \"(x, y) -> (y, -x)\".</p>\n\n<p>Your \"Normal\" function is actually returning the orthogonal vector. \"Normal\" is vectorland means \"Vector of unit length in the same direction\".</p>\n\n<p>To calculate the real normal, it is</p>\n\n<pre><code> ai + bj double mag = sqrt((a*a) + (b*b));\n----------- or Vector2 normal(a / mag, b / mag);\n| ai + bj |\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:32:35.447",
"Id": "8907",
"Score": "0",
"body": "That's what I thought, I read otherwise something else somewhere that confused me. I will be changing the Normal code and get rid of CrossProduct. I will also make a snippet for the OrthogonalVector."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:11:46.993",
"Id": "5857",
"ParentId": "5856",
"Score": "1"
}
},
{
"body": "<p>Vector is a relatively common name (as is vector 2/3 etc). So you may need to make your include guards a bit more unique. I always put my stuff into my own namespace (which happens to match a domain I own to make things unique). I then include the namespace as part of the include guard. Alternatively you can generate a GUID that will also make sure it is unique.</p>\n\n<pre><code>//VECTOR2 H\n#ifndef VECTOR2_H\n#define VECTOR2_H\n</code></pre>\n\n<p>Mine would look like:</p>\n\n<pre><code>#ifndef BOBS_DOMAIN_VECTOR_2_H\n#define BOBS_DOMAIN_VECTOR_2_H\n\nnamespace BobsDomain {\n</code></pre>\n\n<p>Is it valid to create a Vector 2 with zero values? If so does that mean x/y default to 0.0 in which case the following 2</p>\n\n<pre><code>Vector2(void);\nVector2(float32 xValue, float32 yValue);\n</code></pre>\n\n<p>Could be redefined as (Though then it is possible to create a Vector2 with a single value (which may not be desirable).</p>\n\n<pre><code>Vector2(float32 xValue = 0.0, float32 yValue = 0.0);\n</code></pre>\n\n<p>Does your default copy constructor do anything special?</p>\n\n<pre><code>Vector2(const Vector2 & v);\n</code></pre>\n\n<p>If not then I would let the compiler generated version by the one you use.</p>\n\n<p>Not sure you want to be able to construct from a pointer. Very few classes allow this (apart from samart pointers). Does this mean you are taking ownership of the pointer or you will just make a copy of the vector.</p>\n\n<pre><code>Vector2(const Vector2 * v);\n</code></pre>\n\n<p>I would drop this constructor.<br>\nThen the following code</p>\n\n<pre><code>Vector2* data = /* Get Vector2 */;\nVector2 copy(data);\n</code></pre>\n\n<p>Has to be modified like this (not a major change).</p>\n\n<pre><code>Vector2* data = /* Get Vector2 */;\nVector2 copy(*data); // Notice the extra star.\n // But this is not a big cost and simplifies the interface\n // considerably as we do not need to wory about ownership\n // semantics.\n</code></pre>\n\n<p>Don't put the void when you have an empty parameter list.<br>\nAlso if the destructor does not do anything then use the compiler generated version.</p>\n\n<pre><code>~Vector2(void);\n</code></pre>\n\n<p>Why do you have set method when the members are public.</p>\n\n<pre><code>void Set(float32 xValue, float32 yValue);\n</code></pre>\n\n<p>All operators that have an assignment version are easier to define if you define them in terms of the assignment operator. It keeps the meaning consistent.</p>\n\n<p>What I mean is: operator+ is easy to define in terms of operator+=</p>\n\n<pre><code>Vector2 const operator+ (Vector2 const& rhs) const {Vector2 result(*this); return result += rhs;}\nVector2& operator+=(Vector2 const& rhs) {x += v.x; y += v.y; return *this;}\n</code></pre>\n\n<p>Since we are defining all the other operators you may want to define the comparison operator.</p>\n\n<pre><code>bool operator<(Vector const& rhs) {return (x < rhs.x) || ((x == rhs.x) && (y < rhs.y));}\n</code></pre>\n\n<p>Now you can use the Vector2 as the key in a std::map.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:53:55.013",
"Id": "8937",
"Score": "0",
"body": "I will defiantly be taking you up on the unique namespace tip. I kept the void and set constructors for the very reason you listed above. I will keep my © constructor the same but will get rid of the pointer constructor because it is your right its virtually the same as the © version. I will get rid of the deconstructor. I made the set method to make my easier. I forgot about those operators and will be adding them in. Wow thanks for all the advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T23:03:47.890",
"Id": "8938",
"Score": "0",
"body": "Also I created my operator+ that way so you cant do this: (a + b) = c;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T00:36:03.077",
"Id": "8947",
"Score": "0",
"body": "@Liquid Wotter: Fixed my version of +=. I was typing quickly this morning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-06T12:34:34.560",
"Id": "175178",
"Score": "0",
"body": "@LokiAstari, where is Unit-vector implementation? How to do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-06T15:40:37.113",
"Id": "175210",
"Score": "0",
"body": "@BROY: Do you mean `std::vector`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-06T16:01:46.903",
"Id": "175222",
"Score": "0",
"body": "@LokiAstari, no. v = ai + bj + ck.......???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-06T17:20:50.883",
"Id": "175246",
"Score": "0",
"body": "@BROY: I have no idea what you are talking about now."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:31:58.473",
"Id": "5862",
"ParentId": "5856",
"Score": "6"
}
},
{
"body": "<p>One fundamental property of vectors you haven't represented: a scalar times a vector is a vector.</p>\n\n<p>I wouldn't actually implement your vector * vector and vector / vector operations at all ... those are not commonly useful.</p>\n\n<p>Actually there is a meaningful cross product in two dimensions, but the return value is a scalar, not a vector.</p>\n\n<pre><code>float32 Cross(const Vector2& a, const Vector2& b) {\n return a.x * b.y - a.y * b.x;\n}\n</code></pre>\n\n<p>This brings up another point: I prefer free functions to member functions when the meaning is roughly symmetric in two variables, like <code>Dot</code>, <code>Cross</code>, or even <code>operator+</code>. Besides aesthetics, there's the fact that <code>operator+(const X& a, const Y& b)</code> can use implicit conversions on both operands but <code>X::operator+(const Y& b) const</code> can only use implicit conversions on <code>b</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T00:18:11.220",
"Id": "5877",
"ParentId": "5856",
"Score": "1"
}
},
{
"body": "<p><strong>Provide alternatives to methods returning copies.</strong></p>\n\n<p>On such classes, I usually defines a setAdd and setSub method that fill the current vector with the result of an addition (resp subtraction).</p>\n\n<pre><code>void setAdd(const Vector2& v1, const Vector2& v2)\n{\n x = v1.x + v2.x;\n y = v1.y + v2.y;\n}\n</code></pre>\n\n<p>using this kind of method in place of <code>operator+</code> spare a Vector2 copy. In certain cases this as a visible impact on code performance (see Havok Physics math lib).</p>\n\n<p><strong>Handle more use cases in normalize</strong></p>\n\n<p>When normalizing a vector you often do further computation using its previous norm, and you often need to set it to a desired norm. It's easy to modify the <code>Normalize</code> method for those use cases.</p>\n\n<pre><code>float32 Vector2::Normalize(float32 desiredNorm = 1.f)\n{\n float32 len = Length();\n if(len < EPSILON)\n {\n x = y = 0.f;\n return 0.f;\n }\n else\n {\n float32 mult = desiredNorm/len;\n x *= mult; y *= mult;\n return len;\n }\n }\n</code></pre>\n\n<p>NB. I have also make the following changes:</p>\n\n<ul>\n<li>Only one computation of <code>Length()</code>, square root computation are expensive.</li>\n<li>Use a less-than-epsilon instead of a different-to-0 which can lead to various problem because of floating point precision, the value of EPSILON should be small (0.00001 for example).</li>\n</ul>\n\n<p><strong>Provide a truncate method</strong></p>\n\n<p>I've found this very usefull to define a truncate method that enforce an upper-bound on the vector's norm.</p>\n\n<pre><code>void Truncate(float32 upperBound)\n{\n float32 sqrLen = SqrLength();\n if(sqrLen > upperBound * upperBound)\n {\n float32 mult = upperBound/sqrt(sqrLen);\n x *= mult; y *= mult;\n }\n}\n</code></pre>\n\n<p>NB.</p>\n\n<ul>\n<li>You should probably assert that upperBound is positive.</li>\n<li>Again I'm trying to minimize the number of square root computed.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-05T14:40:38.657",
"Id": "6556",
"ParentId": "5856",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T21:42:09.950",
"Id": "5856",
"Score": "6",
"Tags": [
"c++",
"computational-geometry"
],
"Title": "Mathematical Vector2 class implementation"
}
|
5856
|
<p>Should take an array such as <code>['dog', 'cat', 'bird', 'monkey']</code> and return <code>'dog, cat, bird and monkey'</code>.</p>
<p>Looking for a more elegant solution.</p>
<pre><code>def self.english_join(array)
return nil if array.nil?
return array[0] if array.length == 1
return array[0..-2].join(', ') + " and " + array[-1] if array.length > 1
end
</code></pre>
|
[] |
[
{
"body": "<pre><code>def self.english_join(array = nil)\n return array.to_s if array.nil? or array.length <= 1\n array[-1] = \"and #{array[-1]}\"\n array.join(', ')\nend\n</code></pre>\n\n<p>A different way but not much better. Returns an empty string instead of <code>nil</code> if the array is empty. Someone will chime in with a sweet <code>to_sentence</code> method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T23:13:02.487",
"Id": "5874",
"ParentId": "5863",
"Score": "2"
}
},
{
"body": "<pre><code>def english_join(array = nil)\n return array.to_s if array.nil? or array.length <= 1\n array[0..-2].join(\", \") + \" and \" + array[-1]\nend\n</code></pre>\n\n<p>A similar but different approach. Combines the joining of a slice of the array with a string append to get the last \"and\" part.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T16:13:36.900",
"Id": "9079",
"Score": "3",
"body": "However, it might be better to write the last line as `\"#{array[0..-2].join(\", \")} and #{array.last}\"`. `\"#{}\"` creates fewer String objects than `+`, and so should generally be preferred."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T16:14:07.630",
"Id": "9080",
"Score": "2",
"body": "Also, this doesn't get the comma before the \"and\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T23:37:29.810",
"Id": "5876",
"ParentId": "5863",
"Score": "5"
}
},
{
"body": "<p>Rails (actually ActiveSupport, part of the Rails framework) offers a very nice <a href=\"https://github.com/rails/rails/blob/v3.1.1/activesupport/lib/active_support/core_ext/array/conversions.rb#L11-35\"><code>Array#to_sentence</code> method</a>.</p>\n\n<p>If you are using Rails or ActiveSupport, you can call</p>\n\n<pre><code>['dog', 'cat', 'bird', 'monkey'].to_sentence\n# => \"dog, cat, bird, and monkey\"\n</code></pre>\n\n<p>The method is automatically customized according to I18n settings. For example, in Italy you should omit the last comma before the <code>and</code>.</p>\n\n<pre><code>['dog', 'cat', 'bird', 'monkey'].to_sentence\n# => \"dog, cat, bird e monkey\"\n</code></pre>\n\n<p>If you want something without depending on <code>ActiveSupport</code>, you can start using the method source code. </p>\n\n<p>This is just an example</p>\n\n<pre><code>class Array\n def to_sentence\n default_words_connector = \", \"\n default_two_words_connector = \" and \"\n default_last_word_connector = \", and \"\n\n case length\n when 0\n \"\"\n when 1\n self[0].to_s.dup\n when 2\n \"#{self[0]}#{options[:two_words_connector]}#{self[1]}\"\n else\n \"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}\"\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-09T15:52:49.337",
"Id": "99688",
"Score": "0",
"body": "`.to_sentence` is literally magic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T23:26:09.413",
"Id": "424160",
"Score": "0",
"body": "You've forgotten to add a `options` parameter to the method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T22:52:38.567",
"Id": "514301",
"Score": "0",
"body": "This is how I discovered `.to_sentence` and oh my goodness, this made my whole day."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T13:52:22.667",
"Id": "5890",
"ParentId": "5863",
"Score": "28"
}
}
] |
{
"AcceptedAnswerId": "5890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:49:42.143",
"Id": "5863",
"Score": "15",
"Tags": [
"ruby"
],
"Title": "Ruby function to join array with commas and a conjunction"
}
|
5863
|
<p>After taking into account answers for my questions <a href="https://stackoverflow.com/questions/4522931/is-this-xor-based-encryption-function-safe">here</a> and <a href="https://stackoverflow.com/questions/4587863/is-this-encryption-function-safe">here</a> I created (well may-be) improved version of my wrapper. The key issue was what if an attacker is knowing what is encoded - he might then find the key and encode another messages. So I added XOR before encryption. I also in this version prepend IV to the data as was suggested.</p>
<p>SHA256 on key is only for making sure the key is as long as needed for the AES algorithm, but I know that key should not be plain text but calculated with many iterations to prevent dictionary attack</p>
<pre><code>function aes192ctr_en($data,$key) {
$iv = mcrypt_create_iv(24,MCRYPT_DEV_URANDOM);
$xor = mcrypt_create_iv(24,MCRYPT_DEV_URANDOM);
$key = hash_hmac('sha256',$key,$iv,true);
$data = $xor.((string)$data ^ (string)str_repeat($xor,(strlen($data)/24)+1));
$data = hash('md5',$data,true).$data;
return $iv.mcrypt_encrypt('rijndael-192',$key,$data,'ctr',$iv);
}
function aes192ctr_de($data,$key) {
$iv = substr($data,0,24);
$data = substr($data,24);
$key = hash_hmac('sha256',$key,$iv,true);
$data = mcrypt_decrypt('rijndael-192',$key,$data,'ctr',$iv);
$md5 = substr($data,0,16);
$data = substr($data,16);
if (hash('md5',$data,true)!==$md5) return false;
$xor = substr($data,0,24);
$data = substr($data,24);
$data = ((string)$data ^ (string)str_repeat($xor,(strlen($data)/24)+1));
return $data;
}
$encrypted = aes192ctr_en('secret text','password');
echo $encrypted;
echo aes192ctr_de($encrypted,'password');
</code></pre>
<p>Another question is: Is CTR mode is okay in this context, would it be better if I use CBC mode instead?</p>
<p>Again, by safe I mean, could an attacker derive the password if he knows which exact text was encrypted, and knows above method. I assume a random and long password here.</p>
<p>Maybe instead of XOR, will it be safer to use random initial data with another run of AES or other simpler algorithm like TEA or trivium?</p>
|
[
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-04T15:10:36.660",
"Id": "8908",
"Score": "0",
"body": "http://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords Please read this"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-04T15:20:09.063",
"Id": "8909",
"Score": "2",
"body": "consider implementing established authenticated encryption modes like CCM (http://en.wikipedia.org/wiki/CCM_mode) or EAX (http://en.wikipedia.org/wiki/EAX_mode)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-04T16:12:30.523",
"Id": "8910",
"Score": "0",
"body": "do Mcrypt or other package that is compiled into core PHP support EAX or CCM ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-05T00:34:10.917",
"Id": "8911",
"Score": "0",
"body": "See for example [RFC 5116](http://tools.ietf.org/html/rfc5116) and related."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:49:22.933",
"Id": "8912",
"Score": "0",
"body": "If your question would be worded with mathematical formulas instead of PHP (or any other) source code, it would be a good candidate for migration to [Cryptography Stack Exchange](http://crypto.stackexchange.com/), and also would likely get good answers there."
}
] |
[
{
"body": "<p>Your XOR-step is nonsense, it doesn't add any security.</p>\n\n<p>The reason is the way the CTR mode works: It encrypts a counter (thus the name) using the key (and the IV as starting point), and XORs the plaintext with the result.\nXORing the plaintext with some other constant <em>before encryption</em> can be undone by XORing it with the same value <em>after encryption</em>.</p>\n\n<p>Still, CTR mode (with or without this XOR) should be enough for protection, as long as your IV is non-repeating. To break it with some known plaintext, you basically have to brute-force encrypt the counter with different keys, until you get the same output as <code>plaintext XOR ciphertext</code> (for one block).</p>\n\n<p>Also, you are using a simple MD5 hash for integrity protection. While MD5 <em>might</em> be fine in this case, it now has the reputation of being broken (i.e. there are quite easy collision attacks), which makes it not safe. Use a MAC algorithm for integrity protection, for example with <code>hash_hmac</code> (and a strong hash function like sha256, which you used before).</p>\n\n<p>Other than that, PHP's <code>rijndael-192</code> is <em>not</em> one of the AES algorithms. AES is Rijndael with block size of 128 bits (and key sizes of 128, 192 or 256 bits), and you are using an 192-bit block size version here. (This does not necessarily mean it is less secure, you just shouldn't call it AES. It did receive less cryptoanalysis than the variant that got standardized as AES, though.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-07T22:56:28.770",
"Id": "5870",
"ParentId": "5864",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-04T14:13:25.683",
"Id": "5864",
"Score": "6",
"Tags": [
"php",
"security",
"cryptography",
"aes"
],
"Title": "AES encryption wrapper"
}
|
5864
|
<p>I learned here that it is unsafe to design encryption algorithms from scratch. Given that advice, I made a pair of encryption functions based on mcrypt:</p>
<pre><code>function aes128ctr_en($data,$key,$hmac = false) {
$key = ($hmac===false) ? hash('sha256',$key,true) : hash_hmac('sha256',$key,$hmac,true);
$data .= hash('md5',$data,true);
$iv = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
return mcrypt_encrypt('rijndael-128',$key,$data,'ctr',$iv).$iv;
}
function aes128ctr_de($data,$key,$hmac = false) {
$key = ($hmac===false) ? hash('sha256',$key,true) : hash_hmac('sha256',$key,$hmac,true);
$iv = substr($data,-16);
$data = substr($data,0,strlen($data)-16);
$data = mcrypt_decrypt('rijndael-128',$key,$data,'ctr',$iv);
$md5 = substr($data,-16);
$data = substr($data,0,strlen($data)-16);
return (hash('md5',$data,true)===$md5) ? $data : false;
}
$encrypted = aes128ctr_en('secret text','password');
echo aes128ctr_de($encrypted,'password');
</code></pre>
<ol>
<li>Are these safe?</li>
<li>What about the IV? Is it ok to just add it to the end of the encrypted string?</li>
<li>Would it be better/faster to make all this by module, that is by using <code>mcrypt_module_open</code>?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T20:05:45.773",
"Id": "8913",
"Score": "0",
"body": "are you encrypting something to be placed into a database?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T20:08:26.320",
"Id": "8914",
"Score": "0",
"body": "yes, some columns will be encrypted and some not"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T20:10:05.973",
"Id": "8915",
"Score": "5",
"body": "Wait. Someone advised you not do it, and you went right ahead and did anyway? - However it certainly looks complex, though I'm not sure what the point of wrapping mcrypt again is. If this is for a banking site, consult a consultant."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T20:21:15.757",
"Id": "8916",
"Score": "7",
"body": "Well, he's *not* designing his own crypto - he's using `mcrypt_encrypt()`. All he's doing is wrapping it up to make it easier to use and is asking if that wrapper leads to things being less secure. I think it's reasonable to ask if this particular treatment of IVs, hashes, and key creation is done without unintentionally opening a vulnerability."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T20:21:57.720",
"Id": "8917",
"Score": "2",
"body": "@mario: He was advised not to create an encryption algorithm by his own. This he didn't do. He just used an exisiting one."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T20:22:27.347",
"Id": "8918",
"Score": "1",
"body": "Someone advised me not to make my own ecryption alg, here I use AES and CTR mode which I read is safer against some kind of attacks."
}
] |
[
{
"body": "<p>If by safe you mean that you are not deviating from standardized encryption procedures which are thought to be secure, then yes you are safe.</p>\n\n<p>If by safe you mean that no one can ever crack this, then the answer is no. Given enough time and advances in computing power or cryptanalysis will eventually lead to to the cipher being broken.</p>\n\n<p>It is not a requirement to keep the IV secret and it can be transferred in the clear, so yes, you can append the IV to the ciphertext.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-03T20:32:42.840",
"Id": "5867",
"ParentId": "5865",
"Score": "3"
}
},
{
"body": "<p>Things that may or may not be an issue:</p>\n\n<ol>\n<li><p>You are not salting the passwords. If you are storing passwords for more than one user and multiple users have the same password, you will be able to look at the database and detect at a glance which users share the same password. Ideally, this should be avoided.</p></li>\n<li><p>You are not using key-strengthening. This makes it so that brute-forcing the password will be easier than brute-forcing the key itself, which means that most of your encryption algorithm is de facto weaker than claimed . I recommend <a href=\"http://codahale.com/how-to-safely-store-a-password/\" rel=\"nofollow\">bcrypt</a> for this; I believe it is included with php 5.3+.</p></li>\n</ol>\n\n<p>Note that neither of these is necessarily relevant. You have not defined why you are using encryption (i.e., what you wish to be safe from), so it is not possible to fully answer your question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T21:34:57.433",
"Id": "8929",
"Score": "0",
"body": "in php it is called simple \"crypt\": http://php.net/manual/en/function.crypt.php"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T22:26:14.677",
"Id": "8930",
"Score": "0",
"body": "@user393087: My main point about bcrypt was that your current hash might run too fast."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T23:52:22.057",
"Id": "8931",
"Score": "3",
"body": "He doens't say if he's storing passwords, but if he is, he shouldn't even be encrypting them, just hashing them."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-04T02:14:30.980",
"Id": "8932",
"Score": "0",
"body": "@Chochos: That is what crypt does."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T21:10:56.730",
"Id": "5868",
"ParentId": "5865",
"Score": "4"
}
},
{
"body": "<p>No it is not secure.\nFor simplicity assume that your data D is exactly one block long.\nThen the ciphertext contains 3 16-byte blocks as follows.</p>\n<blockquote>\n<p>C0 || C1 || C2</p>\n<p>= D xor AES(IV) || MD5(D) xor AES(IV+1) || IV</p>\n</blockquote>\n<p>(The IV is normally prepended to the message, but that is rather irrelevant here).</p>\n<p>If an attacker can guess D then the attacker can derive AES(IV) and AES(IV+1) and subsequently\ngenerate another valid ciphertext by computing</p>\n<blockquote>\n<p>D' xor AES(IV) || MD5(D') xor AES(IV+1) || IV</p>\n</blockquote>\n<p>for whatever message D' he likes.</p>\n<p>An unkeyed hash just does not give the integrity that you would like. As usual one should use a HMAC or something similar instead of the MD5. Hence the biggest weakness in your protocol is not the primitives that you use, but the fact that you are not using them properly. And just to answer another question posed here: People on SO are far from being competent enough to find every flaw in a new protocol. So you'd better look for an existing standard.</p>\n<p>Let me also add, that protocols similar to the one here have been proposed in the 80s. E.g., Kerberos had a similar flaw. Better message authentications such as HMAc were designed exactly to prevent this kind of ciphertext manipulations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-03T22:48:30.503",
"Id": "5869",
"ParentId": "5865",
"Score": "16"
}
}
] |
{
"AcceptedAnswerId": "5869",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-03T20:01:40.360",
"Id": "5865",
"Score": "21",
"Tags": [
"php",
"security",
"cryptography",
"aes"
],
"Title": "Encryption functions based on mcrypt"
}
|
5865
|
<p>I am having trouble with the random number generator. For week 0 only, I want to set the starting number of roaches in House A (<code>totalRoachesInHouseA</code>) to 97 and the number of roaches in House B (<code>totalRoachesInHouseB</code>) to 79. Then, for weeks 1 to 10, I want to generate random numbers for both houses. I am trying to get the same numbers in the example simulation below.</p>
<pre><code>Initial Population: Week 0: House 1 = 97; House 2 = 79
Week 1: House 1 = 119; House 2 = 109
Week 2: House 1 = 151; House 2 = 144
Week 3: House 1 = 194; House 2 = 189
Week 4: House 1 = 25; House 2 = 247
Week 5: House 1 = 118; House 2 = 235
Week 6: House 1 = 198; House 2 = 260
Week 7: House 1 = 280; House 2 = 314
Week 8: House 1 = 37; House 2 = 395
Week 9: House 1 = 187; House 2 = 374
Week 10: House 1 = 315; House 2 = 414
</code></pre>
<p>Here are the instructions for the project: </p>
<blockquote>
<p>Write a program which keeps track of the number of roaches in two
adjacent houses for a number of weeks. The count of the roaches in the
houses will be determined by the following:</p>
<ol>
<li>The initial count of roaches for each house is a random number between 10 and 100.</li>
<li>Each week, the number of roaches increases by 30%.</li>
<li>The two houses share a wall, through which the roaches may migrate from one to the other. In a given week, if one house has more roaches
than the other, roaches from the house with the higher population
migrate to the house with the lower population. Specifically, 30% of
the difference (rounded down) in population migrates.</li>
<li>Every four weeks, one of the houses is visited by an exterminator, resulting in a 90% reduction (rounded down) in the number of roaches
in that house. Your implementation must use functions and local
variables.</li>
</ol>
</blockquote>
<p>Here's what I have so far:</p>
<pre><code>int roachesInHouseA, roachesInHouseB; //my two houses.
int temporaryHouseA, temporaryHouseB;
double totalRoachesInHouseA, totalRoachesInHouseB; //the total count of houses.
int week;
int main( )
{
int temporaryHouseA = 0; // storage for arithmetic
int temporaryHouseB = 0; // storage for arithmetic
int totalRoachesInHouseA = 97; // test number for A
int totalRoachesInHouseB = 79; // test number for B
roachesInHouseA = rand() % 100 + 10;
roachesInHouseB = rand() % 100 + 10;
//The functions declaring the random count of roaches in both houses between
//10 and 100.
for (int Z = 1; Z < 12; Z++) // My for loop iterating up to 11 weeks.
{
totalRoachesInHouseA = totalRoachesInHouseA + roachesInHouseA * .3;
totalRoachesInHouseB = totalRoachesInHouseB + roachesInHouseB * .3;
// My function declaring that the roach population explodes by 30% weekly.
cout << "The number of roaches in House A is " << totalRoachesInHouseA << endl;
cout << "The number of roaches in House B is " << totalRoachesInHouseB << endl;
if ((week == 4) || (week == 8)) // It's extermination time!
{
totalRoachesInHouseA = totalRoachesInHouseA - roachesInHouseA * .9;
totalRoachesInHouseB = totalRoachesInHouseB - roachesInHouseB * .9;
}
else if (totalRoachesInHouseA > totalRoachesInHouseB) // Migration from
//House A to HouseB
{
temporaryHouseA = totalRoachesInHouseA * .3;
totalRoachesInHouseA = totalRoachesInHouseA - temporaryHouseA;
totalRoachesInHouseB = totalRoachesInHouseB + temporaryHouseA;
}
else if (totalRoachesInHouseA < totalRoachesInHouseB) // Migration from
// House B to House A
{
temporaryHouseB = totalRoachesInHouseB * .3;
totalRoachesInHouseB = totalRoachesInHouseB - temporaryHouseB;
totalRoachesInHouseA = totalRoachesInHouseA + temporaryHouseB;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T04:39:28.210",
"Id": "8949",
"Score": "0",
"body": "You want random numbers that equal a specific set of numbers? That does not sound random but rather like an [oxymoron](http://en.wikipedia.org/wiki/Oxymoron)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T04:40:54.467",
"Id": "8950",
"Score": "0",
"body": "I realized that. Let me post the project requirements so you understand what I'm trying to get."
}
] |
[
{
"body": "<p>Don't use global variables.</p>\n<pre><code>int roachesInHouseA, roachesInHouseB; //my two houses.\nint temporaryHouseA, temporaryHouseB;\ndouble totalRoachesInHouseA, totalRoachesInHouseB; //the total count of houses. \nint week;\n</code></pre>\n<p>It is better to use local variables and pass them as parameters to functions. Having global variables (better know as mutable global state) makes it hard to change the program from other situations (also known as tight coupling).</p>\n<p>Also don't declare multiple variables on a single line (don't be lazy, one variable per line).</p>\n<p>Declare variables close to the point where you are going to use it.<br />\nHere you are declaring temporaries like a million miles from their usage point.</p>\n<pre><code>int temporaryHouseA = 0; // storage for arithmetic\nint temporaryHouseB = 0; // storage for arithmetic\n</code></pre>\n<p>What is the difference between totalRoachesInHouseX and roachesInHouseX</p>\n<pre><code>int totalRoachesInHouseA = 97; // test number for A\nint totalRoachesInHouseB = 79; // test number for B\n</code></pre>\n<p>This gives you a number between 10 and 110. Not quite what you want.</p>\n<pre><code>roachesInHouseA = rand() % 100 + 10;\nroachesInHouseB = rand() % 100 + 10;\n</code></pre>\n<p>To check for things that happen every 4 weeks try:</p>\n<pre><code>(weeks % 4) = 0 /* Or any constant from 0 -> 3 */\n</code></pre>\n<p>I don't think the exterminator and the roach moving are exclusive. The roaches move even if the exterminator comes.</p>\n<p>Also Its 30% of the difference (not 30% of the total).</p>\n<p>As we have two houses exactly the same you may want to use an array rather than separate variables.\nThis allows you to make things more flexible.</p>\n<h3>Handling Random</h3>\n<p>rand() returns a random number from a sequence (ie it returns the current value from the sequence then increments to the next position). The sequence is initiated by srand() which sets the start point of the sequence (note adding one to the input does not move it one place down the sequence its a bit more fancy). Normally you would initiate srand() like this:</p>\n<pre><code>srand(time(NULL)); // Call ONLY once just after main() starts\n</code></pre>\n<p>But for testing it is nice to get the same random numbers each time you run. To do this initiate the random sequence at the same point.</p>\n<pre><code>srand(0); // Initiate the rand at point 0 in the sequence.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T07:10:01.017",
"Id": "5883",
"ParentId": "5879",
"Score": "1"
}
},
{
"body": "<p>First of all, the requirements are specific in requiring that you \"use functions\". I'm pretty sure the intent of that was the exact opposite of how you've structured the code, with everything in <code>main</code>.</p>\n\n<p>You might want to consider some (more or less) top-down style development, where you write a simple main that has practically nothing except calls to lower-level functions. I'd do this by thinking of a short (word or two) summary describing each step in the specification, and use those as function names.</p>\n\n<pre><code>int main(void) { \n house_t houses[2];\n\n // 1. put initial population in each house:\n populate(houses[0]);\n populate(houses[1]);\n\n for (week = 1; week < N; week++) {\n // 2. each week, each house's population increases\n increase_pop(houses[0]);\n increase_pop(houses[1]);\n\n // 3. each week, a percentage of the population may migrate between the houses\n do_migration(houses[0], houses[1]);\n\n // 4. every four weeks, an exterminator visits one of the houses\n if (week % 4 == 0)\n exterminate(random_choice(houses, 2));\n\n // 5. Presumably we want to show the data for each house weekly.\n show(houses[0]);\n show(houses[1]);\n }\n}\n</code></pre>\n\n<p>A few things about that code may be open to question -- for example, the spec doesn't seem to specify how to choose which house is exterminated at any given time. I've used a <code>random_choice</code>, but perhaps you think strict alternation makes more sense. In any case, however, The important point is that what we see here should be about as close as possible to a direct translation of the steps outlined in the requirement into the syntax of the target language. From there, we can define the sub-parts in relative isolation from each other.</p>\n\n<p>Right now, this makes life much easier for your teacher: it's fairly easy to look through main and figure out whether it fits the requirements. He can then glance through each of the functions and see whether that function does what it's supposed to as well.</p>\n\n<p>I'd also note that the same basic idea applies when school is over and you're writing real code. The big difference here is that <em>you</em> will spend a lot of time doing what the teacher is doing now, reading and analyzing code, not just writing it. In school, you tend to write code and (almost) never look at it again. In real life, you <em>live</em> with the code after you've written it.</p>\n\n<p>I suspect that you have the idea of writing the code and getting it working, then breaking it up into functions. I'd advise against that. It makes the job considerably more difficult.</p>\n\n<p>I'd also note how this changes the situation if (for example) you need/want to change the parameters. For example, assume you have 5 (or 50) houses in a row, and wanted to run the situation for a year instead of 10 weeks. With the code as I've written it above, that would mostly mean rewriting most of the code that explicitly refers to <code>houses[0]</code> or <code>houses[1]</code> to instead use loops and refer to <code>houses[i]</code>. Don't try to go overboard with this idea though. If you can make the code more flexible like this <em>without</em> adding extra complexity, great. At the same time, don't spend (much) extra time or work writing against possible changes in requirements that may never happen.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T16:27:24.783",
"Id": "5898",
"ParentId": "5879",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T04:16:13.403",
"Id": "5879",
"Score": "4",
"Tags": [
"c++",
"homework",
"random"
],
"Title": "Program with random number generation"
}
|
5879
|
<p>Windows console windows do unfortunately not support stream I/O of international characters. For instance, in Windows 7, you can still do "chcp 65001" (sets the active code page to UTF-8), type "more", and get a crash.</p>
<p>This means that it's practically impossible for a novice to write a "Hello, world!" program that:</p>
<ul>
<li>has national characters in literals</li>
<li>will yield the same results in *nix and Windows regardless of country</li>
</ul>
<p>After a little discussion about this on a Boost mailing list I set down to implement more fully an idea that I sketched there, namely to <strong>use the natural encoding of the OS</strong> for internal strings, which in practice then means UTF-8 for internal strings on *nix and UTF-16 for internal strings on Windows. It's worth noting that e.g. the ICU library, at least according to its documentation, uses UTF-16 encoded strings.</p>
<p>With UTF-8 as a common external coding, one has:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code> Extern Intern E.g. ICU library
UTF-8 - UTF-8 <-> UTF-16 <- for *nix
UTF-8 <-> UTF-16 - UTF-16 <- for Windows
</code></pre>
</blockquote>
<p>To support that I define a macro with the incredibly short name <strong><code>U</code></strong>, which adapts a literal to the platform one compiles for, and creates a strongly typed string or character. The typing helps to avoid using functions in a non-portable manner. And it enables argument dependent lookup, like this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <progrock/cppx/u/adapted_iostream.h>
using namespace std;
namespace u = progrock::cppx::u;
int main()
{
u::out << U( "Hello, world!" ) << endl;
u::out << U( "2+2 = " ) << 2 + 2 << endl;
u::out << U( "Blåbærsyltetøy! 日本国 кошка!" ) << endl;
}
</code></pre>
<p>Here <code>u::out</code> is either <code>std::cout</code> (for *nix) or <code>std::wcout</code> (for Windows). And the source code needs to be stored as UTF-8 with BOM in order to compile nicely with both g++ and Visual C++.</p>
<p>If standard output goes to a Windows console window, then the Norwegian, Russian and Chinese characters result in correct Unicode code points in the console window's text buffer. The Norwegian and Russian displays OK, the Chinese displays as rectangles (on my machine), and the text can be copied correctly to e.g. Notepad, which can display it all. If standard output is redirected or piped, then the result is UTF-8.</p>
<p>This is mostly just hobby programming, and only with the compilers I happen to have on my machine, namely Visual C++ and g++. I'm hoping that some people not only understand the question but are able to give useful feedback.</p>
<p><strong>progrock/cppx/u/adapted_iostream.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
// Copyright (c) 2011, Alf P. Steinbach
//--------------------------------------------------------- Dependencies:
#include <progrock/cppx/u/translating_streams.compiler_dependent.h> // translating?Stream
#include <progrock/cppx/u/cpp_string_output.os_dependent.h> // writeTo
#include <progrock/cppx/u.h> // Encoding::Enum etc.
#include <iostream>
#include <locale>
//#include <codecvt> // C++11 std::codecvt_utf8_utf16, not supported by g++ 4.4.1.
#include <progrock/cppx/u/CodecUtf8.h> // Sort of equivalent DIY functionality instead.
//--------------------------------------------------------- Implementation:
namespace progrock{ namespace cppx{ namespace u {
namespace naturalEncoding {
namespace detail {
template< Encoding::Enum encoding >
struct StdStreamsBase
{
typedef EncodingTraits< encoding > Traits;
typedef std::basic_istream< typename Traits::Raw::Value > IStream;
typedef std::basic_ostream< typename Traits::Raw::Value > OStream;
};
}; // namespace detail
template< Encoding::Enum encoding >
struct StdStreams;
template<>
struct StdStreams< Encoding::utf8 >
: detail::StdStreamsBase< Encoding::utf8 >
{
static IStream& inStream() { return std::cin; }
static OStream& outStream() { return std::cout; }
static OStream& errStream() { return std::cerr; }
static OStream& logStream() { return std::clog; }
};
template<>
struct StdStreams< Encoding::utf16 >
: detail::StdStreamsBase< Encoding::utf16 >
{
private:
template< class Stream >
static Stream& withUtf8Conversion( Stream& stream )
{
std::locale const utf8Locale( stream.getloc(), new CodecUtf8() );
stream.imbue( utf8Locale );
return stream;
}
public:
static IStream& inStream()
{
static IStream& stream = withUtf8Conversion( translatingInWStream() );
return stream;
}
static OStream& outStream()
{
static OStream& stream = withUtf8Conversion( translatingOutWStream() );
return stream;
}
static OStream& errStream()
{
static OStream& stream = withUtf8Conversion( translatingErrWStream() );
return stream;
}
static OStream& logStream()
{
static OStream& stream = withUtf8Conversion( translatingLogWStream() );
return stream;
}
};
} // namespace naturalEncoding
typedef naturalEncoding::StdStreams< u::encoding >::IStream IStream;
typedef naturalEncoding::StdStreams< u::encoding >::OStream OStream;
static IStream& in = naturalEncoding::StdStreams< encoding >::inStream();
static OStream& out = naturalEncoding::StdStreams< encoding >::outStream();
static OStream& err = naturalEncoding::StdStreams< encoding >::errStream();
static OStream& log = naturalEncoding::StdStreams< encoding >::logStream();
inline bool isCommon( OStream const& stream )
{
OStream const* const p = &stream;
return (p == &out || p == &err || p == &log);
}
inline OStream& operator<<( OStream& stream, CodingValue const v )
{
if( isCommon( stream ) ) // <-- Is just an optimization.
{
return writeTo( stream, v ); // Special-cases Windows console output.
}
else
{
return stream << raw( v );
}
}
inline OStream& operator<<( OStream& stream, CodingValue const s[] )
{
if( isCommon( stream ) ) // <-- Is just an optimization.
{
return writeTo( stream, s ); // Special-cases Windows console output.
}
else
{
return stream << raw( s );
}
}
} } } // namespace progrock::cppx::u
</code></pre>
<p>As I copied it for posting it here, I added a couple of <code>inline</code> that I'd forgotten. This is very much a snapshot of a work in progress. It works for output (I haven't tested C++ iostream level input yet), but possibly very far from perfect code!</p>
<p><strong>progrock\cppx\u.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
// Copyright (c) 2011, Alf P. Steinbach
//--------------------------------------------------------- Dependencies:
#include <progrock/cppx/u_encoding_choice.os_dependent.h> // CPPX_NATURAL_ENCODING
#include <progrock/cppx/c++11_emulation.h> // CPPX_STATIC_ASSERT, CPPX_NOEXCEPT
#include <progrock/cppx/stdlib_typedefs.h> // cppx::Size
#include <locale> // std::char_traits
#include <utility> // comparison operators
//--------------------------------------------------------- Interface:
#if CPPX_NATURAL_ENCODING == CPPX_ENCODING_UTF16
#
CPPX_STATIC_ASSERT( sizeof( wchar_t ) == 2 );
# define CPPX_U_ENCODING ::progrock::cppx::u::Encoding::utf16
# define U( aLiteral ) ::progrock::cppx::u::typed( L##aLiteral )
#
#elif CPPX_NATURAL_ENCODING == CPPX_ENCODING_UTF8
#
# define CPPX_U_ENCODING ::progrock::cppx::u::Encoding::utf8
# define U( aLiteral ) ::progrock::cppx::u::typed( aLiteral )
#
#else
# error "The natural encoding for this OS is not supported, sorry."
#endif
namespace progrock { namespace cppx { namespace u {
using namespace std::rel_ops; // operator!= etc.
struct Encoding { enum Enum{ ansi, utf8, utf16 }; };
template< Encoding::Enum a > struct EncodingUnit;
template<> struct EncodingUnit< Encoding::ansi > { typedef char Type; };
template<> struct EncodingUnit< Encoding::utf8 > { typedef char Type; };
template<> struct EncodingUnit< Encoding::utf16 > { typedef wchar_t Type; };
template< Encoding::Enum e >
struct EncodingTraits; // Must be specialized due to Visual C++ bug.
template<>
struct EncodingTraits< Encoding::utf8 >
{
typedef char UnitType;
typedef std::char_traits< UnitType > UnitTraits;
struct Raw
{
typedef UnitType Value;
typedef UnitTraits::int_type ExtendedValue;
};
enum Value : Raw::Value {};
enum ExtendedValue : Raw::ExtendedValue {};
CPPX_STATIC_ASSERT( sizeof( Value ) == sizeof( Raw::Value ) );
CPPX_STATIC_ASSERT( sizeof( ExtendedValue ) == sizeof( Raw::ExtendedValue ) );
};
template<>
struct EncodingTraits< Encoding::utf16 >
{
typedef wchar_t UnitType;
typedef std::char_traits< UnitType > UnitTraits;
struct Raw
{
typedef UnitType Value;
typedef UnitTraits::int_type ExtendedValue;
};
enum Value : Raw::Value {};
enum ExtendedValue : Raw::ExtendedValue {};
CPPX_STATIC_ASSERT( sizeof( Value ) == sizeof( Raw::Value ) );
CPPX_STATIC_ASSERT( sizeof( ExtendedValue ) == sizeof( Raw::ExtendedValue ) );
};
Encoding::Enum const encoding = CPPX_U_ENCODING;
typedef EncodingTraits< encoding > Traits;
typedef Traits::Value CodingValue;
typedef Traits::ExtendedValue ExtendedCodingValue;
typedef Traits::Raw::Value RawCodingValue;
typedef Traits::Raw::ExtendedValue RawExtendedCodingValue;
inline RawCodingValue raw( CodingValue const v ) CPPX_NOEXCEPT
{
return v;
}
inline RawCodingValue* raw( CodingValue* p ) CPPX_NOEXCEPT
{
return reinterpret_cast< RawCodingValue* >( p );
}
inline RawCodingValue const* raw( CodingValue const* p ) CPPX_NOEXCEPT
{
return reinterpret_cast< RawCodingValue const* >( p );
}
template< Size size >
inline RawCodingValue (&raw( CodingValue (&s)[size] )) [size]
{
return reinterpret_cast< RawCodingValue (&)[size] >( s );
}
template< Size size >
inline RawCodingValue const (&raw( CodingValue const (&s)[size] ) CPPX_NOEXCEPT)[size]
{
return reinterpret_cast< RawCodingValue const (&)[size] >( s );
}
enum Koenig {};
inline CodingValue typed( RawCodingValue const v ) CPPX_NOEXCEPT
{
return CodingValue( v );
}
inline CodingValue typed( Koenig, RawCodingValue const v ) CPPX_NOEXCEPT
{
return CodingValue( v );
}
inline CodingValue* typed( RawCodingValue* const p ) CPPX_NOEXCEPT
{
return reinterpret_cast< CodingValue* >( p );
}
inline CodingValue* typed( Koenig, RawCodingValue* const p ) CPPX_NOEXCEPT
{
return reinterpret_cast< CodingValue* >( p );
}
inline CodingValue const* typed( RawCodingValue const* const p ) CPPX_NOEXCEPT
{
return reinterpret_cast< CodingValue const* >( p );
}
inline CodingValue const* typed( Koenig, RawCodingValue const* const p ) CPPX_NOEXCEPT
{
return reinterpret_cast< CodingValue const* >( p );
}
template< Size size >
inline CodingValue (&typed( RawCodingValue (&s)[size] ) CPPX_NOEXCEPT)[size]
{
return reinterpret_cast< CodingValue (&)[size] >( s );
}
template< Size size >
inline CodingValue (&typed( Koenig, RawCodingValue (&s)[size] ) CPPX_NOEXCEPT)[size]
{
return reinterpret_cast< CodingValue (&)[size] >( s );
}
template< Size size >
inline CodingValue const (&typed( RawCodingValue const (&s)[size] ) CPPX_NOEXCEPT)[size]
{
return reinterpret_cast< CodingValue const (&)[size] >( s );
}
template< Size size >
inline CodingValue const (&typed( Koenig, RawCodingValue const (&s)[size] ) CPPX_NOEXCEPT)[size]
{
return reinterpret_cast< CodingValue const (&)[size] >( s );
}
} } } // namespace progrock::cppx::u
namespace std {
// Requirements specified by C++11 §21.2.1/1 table 62.
template<>
class char_traits< ::progrock::cppx::u::CodingValue >
{
private:
typedef ::progrock::cppx::u::Koenig adl;
public:
typedef ::progrock::cppx::u::CodingValue char_type;
typedef ::progrock::cppx::u::ExtendedCodingValue int_type;
typedef ::progrock::cppx::u::Traits::UnitTraits Std;
typedef Std::off_type off_type;
typedef Std::pos_type pos_type;
typedef Std::state_type state_type;
static bool eq( char_type a, char_type b ) CPPX_NOEXCEPT
{ return (a == b); }
static bool lt( char_type a, char_type b ) CPPX_NOEXCEPT
{ return (a < b); }
static int compare( char_type const* s1, char_type const* s2, size_t n )
{ return Std::compare( raw( s1 ), raw( s2 ), n ); }
static size_t length( char_type const* s )
{ return Std::length( raw( s ) ); }
static char_type const* find( char_type const* s, size_t n, char_type const a )
{ return typed( adl(), Std::find( raw( s ), n, raw( a ) ) ); }
static char_type* move( char_type* s1, char_type const* s2, size_t n )
{ return typed( adl(), Std::move( raw( s1 ), raw( s2 ), n ) ); }
static char_type* copy( char_type* s1, char_type const* s2, size_t n )
{ return typed( adl(), Std::copy( raw( s1 ), raw( s2 ), n ) ); }
static void assign( char_type& c1, char_type const c2 ) CPPX_NOEXCEPT
{ c1 = c2; }
static char_type* assign( char_type* s, size_t n, char_type const a )
{ return typed( adl(), Std::assign( raw( s ), n, raw( a ) ) ); }
static int_type not_eof( int_type const c ) CPPX_NOEXCEPT
{ return int_type( Std::not_eof( c ) ); }
static char_type to_char_type( int_type const c ) CPPX_NOEXCEPT
{ return typed( c ); }
static int_type to_int_type( char_type const c ) CPPX_NOEXCEPT
{ return int_type( c ); }
static bool eq_int_type( int_type const c1, int_type const c2 ) CPPX_NOEXCEPT
{ return (c1 == c2); }
static int_type eof() CPPX_NOEXCEPT
{ return int_type( Std::eof() ); }
};
} // namespace std
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:19:25.037",
"Id": "8965",
"Score": "0",
"body": "I don't agree that the natural internal encoding for string in *nix is UTF-8. I would argue that internally the strings are UTF-32 (normally). **BUT** when you stream them (to either a file (including the console) or network socket) that they are converted to UTF-8. This is what I would consider normal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:29:34.213",
"Id": "8966",
"Score": "0",
"body": "But more importantly **you have not provided any real code to review**. This is more like a blog post where you describe your findings after some research and are trying to establish best practice. But nobody can answer the question as you have provided nothing to comment on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:50:51.563",
"Id": "8968",
"Score": "0",
"body": "@LokiAstari: Thanks for the comments. The guys over at boost all insisted on UTF-8 as being the de facto standard for internal strings in *nix programs, I just believed it. Shouldn't I? Anyway, what strikes you as not \"real\" about the presented program? It works, that's real for me. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:56:46.350",
"Id": "8970",
"Score": "0",
"body": "The *nix programs I know of use UTF8 internally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:15:03.437",
"Id": "8972",
"Score": "0",
"body": "@AlfP.Steinbach: There is not really anything to review. If you posted the content of `#include <progrock/cppx/u/adapted_iostream.h>` then there would be something to review. But the code above is meaningless without it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:17:03.293",
"Id": "8973",
"Score": "0",
"body": "@AlfP.Steinbach: Maybe you could post a link to your discussion thread with the boost guys so we can read it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:24:38.437",
"Id": "8974",
"Score": "0",
"body": "@LokiAstari: well it was a couple of threads. The most positive result being Beman promising to sooner or later act on a ticket to fix the (lack of) support for long Windows filenames for Boost Filesystem v3 built with g++ in Windows. By porting over the relevant v2 code... :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:41:44.203",
"Id": "8975",
"Score": "0",
"body": "@AlfP.Steinbach: context is important, you seem to be missing some. If filenames yes they would be in UTF-8 also plain text message for printing (potentially). But raw data for manipulation I would still consider this to be UTF-32 internally."
}
] |
[
{
"body": "<p>Since the code is supposed to work for Unix the pragma is a bad idea.</p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p>Prefer to use normal include guards.</p>\n\n<p>You are imbuing streams here:</p>\n\n<pre><code> std::locale const utf8Locale( stream.getloc(), new CodecUtf8() );\n stream.imbue( utf8Locale );\n return stream;\n</code></pre>\n\n<p>The only problem I see with this is that after you have started using the stream any attempt to imbue can silently fail (or it used too they may have fixed that in C++11). </p>\n\n<p>Now I assume you are trying to force this initialization before use with:</p>\n\n<pre><code>static IStream& in = naturalEncoding::StdStreams< encoding >::inStream();\nstatic OStream& out = naturalEncoding::StdStreams< encoding >::outStream();\nstatic OStream& err = naturalEncoding::StdStreams< encoding >::errStream();\nstatic OStream& log = naturalEncoding::StdStreams< encoding >::logStream();\n</code></pre>\n\n<p>This will work 99% of the time but if somebody starts logging (using one of the std:: streams (in/out/err/log) in the constructor of a global scope static storage duration object then all bets are off). Since this is a rare case I am not too worried but you should document this somewhere like at the top of the header file (assuming it is still a problem).</p>\n\n<p>I don't see a definition for <code>U()</code> or <code>writeTo()</code> or <code>raw()</code> or <code>CodingValue</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:50:27.450",
"Id": "8976",
"Score": "0",
"body": "Thanks for those comments. Does the `#pragma once` not work in nix? Regarding the definitions you ask for, `U()` and `raw()` is one header, while `writeTo` is a platform-dependent operation and so is in a couple of headers. I think it is perhaps enough to post the former header?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:54:52.390",
"Id": "8978",
"Score": "1",
"body": "All pragmas are compiler specific. Not all compilers support `once`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T16:03:29.947",
"Id": "8980",
"Score": "1",
"body": "well, that's an well-considered engineering decision. support everything under the sun, or something more reasonable? i landed on reasonable. the issue has been been discussed extensively even here on SO. and i couldn't support those non-mainstream compilers anyway -- there's enough compiler specific stuff with just g++ and msvc involved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:05:02.217",
"Id": "8995",
"Score": "0",
"body": "@AlfP.Steinbach: Three lines rather than one does not seem an unreasonable cost for greater support. I assume your platform specific files will generate the appropriate errors for unsupported platforms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:05:46.663",
"Id": "8997",
"Score": "1",
"body": "@AlfP.Steinbach: Maybe you should change your support from *nix to Linux (gcc is practically default for Linux but not *nix)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:22:28.043",
"Id": "9001",
"Score": "0",
"body": "Instead of brittle & complex platform detection the platform and compiler dependent files simply rely on include paths being set properly for the platform and compiler. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:41:16.197",
"Id": "9003",
"Score": "0",
"body": "@Alf P. Steinbach: That's what I said to lines ago. But people the write compiler specific code (like people who live in glass houses) should be careful about the adjectives they throw (like brittle)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T22:06:23.393",
"Id": "9014",
"Score": "0",
"body": "The technical notion of brittleness should be easy to understand. It is the same for platform detection in C++, as for browser detection in web pages. I could understand that hostility, that urge to go personal, if you had previously argued otherwise, but you haven't, so I'm at a loss as to how to respond to that sillyness. Again I thank you for you comments. It is helpful just to see nothing serious was amiss."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T18:54:56.057",
"Id": "9087",
"Score": "0",
"body": "@AlfP.Steinbach: Sorry if you took that personally (not sure how) but sorry. What the intended message was: You can't complain about technique being brittle when you are espousing the usage of another inherently brittle technique."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:39:46.420",
"Id": "5897",
"ParentId": "5889",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T13:52:18.690",
"Id": "5889",
"Score": "8",
"Tags": [
"c++",
"macros",
"unicode"
],
"Title": "Source code level portable C++ Unicode literals"
}
|
5889
|
<pre><code>//parses the text path vector into the engine
void Level::PopulatePathVectors(string pathTable)
{
// Read the file line by line.
ifstream myFile(pathTable);
for (unsigned int i = 0; i < nodes.size(); i++)
{
pathLookupVectors.push_back(vector<vector<int>>());
for (unsigned int j = 0; j < nodes.size(); j++)
{
string line;
if (getline(myFile, line)) //enter if a line is read successfully
{
stringstream ss(line);
istream_iterator<int> begin(ss), end;
pathLookupVectors[i].push_back(vector<int>(begin, end));
}
}
}
myFile.close();
}
</code></pre>
<p>This function is taking about 5 minutes to pass in a text file which is 744 * 744 lines long. Each line is a list of integers like this:</p>
<pre><code>1 4 6 24 7 4 8 n
</code></pre>
<p>they can be of varying length. I have no idea why it's taking so long, but it needs to run in a matter of seconds, not minutes! The odd thing is that the same function in C# (in fact a very unoptimised version) does in fact only take seconds to run.</p>
<p>Could the problem be a setting?</p>
<p>This is a link to the path table it is parsing <a href="http://dl.dropbox.com/u/13519335/WepTestLevelPathTable.txt">http://dl.dropbox.com/u/13519335/WepTestLevelPathTable.txt</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:11:39.553",
"Id": "8962",
"Score": "0",
"body": "what is the type of `nodes`, it seems like, if nothing else, you could at least evaluate that once outside the double loop. I don't suspect that is the culprit, just mentioning it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:42:48.860",
"Id": "8967",
"Score": "0",
"body": "First this is not C++ code this is C++11. (It does not compile as C++03) So I'll change the tag. So I presume you are trying to get the move semantics of vector to work correctly to prevent copying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:59:28.457",
"Id": "8971",
"Score": "0",
"body": "Well I don;t know what you are doing. But with node.size() = 744 It only takes 3 seconds to load the file for me. So this looks like more of a problem for [SO](http://Stackoverflow.com) than here."
}
] |
[
{
"body": "<p>I setup nodes.size() to return 744.<br>\nThis then forces all 553536 to be read from the file.</p>\n\n<p>When I run your code it completes in 3.8 seconds (with -O3 it takes 2.5 seconds).</p>\n\n<p>If I update the code to reserve the appropriate amount of space in each vector we can reduce the time it takes to: 3.3 seconds (with -O3 2.2 seconds).</p>\n\n<p>So for the 5 minute figure you are quoting there must be some other error in your code.</p>\n\n<h3>Comments on your code:</h3>\n\n<p>Pass no-mutable parameters by cost reference (to avoid the copy).</p>\n\n<pre><code>void Level::PopulatePathVectors(string pathTable)\n</code></pre>\n\n<p>Add lines to reserve the appropriate space in each vector. This will prevent multiple re-allocations of the vector while you read. This is important when you have a triply nested vector.</p>\n\n<pre><code> pathLookupVectors.push_back(vector<vector<int> >());\n pathLookupVectors.reserve(nodes.size()); // Add this line\n\n for (unsigned int i = 0; i < nodes.size(); i++)\n {\n pathLookupVectors.push_back(vector<vector<int>>());\n pathLookupVectors.back().reserve(nodes.size()) // Add this line\n</code></pre>\n\n<p>No Need to manually close the file.<br>\nsee <a href=\"https://stackoverflow.com/q/748014/14065\">https://stackoverflow.com/q/748014/14065</a><br>\n<a href=\"https://codereview.stackexchange.com/q/540/507\">Implementation using fstream failed evaluation</a></p>\n\n<pre><code>myFile.close();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T15:13:00.287",
"Id": "5895",
"ParentId": "5892",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "5895",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T14:02:50.533",
"Id": "5892",
"Score": "7",
"Tags": [
"c++",
"c++11"
],
"Title": "I/O function takes far too long"
}
|
5892
|
<p>I was wondering if you could review the following code I've written as a polyfill for the placeholder attribute in HTML5?</p>
<p>The object of the polyfill is to replicate the functionality of the placeholder attribute. In effect, the polyfill is supposed to do the following:</p>
<ol>
<li>Default text to be shown.</li>
<li>On Focus: Erase the default text.</li>
<li>On Focus Out: Put in default text if nothing has been entered</li>
</ol>
<p>Dependancies:</p>
<ol>
<li><p>jQuery</p>
<pre><code>var Utils = Utils || {};
Utils = (function (window, $) {
var _c, _private, _public;
_private = {
/**
* @event
* @param e The event object.
*/
'handleFocusIn': function (e) {
var $target = $(e.currentTarget);
if($target.val() === $target.attr('placeholder')) {
$target.val('');
}
$target
.unbind('focusin')
.bind('focusout', _private.handleFocusOut);
},
/**
* @event
* @param e The event object.
*/
'handleFocusOut': function (e) {
var $target = $(e.currentTarget);
if($target.val() === '') {
$target.val($target.attr('placeholder'));
}
$target
.unbind('focusout')
.bind('focusin', _private.handleFocusIn);
}
};
_public = {
/**
* @function
* @description
* A poly-fill for the placeholder attribute.
*/
'supportsPlaceholderAttr': function (enableFallback) {
var placeHolderSupported = false;
//If enableFallback is either undefined or not a Boolean, set it to false
if((typeof enableFallback === 'undefined') || !(enableFallback instanceof Boolean)) {
enableFallback = false;
}
//if placeholder is supported, no reason to continue on
if ('placeholder' in document.createElement("input")) {
return placeHolderSupported = true;
}
if (!placeHolderSupported && !!enableFallback) {
var $inputEle;
$('input')
.each( function(index, ele) {
$inputEle = $(ele);
if($inputEle.attr('placeholder')) {
$inputEle
.val($inputEle.attr('placeholder'))
.bind('focusin', _private.handleFocusIn);
}
});
}
}
};
return _public;
}(window, jQuery));
</code></pre></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T16:57:37.443",
"Id": "8983",
"Score": "0",
"body": "[fixed](http://jsfiddle.net/HWKKa/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:02:47.163",
"Id": "8985",
"Score": "0",
"body": "@Raynos I liked how you shortened up the code, however what if I wanted to extend shim to have more than just the polyfill for the placeholder attribute? Also, there are no checks for the enableFallback parameter - shouldn't best practices have you check for that value?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:07:32.017",
"Id": "8986",
"Score": "0",
"body": "[mocked](http://jsfiddle.net/RJhn4/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:08:38.270",
"Id": "8987",
"Score": "0",
"body": "I checked with `enableFallback && run loop`. i used a short circuiting trickery to make sure you only bunch the focusin/out handlers in if the enableFallback flag is set"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:26:36.710",
"Id": "8988",
"Score": "0",
"body": "@Raynos not sure if you're taking IE into consideration? handleFocusIn/handleFocusOut binds/unbinds due to the nature of IE7 mobile. Perhaps I wasn't clear on what devices this would support. As for _c, _private and _public; they were just included for extensibility (_c = cached variables, _private for the event handlers and _public for the actual supportsPlaceholderAttr method. Although I can re-name them anytime - an no I'm not familiar with Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:36:35.607",
"Id": "8990",
"Score": "1",
"body": "@alvincrespo Could you elaborate on or link to some information regarding \"the nature of IE7 mobile\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T17:58:24.673",
"Id": "8993",
"Score": "0",
"body": "@RyanKinal What I mean by \"IE7 Mobile\" - I mean that the focusIn and focusOut event happens several times upon focusing in on the input field, thus causing the events to trigger to many times. So I bind/unbind based on the current action of the user. This also goes hand in hand with predicting user interaction and only using what you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:03:13.827",
"Id": "8994",
"Score": "0",
"body": "Ah, yes. `focusin` and `focusout` will bubble. If, however, you use `focus`, and `blur`, that will solve your problem. See my answer."
}
] |
[
{
"body": "<p><strong>Note:</strong> Regarding the OP's comment on the \"nature of IE7 mobile\", I suspect it has more to do with jQuery's implementation of <code>focusin</code> and <code>focusout</code>. This may not be the case, but I have written my review with that assumption in mind.</p>\n\n<p>There are a few things about your code that are, to put it bluntly, pointless.</p>\n\n<p>First, checking whether <code>Utils</code> exists is a good thing, but you then immediately clobber it with the return of your function:</p>\n\n<pre><code>var Utils = Utils || {};\n\nUtils = (function(window, $) {\n /* ... */\n return _public;\n})(window, jQuery);\n</code></pre>\n\n<p>Something like the following would most likely be better:</p>\n\n<pre><code>var Utils = Utils || (function(window, $) {\n /* ... */\n return _public;\n})(window, jQuery);\n</code></pre>\n\n<p>Second, why pass <code>window</code> to the function at all? Browsers will not allow overwriting of the <code>window</code> object, and your parameter name is <code>window</code> anyway, so it doesn't save you anything.</p>\n\n<p>Third, <code>_private</code> is unnecessary. Any variables (including functions) that you don't include in whatever object you return will be hidden by the local scope of your self-executing function.</p>\n\n<pre><code>var handleFocusIn = function(e) { /*...*/ },\n handleFocusOut = function(e) { /*...*/ };\n</code></pre>\n\n<p><code>_public</code> is also unnecessary, though not as much as <code>_private</code>. If it were me, I would simply return the object literal, rather than bothering with the <code>_public</code> variable.</p>\n\n<p>Lastly, given that your elements will always be <code>input</code> elements, there is no need to use <code>focusin</code> and <code>focusout</code>; Simply use <code>focus</code> and <code>blur</code> - this will avoid any possible bubbling issues, and then, most importantly, allow you to dispense with the unbinding/rebinding that happens in your handlers.</p>\n\n<p>@Raynos also makes some good points on your implementation of <code>supportsPlaceHolderAttr</code>, regarding variables and conditionals.</p>\n\n<pre><code>//if placeholder is supported, no reason to continue on\nif ('placeholder' in document.createElement(\"input\")) {\n // useless variable, just return true\n return placeHolderSupported = true;\n}\n\n// useless placeHoldSupported check, always false. Useless enableFallback conversion always a bool\nif (!placeHolderSupported && !!enableFallback) {\n</code></pre>\n\n<p>It's a good attempt at writing unobtrusive code, but it falls short of good modularity and namespacing. Still, like I said, a good start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:05:13.660",
"Id": "8996",
"Score": "3",
"body": "Passing `window` into an anoymous closure is a tiny micro optimisation (one less layer of lookup) and allows you to minify the `window` variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:06:11.310",
"Id": "8998",
"Score": "0",
"body": "Point taken. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:09:22.477",
"Id": "8999",
"Score": "0",
"body": "This is exactly what I am looking for. A clear explanation of why my code doesn't really make sense - if it doesn't. Thanks so much @RyanKinal It was clear and to the point and definitely helps me improve. Any more answers/suggestions would be great. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:19:52.790",
"Id": "9000",
"Score": "0",
"body": "I added a suggestion on the idea of detecting whether `Utils` exists."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T18:02:26.603",
"Id": "5902",
"ParentId": "5899",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T16:37:36.147",
"Id": "5899",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html5"
],
"Title": "Javascript Placeholder Polyfill"
}
|
5899
|
<p>There are two keys: the main is aes128 and the second is XTEA, used just for randomization of data inside the AES. Randomization is done with secret random key that is not know even if someone knows exactly what is encrypted. Also the key is produced by doing hash many number of times and this hash is salted with the iv so it is not possible to make a dictionary attack with precomputed hashes.</p>
<pre><code>function aes128ctr_en($data,$key,$hash_rounds = 0) {
//iv is created
$iv = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
//internal secret random string is created so no one knows what
//is exactly encoded by main cipher
$xtea = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
//password is hashed in many rounds to prevent dictionary attack,
//hashing is done with individual iv for hmac so it make no sense to use
//precalculated hashes
for($i=0;$i<=$hash_rounds;++$i) $key = hash_hmac('sha256',$key,$iv,true);
//string is randomized for use in aes, so no one knows what actually will be encoded
//this is not actual encoding so password is stored inside with xtea encoded string,
//second half of this password is used as IV for xtea
//again: THIS IS NOT ACTUAL ENCODING
$data = $xtea.mcrypt_encrypt('xtea',$xtea,$data,'ofb',substr($xtea,8));
//hash is added to check if return string is really what we looked for,
//must match with string on decoding
$data = hash('md5',$data,true).$data;
//actual encoding, IV is prepended to encrypted string
return $iv.mcrypt_encrypt('rijndael-128',$key,$data,'ctr',$iv);
}
function aes128ctr_de($data,$key,$hash_rounds = 0) {
$iv = substr($data,0,16);
$data = substr($data,16);
for($i=0;$i<=$hash_rounds;++$i) $key = hash_hmac('sha256',$key,$iv,true);
$data = mcrypt_decrypt('rijndael-128',$key,$data,'ctr',$iv);
$md5 = substr($data,0,16);
$data = substr($data,16);
if (hash('md5',$data,true)!==$md5) return false;
$xtea = substr($data,0,16);
$data = substr($data,16);
return mcrypt_decrypt('xtea',$xtea,$data,'ofb',substr($xtea,8));
}
$key = 'suPer_secret aAnd L10ng ppswrd$%';
$encrypted = aes128ctr_en('the bomb will blow up at 1 pm',$key,12345);
echo aes128ctr_de($encrypted,$key,12345);
</code></pre>
<p>I really don't have knowledge to make it better. I'm not that educated in all this to read RFCs and make algorithms out of it. I'm also constrained to methods that are precompiled in core PHP binary as I want these methods to be able to run on remote servers.</p>
|
[
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-05T21:55:18.883",
"Id": "9061",
"Score": "3",
"body": "I hope this is the last of your \"I wrote some algorithm and don't know exactly how it works, but tell me if it is secure\" questions. At the very least you could have used test data to compare the output of your unreadable functions to a reference implemention like openssl."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-05T22:11:41.777",
"Id": "9062",
"Score": "4",
"body": "take sha256, md5, xtea, and aes-128, place into a blender with some cool random bytes, and press the liquefy button. Pour the results out onto Stackoverflow for analysis."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-05T22:39:41.370",
"Id": "9063",
"Score": "0",
"body": "Yes, this is last as I do not have knowledge to improve it. And second to Greg - WHAT random bytes ? Are there any arbitrary random bytes ? For example sha256 is used because it produces key lenght that match what is needed for aes. MD5 is only for checking if password is ok. XTEA is chosen because it is a very simple algorithm and it is not used for actual encoding. Again - whats wrong ? All I try is to make secure encryption by using what I have available in basic configuration of PHP."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-05T22:51:58.170",
"Id": "9064",
"Score": "0",
"body": "And again to first comment. How I'm supposed to not know how this works since I WROTE it ? Did you even read the code ? Where I have written that I do not know how it works. What I do not know is if I'm using all the cryptographic methods in correct way so security is not undermined."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-05T23:09:45.333",
"Id": "9065",
"Score": "0",
"body": "There is no way to tell if you chained the crypto functions in the right fashion. But you very much succeeded at obfuscating the processing logic. Which in turn is the reason for nobody bothering to analyze it. - If you want sensible comments, you should first post sensible code. Add comments, and split up your spaghetti code into well-named functions. - And instead of reposting code variations without substantiated change explanations, add a bounty to your question. - Second tip again: just compare your output to a well-known reference implementation. http://google.com/search?q=php+aes+class"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-06T09:32:05.243",
"Id": "9066",
"Score": "0",
"body": "I added comments to first function, second is basicaly doing the same but vice versa. And what spagetthi code ? There are only TWO functions written by me, rest is PHP (how I'm supposed to name php function myself?) and couple of variables, and those two functions are well named."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-06T14:42:43.937",
"Id": "9067",
"Score": "1",
"body": "You should read [Security through obscurity](http://en.wikipedia.org/wiki/Security_through_obscurity)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-06T16:20:09.763",
"Id": "9068",
"Score": "0",
"body": "Give me one thing that is obscure here or you do not know for why is something used."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-06T20:01:26.493",
"Id": "9069",
"Score": "3",
"body": "Well, the comments do very much improve this question. Spend your reputation on a bounty now and it's likely to get answered instead of closevoted. - It's even obvious now why the first function is a blob instead of being split up into the three subparts (hashing, shuffling, encryption stage). - At the very least it looks like a plausible approach. Yet I'm not stating this as answer, but to make it go away faster. Also consider that while the algorithm might be ok; running this in a PHP runtime ensures that the plain $key, $iv and $xtea variables will remain somewhere in memory on script exit."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-09T10:50:42.227",
"Id": "9070",
"Score": "1",
"body": "Safe for what? What are you trying to achieve? What is your threat model? Why have you chosen the algorithms and compositions that you have? Why are the existing compositions of algorithms unsuitable for your purposes?"
}
] |
[
{
"body": "<p>The basic answer is: No</p>\n\n<p>Where is your random seed being generated from? (Oh wait, you are not using a random see - seriously big issue #1) Where it is being stored? What cryptographic symmetric ciphers are being used to generate your seed.</p>\n\n<p>You expect the method you are using to be secure? You expect your server to never be compromised?</p>\n\n<p>Failure to apply systematic cryptographic principles to the very basic of what you appear to be trying to do (Security through Obscurity) will always result in a failure of your cryptographic procedures because you fail to understand the necessary principles that need to be applied.</p>\n\n<p>All I see is a whole lot of code designed to do one thing, yet is 100% at risk because you have failed to do other things that are necessary to the process of data encryption.</p>\n\n<p>All that said, it would be very easy to produce something more secure than your 33 lines of code.</p>\n\n<p>But first you need to learn the basics. After that, start looking into using <code>openssl_public_encrypt()</code> and <code>Crypt_Blowfish()</code>.</p>\n\n<p>In about 8-10 lines of code you can have a solid cryptographic procedure that will be much more secure than your <code>StO</code> method that you are attempting here - and use methods that are time-proven to be unbreakable by all modern standards within the RAT (Reasonable Amount of Time) factor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T09:37:07.120",
"Id": "9071",
"Score": "0",
"body": "WHAT 33 lines of code ? the encoding part is only 6 lines, what are you talking about ?, Second - didn't you see MCRYPT_DEV_URANDOM ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-28T07:07:33.493",
"Id": "9072",
"Score": "0",
"body": "Regardless of it being 6 lines or not, the code still fail the very basic of cryptographic methodology. Hard-coded seeds are never - and never will be - secure."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T14:05:18.907",
"Id": "9073",
"Score": "0",
"body": "Sorry but I do not understand what \"hard coded seed\" means in this context ? I'm generating one public seed that seves as IV for crypt and one secret that is used to randomize string that is inside."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-27T00:46:26.633",
"Id": "5916",
"ParentId": "5915",
"Score": "4"
}
},
{
"body": "<p>You should use a key strengthening function like PKBDF2, scrypt or bcrypt to generate a key from the password.\nThe part with XTEA is useless: you're relying on security through obscurity.\nYou shouldn't hash before encrypting if you want to ensure the data has not been tampered with. Use HMAC SHA-256 on the encrypted data.</p>\n\n<p>And finally: don't write your own crypto algorithm. Use well known and audited solutions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:18:13.590",
"Id": "5917",
"ParentId": "5915",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-05T21:26:20.237",
"Id": "5915",
"Score": "13",
"Tags": [
"php",
"security",
"cryptography",
"aes"
],
"Title": "PHP mcrypt AES encryption wrapper"
}
|
5915
|
<p>I am developing a multilingual site, so i needed some sort of a function to detect user locale, as well as not to scare away search engines, so I wrote this kind of a method to detect locale.
The priority is as following:</p>
<ol>
<li><p>We look if user has active language in $_SESSION;</p></li>
<li><p>If not, we look in the database to detect user preference;</p></li>
<li><p>If nothing in the database, we look on the domain name and try to detect locale from domain name and superglobal $_SERVER;</p></li>
<li><p>If we failed, we look at user's browser locale ($_SERVER again) and try to detect from it.</p></li>
<li><p>If we are totally a failure, we fallback to English.</p></li>
</ol>
<p>This method is called on every page of a website.</p>
<pre><code>public static function detect_locale() {
if(isset($_SESSION["lang"])){
$lang = $_SESSION["lang"];
return $lang;
}
if(isset($_SESSION["id"])){
$user = new User($_SESSION["id"]);
$lang = $user->get_locale();
return $lang;
}
if($_SERVER["HTTP_HOST"] == "ru.mysupersite.com" || $_SERVER["HTTP_HOST"] == "www.mysupersite.ru"){
$lang = "ru";
return $lang;
}
if(isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])){
$lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
return $lang;
}
$lang = "en";
return $lang;
}
</code></pre>
<p>I see it as a pretty straightforward solution, but something in the back of my mind says that there might be some flaws. Are there any or am I just paranoid?</p>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T16:53:44.940",
"Id": "9082",
"Score": "1",
"body": "Can you check if the locale is available/valid? If yes then I'd check `$lang` and only return if it's accepted and otherwise fall through to the subsequent tests. I'd also move the language-from-host detection code to it's own function to allow for easier testing and extension."
}
] |
[
{
"body": "<p>Your basic hierarchy seems fairly solid. There is just one thing - HTTP_ACCEPT_LANGUAGE is not so simple. I wrote an answer on it <a href=\"https://stackoverflow.com/questions/7466208/php-or-htaccess-rewrite-url-by-accept-language/7494297#7494297\">here</a>. What follows is the relevant code from that:</p>\n\n<pre><code>// Parse the Accept-Language according to:\n// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4\npreg_match_all(\n '/([a-z]{1,8})' . // M1 - First part of language e.g en\n '(-[a-z]{1,8})*\\s*' . // M2 -other parts of language e.g -us\n // Optional quality factor M3 ;q=, M4 - Quality Factor\n '(;\\s*q\\s*=\\s*((1(\\.0{0,3}))|(0(\\.[0-9]{0,3}))))?/i',\n $_SERVER['HTTP_ACCEPT_LANGUAGE'],\n $langParse);\n\n$langs = $langParse[1]; // M1 - First part of language\n$quals = $langParse[4]; // M4 - Quality Factor\n\n$numLanguages = count($langs);\n$langArr = array();\n\nfor ($num = 0; $num < $numLanguages; $num++)\n{\n $newLang = strtoupper($langs[$num]);\n $newQual = isset($quals[$num]) ?\n (empty($quals[$num]) ? 1.0 : floatval($quals[$num])) : 0.0;\n\n // Choose whether to upgrade or set the quality factor for the\n // primary language.\n $langArr[$newLang] = (isset($langArr[$newLang])) ?\n max($langArr[$newLang], $newQual) : $newQual;\n}\n\n// sort list based on value\n// langArr will now be an array like: array('EN' => 1, 'ES' => 0.5)\narsort($langArr, SORT_NUMERIC);\n\n// The languages the client accepts in order of preference.\n$acceptedLanguages = array_keys($langArr);\n\n// Set the most preferred language that we have a translation for.\nforeach ($acceptedLanguages as $preferredLanguage)\n{\n if (in_array($preferredLanguage, $websiteLanguages))\n {\n $_SESSION['lang'] = $preferredLanguage;\n return $preferredLanguage;\n }\n}\n</code></pre>\n\n<p>You would need to define website languages or just set the most preferred language.</p>\n\n<p>Also as a very minor point I would change:</p>\n\n<pre><code>$lang = xxx;\nreturn $lang;\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>return xxx;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T00:10:36.250",
"Id": "9165",
"Score": "0",
"body": "Thank you! That's a sweet idea about more detailed parsing of ACCEPT_LANGUAGE. With the link you gave, always wondered, is there some sort of sacred knowledge behind using $_COOKIE instead of $_SESSION for language setting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T02:23:29.990",
"Id": "9166",
"Score": "0",
"body": "@paulus $_COOKIE is stored by the browser whereas $_SESSION is stored on the server. The different lifetimes might make COOKIE a better choice for language in a lot of situations. This describes it well: http://buildinternet.com/2010/07/when-to-use-_session-vs-_cookie/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T03:40:59.920",
"Id": "5941",
"ParentId": "5918",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5941",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T13:34:00.463",
"Id": "5918",
"Score": "4",
"Tags": [
"php"
],
"Title": "Detect locale with PHP"
}
|
5918
|
<p>In this case I have an array that is parsed from a JSON file. Normally I use all the elements in the array, but for <a href="http://code.google.com/web/ajaxcrawling/">AJAX crawling</a> I only show the parts the search engine asked for:</p>
<pre><code><?php $fitstyles = json_decode(file_get_contents(DATA_FILE), true); ?>
…
<?php
if ($base == "fits" || $base == "gallery") {
/* For fragment handler, delete out the parts of the fits array that aren't needed. */
$keep_fit = $fragments[1];
$keep_style = $fragments[2];
foreach ($fitstyles as $fit => $styles) {
if ($fit != $keep_fit) {
unset($fitstyles[$fit]);
continue;
}
foreach ($styles as $style => $styleinfo) {
if ($style != $keep_style) {
unset($fitstyles[$fit][$style]);
continue;
}
}
}
} ?>
</code></pre>
<p>Here, <code>$fragments</code> looks like:</p>
<pre><code>(
[0] => fits
[1] => straight
[2] => utility
)
</code></pre>
<p>and <code>$fitstyles</code> takes the following form:</p>
<pre><code>Array
(
[straight] => Array
(
[utility] => Array
( … )
)
[anotherfit] => Array
(
[anotherstyle] => ( … )
)
)
</code></pre>
<p>The approach appears to work; however, please give me feedback as to the effectiveness, efficiency and readability of this approach.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T17:05:53.253",
"Id": "9083",
"Score": "1",
"body": "IMO it would be more clear if you inverted the logic and built the resulting array instead of modifying an existing one (you can just assign `$fitstyles` with the resulting array if you want to keep the changes localized). I don't know enough about PHP to comment on whether this has any impact on efficiency."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T17:24:09.850",
"Id": "9084",
"Score": "0",
"body": "@user786653 I'd agree with you if $fitstyles were being put together iteratively, but the entire array comes from a one-line call to `json_decode`. I've edited my question to include that. Is there some alternative approach to parsing the JSON that would allow me to cherry-pick a given *key*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T17:52:15.240",
"Id": "9085",
"Score": "1",
"body": "I don't know, sorry, I was just commenting in general. Writing it the other way round seems more naturally (again this is only IMO) fits the problem statement and you're more likely to be able to extend and reuse the code for it (or find a built-in function to replace it)."
}
] |
[
{
"body": "<p>Your code is just fine, exactly how I would do it. </p>\n\n<p>There isn't much to discuss really, it's kind of simple. It's as effective / efficient as it could be, and fairly readable. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T01:32:06.303",
"Id": "7368",
"ParentId": "5919",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7368",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T15:28:42.350",
"Id": "5919",
"Score": "5",
"Tags": [
"php",
"array"
],
"Title": "How should I efficiently delete elements from a PHP array?"
}
|
5919
|
<p>I have the following code as part of an <code>sqlCommand</code> which is calling a stored procedure:</p>
<pre><code>Dim groupObj
If groupId = 0 Then
groupObj = DBNull.Value
Else
groupObj = groupId
End If
Dim siteObj
If siteId = 0 Then
siteObj = DBNull.Value
Else
siteObj = siteId
End If
sqlCommand.Parameters.Add(New SqlClient.SqlParameter("GroupID", SqlDbType.Decimal)).Value = groupObj
sqlCommand.Parameters.Add(New SqlClient.SqlParameter("SiteID", SqlDbType.Decimal)).Value = siteObj
</code></pre>
<p>I basically want to check for a condition and (if <code>true</code>) send a <code>DBNull</code> instead. This code looks awful however - is there a way to succinct this up?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:04:41.213",
"Id": "9099",
"Score": "2",
"body": "You should probably use nullable types for the inputs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:00:07.673",
"Id": "11641",
"Score": "0",
"body": "I definitely agree with using nullable types. Just to clarify that further, the SqlParameter class should have no problem with taking a plain old .NET `null` / `Nothing` value and automatically translating that into a database null value. DBNull generally comes into play when you are reading data out of a database, rather than writing to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T12:36:22.947",
"Id": "16653",
"Score": "0",
"body": "Actually, .NET will not translate null/nothing into a DBNull.Value. A SqlParameter with a null value will not be sent to the database at all. You can easily test this by creating a stored proc (or possibly prepared statement) with a parameter (with no default value) and try to send it in as a .NET null. You should get an exception saying stored procedure expected parameter but it was not passed in. if you have nulls that you want to send in you must explicitly set them to DBNull.Value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T08:24:54.880",
"Id": "105492",
"Score": "0",
"body": "You might want to check out [Nullable Types](http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx) and [?? Operator](http://msdn.microsoft.com/en-us/library/ms173224%28v=vs.80%29.aspx). You can significantly decrease the no of lines and improve your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:13:57.910",
"Id": "105493",
"Score": "0",
"body": "I like this answer. Would upvote if it provided just a little more specifics. Additionally, the `??` operator would not be applicable in this specific situation. Finally, `??` is the C# coalesce operator; the VB.NET equivalent would be to call the `If` function with only 2 arguments."
}
] |
[
{
"body": "<p>You could define an extension method like this (I'm not a VB programmer so please excuse the syntax errors):</p>\n\n<pre><code><Extension()> \nPublic Sub OrDBNull(ByVal val As Decimal)\n If val = 0\n return DBNull.Value\n End If\n\n return val ;\nEnd Sub\n</code></pre>\n\n<p>So your command parameters would become:</p>\n\n<pre><code>sqlCommand.Parameters.Add(New SqlParameter(\"GroupID\", SqlDbType.Decimal)).Value = groupObj.OrDBBull()\nsqlCommand.Parameters.Add(New SqlParameter(\"SiteID\", SqlDbType.Decimal)).Value = siteObj.OrDBNull()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:14:43.010",
"Id": "16736",
"Score": "0",
"body": "And also add an extension method to add the parameter. This is so repetitive!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T16:19:34.083",
"Id": "5921",
"ParentId": "5920",
"Score": "1"
}
},
{
"body": "<p>You can use the ternary operator If():</p>\n\n<pre><code>sqlCommand.Parameters.Add(New SqlClient.SqlParameter(\"GroupID\", SqlDbType.Decimal)).Value = If(groupID = 0, DBNull.Value, groupID)\nsqlCommand.Parameters.Add(New SqlClient.SqlParameter(\"SiteID\", SqlDbType.Decimal)).Value = If(siteId = 0, DBNull.Value, siteId)\n</code></pre>\n\n<p>Be aware that this can cause a compiler error if you have Option Strict turned on. The following is Option Strict compatible...</p>\n\n<pre><code>sqlCommand.Parameters.Add(New SqlClient.SqlParameter(\"GroupID\", SqlDbType.Decimal)).Value = If(groupID = 0, DBNull.Value, CObj(groupID))\nsqlCommand.Parameters.Add(New SqlClient.SqlParameter(\"SiteID\", SqlDbType.Decimal)).Value = If(siteId = 0, DBNull.Value, CObj(groupID))\n</code></pre>\n\n<p>The If ternary operator was added in .Net 3.5/Visual Basic 2008. If you're using and older version you'll need to use the IIF function. The syntax is almost the same, just replace if with iif </p>\n\n<pre><code>sqlCommand.Parameters.Add(New SqlClient.SqlParameter(\"GroupID\", SqlDbType.Decimal)).Value = IIF(groupID = 0, DBNull.Value, groupID)\nsqlCommand.Parameters.Add(New SqlClient.SqlParameter(\"SiteID\", SqlDbType.Decimal)).Value = IIF(siteId = 0, DBNull.Value, siteId)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T19:13:32.283",
"Id": "5926",
"ParentId": "5920",
"Score": "3"
}
},
{
"body": "<p>You should write an extension method for SqlCommand class</p>\n\n<pre><code><Extension()>\nPublic Sub AddParamWhereZeroIsNull(command As SqlCommand, name As String, value As Decimal?)\n command.Parameters.Add(New SqlParameter(name, SqlDbType.Decimal) With {.Value = If(value.GetValueOrDefault() = 0, DbNull.Value, value)})\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T12:16:15.380",
"Id": "10443",
"ParentId": "5920",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T15:51:15.287",
"Id": "5920",
"Score": "2",
"Tags": [
"sql",
".net",
"asp.net",
"vb.net"
],
"Title": "Calling stored procedure with a sqlCommand"
}
|
5920
|
<p>Does anyone know of a better / cleaner way to write the following:</p>
<pre><code>GetSafeTagName(txtUserInput.text);
public static string GetSafeTagName(string tag)
{
tag = tag.ToUpper()
.Replace("'","`")
.Replace('"','`')
.Replace("&", "and")
.Replace(",",":")
.Replace(@"\","/"); //Do not allow escaped characters from user
tag = Regex.Replace(tag, @"\s+", " "); //multiple spaces with single spaces
return tag;
}
</code></pre>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T18:54:04.213",
"Id": "9086",
"Score": "0",
"body": "[Here](http://stackoverflow.com/questions/1321331/replace-multiple-string-elements-in-c-sharp) is a SO question where the answer recommends using a `StringBuilder`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T17:48:26.867",
"Id": "9101",
"Score": "0",
"body": "wow, I didn't even know that site existed, I will ask over there thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T15:41:45.517",
"Id": "22518",
"Score": "0",
"body": "I once read an article by Jesse Liberty that said the decent support structure actually slowed the code down........"
}
] |
[
{
"body": "<p>When I had to do something similar, I used a <code>Dictionary<string, string></code> to define the replacements.</p>\n\n<p>And then something like this to replace:</p>\n\n<pre><code>foreach( KeyValuePair<string, string> pair in replacements)\n{\n str = str.Replace(pair.Key, pair.Value);\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T18:10:55.393",
"Id": "5925",
"ParentId": "5924",
"Score": "0"
}
},
{
"body": "<p>I think your method is pretty readable and clean as it stands. However, if you want to simplify the method itself, I have a decent support structure that would do so and possibly speed it up for particularly long strings:</p>\n\n<pre><code>internal static class SafeTag\n{\n private static readonly List<Replacement> replacements = new List<Replacement>\n {\n new Replacement(\"'\", \"`\"),\n new Replacement(\"\\\"\", \"`\"),\n new Replacement(\"&\", \"and\"),\n new Replacement(\",\", \":\"),\n new Replacement(\"\\\\\", \"/\")\n };\n\n private static readonly Regex spaces = new Regex(\"\\\\s+\", RegexOptions.Compiled);\n\n public static string GetSafeTagName(this string tag)\n {\n var parse = new StringBuilder(tag.ToUpper());\n replacements.ForEach(replacement => parse = parse.Replace(replacement.Original, replacement.ToReplaceWith));\n return spaces.Replace(parse.ToString(), \" \");\n }\n\n private struct Replacement\n {\n private readonly string original;\n\n private readonly string toReplaceWith;\n\n internal Replacement(string original, string toReplaceWith)\n {\n this.original = original;\n this.toReplaceWith = toReplaceWith;\n }\n\n internal string Original\n {\n get\n {\n return this.original;\n }\n }\n\n internal string ToReplaceWith\n {\n get\n {\n return this.toReplaceWith;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T19:54:28.160",
"Id": "5928",
"ParentId": "5924",
"Score": "0"
}
},
{
"body": "<p>You could use a regular expression and <code>Dictionary<string, string></code> to do the search replace:</p>\n\n<pre><code>// This regex matches either one of the special characters, or a sequence of \n// more than one whitespace characters.\nRegex regex = new Regex(\"['\\\"&,\\\\\\\\]|\\\\s{2,}\");\n\nvar map = new Dictionary<string, string> {\n { \"'\", \"`\"},\n { \"\\\"\", \"`\"},\n { \"&\", \"and\" },\n { \",\", \":\" },\n { \"\\\\\", \"/\" }\n};\n\n// If the length of the match is greater that 1, then it's a sequence\n// of spaces, and we can replace it by a single space. Otherwise, we\n// use the dictionary to map the character.\nstring output = regex.Replace(input.ToUpper(), \n m => m.Value.Length > 1 ? \" \" : map[m.Value]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-24T15:21:38.230",
"Id": "152769",
"Score": "0",
"body": "As elegant as it may seem, sadly this alternative is 3 times slower."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T17:49:46.827",
"Id": "5936",
"ParentId": "5924",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T17:51:03.453",
"Id": "5924",
"Score": "4",
"Tags": [
"c#",
"regex"
],
"Title": "Regular Expression replace specific characters"
}
|
5924
|
<p>This is a simple form validation script.</p>
<p>I'd like to:</p>
<ul>
<li>improve the jQuery validation</li>
<li>simplify the jQuery code</li>
</ul>
<p>Questions:</p>
<ol>
<li>Should I be exporting pure JS validation to avoid potential conflicts with other libraries that users might have installed?</li>
<li>Is it worth the effort or should I stick with my jQuery code?</li>
<li>Is there a way to reduce the chances for conflict with the jQuery code without having to reworking it to JS?</li>
</ol>
<p></p>
<pre><code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function() {
// when submit button is pressed
$("#form_name").submit(function() {
var pass = true;
var errors = {
required : 'this field is required',
email : 'enter a valid email address',
numeric : 'enter a number without spaces, dots or commas',
alpha : 'this field accepts only letters &amp; spaces'
};
var tests = {
email : /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
numeric : /^[0-9]+$/,
alpha : /^[a-zA-Z ]+$/
};
// clear error messages
$(".error").removeClass();
$(".error-message").remove();
function displayError(el, type) {
$(el).parent().addClass("error").find('label').append('<span class=\"error-message\"> &#8211; ' + errors[type] + '</span>');
}
$('.required, .email, .numeric, .alpha').each(function(){
var value = $(this).val();
var valueExists = value.length === 0 ? false : true;
var required = $(this).hasClass('required');
var email = $(this).hasClass('email');
var numeric = $(this).hasClass('numeric');
var alpha = $(this).hasClass('alpha');
if (required && value.length===0) {
displayError(this,'required');
pass=false;
}
else if (email && valueExists && !tests.email.test(value)) {
displayError(this,'email');
pass=false;
}
else if (numeric && valueExists && !tests.numeric.test(value)) {
displayError(this,'numeric');
pass=false;
}
else if (alpha && valueExists && !tests.alpha.test(value)) {
displayError(this,'alpha');
pass=false;
}
});
return pass;
});
});
/*]]>*/
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T19:39:23.130",
"Id": "9088",
"Score": "1",
"body": "You need a cross browser solution. jQuery is one of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T19:42:01.300",
"Id": "9089",
"Score": "0",
"body": "The thing that worries me is what happens when suddenly someone uses this on a site that also uses three other JS frameworks. Also, what happens when someone is already using another version of jquery and pastes this in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T20:41:54.127",
"Id": "9091",
"Score": "2",
"body": "This should be asked on stackoverflow as its a \"how do I\" question, not a code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T20:56:37.120",
"Id": "9093",
"Score": "2",
"body": "@Justin808 Since the code is working in working condition, I figured code review would be better suited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T09:31:49.103",
"Id": "9112",
"Score": "0",
"body": "+1 @Justin. The question actually has several points: the one about conflicts belongs in Stackoverflow; the one about improving the JQuery code belongs here. This is one good example why, if one has several questions, it's better to separate them into different threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T11:04:43.393",
"Id": "9116",
"Score": "0",
"body": "Is there a way to shift it to StackOverflow without duplicating it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T14:45:59.427",
"Id": "9123",
"Score": "1",
"body": "I have the power to shift the question to StackOverflow, but I'm not sure thats the correct thing to do. The question seems to mostly be about improving the existing code which belongs here. Ideally, the part about how to avoid conflict should have been asked on StackOverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T20:12:51.743",
"Id": "9191",
"Score": "0",
"body": "You are defining a function (displayError) inside of an event (#form_name.submit()). I would factor that out in any case. I would also feel compelled to remove a function which just duplicates jQuery functionality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T09:25:20.983",
"Id": "20365",
"Score": "1",
"body": "Are you really serving the document as XML? Otherwise the `CDATA` section makes no sense (HTML doesn’t recognise it) – and MSIE doesn’t render XML so I doubt it. For that reason, it’s generally a good idea to have JavaScript in external files, since you technically would need to escape `&` and `<` as entities otherwise."
}
] |
[
{
"body": "<p>To avoid conflict with any other libraries, wrap your code using the jQuery function, and additionally call jQuery.noConflict();</p>\n\n<p>The only conflict you may have is if somebody else imported an object named jQuery into the global namespace.</p>\n\n<p>Reference: <a href=\"http://docs.jquery.com/Using_jQuery_with_Other_Libraries\">http://docs.jquery.com/Using_jQuery_with_Other_Libraries</a></p>\n\n<p>Example:</p>\n\n<pre><code>jQuery.noConflict();\njQuery(document).ready(function($){\n //This is a jQuery function\n $('.myClass');\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T21:30:04.490",
"Id": "5929",
"ParentId": "5927",
"Score": "11"
}
},
{
"body": "<p>To protect from conflicting libraries wrap your code in an <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow\">immediately invoked function expression</a></p>\n\n<pre><code>(function ($, undefined) {\n $(document).ready(function() {\n // ...\n });\n} (jQuery.noConflict()));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T19:59:11.860",
"Id": "5950",
"ParentId": "5927",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5929",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T19:24:21.480",
"Id": "5927",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"validation"
],
"Title": "Simple form validation script"
}
|
5927
|
<p>I've created a small method to test the connection to a database:</p>
<pre><code>public bool TestConnection(string provider, string serverName, string initialCatalog, string userId, string password, bool integratedSecurity)
{
var canConnect = false;
var connectionString = integratedSecurity ? string.Format("Provider={0};Data Source={1};Initial Catalog={2};Integrated Security=SSPI;", provider, serverName, initialCatalog)
: string.Format("Provider={0};Data Source={1};Initial Catalog={2};User ID={3};Password={4};", provider, serverName, initialCatalog, userId, password);
var connection = new OleDbConnection(connectionString);
try
{
using (connection)
{
connection.Open();
canConnect = true;
}
}
catch (Exception exception)
{
}
finally
{
connection.Close();
}
return canConnect;
}
</code></pre>
<p>Despite the method works it doesn t seems right to me. Is any way to test the connection without having to catch the exception?
Is it possible to achieve the same result in a different way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T22:57:55.433",
"Id": "9094",
"Score": "1",
"body": "You should use `OleDbConnectionStringBuilder`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T22:58:18.087",
"Id": "9095",
"Score": "0",
"body": "seems like a reasonable use of exceptions as logic to me, you can omit the catch since its empty and just have a try/finally block"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:00:09.567",
"Id": "9096",
"Score": "3",
"body": "@Gabriel: Wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:14:37.917",
"Id": "9100",
"Score": "0",
"body": "@Slaksi know! thanks - I took your suggestion and what was left of mine (taking away the unused parameter to the catch) and made an answer.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T08:29:14.687",
"Id": "9111",
"Score": "2",
"body": "If you are going to use strings in complex scenarios such as that, I would suggest storing them in constants to make them more easily readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T11:37:36.083",
"Id": "63127",
"Score": "0",
"body": "If you want to check whether a connection is able to connect to a database successfully, there is no other way than the one posted by you or @Slaks and as given in this link: http://stackoverflow.com/questions/434864/how-to-check-if-connection-string-is-valid But, you can certainly validate whether the connection string is filled with proper values before passing it to the connection object."
}
] |
[
{
"body": "<p>It's a little verbose.</p>\n\n<p>I would write</p>\n\n<pre><code>try {\n using(var connection = new OleDbConnection(...)) {\n connection.Open();\n return true;\n }\n} catch {\n return false;\n}\n</code></pre>\n\n<p>You should also use <code>OleDbConnectionStringBuilder</code> to properly escape the variables in the connection string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:02:32.397",
"Id": "9097",
"Score": "1",
"body": "Is there a more specific exception that should be getting caught here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:03:47.420",
"Id": "9098",
"Score": "3",
"body": "@WinstonEwert: Good question. In principal, yes (`OleDbException` or `DataException`), but I'm not sure if I would rely on all providers conforming to that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:01:35.167",
"Id": "9175",
"Score": "0",
"body": "You definitely should NOT be catching all exceptions. Any good provider (like the ones in the framework) will document the exceptions they through. The SQL provider throws just SQLExceptions if its a SQL specific problem. (I tried to find a good reference for my assertion but could not in a quick search ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:12:23.040",
"Id": "9176",
"Score": "0",
"body": "@TomWinter: The Framework providers certainly will, but others may not, and unmanaged OleDEb drivers may have their own issues."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:01:32.840",
"Id": "5931",
"ParentId": "5930",
"Score": "14"
}
},
{
"body": "<p>You could refactor it to a TryOpenConnection method, which would be more a more commonly accepted reason to mix logic and error handling (which otherwise is a bad idea). I would think you actually want to use this connection? You don't have to open/close just for confirmation. I also think its a bit verbose to pass in each part of the connection string seperately, but you get the point: </p>\n\n<pre><code> public bool TryOpenConnection(string connectionString, out OleDbConnection connection)\n {\n try { \n var conn = new OleDbConnection(connectionString); \n conn.Open();\n connection = conn;\n return true; \n } \n catch (OleDbException exception) {\n connection = null; \n return false; \n } \n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T02:18:47.610",
"Id": "9105",
"Score": "2",
"body": "Good idea ...except that you should use the `using` clause. Set connection to null before `try-catch`; then `return connection != null`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T14:33:25.577",
"Id": "9122",
"Score": "0",
"body": "@ANeves: No...conn.Open() is still in a try-catch. Without proper formatting the following may be a little difficult to read, but I think you will see what I'm talking about :) ...\n `connection = null;\n try { \n using( var conn = new OleDbConnection(connectionString)) {\n conn.Open();\n connection = conn; }\n } \n catch (OleDbException exception) {\n // log failure\n } \n return connection != null`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:06:43.970",
"Id": "5932",
"ParentId": "5930",
"Score": "1"
}
},
{
"body": "<p>I wrote one a little ways back that worked with SQL Server and your current user identity:</p>\n\n<pre><code>namespace DatabaseConnectionTester\n{\n using System;\n using System.Data.Common;\n using System.Data.SqlClient;\n\n internal static class Program\n {\n private static int Main(string[] args)\n {\n bool result;\n\n if (args.Length == 0)\n {\n result = true;\n }\n else\n {\n try\n {\n var connectionString =\n \"Connect Timeout=10;Pooling=false;Integrated Security=sspi;server=\" + args[0];\n\n using (var connection = new SqlConnection(connectionString))\n {\n connection.Open();\n result = true;\n }\n }\n catch (DbException)\n {\n result = false;\n }\n\n if (args.Length > 1)\n {\n Console.WriteLine(result);\n }\n }\n\n return Convert.ToInt32(result);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:09:25.970",
"Id": "5933",
"ParentId": "5930",
"Score": "2"
}
},
{
"body": "<pre><code>void Main()\n{\n TestConnection(\n \"myprovider\",\n \"myserver\",\n \"myinitcat\",\n \"theuser\",\n \"thepass\",\n true);\n\n TestConnection(\n \"myprovider\",\n \"myserver\",\n \"myinitcat\",\n \"theuser\",\n \"thepass\",\n false);\n}\npublic bool TestConnection(string provider, string serverName, string initialCatalog, string userId, string password, bool integratedSecurity) \n{ \n var canConnect = false; \n var csb = new OleDbConnectionStringBuilder();\n csb.Provider = provider;\n csb.DataSource = serverName;\n csb.Add(\"Initial Calalog\", initialCatalog);\n if(integratedSecurity)\n {\n csb.Add(\"Integrated Security\", \"SSPI\");\n }\n else\n {\n csb.Add(\"User\", userId);\n csb.Add(\"Password\", password);\n } \n var connection = new OleDbConnection(csb.ToString()); \n try \n { \n using (connection) \n { \n connection.Open(); \n canConnect = true; \n } \n } \n catch\n {\n }\n finally \n { \n connection.Close(); \n }\n Console.WriteLine (csb.ToString());\n return canConnect; \n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Provider=myprovider;Data Source=myserver;Initial Calalog=myinitcat;Integrated Security=SSPI\nProvider=myprovider;Data Source=myserver;Initial Calalog=myinitcat;User=theuser;Password=thepass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T13:35:13.993",
"Id": "9119",
"Score": "0",
"body": "Use an object initializer: http://msdn.microsoft.com/en-us/library/bb384062.aspx `var csb = new OleDbConnectionStringBuilder { Provider = provider, DataSource = serverName };`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T23:13:26.793",
"Id": "5934",
"ParentId": "5930",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T22:54:38.487",
"Id": "5930",
"Score": "13",
"Tags": [
"c#",
".net"
],
"Title": "Test connection to database C#"
}
|
5930
|
<p>I'm working on a small project with dBase files from a 3rd party. Realizing that most of the code to fetch tables and form objects is the same, I made this function:</p>
<pre><code>public static IEnumerable<T> OleDbFetch<T>(Func<OleDbDataReader, T> formator, string connectionString, string query)
{
var conn = new OleDbConnection(connectionString);
conn.Open();
var cmd = new OleDbCommand(query, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
yield return formator(reader);
conn.Close();
}
</code></pre>
<p>That way I can use it with all sorts of classes (pre-made, imposed) that have mostly parameter-less constructors:</p>
<pre><code>class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Person() { }
}
//...
var persons = OleDbFetch<Person>(
r => new Person()
{
ID = Convert.ToInt32(r["ID"]),
Name = r["Name"].ToString()
},
connString, "SELECT ID, Name FROM Person");
</code></pre>
<p>Am I missing something obvious, being reckless, or giving myself too much trouble?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T02:48:55.637",
"Id": "9106",
"Score": "0",
"body": "I guess I should secure the connection... Make sure it's open."
}
] |
[
{
"body": "<p><code>Dispose()</code> of types that implement <code>IDisposable</code> with <code>using</code> blocks:</p>\n\n<pre><code>using (var conn = new OleDbConnection(connectionString))\n{\n conn.Open();\n using (var cmd = new OleDbCommand(query, conn))\n using (var reader = cmd.ExecuteReader())\n {\n while (reader.Read())\n yield return formator(reader);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T03:50:20.307",
"Id": "9108",
"Score": "0",
"body": "I'm a sucker for explicitly closing connections..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T03:08:48.010",
"Id": "5940",
"ParentId": "5938",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "5940",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T01:58:01.503",
"Id": "5938",
"Score": "5",
"Tags": [
"c#",
"linq",
"database"
],
"Title": "OLEDB table fetching function in C#"
}
|
5938
|
<p>EDIT - 0 - Still need to fix markup language to make more unique so escaping is not needed:</p>
<p>This will be a JSON / JQuery Alternative.</p>
<pre><code>/********************
group:ajax
********************/
/*
- ajax_object() - creates a browser dependent ajax_object for the ajax method call
- good place to add mysql logging to track object usage and reshape code via machine learning
- ouptut - returns false or ajax_object
*/
function ajax_object()
{
var object;
try
{
object=new XMLHttpRequest();
}
catch(error_1)
{
alert('ajax_object : not instantiated:contact-support@archemarks.com : Error : ' + error_1)
}
return object;
}
/*
- ajax() - post style ajax
- 'path' holds the servers side function to respond to the request
- 'param' hold the serialized information to send the server
- 'ajax_func' holds the javascript function to respond to the server
- 'div' div holds the html location to send the response text
- Output: returns 1 for pass.
*/
function ajax(path,param,ajax_func,html_div)
{
var object=new ajax_object();
object.open("POST",path,true);
object.setRequestHeader("Content-type","application/x-www-form-urlencoded");
object.setRequestHeader("Content-length",param.length);
object.setRequestHeader("Connection","close");
object.onreadystatechange=function()
{
if(this.readyState===4)
{
if(this.status===200)
{
if(this.responseText!=null)
{
ajax_func(this.responseText,html_div);
}
else alert("ajax: responseText is null")
}
else alert('AJAX FAIL: Path - ' + path + ' .status = ' + this.status + ' . responseText = ' + this.responseText)
}
}
object.send(param);
return 1;
}
/*
- "enumeration" for aml_status_type
*/
var aml_status_type =
{
"pass":0,
"fail":1,
"undefined":2
}
/*
- check_aml()
*/
function check_aml(text)
{
var aml_response=patterns.aml.exec(text);
if(aml_response)
{
if(aml_response[2]=='p')
{
return aml_status_type.pass;
}
else if (aml_response[2]=='f')
{
return aml_status_type.fail;
}
}
else
{
return aml_status_type.undefined;
}
}
/*
- ajax_signin()
*/
function ajax_signin(server_response_text,html_div)
{
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_status_type.pass)
{
reload();
}
else if(aml_status===aml_status_type.fail)
{
document.getElementById(html_div).innerHTML='';
document.getElementById(html_div).innerHTML=server_response_text;
}
else if(aml_status===aml_status_type.undefined)
{
server_response_text=server_response_text.substr(6);
alert('php error: ' + server_response_text);
}
}
/*
- ajax_singup()
*/
function ajax_signup(server_response_text,html_div)
{
aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_status_type.pass)
{
document.forms['upload_form'].submit();
}
else if(aml_status===aml_status_type.fail)
{
document.getElementById(html_div).innerHTML=server_response_text;
}
else if(aml_status===aml_status_type.undefined)
{
server_response_text=server_response_text.substr(6);
alert('php error: ' + server_response_text);
}
}
/*
- ajax_bookmark()
*/
function ajax_bookmark(server_response_text,html_div)
{
aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_status_type.pass)
{/*add code here when ready */}
else if (aml_status===aml_status_type.fail)
{/*add code here when ready */}
else if (aml_status===aml_status_type.undefined)
{
server_response_text=server_response_text.substr(6);
alert('php error: ' + server_response_text);
}
}
/*
- ajax_tweet() - takes in sturctured data and converts to html - remove the conversion into another method
*/
function ajax_tweet(server_response_text,html_div)
{
var first_split,second_split,tweet_count,return_string='';
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_status_type.pass)
{
server_response_text=server_response_text.substr(6);
first_split=server_response_text.split(/\|\|/);
for(tweet_count=0;tweet_count<first_split.length;tweet_count++)
{
second_split=first_split[tweet_count].split(/\|/);
return_string=return_string+'<div class="Bb2b"><img class="a" src="pictures/' + second_split[0] + '.jpg" alt=""/><a class="a" href="javascript:void(0)\">' + second_split[1] + ' posted ' + view_date(second_split[2],second_split[3]) + '</a><br/><p class="c">' + second_split[4] + '</p></div>';
}
fill_id(html_div,return_string);
}
else if (aml_status===aml_status_type.fail)
{/*add code here when ready */}
else if (aml_status===aml_status_type.undefined)
{
server_response_text=server_response_text.substr(6);
alert('php error: ' + server_response_text);
}
}
/*
- ajax_null()
*/
function ajax_null()
{
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>If you're just passing the IDs of elements, rather than the elements themselves, your variable names should reflect that. (Yes, it's possible to pass DOM elements around -- they're just objects, as far as JS cares. And if you passed the elements instead of their IDs, the code to do stuff with them would be shorter and you wouldn't feel the need for all those annoying <code>m#</code> functions.)</p></li>\n<li><p><code>ajax_object</code> returns <code>false</code> rather than throwing an error if AJAX isn't supported. Moreover, it's more complicated than it needs to be. Every browser that matters now supports <code>XMLHttpRequest</code>; the two <code>ActiveXObject</code>s are allowances for IE6, which IMO can safely be ignored. The only ones still stuck with IE6 are companies with pigheaded IT departments (which would probably blacklist your site anyway as \"not work related\") and people in China (but can they even get to non-whitelisted sites? The thought police seem really strict there). But even if you wanted to support them, it can be simpler -- you can define <code>XMLHttpRequest</code> yourself.</p>\n\n<p>Observe:</p>\n\n<pre><code>if (!window.XMLHttpRequest) {\n XMLHttpRequest = function() {\n // try getting the newest version first\n // if that fails, return a mostly-harmless fallback\n // if *that* fails, MSXML2 isn't supported and an error is thrown\n try {\n return new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch (ex) {\n return new ActiveXObject(\"Msxml2.XMLHTTP\");\n }\n };\n}\n\n// delete function ajax_object altogether; you don't need it anymore\n\nfunction ajax(path,param,ajax_func,html_div) {\n var object=new XMLHttpRequest();\n ...\n</code></pre>\n\n<p>IE6 includes MSXML v3, as does every OS since Win2k SP4. And v2, i believe, is supported as far back as IE5 and Win98. If your user is running something older than that, stuff should break. Gleefully. And <code>Microsoft.XMLHTTP</code> is just an alias for <code>Msxml2.XMLHTTP</code>, so you don't really gain anything by trying to use that name as a fallback.</p></li>\n<li><p>This \"aml\" stuff kinda creeps me out. If you intend for the response to be interpreted by JS, a more standard solution like JSON may be a better way to go. It's more portable (namely, you end up with built-in encoding/decoding in both JS and PHP), and you don't need to call a function like <code>check_aml</code>. In this case, it could be something like <code>var response = JSON.parse(server_response_text); if (response.status == 'fail') {...}</code>, and you could get rid of <code>aml_status_type</code> and <code>check_aml</code>. Though ideally, you'd parse the response in your <code>onreadystatechange</code> handler and pass that to the various functions.</p></li>\n<li><p>In <code>ajax_bookmark</code>, you have code like</p>\n\n<pre><code>if(aml_status===aml_status_type.pass)\n {;}\nelse if (aml_status===aml_status_type.fail)\n {;}\nelse if (aml_status===aml_status_type.undefined)\n {\n</code></pre>\n\n<p>The first two if sections should not exist, if you're not going to have anything in them. Only test for the conditions you actually intend to do something about. (If you actually had code there and took it out to lessen the amount of code you paste here, ok. Ignore the suggestion to remove. But for future reference, when you omit stuff, a comment like <code>/* do stuff here */</code> or an ellipsis (<code>...</code>) helps us know that.)</p></li>\n<li><p><code>document.f1_1.submit();</code>? You use <code>document.getElementById('...')</code> everywhere else; this is inconsistent. Either way, though, you're hard-coding the form name/id, which is kinda...eh. </p></li>\n<li><p>I see references to <code>m2()</code> and <code>m6()</code>. These names are useless; without the code to the functions, there's no way to say what they do. The names should be descriptive enough that one can come in without prior knowledge, read each function individually and get the gist of it, without having to know intimate details about every other function in the script. As it is, i'd have to yoyo through the file (if there were even definitions for the functions, which there aren't in this sample).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:53:57.567",
"Id": "9144",
"Score": "0",
"body": "in progress....(1) nice eye on the inconsistent usage of accessing the forms...I fixed this....(2)..added in comments to empty structures...I will fill these out later...2 complete..question on my item #3..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:02:09.197",
"Id": "9148",
"Score": "0",
"body": "You pass elements the same way you pass any other object in JS. `var element = document.getElementById('some_id');`...and now you can say `doStuffWith(element);` and such as that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:04:28.037",
"Id": "9149",
"Score": "0",
"body": "Posted minified methods. (3). Will remove these bit by bit as it might take a while."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:14:32.707",
"Id": "9152",
"Score": "0",
"body": "I'm assuming the reason for m{1,2,4,5} is to avoid typing `document.getElementById(html_div)` etc a bunch of times. Imagine you were passing around the element instead of its id. You could say `document.getElementById` once per element, and pass the element along -- where you needed to do stuff with it, instead of (say) `m2(html_div_id,return_string);`, you could say `html_div.innerHtml = return_string;`. It's clearer, and doesn't require even knowing about some other function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:17:17.163",
"Id": "9153",
"Score": "0",
"body": "Regarding JSON....how is the form any better on a conceptual level from my simple messages <xx_p> for messages and ||data1|data2||data1|data2||.....etc...when you say encoding/decoding..what do you mean exactly...do you mean for security purposes...these are just bookmarks...so i'm not using encoding yet...though it might be a neat feature to add in some encoding.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:18:44.137",
"Id": "9154",
"Score": "0",
"body": "Good point regarding getElementbyID...however I don't need to pass my elements around quite yet...but I'll keep that in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:26:39.180",
"Id": "9156",
"Score": "2",
"body": "I mean, that (1) JSON is standard, so everybody who looks at the code will know what's going on immediately; (2) JS and PHP (and just about all the other languages in common use) have built-in parsers and serializers for it, so you don't need to write your own; and (3) it can handle structures of arbitrary complexity, so you can return something like `{\"status\":\"success\",\"items\":[{\"id\":\"item1\",\"message\":\"Hi!\"},{\"id\":\"item2\",\"message\":\"another message\"},...]}` without having to even worry about how you're going to parse that. It'll just be an object or array almost the entire time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:35:57.967",
"Id": "9158",
"Score": "0",
"body": "And it's not so much about security here (though it wouldn't hurt); it's about data integrity and standards. Suppose the data could have a | in it. With your parser, you either have to figure out all the grammar rules yourself and implement them (read: reinvent JSON's escape mechanism), end up with broken data, or say \"you can't use |\". The first is just making more work for yourself, and the other two both look half-assed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:37:36.267",
"Id": "9159",
"Score": "0",
"body": "I did not follow your comments on ajax objects...a wrather recent book learning php mysql and javascript by Oreilly suggests calling the objects in that order...but if you have experience otherwise....you are saying the last two I use are outdated...so I will just remove these..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:38:45.110",
"Id": "9160",
"Score": "0",
"body": "Or simply used somting like <|> and <||>...woudl be better you are correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:39:55.717",
"Id": "9161",
"Score": "0",
"body": "I'm not concerned about IE6 and previous so I am not going to worry about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:43:26.273",
"Id": "9162",
"Score": "0",
"body": "`Microsoft.XMLHTTP` is just an alias to `Msxml2.XMLHTTP` (both have registry entries that point to the same classes) in every version of Windows since 2000 SP4. If one succeeds, the other will -- and if one fails, the other will too. There's supposedly security benefits to using the 6.0 one, but they all work pretty much the same from an ajax point of view. (And yes, the O'Reilly book is giving you old info.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:45:02.463",
"Id": "9163",
"Score": "0",
"body": "If you don't care about IE6, then drop the ActiveXObject stuff (and `ajax_object`) entirely. Every version of IE from 7 up supports XMLHttpRequest. Just say `new XMLHttpRequest()` everywhere you used to say `ajax_object()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T02:39:58.550",
"Id": "9167",
"Score": "2",
"body": "@stack.user.0 cHao is very wise and has given you very good suggestions. Don't implement a third of what cHao has suggested. Do all of it. JSON, passing DOM elements, removal of minified names, etc. If you only do a third your code is still going to be two thirds bad. Also, change your brace style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T19:48:45.197",
"Id": "9187",
"Score": "0",
"body": "I have removed all minified code...will update soon"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T03:04:11.357",
"Id": "9324",
"Score": "0",
"body": "...I've made most of the updates...I need to a tool to change the style..so i can't do this until I find a tool"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T03:05:07.253",
"Id": "9326",
"Score": "0",
"body": "incnsistent from access...was just caused by jshint...so I need to revisit this...www.jshint.com..complained about one way...so I switched back...on part"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:01:26.057",
"Id": "12265",
"Score": "0",
"body": "Fixed like 90% of this and reposted. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:03:23.060",
"Id": "12267",
"Score": "0",
"body": "Turns out that my markup language is actually leaner then JSON as far as # of characters needed..but b.c. it is written in Javascript/PHP (hella slow) instead of C++ not usable yet. Working on a C++ implementation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:46:32.187",
"Id": "12275",
"Score": "0",
"body": "repetetive conent was consolidated as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:56:29.487",
"Id": "12276",
"Score": "0",
"body": "added in older object calls as i have repeatability issues...not sure if removing these caused it but...the book at lpmj.net is not that old...and the author may have used that call order for a spcefic reason."
}
],
"meta_data": {
"CommentCount": "21",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:42:41.870",
"Id": "5947",
"ParentId": "5939",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "5947",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T03:00:10.023",
"Id": "5939",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "group - ajax - 0 - to_do - consistent access, styling"
}
|
5939
|
<p>I am working on a fifteen puzzle, and just got it working finally.
My next step is to implement an Iterative Deepening search on the puzzle to solve it.</p>
<p>I assume you go column by column, row by row with a loop until the checkwin function is complete?
I would really love any pointers or guidance that can be given.
Does not have to be code.</p>
<p>(A* is included, as that is the next step of my project to implement IDA*)</p>
<p>Here is my Code:</p>
<pre><code>#include <iostream>
#include <ctime>
enum EMove { keUp = 'w',
keDown = 's',
keLeft = 'a',
keRight = 'd'};
// Function declarations
void InitializeBoard(char[4][4]);
void PrintBoard(char[4][4]);
void LocateSpace(int&, int&, char[4][4]);
void Randomize(char[4][4]);
void Move(char[4][4], const EMove);
void InitializeTestBoard(char[4][4]);
char checkWin(char[4][4], char);
int main() {
char fBoard[4][4];
char mode;
int boardStates;
int depth;
using namespace std;
cout << "Would you like to do Test mode, Normal Mode, or Solve Mode? Type 't' or 'n' or 's'" << endl;
cin >> mode;
int counter = 0;
char isComplete = ' ';
if (mode == 't') //Test Mode
{
InitializeTestBoard(fBoard);
do {
counter++;
PrintBoard(fBoard);
cout << endl << "w = Up, s = Down, a = Left, d = Right" << endl;
cout << endl << "A = 10, B = 11, C = 12, D = 13, E = 14, F = 15" << endl;
char cNextMove;
cin >> cNextMove;
EMove eNextMove = (EMove)cNextMove;
Move(fBoard, eNextMove);
cout << endl;
checkWin(fBoard, isComplete);
} while (isComplete == 'n');
cout << "You Win!!" << endl;
cout << "In " << counter << " moves"<< endl;
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
else if (mode == 'n') //Normal Mode
{
InitializeBoard(fBoard);
Randomize(fBoard);
do {
counter++;
PrintBoard(fBoard);
cout << endl << "w = Up, s = Down, a = Left, d = Right" << endl;
cout << endl << "A = 10, B = 11, C = 12, D = 13, E = 14, F = 15" << endl;
char cNextMove;
cin >> cNextMove;
EMove eNextMove = (EMove)cNextMove;
Move(fBoard, eNextMove);
cout << endl;
checkWin(fBoard, isComplete);
} while (isComplete == 'n');
cout << "You Win!!" << endl;
cout << "In " << counter << " moves" << endl;
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
else if (mode == 's') //solve mode (Iterative Deepening Search)
{
InitializeBoard(fBoard);
Randomize(fBoard);
do {
PrintBoard(fBoard);
cout << endl << "Number of Board States: " << boardStates << endl;
cout << endl << "Depth Level:"<< depth << endl;
cout << endl;
checkWin(fBoard, isComplete);
} while (isComplete == 'n');
cout << "Puzzle Has been solved" << endl;
cout << "In " << boardStates << " Board States" << endl;
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void InitializeTestBoard(char fBoard[4][4]) {
const char tInitial[4][4] = {
{'1', '2', '3', '4'},
{'5', '6', '7', '8'},
{'9', 'A', 'B', 'C'},
{'D', 'E', ' ', 'F'}
};
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
fBoard[iRow][iCol] = tInitial[iRow][iCol];
}
}
}
void InitializeBoard(char fBoard[4][4]) {
const char fInitial[4][4] = {
{'1', '2', '3', '4'},
{'5', '6', '7', '8'},
{'9', 'A', 'B', 'C'},
{'D', 'E', 'F', ' '}
};
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
fBoard[iRow][iCol] = fInitial[iRow][iCol];
}
}
}
void PrintBoard(char fBoard[4][4]) {
using namespace std;
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
cout << fBoard[iRow][iCol];
}
cout << endl;
}
}
void LocateSpace(int& irRow, int& irCol, char fBoard[4][4]) {
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
if (fBoard[iRow][iCol] == ' ') {
irRow = iRow;
irCol = iCol;
}
}
}
}
void Randomize(char fBoard[4][4]) {
using namespace std;
srand((unsigned int)time(0));
for (int iIndex = 0; iIndex < 1000000; ++iIndex) {
const int kiNextMove = (rand() % 4);
switch (kiNextMove) {
case 0:
{
Move(fBoard, keUp);
break;
}
case 1:
{
Move(fBoard, keDown);
break;
}
case 2:
{
Move(fBoard, keLeft);
break;
}
case 3:
{
Move(fBoard, keRight);
break;
}
}
}
}
void Move(char fBoard[4][4], const EMove keMove) {
int iRowSpace;
int iColSpace;
LocateSpace(iRowSpace, iColSpace, fBoard);
int iRowMove(iRowSpace);
int iColMove(iColSpace);
switch (keMove) {
case keUp:
{
iRowMove = iRowSpace + 1;
break;
}
case keDown:
{
iRowMove = iRowSpace - 1;
break;
}
case keLeft:
{
iColMove = iColSpace + 1;
break;
}
case keRight:
{
iColMove = iColSpace - 1;
break;
}
}
// Make sure that the square to be moved is in bounds
if (iRowMove >= 0 && iRowMove < 4 && iColMove >= 0 && iColMove < 4) {
fBoard[iRowSpace][iColSpace] = fBoard[iRowMove][iColMove];
fBoard[iRowMove][iColMove] = ' ';
}
}
char checkWin(char fBoard[4][4], char isComplete)
{
const char fInitial[4][4] = {
{'1', '2', '3', '4'},
{'5', '6', '7', '8'},
{'9', 'A', 'B', 'C'},
{'D', 'E', 'F', ' '}
};
for (int i= 0; i < 5; i++)
{
if (fBoard[1][i] == fInitial[1][i] || fBoard[1][i] == fInitial[1][i] || fBoard[1][i] == fInitial[1][i] || fBoard[1][i] == fInitial[1][i])
{
isComplete = 'y';
}
else
isComplete = 'n';
if (fBoard[2][i] == fInitial[2][i] || fBoard[2][i] == fInitial[2][i] || fBoard[2][i] == fInitial[2][i] || fBoard[2][i] == fInitial[2][i])
{
isComplete = 'y';
}
else
isComplete = 'n';
if (fBoard[3][i] == fInitial[3][i] || fBoard[3][i] == fInitial[3][i] || fBoard[3][i] == fInitial[3][i] || fBoard[3][i] == fInitial[3][i])
{
isComplete = 'y';
}
else
isComplete = 'n';
if (fBoard[4][i] == fInitial[4][i] || fBoard[4][i] == fInitial[4][i] || fBoard[4][i] == fInitial[4][i] || fBoard[4][i] == fInitial[4][i])
{
isComplete = 'y';
}
else
isComplete = 'n';
}
return isComplete;
}
</code></pre>
<p>Any help you can give would be awesome!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T14:24:51.220",
"Id": "11962",
"Score": "0",
"body": "Can you factorize a bit the code duplicated for Test Mode and Normal Mode ?"
}
] |
[
{
"body": "<p>I see that your using <code>system(\"PAUSE\")</code> it works all fine and dandy but behind the scenes it creates some extra overhead that could be avoided using standard c++ calls</p>\n\n<p>read this article for more info on it...</p>\n\n<p><a href=\"http://www.gidnetwork.com/b-61.html\" rel=\"nofollow\">http://www.gidnetwork.com/b-61.html</a></p>\n\n<p>anyway if you replace it with <code>cin.get();</code>\nit has the same effect... it's just a matter of pressing enter to continue\nalso if you wanted to port this application to unix or mac os x, the system pause wouldn't work: you would get one of those \"this command is not recognizable\" messages.\nso... in conclusion, changing the <code>system('PAUSE')</code>'s to <code>cin.get();</code>'s is the way to go</p>\n\n<p>also the codes readability might benefit if you put the function implementations in a separate file</p>\n\n<p>hope this helped</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T11:04:49.517",
"Id": "9899",
"Score": "2",
"body": "IMO it doesn't matter that there will be a pause (overhead) when performing system(\"pause\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T04:50:47.193",
"Id": "13769",
"Score": "0",
"body": "Why would anybody advocate using a system call if its only to pause a program? (The answer isn't exactly related to the questions asked but still...)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T02:38:20.377",
"Id": "5943",
"ParentId": "5942",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-09T02:18:41.940",
"Id": "5942",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Iterative Deepening and A*"
}
|
5942
|
<p>I just started working in a project that wasn't developed by me, I'm worried about some of the functionalities and I would like some suggestions.</p>
<p>After the login validations, the login procedure is made like this:</p>
<pre><code>var _ticket = new FormsAuthenticationTicket(1, user.ID, DateTime.Now, DateTime.Now.AddDays(30), true, user.ID);
string encTicket = FormsAuthentication.Encrypt(_ticket);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
</code></pre>
<p>As we can see, there is a user object which stores the details of the logged in user (Id, name, e-mail...)</p>
<p>The first problem that I see is that on the FormsAuthenticationTicket the user ID is passed as the name. And every time I want to get any info from the user I have to do this:</p>
<pre><code>Item user = Framework.Business.Item.Load(HttpContext.Current.User.Identity.Name);
</code></pre>
<p>The project uses master page, and on every page I have to do this to get the ID/name/picture of the logged user</p>
<p>By the way, at least the load method gets the user date from a collection, BUT, this collection stores not only the users data but all the data that needs to be cached (since ID's are GUIDs) ids won't be duplicated and I think because of this reason, there is only one Collection for everything.</p>
<p>I would like to know if this is right, or what should I do to make it better</p>
|
[] |
[
{
"body": "<p>I think you can simply create a method (or even a property) in your master page, and use it in your pages to follow and adhere to the principal of DRY (Do not repeat yourself). Also in master page function (or property), you can use caching by a hidden class field, to make the performance even better. For example in your master page:</p>\n\n<pre><code>private User user;\npublic User User\n{\n get\n {\n if (user == null)\n {\n // Load user and assign it to the user field\n user = LoadUser(HttpContext.Current.User.Identity.Name);\n }\n return user;\n }\n}\n</code></pre>\n\n<p>Then in your pages, you can refer to your master page, by casting it to the type of your master page. For example, if the name of the master page class is GeneralMaterPage, then in a page using that master page, you can write:</p>\n\n<pre><code>public Page_Load(Object sender, EventArts e)\n{\n User user = (MasterPage as GeneralMasterPage).User;\n}\n</code></pre>\n\n<p>This way, you've implemented user extraction and loading code in one place. However, there is a better method for that. </p>\n\n<p>You can write an HTTP Module and bind to <code>AuthenticateRequest</code> event, and do the authentication mechanism yourself. Then, if the user is valid, you can simply create a <code>GeneralPrincipal</code> including the real user name and populate <code>HttpContext.Current.User</code> with that principal.</p>\n\n<p>Take a look at <a href=\"http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx\" rel=\"nofollow\">this link</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T09:45:17.143",
"Id": "5984",
"ParentId": "5944",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T13:50:38.797",
"Id": "5944",
"Score": "3",
"Tags": [
"c#",
".net",
"asp.net"
],
"Title": "C# asp.net project functionalities"
}
|
5944
|
<p>First of all: I am a total javascript beginner and therefore I am asking you to rate my script and tell me whether its okay or just a big mess. Note: it does work, but I guess it could be improved.</p>
<p>My main goal was to create a script, than can be used multiple times and does not depend on any class or id name (thats why I am using the data attribute).</p>
<pre><code>$(function(){
var toggleOpen = $('*.[data-toggle="open"]');
var toggleContent = $('*.[data-toggle="content"]');
var toggleClose = $('*.[data-toggle="close"]');
var toggleSpeed = 500;
//Set height of toggle content to avoid animation jumping
toggleContent.css('height', toggleContent.height() + 'px');
//Find content to toggle
function findNextContent(target){
var nextContent = target.parent().parent().parent().find(toggleContent);
return nextContent;
}
//Toggle content
function slideToggle(target){
target.stop(true,true).slideToggle(toggleSpeed);
}
//CLose toggled content
function closeToggle(target){
target.slideUp(toggleSpeed);
}
//On Open Click
toggleOpen.click(function(){
var clicked = $(this);
var nextContent = findNextContent(clicked);
//Check if hidden to either scroll to bottom or not
if(nextContent.is(':hidden')){
slideToggle(nextContent);
smoothScrolling(toggleClose);
}else{
slideToggle(nextContent);
}
return false;
});
//On Close click
toggleClose.click(function(){
var clicked = $(this);
var nextContent = findNextContent(clicked);
closeToggle(nextContent);
return false;
});
});
</code></pre>
<p>What it does: It toggles an element and it also takes care of a seperate close button.</p>
<p>I am glad for any feedback - be it positive or negative!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:21:42.600",
"Id": "9125",
"Score": "1",
"body": "Before I get started reviewing, have you [linted](http://www.jshint.com/) your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:39:41.627",
"Id": "9127",
"Score": "1",
"body": "@kojiro No, actually its the first time I heard of this tool and thanks a lot for sharing!! After doing it: I get a couple of \"Unnecessary semicolon\" (I´d like to keep them though - in case they dont have any negative impact?). And \"'smoothScrolling' is not defined.\" (thats because this function is outside my pasted example, but it does ofc exist in my whole code). Thanks again for sharing that tool!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:41:40.203",
"Id": "9128",
"Score": "0",
"body": "Oh and one more thing: \"Line 3: var toggleOpen = $('*.[data-toggle=\"open\"]'); Missing \"use strict\" statement.\" I am not sure what this means and how to solve it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:48:00.460",
"Id": "9129",
"Score": "0",
"body": "`\"use strict\"` is a feature of newer versions of JS. It means to make sure you're not doing a bunch of stuff that people accidentally do that causes lots of headaches. To use it, basically, you put that string (*just* that string; no var, no whatever=, none of that. just `\"use strict\";`) as the first line of your function, and then fix all the errors you'll probably get. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:51:50.847",
"Id": "9130",
"Score": "0",
"body": "[Here's some information on strict mode.](http://stackoverflow.com/questions/1335851) If you decide not to use it, you can turn it off in the [linter's options](http://www.jshint.com/options/). Get rid of the extra semicolons and read about the [difference between function declarations and function expressions.](http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/) As for `smoothScrolling`, you can just tell the linter that it's a global, and it won't complain anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:53:21.063",
"Id": "9131",
"Score": "0",
"body": "@cHao: Thanks for the explanation. So would you suggest to basically always use it in every script by putting it on top of any .js file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:56:42.383",
"Id": "9132",
"Score": "0",
"body": "@Andrej: If you like the idea of saying \"hey, JavaScript, help me write better code\", then try it out. Personally, i don't use it...but i can see where it might provide some huge benefits (assuming it's watching for actual common flaws and not just style issues)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:58:11.650",
"Id": "9133",
"Score": "0",
"body": "@kojiro: Following your advices, I have eliminated all errors and warnings and Lint gives me a \"Good Job\" :) - but this doesnt mean the script is well-written and efficient, does it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T17:05:59.770",
"Id": "9134",
"Score": "0",
"body": "@Andrej it means your script is lint-free and that if there are logic errors or other problems they'll be easier to pick out. So now, update your above code to the lint-free version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T17:09:51.820",
"Id": "9135",
"Score": "0",
"body": "@kojiro: Did that! Thanks for all your support."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:25:20.540",
"Id": "9155",
"Score": "0",
"body": "What does the `*.` part do in those first three selectors?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T11:51:10.660",
"Id": "9171",
"Score": "0",
"body": "@DisgruntledGoat: Thanks for your input! I initially thought it might be a good idea to add it to target all elements, which have the data attribute. But due to your comment and after testing it, I removed it now, because it works just fine for all elements without `*.`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T14:47:27.907",
"Id": "9174",
"Score": "0",
"body": "@Andrej I thought that may be the case but I was confused how `.[attr]` actually selected anything at all, unless it was a special character somehow (it's normally used for class selection). So yes, `[attr]` is the same as `*[attr]` - or in the more general sense: `*` is only necessary when alone and not combined with any other selectors."
}
] |
[
{
"body": "<p>OK, this code looks fine to me. The only thing I can suggest is that you might prefer to use <code>event.preventDefault</code> instead of <code>return false</code> in your event handlers, because in jQuery, <code>return false</code> in an event handler causes both event.preventDefault() <em>and</em> <code>event.stopPropagation()</code>, which you may not want.</p>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false\">https://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false</a></li>\n<li><a href=\"http://api.jquery.com/event.preventDefault/\" rel=\"nofollow noreferrer\">http://api.jquery.com/event.preventDefault/</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T17:44:28.363",
"Id": "9136",
"Score": "0",
"body": "Thanks again for the time you spent to look into it! I will go with `event.preventDefault`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T17:24:10.947",
"Id": "5949",
"ParentId": "5946",
"Score": "2"
}
},
{
"body": "<pre><code>function findNextContent(target){\n var nextContent = target.parent().parent().parent().find(toggleContent);\n return nextContent;\n}\n</code></pre>\n\n<p>You could possibly use the jQuery <a href=\"http://api.jquery.com/closest/\" rel=\"nofollow\">closest</a> function here.\nOr you could remove the variable and just do <code>return target.parent().parent().parent().find(toggleContent);</code></p>\n\n<pre><code>toggleClose.click(function(){\n var clicked = $(this);\n var nextContent = findNextContent(clicked);\n closeToggle(nextContent);\n return false;\n});\n</code></pre>\n\n<p>There is no need for the <code>clicked</code> variable. You can just write <code>findNextContent($(this));</code></p>\n\n<p>You might also want to look into the <a href=\"http://www.w3.org/TR/wai-aria/states_and_properties#aria-expanded\" rel=\"nofollow\">aria-expanded</a> attribute.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T20:43:31.367",
"Id": "9137",
"Score": "0",
"body": "Hi! Thanks for the improvements! I am gonna use `closest()` (edit: I ended up using `parents()` instead of `closest()`), since it makes more sense and I will remove the `var nextContent`. About the `clicked` variable: i thought that I maybe need to use `$(this)` more than once (not at the moment, but maybe when I expand the script with some more functionality) and I have read somewhere that when using it or any other selector more than once or twice, its a good idea to save it as a variable (not sure if thats true?). Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T20:52:06.973",
"Id": "9138",
"Score": "0",
"body": "For some reason `target.closest(toggleContent);` doesnt work, but `target.parents().find(toggleContent);` does. I would like to use closest() though, because it would not return multiple elements (if there are more than one). I will try to find the problem and post the edit in my original question!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T21:15:02.397",
"Id": "9139",
"Score": "1",
"body": "Great! As for the $(this), it is indeed better to cache it if you intend to use it multiple times. However, you can just do that when (and if) you expand the script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:56:18.840",
"Id": "9146",
"Score": "1",
"body": "@Andrej I agree With DADU, I think the saying is: \"Premature Optimisation is the root of all evil.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T23:33:41.887",
"Id": "9157",
"Score": "0",
"body": "@James That's correct. A trap I've been fallen into too many times (I can sense if from far now)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T11:55:00.373",
"Id": "9172",
"Score": "0",
"body": "@JamesKhoury: That really helped a lot! I didnt look at it from your point of view and was thinking \"I am probably gonna need it\". But thinking about it again, you are totally right to not use it until I actually need it. A great lesson to keep in mind for all future projects."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T20:31:04.223",
"Id": "5951",
"ParentId": "5946",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5951",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T15:58:04.500",
"Id": "5946",
"Score": "2",
"Tags": [
"javascript",
"performance",
"beginner",
"jquery"
],
"Title": "jQuery script to toggle an element and handle a Close button"
}
|
5946
|
<p>I was wondering if there was a more efficient way of taking strings that represent dates with the pattern being <code>mmddyy</code> or <code>mmd yy</code> or <code>m d yy</code> and converting them into a DateTime object?</p>
<p><code>111110</code> would be <code>11 11 10</code></p>
<p><code>111 10</code> would be <code>11 1 10</code></p>
<p><code>1 1 10</code> would be <code>1 1 10</code></p>
<p>The spaces are either ' ' or '\0' (the input I am given is not very clean)</p>
<p>This is what I have so far, which works for all cases.</p>
<pre><code>//Converts a given input string into a valid date
private DateTime convertToDateFromString(string dateString)
{
int length = dateString.Length;
int month = 1;
int day = 1;
int year = 1;
bool gotMonth = false;
bool gotDay = false;
bool gotYear = false;
char c = ' ';
char peek = ' ';
string buffer = "";
DateTime bufferDate;
int count = 0;
try
{
for (int i = 0; i < dateString.Length; i++)
{
c = dateString[i];
if ((i + 1) < dateString.Length)
peek = dateString[i + 1];
else
peek = '\0';
if (c != ' ' && c != '\0')
{
buffer += c;
count++;
if ((peek == ' ' || peek == '\0' || count == 2) && gotMonth == false)
{
count = 0;
gotMonth = true;
month = int.Parse(buffer);
buffer = null;
}
else if ((peek == ' ' || peek == '\0' || count == 2) && gotDay == false && gotMonth == true)
{
count = 0;
gotDay = true;
day = int.Parse(buffer);
buffer = null;
}
else if ((peek == ' ' || peek == '\0' || count == 2) && gotYear == false && gotMonth == true && gotDay == true)
{
count = 0;
gotYear = true;
year = int.Parse(buffer);
buffer = null;
if (year >= 80 && year <= 99)
year += 1900;
else if (year >= 0 && year <= 79)
year += 2000;
}
}
}
bufferDate = new DateTime(year, month, day);
}
catch (System.Exception ex)
{
bufferDate = new DateTime(1, 1, 1);
}
return bufferDate;
}
</code></pre>
|
[] |
[
{
"body": "<p>Here's a one-liner for you:</p>\n\n<pre><code> private DateTime convertToDateFromString(string dateString)\n {\n DateTime bufferDate;\n\n return DateTime.TryParseExact(\n dateString,\n new[] { \"MMddyy\", \"MMd yy\", \"M d yy\" },\n CultureInfo.InvariantCulture,\n DateTimeStyles.None,\n out bufferDate)\n ? bufferDate\n : new DateTime(1, 1, 1);\n }\n</code></pre>\n\n<p>With more than one line:</p>\n\n<pre><code> private DateTime convertToDateFromString(string dateString)\n {\n var allowedFormats = new[] { \"MMddyy\", \"MMd yy\", \"M d yy\" };\n DateTime parsedDate;\n var couldParse = DateTime.TryParseExact(\n dateString,\n allowedFormats,\n CultureInfo.InvariantCulture,\n DateTimeStyles.None,\n out parsedDate);\n\n if (couldParse)\n {\n return parsedDate;\n }\n\n return new DateTime(1, 1, 1); // or throw an exception\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:29:10.917",
"Id": "9140",
"Score": "0",
"body": "The idea is good but the implementation is unreadable. You should use some line breaks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:30:08.300",
"Id": "9141",
"Score": "0",
"body": "Yes, have some."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:47:54.700",
"Id": "9142",
"Score": "0",
"body": "Thanks :) Some temporary variable are also useful. I hope you wouldn't mind the edit but I didn't want to write it as a new asnwer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:50:31.190",
"Id": "9143",
"Score": "2",
"body": "Now you're pushing it :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T22:22:37.920",
"Id": "5953",
"ParentId": "5952",
"Score": "5"
}
},
{
"body": "<p>Here is what I found after more research (Stack Overflow)</p>\n\n<pre><code>private DateTime convertToDateFromString(string s)\n{\n string[] formats = new string[] { \"MMddyy\", \"MMd yy\", \"M d yy\" };\n string dateString = s.Replace('\\0', ' ');\n dateString = dateString.Trim();\n\n int spaces = dateString.Count(c => c == ' ');\n DateTime date = DateTime.ParseExact(dateString, formats[spaces], null);\n\n return date;\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/8086726/converting-a-string-to-a-date-in-c-sharp/8086902#8086902\">https://stackoverflow.com/questions/8086726/converting-a-string-to-a-date-in-c-sharp/8086902#8086902</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T14:47:09.140",
"Id": "5962",
"ParentId": "5952",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5953",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T21:24:20.707",
"Id": "5952",
"Score": "3",
"Tags": [
"c#"
],
"Title": "optimizing conversion between string and date"
}
|
5952
|
<p>How can I improve this?</p>
<p><a href="https://github.com/harbhag/Python-Scripts/blob/master/backup_script.py" rel="nofollow">GitHub</a> </p>
<pre><code>import os, platform, logging, logging.handlers, glob
from time import *
import tarfile
import zipfile, zlib
class backup:
source_s = ''
destination_d = ''
def __init__(self):
if strftime("%p") == 'AM':
if strftime("%I") in ['12', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']:
time_d = 'Morning'
else:
pass
if strftime("%p") == 'PM':
if strftime("%I") in ['12', '01', '02', '03']:
time_d = 'Afternoon'
elif strftime("%I") in ['04', '05', '06', '07', '08']:
time_d = 'Evening'
elif strftime("%I") in ['09', '10', '11']:
time_d = 'Night'
else:
pass
print "Date:",strftime("%d %b %Y")
print "Hi There, Today is ",strftime("%A")," And time is ", strftime("%I:%M:%S:%P"), ", So on this beautiful ",strftime("%A"),"", time_d," I welcome you to this Backup program."
def source_destination(self):
w_s = True
w_ss = True
while w_s:
source = raw_input('Please Enter The Complete Path of Source Directory: ')
if source == '':
print "***You have not Specified Anything***"
print "***Source Directory is required in Order to make backup***"
continue
elif os.path.exists(source) == False:
print "***Source Path Does not Exists***"
print "***Please check source path and Try Again***"
continue
else:
print "***Specified source path is ACCEPTED***"
w_s = False
backup.source_s = source
while w_ss:
destination = raw_input('Please Enter Complete Path of Destination Directory:')
destination = destination.replace(' ','_')
if destination == '':
print "***You have not Specified Anything***"
print "***Destination Directory is required to store the backup files***"
continue
elif os.path.exists(destination) == False:
print "***Destination Path Does not Exists***"
decision = raw_input('Do you Want me to Create Destination For you (yes or no or just hit enter for yes):')
if decision == 'yes':
print "***Destination Path Will now be created***"
os.mkdir(destination)
print "***Directory has been created now***"
print "***Program will now continue***"
backup.destination_d = destination
w_ss = False
elif decision == 'no':
print "***As You Wish, because Your wish is my Command***"
print "***Program will now Terminate***"
print "Bye !!!"
exit()
elif decision == '':
print "***Destination Path Will now be created***"
mk_d = 'mkdir {0}'.format(destination)
os.system(mk_d)
print "***Directory has been created now***"
print "***Program will now continue***"
backup.destination_d = destination
w_ss = False
elif decision not in ['yes','no','']:
print "***What you think you are doing, you just have to choose yes or no, is it that HARD?***"
print "***Try again now***"
continue
elif os.path.exists(destination) == True:
if os.path.isdir(destination)== False:
print "***Specified location is a file and not a directory, so try again and enter path of a directory***"
continue
else:
print "***Specified destination path is ACCEPTED***"
w_ss = False
backup.destination_d = destination
else:
print "***Specified destination path is ACCEPTED***"
w_ss = False
backup.destination_d = destination
def compress(self):
source = backup.source_s
destination = backup.destination_d
w_sss = True
f_name = raw_input('Please Enter The Desired name for output file(without extension):')
if f_name == '':
print "***You have not specified any name so DEFAULT will be used.(i.e 'untitled')***"
f_name = 'untitled'
else:
pass
while w_sss:
c_method = raw_input('How you want your backup file to be compressed ?(tar, tar.gz, tar.bz2, or zip):')
if c_method == 'tar':
ff_name = f_name.replace(' ', '_') + '.tar'
w_sss = False
elif c_method == 'tar.gz':
ff_name = f_name.replace(' ', '_') + '.tar.gz'
w_sss = False
elif c_method == 'tar.bz2':
ff_name = f_name.replace(' ', '_') + '.tar.bz2'
w_sss = False
elif c_method == 'zip':
ff_name = f_name.replace(' ', '_') + '.zip'
w_sss = False
elif c_method == '':
print "***You have not selected any method of compression***"
print "***Please select atleast one method of compression***"
continue
else:
print "***Sorry, The method you specified is not supported yet***"
print "Please choose from the given options i.e tar, tar.gz, tar.bz2 or zip "
continue
suffix = ("/")
if source.endswith(suffix) == True:
pass
else:
source = source + os.sep
if destination.endswith(suffix) == True:
pass
else:
destination = destination + os.sep
values = [source, destination, ff_name]
if c_method == 'tar':
print "***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***"
tar = tarfile.open(destination+ff_name, 'w')
for item in os.listdir(source):
print "Adding",item,"to archive"
tar.add(os.path.join(source,item))
tar.close()
print "Operation successful"
exit()
elif c_method == 'tar.gz':
print "***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***"
tar = tarfile.open(destination+ff_name, 'w:gz')
for item in os.listdir(source):
print "Adding",item,"to archive"
tar.add(os.path.join(source,item))
tar.close()
print "Operation successful"
exit()
elif c_method == 'tar.bz2':
print "***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***"
tar = tarfile.open(destination+ff_name, 'w:bz2')
for item in os.listdir(source):
print "Adding",item,"to archive"
tar.add(os.path.join(source,item))
tar.close()
print "Operation successful"
exit()
else:
print "***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***"
zipf = zipfile.ZipFile(destination+ff_name,"w", compression=zipfile.ZIP_DEFLATED)
def recursive_zip(a, b):
for item in os.listdir(b):
if os.path.isfile(os.path.join(b, item)):
print "Adding",item,"to archive"
a.write(os.path.join(b, item))
elif os.path.isdir(os.path.join(b, item)):
recursive_zip(a, os.path.join(b, item))
recursive_zip(zipf, source)
zipf.close()
print "Operation successful"
exit()
try:
p = backup()
p.source_destination()
p.compress()
except KeyboardInterrupt:
print "Why are you leaving me "
reason = raw_input("1. Your program is not good enough 2. I will be back (1 or 2):")
if(reason == '1'):
print "Thanks for using my program, I will try to Improve it, so till then, Good Bye !"
exit();
elif(reason == '2'):
print "OK then, See you Soon"
exit()
else:
print "Invalid Input !!!"
exit()
except EOFError:
print "Why are you leaving me "
reason = raw_input("1. Your program is not good enough 2. I will be back (1 or 2):")
if(reason == '1'):
print "Thanks for using my program, I will try to Improve it, so till then, Good Bye !"
exit();
elif(reason == '2'):
print "OK then, See you Soon"
exit()
else:
print "Invalid Input !!!"
exit()
</code></pre>
|
[] |
[
{
"body": "<pre><code>import os, platform, logging, logging.handlers, glob\nfrom time import *\nimport tarfile\nimport zipfile, zlib\n\nclass backup:\n</code></pre>\n\n<p>The python style guide recommends CamelCase for class names</p>\n\n<pre><code> source_s = ''\n destination_d = ''\n</code></pre>\n\n<p>Why are these class attributes rather then instance attributes?</p>\n\n<pre><code> def __init__(self):\n\n if strftime(\"%p\") == 'AM':\n if strftime(\"%I\") in ['12', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']:\n time_d = 'Morning'\n</code></pre>\n\n<p>I recommend not using _d in your variable name, its not clear what it means. Name your variables with something meaningful.</p>\n\n<pre><code> else:\n pass \n if strftime(\"%p\") == 'PM':\n if strftime(\"%I\") in ['12', '01', '02', '03']:\n time_d = 'Afternoon'\n elif strftime(\"%I\") in ['04', '05', '06', '07', '08']:\n time_d = 'Evening'\n elif strftime(\"%I\") in ['09', '10', '11']:\n time_d = 'Night'\n else:\n pass \n</code></pre>\n\n<p>Don't convert the time to a string, and then test it, it'll be easier if you get the time as numbers</p>\n\n<pre><code>current_time = time.localtime()\nif 0 <= current_time.tm_hour < 12:\n time_d = 'Morning'\n</code></pre>\n\n<p>For a self-contained unit this size, I'd move it into a seperate function that returns time_d</p>\n\n<pre><code> print \"Date:\",strftime(\"%d %b %Y\")\n print \"Hi There, Today is \",strftime(\"%A\"),\" And time is \", strftime(\"%I:%M:%S:%P\"), \", So on this beautiful \",strftime(\"%A\"),\"\", time_d,\" I welcome you to this Backup program.\"\n\n\n def source_destination(self):\n w_s = True\n w_ss = True\n</code></pre>\n\n<p>Bad variables names, they are pretty inscrutable</p>\n\n<pre><code> while w_s:\n source = raw_input('Please Enter The Complete Path of Source Directory: ')\n if source == '':\n print \"***You have not Specified Anything***\"\n print \"***Source Directory is required in Order to make backup***\"\n continue\n</code></pre>\n\n<p>This continue is pointless because the rest of the code is an else block, get rid of this.</p>\n\n<pre><code> elif os.path.exists(source) == False:\n print \"***Source Path Does not Exists***\"\n print \"***Please check source path and Try Again***\"\n continue\n</code></pre>\n\n<p>Same here</p>\n\n<pre><code> else:\n print \"***Specified source path is ACCEPTED***\"\n w_s = False\n</code></pre>\n\n<p>Use break, somebody may have told you not to use break, they were wrong. Break can be bad for readability, but setting boolean flags is worse.</p>\n\n<pre><code> backup.source_s = source\n</code></pre>\n\n<p>Don't start data on your class, store it on self.</p>\n\n<pre><code> while w_ss:\n</code></pre>\n\n<p>You set w_ss way above, don't do that. set variables close to their use</p>\n\n<pre><code> destination = raw_input('Please Enter Complete Path of Destination Directory:')\n destination = destination.replace(' ','_')\n</code></pre>\n\n<p>Magically replacing parts of the path is suspicous</p>\n\n<pre><code> if destination == '':\n print \"***You have not Specified Anything***\"\n print \"***Destination Directory is required to store the backup files***\"\n\n continue\n elif os.path.exists(destination) == False:\n print \"***Destination Path Does not Exists***\"\n decision = raw_input('Do you Want me to Create Destination For you (yes or no or just hit enter for yes):')\n if decision == 'yes':\n</code></pre>\n\n<p>use if decision == 'yes' or decision == '': to avoid duplicating this</p>\n\n<pre><code> print \"***Destination Path Will now be created***\"\n os.mkdir(destination)\n print \"***Directory has been created now***\"\n print \"***Program will now continue***\"\n</code></pre>\n\n<p>Your script is overly printy. It says a lot more then it does.</p>\n\n<pre><code> backup.destination_d = destination\n w_ss = False\n</code></pre>\n\n<p>as before, boolean flags are delayed gotos. Don't use them unless you must. Use break.</p>\n\n<pre><code> elif decision == 'no':\n print \"***As You Wish, because Your wish is my Command***\"\n print \"***Program will now Terminate***\"\n print \"Bye !!!\"\n exit()\n</code></pre>\n\n<p>Doing this is generally not considered good form. There is nothing terribly wrong with it, but generally you should terminate your program by returning back to the main loop.</p>\n\n<pre><code> elif decision == '':\n print \"***Destination Path Will now be created***\"\n mk_d = 'mkdir {0}'.format(destination)\n os.system(mk_d)\n</code></pre>\n\n<p>Why are you using system to make a directory? Use the os.mkdir function as you did above</p>\n\n<pre><code> print \"***Directory has been created now***\"\n print \"***Program will now continue***\"\n backup.destination_d = destination\n w_ss = False\n elif decision not in ['yes','no','']:\n print \"***What you think you are doing, you just have to choose yes or no, is it that HARD?***\"\n print \"***Try again now***\"\n continue\n</code></pre>\n\n<p>Don't insult your users</p>\n\n<pre><code> elif os.path.exists(destination) == True:\n</code></pre>\n\n<p>Don't use <code>== True</code> just use <code>if os.path.exists(destination):</code>\n if os.path.isdir(destination)== False:</p>\n\n<p>Same with False. use <code>if not os.path.isdir(destination)</code></p>\n\n<pre><code> print \"***Specified location is a file and not a directory, so try again and enter path of a directory***\"\n continue\n else:\n print \"***Specified destination path is ACCEPTED***\"\n w_ss = False\n backup.destination_d = destination\n\n else:\n</code></pre>\n\n<p>Can this ever happen? You should either find yourself in the destination exists or destination does not exist category</p>\n\n<pre><code> print \"***Specified destination path is ACCEPTED***\"\n w_ss = False\n backup.destination_d = destination\n</code></pre>\n\n<p>This function is too long. You should break it up. I'd want to make this function something like:</p>\n\n<pre><code> def backup_destination(self):\n while True:\n destination = raw_input()\n if validate_destination(destination):\n self.destination = destination\n return \n</code></pre>\n\n<p>See how short it is and how easy it is to see what its doing. All the details are tucked away in other functions.</p>\n\n<pre><code> def compress(self):\n source = backup.source_s\n destination = backup.destination_d\n\n w_sss = True\n</code></pre>\n\n<p>You do realize you can reuse the same variable name across different functions don't you?</p>\n\n<pre><code> f_name = raw_input('Please Enter The Desired name for output file(without extension):')\n\n if f_name == '':\n print \"***You have not specified any name so DEFAULT will be used.(i.e 'untitled')***\"\n f_name = 'untitled'\n else:\n pass\n</code></pre>\n\n<p>No need for an en empty else clause</p>\n\n<pre><code> while w_sss:\n c_method = raw_input('How you want your backup file to be compressed ?(tar, tar.gz, tar.bz2, or zip):') \n\n if c_method == 'tar':\n ff_name = f_name.replace(' ', '_') + '.tar'\n w_sss = False\n elif c_method == 'tar.gz':\n ff_name = f_name.replace(' ', '_') + '.tar.gz'\n w_sss = False\n elif c_method == 'tar.bz2':\n ff_name = f_name.replace(' ', '_') + '.tar.bz2'\n w_sss = False\n elif c_method == 'zip':\n ff_name = f_name.replace(' ', '_') + '.zip'\n\n w_sss = False\n</code></pre>\n\n<p>instead use </p>\n\n<pre><code> if c_method in ('tar','tar.gz','tar.bz2','zip'):\n ff_name = f_name.replace(' ','_') + '.' + c_method\n break\n</code></pre>\n\n<p>That reduces duplication</p>\n\n<pre><code> elif c_method == '':\n print \"***You have not selected any method of compression***\"\n print \"***Please select atleast one method of compression***\"\n\n continue\n else:\n print \"***Sorry, The method you specified is not supported yet***\"\n print \"Please choose from the given options i.e tar, tar.gz, tar.bz2 or zip \"\n\n continue\n\n suffix = (\"/\")\n</code></pre>\n\n<p>The parens do nothing</p>\n\n<pre><code> if source.endswith(suffix) == True:\n pass \n else:\n source = source + os.sep\n</code></pre>\n\n<p>Why are you using \"/\" above and os.sep here? Use os.sep everywhere</p>\n\n<pre><code> if destination.endswith(suffix) == True:\n pass\n</code></pre>\n\n<p>Don't have empty if blocks, invert the logic of the if statement \n else:\n destination = destination + os.sep</p>\n\n<p>You do the same thing to destination and source, write a function to do it</p>\n\n<pre><code> values = [source, destination, ff_name]\n</code></pre>\n\n<p>Unused variable, delete it</p>\n\n<pre><code> if c_method == 'tar':\n print \"***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***\"\n</code></pre>\n\n<p>You have the same print in every if block, copy it outside of the if block</p>\n\n<pre><code> tar = tarfile.open(destination+ff_name, 'w')\n</code></pre>\n\n<p>use os.path.join to combine pieces of a path. It will take care of the os.sep you were dealing with earlier</p>\n\n<pre><code> for item in os.listdir(source):\n print \"Adding\",item,\"to archive\"\n tar.add(os.path.join(source,item))\n\n\n tar.close()\n print \"Operation successful\"\n exit()\n</code></pre>\n\n<p>again, exiting midscript is considered bad form. (in most cases)</p>\n\n<pre><code> elif c_method == 'tar.gz':\n print \"***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***\"\n tar = tarfile.open(destination+ff_name, 'w:gz')\n for item in os.listdir(source):\n print \"Adding\",item,\"to archive\"\n tar.add(os.path.join(source,item))\n\n\n tar.close()\n print \"Operation successful\"\n exit()\n</code></pre>\n\n<p>See how this is exactly the same as the first case, but with a different mode, write a function that takes the mode as a parameter</p>\n\n<pre><code> elif c_method == 'tar.bz2':\n print \"***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***\"\n tar = tarfile.open(destination+ff_name, 'w:bz2')\n for item in os.listdir(source):\n print \"Adding\",item,\"to archive\"\n tar.add(os.path.join(source,item))\n\n tar.close()\n print \"Operation successful\"\n exit()\n</code></pre>\n\n<p>And again!</p>\n\n<pre><code> else:\n print \"***Compression can take sometime depending upon method you selected and the size of the source, so please be patient***\"\n zipf = zipfile.ZipFile(destination+ff_name,\"w\", compression=zipfile.ZIP_DEFLATED)\n def recursive_zip(a, b):\n for item in os.listdir(b):\n if os.path.isfile(os.path.join(b, item)):\n print \"Adding\",item,\"to archive\"\n a.write(os.path.join(b, item))\n elif os.path.isdir(os.path.join(b, item)):\n recursive_zip(a, os.path.join(b, item))\n\n\n\n recursive_zip(zipf, source)\n</code></pre>\n\n<p>Why are you supporting recursive for zip, but nobody else?</p>\n\n<pre><code> zipf.close()\n print \"Operation successful\"\n exit()\n</code></pre>\n\n<p>Zip is different, but similiar to the others. I'd make it so they share code, but that's ab it trickier. </p>\n\n<pre><code>try:\n p = backup()\n</code></pre>\n\n<p>Don't use one letter variable names, unless the abbreviation is really common</p>\n\n<pre><code> p.source_destination()\n p.compress()\nexcept KeyboardInterrupt:\n print \"Why are you leaving me \"\n reason = raw_input(\"1. Your program is not good enough 2. I will be back (1 or 2):\")\n if(reason == '1'):\n print \"Thanks for using my program, I will try to Improve it, so till then, Good Bye !\"\n exit();\n elif(reason == '2'):\n print \"OK then, See you Soon\"\n exit()\n else:\n print \"Invalid Input !!!\"\n exit()\n\nexcept EOFError:\n print \"Why are you leaving me \"\n reason = raw_input(\"1. Your program is not good enough 2. I will be back (1 or 2):\")\n if(reason == '1'):\n print \"Thanks for using my program, I will try to Improve it, so till then, Good Bye !\"\n exit();\n elif(reason == '2'):\n print \"OK then, See you Soon\"\n exit()\n else:\n print \"Invalid Input !!!\"\n exit()\n</code></pre>\n\n<p>use <code>except (KeyboardInterrupt, EOFError):</code> to catch multiple exceptions</p>\n\n<p>Generally</p>\n\n<ol>\n<li>You have a lot of useless continue statements that don't do anything</li>\n<li>You use boolean flag variables, you should use break</li>\n<li>Your variable names are cryptic</li>\n<li>You duplicate a lot of logic. You should strive to have each piece of logic once</li>\n<li>Your functions tend to be long and complicated, they should be broken up into smaller functions</li>\n<li>Your compare boolean values with <code>== True</code> and <code>== False</code> DON'T!</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T16:02:16.383",
"Id": "9178",
"Score": "0",
"body": "Thanks man, I am gonna rewrite this script by following your suggestions. Can you recommend me some good book/tutorial/paper so that I can be a good programmer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-31T19:05:22.667",
"Id": "33920",
"Score": "0",
"body": "@Harbhag: I'd suggest [Dive Into Python](http://www.diveintopython.net/). Reading the [Standard Library sources](http://hg.python.org/cpython/file/tip/Lib) can be helpful as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T14:00:54.040",
"Id": "5961",
"ParentId": "5956",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "5961",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T06:43:14.700",
"Id": "5956",
"Score": "2",
"Tags": [
"python",
"file-system"
],
"Title": "Simple interactive backup script"
}
|
5956
|
<p><strong>Topic 1: Switching to another form from the project startup form</strong></p>
<p>I use the following code that calls an instance of my form for payment (<code>frmPayment</code>) from my startup form (<code>frmMainMenu</code>) using a click event:</p>
<pre><code>Private Sub btnPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPayment.Click, PaymentToolStripMenuItem.Click
Dim frmPaymentX As New frmPayment() 'declare payment form
Me.Visible = False
frmPaymentX.ShowDialog()
End Sub
</code></pre>
<p>Should I use something other than <code>Me.Visible = False</code> in handling my startup form (<code>frmMainMenu</code>) during my form switch?</p>
<p><strong>Topic 2: Switching back to the startup form</strong></p>
<p>Likewise, I use the following code to return to my startup form (<code>frmMainMenu</code>) from my form for payment (<code>frmPayment</code>):</p>
<pre><code>Private Sub btnMainMenu_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMainMenu.Click
frmMainMenu.Show()
Me.Close()
End Sub
</code></pre>
<ol>
<li>Should I directly call my startup form (<code>frmMainMenu</code>) as I am doing in my example or should I be calling an instance of my starup form (<code>frmMainMenu</code>)?</li>
<li>I believe that I should use <code>show()</code> and not <code>showdialog()</code> for this. Is this correct?</li>
<li>Should I use something other than <code>Me.Close()</code>?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T16:42:37.783",
"Id": "9170",
"Score": "0",
"body": "The best practice is the one that works. What doesn't work?"
}
] |
[
{
"body": "<p>Firstly, I think you need to clarify why you are wanting to show the payment form and hide the main form. In most applications, when you want to show a dialog of some description, you would show it modally (using <code>dialog.ShowDialog()</code>) so that it appears over the top of your current form and prevents the user from interacting with the other form until the opened dialog is closed.</p>\n\n<p>Secondly, if you are wanting your current main form and payment dialog as two screens as opposed to a form and a dialog, then you may be better off creating some shell form that can contain a <code>UserControl</code>. You can then build the main form and payment form as two <code>UserControl</code>'s and simply switch which is being displayed on your window.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T13:23:54.893",
"Id": "5960",
"ParentId": "5957",
"Score": "1"
}
},
{
"body": "<p>The hiding thing strikes me as a little bit odd. Generally one doesn't care about hiding the main form. If the intent is to switch between \"pages\" in the app, a tab pane or wizard-style setup might be a better idea.</p>\n\n<p>As for your existing code (should you keep it), in the main form, i'd recommend</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub btnPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _\nHandles btnPayment.Click, PaymentToolStripMenuItem.Click\n ' use `Using` here to ensure the subform is disposed when we're done.\n ' `Close` doesn't dispose forms shown via `ShowDialog`.\n Using frmPaymentX As New frmPayment() 'declare payment form\n Me.Hide() ' works like `Me.Visible = False`,but more OOPish IMO\n frmPaymentX.ShowDialog()\n Me.Show() ' duh\n End Using\nEnd Sub\n</code></pre>\n\n<p>In the subform...</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub btnMainMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _\nHandles btnMainMenu.Click\n ' (don't worry about controlling the main form here; it'll take care of itself)\n Me.Close()\nEnd Sub\n</code></pre>\n\n<p>Note, all this is assuming that the subform is indeed a subform (and that the first <em>aka</em> 'main' form should control things). If the two are logically independent and equally in control, then tabs or a wizard would probably be better, depending on which one fits (which only you would know, since we don't have the UI in hand).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T16:21:18.263",
"Id": "5966",
"ParentId": "5957",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5960",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T15:17:20.480",
"Id": "5957",
"Score": "3",
"Tags": [
"vb.net",
"winforms"
],
"Title": "Switching back and forth between forms"
}
|
5957
|
<p>The following is the producer-consumer algorithm for a piece of software that I'm upgrading to take advantage of multi-core processing. The intended platform is some flavor of Linux running on an <a href="http://aws.amazon.com/ec2/instance-types/" rel="nofollow">EC2 HPC cc4x.large cluster</a>, which feature 2 x Intel Xeon X5570, quad-core “Nehalem” architecture processors (2*4=8 cores). The software runs a genetic algorithm for optimizing artificial neural networks.</p>
<p>My dominating concern is performance. RAM and HD capacity are not an issue, but CPU time and anything else that delays processing is. Right now I've made a few (noted below), hopefully trivial, compromises to make the program portable to Mac OS X, which is on my home computer that I use for coding/debugging. I note a few other minor issues in the comments, most notably an uncertainty about thread-safeness in the consumer function. This is my first time working with threads. Advice/criticism of any kind is much appreciated.</p>
<pre><code>#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <vector>
#define NUM_THREADS 3 //will be >= to # of cores
#define N 30
//globals
sem_t* producer_gate;
sem_t* consumer_gate;
pthread_mutex_t access_queued =PTHREAD_MUTEX_INITIALIZER;
int queued;
int completed;
//a dummy class for testing thread-safeness
class the_class
{
public:
void find_num()
{
//make sure completion is non-instant and variable
double num = rand();
for(double q=0; 1; q++)
if(num == q)
return;
}
};
//the consumer function for handling the parallelizable code
void* Consumer(void* argument)
{
std::vector <the_class>* p_v_work = (std::vector <the_class>*) argument ;
while(1)
{
sem_wait(consumer_gate);
pthread_mutex_lock (&access_queued);
int index = queued;
queued--;
pthread_mutex_unlock (&access_queued);
(*p_v_work)[index-1].find_num();
completed++; //<-- thread safe??
std::cout << "\n" << index;
if(completed == N)
sem_post(producer_gate);
}
return NULL;
}
int main ()
{
srand(5);
//holds data to be processed and the methods for processing it
std::vector <the_class> work(N);
std::vector <the_class>* p_work = &work;
sem_unlink("producer_gate");
sem_unlink("consumer_gate");
//can't use `sem_init();` under Mac OS X so use sem_open instead
producer_gate = sem_open("producer_gate", O_CREAT, 0700, 0);
consumer_gate = sem_open("consumer_gate", O_CREAT, 0700, N);
completed = 0;
queued = N;
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); //no joining necessary
pthread_t threads[NUM_THREADS];
for(int q=0; q<NUM_THREADS; q++)
//on OS X, a pthread_t must be provided or a bus error occurs. relevant to performance?
pthread_create(&threads[q], &attr, Consumer, (void*) p_work );
for( int q=0; q < 4; q++)
{
sem_wait(producer_gate);
std::cout << "\nDONE\n";
////////////////////////////////////////////////////////
// Summate work done and layout work for next iteration
////////////////////////////////////////////////////////
completed = 0;
queued = N;
for(int q=0;q<N;q++)
sem_post(consumer_gate); //some way to just set this instead of incrementing?
}
sem_wait(producer_gate);
std::cout << "\n\nCompleted (: !!\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T20:49:31.180",
"Id": "9300",
"Score": "1",
"body": "http://stackoverflow.com/questions/4682889/is-floating-point-ever-ok/4682941#4682941"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T12:20:27.227",
"Id": "9336",
"Score": "0",
"body": "Oh yeah, I ignored the possibly-never-terminating loop and addressed only the threading part. @palacsint is right though, this is unlikely to work even as a dummy test case."
}
] |
[
{
"body": "<h1>Style</h1>\n\n<p>I see something that looks like a <em>thread safe queue</em> abstraction, which is mysteriously implemented as a collection of globals and one argument. These are a fairly well-known subspecies of container, so write one (or find an existing one that suits your purposes)</p>\n\n<pre><code>template <typename T>\nclass MTQueue\n{\npublic:\n // simple operations will lock & unlock on every call\n void push(T const &);\n T pop();\n\n // ...\n};\n</code></pre>\n\n<p>Just pass a pointer to this to your thread function, and your threads can <code>pop</code> at will.\nNote this could trivially use a std::queue or any other container internally (and you may prefer FIFO rather than LIFO) - all you're really doing is bundling some container with a mutex and enforcing the lock semantics when you change (or inspect) it.</p>\n\n<p>I also see something that looks like a barrier (your use of semaphores), but I suspect your consumers can start consuming as soon as there's something in the queue, so you just need a way for the producer to wait until they're all done. We could add a method to wait until the work queue is empty, but that doesn't tell us the work is complete. Should there be a results queue? If so, use another instance of the same type: the producer can be popping results in parallel, it doesn't need to wait until the last one is calculated.</p>\n\n<h1>Performance</h1>\n\n<p>There are a couple of approaches to making it fast:</p>\n\n<h2>Batching</h2>\n\n<p>Consider the relative cost of the synchronization involved in popping an item from the queue, and actually doing the work: it might be faster overall to add a more elaborate interface so you can push/pop multiple items with only the same synchronization overhead, eg.</p>\n\n<pre><code> // more elaborate interface to amortise synchronization cost?\n void push(std::vector<T> const &);\n void pop(std::vector<T> &out);\n</code></pre>\n\n<p>or you could just switch to pushing/popping a <em>batch of work</em> object instead of single jobs: same effect, may leave you with a simpler and more reuseable queue.</p>\n\n<h2>Alternative Synchronization Strategies</h2>\n\n<p>Mutual exclusion is only one way of sharing data across multiple cores, and to be honest it's probably a good fit here (especially if you calibrate the batch size correctly).\nHowever, if you really want to get stuck in, look up <em>lock free</em> or <em>non-blocking</em> queues as well - for some workloads and core counts, they might suit you better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T21:19:25.623",
"Id": "9382",
"Score": "0",
"body": "good points on the batch work, lock-free algorithms, and results queue. It just happens that in my case all operations are more or less trivial in comparison to the threaded function (not shown here, replaced with dummy for concision), but its good to know. Never encountered a thread-safe cue before so I'll have to look into that. Thanks for the comments."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T17:49:00.113",
"Id": "6036",
"ParentId": "5963",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "6036",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T14:56:26.803",
"Id": "5963",
"Score": "8",
"Tags": [
"c++",
"performance",
"multithreading",
"pthreads"
],
"Title": "Multithreading algorithm for high performance parallel computing and Producer-Consumer queue using POSIX threads"
}
|
5963
|
<p>I'm in the middle of writing my own little bullet shooter game much in the style of Touhou. Everything works fine so far but I'm disliking certain aspects of my code. Take this function for showing and unshowing the title screen:</p>
<pre><code> private function runIntro() : void
{
if (introFadeInTitle_ && aliceIntroTxt.alpha < 1)
aliceIntroTxt.alpha += 0.02;
else if (introFadeInTitle_)
{
var timer : Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, function() {
timer.stop();
introFadeInBtns_ = true;
});
timer.start();
introFadeInTitle_ = false;
}
else if (introFadeInBtns_ && startBtn.alpha < 1)
{
startBtn.alpha += 0.02;
optionsBtn.alpha += 0.02;
}
else if (introFadeInBtns_)
{
introFadeInBtns_ = false;
gameState = GameState.READY;
}
if (introFadeOutBtns_ && startBtn.alpha > 0)
{
startBtn.alpha -= 0.02;
optionsBtn.alpha -= 0.02;
}
else if (introFadeOutBtns_)
{
var timer : Timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, function() {
timer.stop();
introFadeOutTitle_ = true;
});
timer.start();
introFadeOutBtns_ = false;
}
else if (introFadeOutTitle_ && aliceIntroTxt.alpha > 0)
aliceIntroTxt.alpha -= 0.02;
else if (introFadeOutTitle_)
{
var timer : Timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, function() {
timer.stop();
introFadeOutBg_ = true;
});
timer.start();
introFadeOutTitle_ = false;
}
else if (introFadeOutBg_ && introBg.alpha > 0)
introBg.alpha -= 0.02;
else if (introFadeOutBg_)
{
introFadeOutBg_;
gameState = GameState.RUNNING;
}
}
</code></pre>
<p>At a glance, it's just a bunch of if-else-if statements that check whether or not a given object has faded out and what the current state of the animation is. I feel that this if-else-if chain is alright for a rather short function like this, but I do have more complicated states that I wish to show (for example a ready-set-go splash before the fight begins) that would just balloon this kind of structure into an unholy mess.</p>
<p>What is the best way to deal with this code?</p>
|
[] |
[
{
"body": "<p>Start with simple re factoring. </p>\n\n<p>1) Create a class called stateclass with variables introFadeInTitle_ , aliceIntroTxt , introFadeInBtns_ , startBtn etc. Set the variables of this class with the values </p>\n\n<p>2) Instead of checking and setting properties in runIntro , hide the complexities in functions of the class and use those functions. Remember to give the functions a meaningful name so that the code flow is clear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T17:56:05.000",
"Id": "9180",
"Score": "0",
"body": "I thought of creating a class called 'Intro' or something that would display everything pertaining to my intro screen, but doing that would mean that I need one for all of my state-functions. If I decided to dump it all in my stateclass I think I would violate the single-responsibility rule, it would have states of multiple things in my game and that sounds like a mess. If you think I'm not understanding your concept correctly, would you please elaborate more on it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T18:02:16.070",
"Id": "9181",
"Score": "0",
"body": "While answering your question I also had a similar doubt. In this case the single responsibility could be setting the over all state but can also be setting individual state. Another design is creating different classes for different conditions and using a factory pattern."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T17:42:55.547",
"Id": "5967",
"ParentId": "5964",
"Score": "3"
}
},
{
"body": "<p>If ActionScript supports enums use an enum instead of the many booleans. If not, use a string with one constant for every state. It's also better than the booleans. For example:</p>\n\n<pre><code>...\nelse if (state == FADE_INT_ASDF) {\n state = CODE_OF_NEXT_STATE;\n gameState = GameState.READY;\n}\n...\n</code></pre>\n\n<p>If the logic was more complicated it would be worth implementing the <a href=\"http://en.wikipedia.org/wiki/State_pattern#Java\" rel=\"nofollow\">State pattern</a>.</p>\n\n<hr>\n\n<p>If the booleans were replaced to an enum/string constants you can create a new <code>setTimer</code> function which could remove some code duplication:</p>\n\n<pre><code>private function setTimer(int timeout, IntroState/String newState) : void {\n var timer : Timer = new Timer(timeout);\n timer.addEventListener(TimerEvent.TIMER, function() {\n timer.stop();\n state = newState;\n });\n timer.start();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T06:41:38.670",
"Id": "9274",
"Score": "0",
"body": "Wouldn't state pattern be an over kill here ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T21:07:41.003",
"Id": "5971",
"ParentId": "5964",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "5971",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:10:27.740",
"Id": "5964",
"Score": "4",
"Tags": [
"actionscript-3",
"state",
"actionscript"
],
"Title": "Using Booleans to Manage State"
}
|
5964
|
<p>Examples of where I've started migrating to short-circuit evaluation:</p>
<p><strong>PHP</strong></p>
<pre><code>$id=0;//initialized in case of no result
$r=mysql_query(SQL);
if($r && mysql_num_rows($r)>0){
list($id)=mysql_fetch_row($r);
}
</code></pre>
<p>becomes</p>
<pre><code>$id=0;
$r=mysql_query(SQL);
$r && mysql_num_rows($r)>0 && list($id)=mysql_fetch_row($r);
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code>var Req=jQuery.ajax(OBJECT);
//Something has happened and now i want to abort if possible
if(Req && Req.abort){
Req.abort();
}
</code></pre>
<p>becomes</p>
<pre><code>var Req=jQuery.ajax(OBJECT);
//Something has happened and now i want to abort if possible
Req && Req.abort && Req.abort();
</code></pre>
<p>I'm familiar with the short <code>if</code> style of </p>
<pre><code>if(Req && Req.abort) Req.abort();
</code></pre>
<p>but it feels clunkier than short-circuit evaluation.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-10T20:08:50.337",
"Id": "163802",
"Score": "0",
"body": "This question may have been acceptable at the time it was asked, but it does not meet Code Review's question standards in 2015. Since you've asked about two isolated excerpts in two different languages that have nothing to do with each other besides the use of `&&`, this is a generic best-practices question, and therefore off-topic."
}
] |
[
{
"body": "<p>This is an abuse of short-circuit evaluation. It's not immediately obvious what the intent is. Sure, i can <em>eventually</em> see that you're getting an ID, calling <code>Req.abort()</code>, whatever. But i shouldn't have to decipher a line of code first to figure out what it does.\nConciseness never trumps readability in source code. (Sure, minifying/packing JS has its benefits. But you don't write packed/minified code; you start out with decent code and then run a tool on it.)</p>\n\n<p>Since your intent is to do the one thing <strong>if</strong> the other stuff is true, the code should say that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-01T21:14:23.307",
"Id": "98024",
"Score": "1",
"body": "The added benefit is that when you see `if (x) { y }`, you can read `x` or `y` quickly and decide if you need to read the full statement or can skip it because it doesn't apply to your current task. With a single statement, you must read `x` plus enough of `y` to parse it. It makes scanning the code much harder."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T06:12:06.807",
"Id": "5982",
"ParentId": "5976",
"Score": "8"
}
},
{
"body": "<p>Also, jsbeautifier will format your code like this:</p>\n\n<pre><code>var Req = jQuery.ajax(OBJECT); //<- Note the spaces around the equal sign\n//Something has happened and now i want to abort if possible\nif(Req && Req.abort)\n{\n Req.abort();\n}\n</code></pre>\n\n<p>Beyond, that lowerCamelCase should apply so <code>Req</code> -> <code>req</code> or even better <code>request</code> and <code>OBJECT</code> -> <code>object</code>, I am not too excited about either generic name, but I guess this is just a stub.</p>\n\n<p>Furthermore it seems a bit paranoid to not trust <code>request</code> or <code>request.abort()</code>, I don't have enough code to see if this paranoia is justified.</p>\n\n<p>Personally, I have taken to write this as :</p>\n\n<pre><code>( request && request.abort ) ? request.abort() : undefined;\n</code></pre>\n\n<p>or, with jQuery providing <code>noop</code></p>\n\n<pre><code>( request && request.abort ) ? request.abort() : $.noop();\n</code></pre>\n\n<p>The <code>undefined</code> yells at my subconscious that I should really handle <code>request</code> or <code>request.abort</code> being falsey.</p>\n\n<p>Furthermore, on <code>if</code> statements with 1 statement in the <code>true</code> block</p>\n\n<p>Not acceptable:</p>\n\n<pre><code>if(Req && Req.abort) Req.abort();\n</code></pre>\n\n<p>Somewhat acceptable:</p>\n\n<pre><code>if(Req && Req.abort) \n Req.abort();\n</code></pre>\n\n<p>Best practice:</p>\n\n<pre><code>if(Req && Req.abort){\n Req.abort();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-01T22:53:54.567",
"Id": "98036",
"Score": "1",
"body": "If the coding standard were to allow single-statement blocks without braces, I would prefer to keep it in the same line to minimize the chance of adding a second statement without also adding braces. That said, I vastly prefer requiring braces in all cases for safety."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T12:30:08.060",
"Id": "98113",
"Score": "0",
"body": "Hmmm, I never thought of it that way"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-01T21:15:30.313",
"Id": "55820",
"ParentId": "5976",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "5982",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T23:59:29.447",
"Id": "5976",
"Score": "6",
"Tags": [
"javascript",
"php"
],
"Title": "Relying on short-circuit evaluation instead of using the IF control structure"
}
|
5976
|
<p>This is a function which produces the sum of primes beneath (not including) a certain number (using a variant on the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">sieve of Eratosthenes</a>). </p>
<pre><code>erastosum = lambda x: sum([i for i in xrange(2, x) if i == 2 or i == 3 or reduce(lambda y,z: y*z, [i%j for j in xrange(2,int(i ** 0.5) + 1)])])
</code></pre>
<p>Excessive use of lambda? Perhaps. Beautification would be nice, but I'm looking for performance optimizations. Sadly, I'm not sure if there is any further way to optimize the setup I've got right now, so any suggestions (on how to, or what else to do) would be nice.</p>
|
[] |
[
{
"body": "<p>As much as I love anonymous functions, they can be a nightmare to debug. Splitting this code up piece wise (into an actual function or otherwise) shouldn't and wouldn't decrease it's performance while improving maintenance and portability for you later on.</p>\n\n<p><a href=\"http://www.rfc1149.net/blog/2006/02/10/prime-numbers-and-pell-equation/\" rel=\"nofollow\">This class</a> is quite efficient for determining primes. Despite being quite lengthy is more efficient than the more usual approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T05:18:30.977",
"Id": "5981",
"ParentId": "5977",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "5981",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T00:09:50.663",
"Id": "5977",
"Score": "1",
"Tags": [
"python",
"optimization",
"lambda"
],
"Title": "Excessive use of lambda with variant of Sieve of Eratosthenes?"
}
|
5977
|
<p>I'm using this C# function to generate random coupons for a system. How can I improve it?</p>
<pre><code>public static string GenerateCoupon(int length)
{
string result = string.Empty;
Random random = new Random((int)DateTime.Now.Ticks);
List<string> characters = new List<string>() { };
for (int i = 48; i < 58; i++)
{
characters.Add(((char)i).ToString());
}
for (int i = 65; i < 91; i++)
{
characters.Add(((char)i).ToString());
}
for (int i = 97; i < 123; i++)
{
characters.Add(((char)i).ToString());
}
for (int i = 0; i < length; i++)
{
result += characters[random.Next(0, characters.Count)];
Thread.Sleep(1);
}
return result;
}
</code></pre>
<p>Business requirements are:</p>
<ol>
<li>The length of coupons are not fixed and static</li>
<li>Coupons can contain A-Z, a-z and 0-9 (case sensitive alphanumeric) </li>
<li>Coupons should be unique (which means that we store them as key in a table in database, and for each coupon, we check its uniqueness)</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T23:47:15.430",
"Id": "9450",
"Score": "0",
"body": "I think in general you probably ought to avoid using _both_ upper and lower case letters. Especially if you're including numbers... What font are you outputting these in - how do the characters `I` (upper-case I), `l` (lower-case L) and `1` (the number 1) appear?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:43:14.897",
"Id": "9484",
"Score": "0",
"body": "@X-Zero using both upper & lower increases the availably data space (number of combinations) by a huge factor. Why wouldn't you use these? If they are to be entered by humans, choose a good font that makes the difference between 1, I & l apparent (i.e. don't let the marketing team stuff it up)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:54:33.327",
"Id": "9487",
"Score": "0",
"body": "@KirkBroadhurst - I'm aware that using both increases the possible combinations - Although I somewhat doubt that many possibilities are needed (A 10-character code has 36^10 = 3,656,158,440,062,976 or 3 _quadrillion_ combinations). And you can only hope that the marketing department has control over this - if these are being _emailed_ to customers they may not be printed in the font you expect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T00:31:53.003",
"Id": "9489",
"Score": "0",
"body": "@X-Zero If they're emailed, then I would *hope* that there's a link that means the user doesn't need to re-enter the code. Having worked in this 'coupon' environment, they issue is when you move from digital (email, tweet, facebook - where you can use a hyperlink) to print, where you rely on re-entry. Ideally you avoid that re-entry, but not always possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T00:41:17.290",
"Id": "9490",
"Score": "0",
"body": "@KirkBroadhurst - Agreed, it's the re-entry that's the problem (either online or in a store). The other thing to keep in mind is that some store registers don't support entering different (usually lower) cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T14:28:34.473",
"Id": "60204",
"Score": "0",
"body": "Here's [a Stack Overflow answer of mine](http://stackoverflow.com/questions/4616685/how-to-generate-a-random-string-and-specify-the-length-you-want-or-better-gene/4616709#4616709) regarding precisely this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T14:33:04.520",
"Id": "60205",
"Score": "0",
"body": "I still think that my own solution is much more readable than yours, and beyond that, I think the solution of palacsint is the most readable one, which implements SRP also (two methods, one for getting the allowed characters even from an external configuration source, and one for generating random strings out of that list). :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T17:18:29.377",
"Id": "60206",
"Score": "0",
"body": "To each their own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-16T23:52:38.127",
"Id": "369243",
"Score": "0",
"body": "A Coupon sounds like something that should be secure, in general rolling your own security is a bad idea, but at the very least you should be using RNGCryptoServiceProvider"
}
] |
[
{
"body": "<p>Some general idea, I hope all work in C# too. Feel free to edit the answer if it is not a proper C# syntax.</p>\n\n<p>1, Change the type of the <code>characters</code> list to <code>char</code> and change the loop variable to <code>char</code> too. This way you don't have to cast and the <code>for</code> loops are easier to read:</p>\n\n<pre><code>List<char> characters = new List<char>() { };\nfor (char c = '0'; i <= '9'; c++) {\n characters.Add(c);\n}\n...\nfor (int i = 0; i < length; i++){\n result += characters[random.Next(0, characters.Count)];\n}\n</code></pre>\n\n<p>2, Is there any reason of the <code>Thread.Sleep(1);</code>. It looks unnecessary.</p>\n\n<p>3, I'd remove <code>0</code>, <code>O</code>, <code>o</code> and <code>l</code>, <code>1</code> from the list. It's easy to mix up them.</p>\n\n<p>4, I'd pull out an <code>AllowedCharacters</code> method:</p>\n\n<pre><code>public static List<char> AllowedCharacters() {\n List<char> characters = new List<char>() { };\n for (char c = '0'; i <= '9'; c++) {\n characters.Add(c);\n }\n ...\n characters.Remove('O');\n characters.Remove('0');\n ...\n return characters;\n}\n\npublic static string GenerateCoupon(int length)\n{\n string result = string.Empty;\n Random random = new Random((int)DateTime.Now.Ticks);\n List<string> characters = AllowedCharacters();\n\n for (int i = 0; i < length; i++) {\n result += characters[random.Next(0, characters.Count)];\n }\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T13:04:33.393",
"Id": "5985",
"ParentId": "5983",
"Score": "6"
}
},
{
"body": "<p>Let's look at some of the code:</p>\n<pre><code>Random random = new Random((int)DateTime.Now.Ticks);\n</code></pre>\n<p>You don't need to create a seed for the Random constructor from the clock, the parameterless constructor does that:</p>\n<pre><code>Random random = new Random();\n</code></pre>\n<hr />\n<pre><code>List<string> characters = new List<string>() { };\n</code></pre>\n<p>You don't need the initialiser brackets when you don't put any items in the list at that point:</p>\n<pre><code>List<string> characters = new List<string>();\n</code></pre>\n<hr />\n<pre><code>result += characters[random.Next(0, characters.Count)];\n</code></pre>\n<p>Using <code>+=</code> to concatenate strings is bad practice. Strings are not appended at the end, as strings are immutable. Code like <code>x += y;</code> actually end up as <code>x = String.Concat(x, y)</code>. You should rather use a <code>StringBuilder</code> to build the string.</p>\n<hr />\n<pre><code>Thread.Sleep(1);\n</code></pre>\n<p>Why on earth are you sleeping in the middle of the loop?</p>\n<hr />\n<p>Instead of creating a list of strings, just use a string literal to pick characters from:</p>\n<pre><code>public static string GenerateCoupon(int length) {\n Random random = new Random();\n string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";\n StringBuilder result = new StringBuilder(length);\n for (int i = 0; i < length; i++) {\n result.Append(characters[random.Next(characters.Length)]);\n }\n return result.ToString();\n}\n</code></pre>\n<p>Consider if all those characters should be included, or wheter you should omit similar looking characters like <code>o</code>, <code>O</code> and <code>0</code>. Having the characters in a string literal makes it easy to do that.</p>\n<h3>Edit:</h3>\n<p>If you are going to call the method more than once, you should send in the random generator as a parameter:</p>\n<pre><code>public static string GenerateCoupon(int length, Random random) {\n string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";\n StringBuilder result = new StringBuilder(length);\n for (int i = 0; i < length; i++) {\n result.Append(characters[random.Next(characters.Length)]);\n }\n return result.ToString();\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>Random rnd = new Random();\nstring[] coupon = new string[10];\nfor (int i = 0; i < coupon.Length; i++) {\n coupon[i] = GenerateCoupon(10, rnd);\n}\nConsole.WriteLine(String.Join(Environment.NewLine,coupon));\n</code></pre>\n<p>Example output:</p>\n<pre><code>LHUSer9dPZ\nbtK0S01yLb\nhruw4IXINJ\nhwMdRDRujt\ncr4TDezvcZ\nb8tVETNXNL\nJrG6sfXgZF\nY7FRypnRiQ\nJbfnhY3qOx\nquWNakbybY\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T13:03:15.707",
"Id": "9253",
"Score": "1",
"body": "I sleep `1` millisecond, because, generated coupons would be the same. Try it. Microsoft says that the `Random` algorithm is based on time, and when you simply create many random numbers in one CPU clock tick, then you get the same numbers for each random generation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T13:17:05.810",
"Id": "9254",
"Score": "11",
"body": "@SaeedNeamati: It's only the initial seed that is based on the clock, the following random numbers are based on the previous, not on the clock. So, sleeping between each use of `Next` has no effect at all. If you are going to call `GenerateCoupon` more than once, you should create one random generator outside the method, and pass it in as a parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T14:24:07.763",
"Id": "9255",
"Score": "0",
"body": "+1 for your good answer, :). But give it a try yourself. Create a simple loops (something like 500 times), and print the randomly generated numbers to the screen. See the result. Even if you pass it to the generation method as a parameter. I'd love to be wrong, since it means that I'll gain `1` millisecond of performance boost, per each generated coupon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T16:47:11.883",
"Id": "9262",
"Score": "1",
"body": "@SaeedNeamati: Then you are doing something wrong... I added an example above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:03:44.820",
"Id": "9302",
"Score": "0",
"body": "Sleeping in the loop ensures that there's sleeping between creations of `Random` objects, and thus that the seeds are different - which is why simply taking the `Sleep` out of @Saeed's code ends up with duplicate coupons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:44:08.467",
"Id": "9303",
"Score": "2",
"body": "@EdmundSchweppe: Yes, that is why I wrote above that he should create one random generator outside the method, and pass it in as a parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T02:02:39.147",
"Id": "9316",
"Score": "0",
"body": "@Guffa: I figured you knew that; I wanted to make sure the OP realized it as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:16:56.647",
"Id": "9481",
"Score": "0",
"body": "@Guffa This is one thing that always puzzles me about these unique id generators, how do you know they are unique. Could the above code generate 2 strings that are the same?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:48:03.837",
"Id": "9485",
"Score": "0",
"body": "@JamesHurford: This doesn't generate unique strings, only random strings. You would have to keep all strings that are in use so that you can check that one hasn't been used before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:59:33.533",
"Id": "9488",
"Score": "1",
"body": "I realise this, but since the question specified requiring unique strings, I thought that that was what was being attempted. \"Coupons should be unique\". This is why I asked, as there is lots of stuff to learn out there, and there was no way I thought that this could guarantee a unique string, but since it was what was required than I thought maybe this code actually somehow does."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T22:21:10.107",
"Id": "5994",
"ParentId": "5983",
"Score": "33"
}
},
{
"body": "<p>That <code>Thread.Sleep(1)</code> is a real problem, especially if you're going to use this to generate thousands or millions of coupons at a time. The only reason you need it is because you're creating a new instance of <code>Random</code> <strong>for each coupon</strong> and seeding that instance with the current time. The default constructor of <code>Random</code> already handles time-based seeding; if you make the instance static, you only need to construct it once and thus avoid the duplication issue.</p>\n\n<p>I like @palacsint's idea of using a <code>List<char></code> to store allowed characters and populating it with character-indexed <code>for</code> loops, although I'd make the list a lazy-initialized property rather than recreating it each time. And I fully agree with @Guffa's point about using <code>StringBuilder</code> to create the coupon rather than the <code>+=</code> operator.</p>\n\n<pre><code>public class CouponGenerator\n{\n private static List<char> _allowed = null;\n private static List<char> AllowedChars\n {\n get\n {\n if (_allowed == null)\n {\n _allowed = new List<char>();\n for (char c = 'A'; c < 'Z'; c++)\n {\n _allowed.Add(c);\n }\n for (char c = 'a'; c < 'z'; c++)\n {\n _allowed.Add(c);\n }\n for (char c = '0'; c < '9'; c++)\n {\n _allowed.Add(c);\n }\n }\n return _allowed;\n }\n }\n private static Random _rg = new Random();\n public static string GenerateCoupon(int length)\n {\n StringBuilder sb = new StringBuilder(length);\n for (int i = 0; i < length; i++)\n {\n sb.Append(AllowedChars[_rg.Next(0, AllowedChars.Count)]);\n }\n return sb.ToString();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T19:03:02.997",
"Id": "6013",
"ParentId": "5983",
"Score": "3"
}
},
{
"body": "<p>You should not be using <a href=\"http://msdn.microsoft.com/en-us/library/system.random.aspx\" rel=\"nofollow noreferrer\"><code>Random</code></a> to generate coupons. Your coupons will be somewhat predictable: if someone can see a few coupons (especially a few consecutive coupons), they will be able to reconstruct the seed and generate all the coupons. <code>Random</code> is ok for most numeric simulations and for some games, it's not good at all when you need to generate unpredictable values. Your coupons act like passwords; you need cryptographic-quality randomness. Fortunately, there is a crypto-quality random generator in the C# library: <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx\" rel=\"nofollow noreferrer\"><code>System.Security.Cryptography.RNGCryptoServiceProvider</code></a>.</p>\n<p>This RNG returns bytes. There are 256 possible values in a byte. Your coupons can only use one of 62 characters, so you need to reject bytes that do not map to ASCII letters or digits.</p>\n<p>Also, you should <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx\" rel=\"nofollow noreferrer\">use <code>StringBuilder</code></a> when building a string chunk by chunk. Resolve it into a string when you've finished building it.</p>\n<pre><code>var couponLength = 32;\nStringBuilder coupon = new StringBuilder(couponLength);\nRNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\nbyte[] rnd = new byte[1];\nint n = 0;\nwhile (n < couponLength) {\n rng.GetBytes(rnd);\n char c = (char)rnd[0];\n if ((Char.IsDigit(c) || Char.IsLetter(c)) && rnd[0] < 127) {\n ++n;\n coupon.Append(c);\n }\n}\nreturn coupon.ToString();\n</code></pre>\n<p>You can make the generation about 4 times faster by rejecting fewer values. Instead of accepting only the 62 values that map to the characters you want, divide by 4 to get one of 64 equiprobable values, and accept 62 of these (mapping them to the right characters) and reject 2.</p>\n<pre><code>while (n < couponLength) {\n rng.GetBytes(rnd);\n rnd[0] %= 64;\n if (rnd[0] < 62) {\n ++n;\n coupon.Append((char)((rnd[0] <= 9 ? '0' : rnd[0] <= 35 ? 'A' - 10 : 'a' - 36) + rnd[0]);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T11:40:59.863",
"Id": "474991",
"Score": "0",
"body": "Why do we reject numbers and not get reminder right from 62? Is it to make uniform distribution because 256 is not dividable by 62?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T14:45:15.240",
"Id": "474993",
"Score": "1",
"body": "@C0DEF52 Yes. See e.g. https://cs.stackexchange.com/questions/29204/how-to-simulate-a-die-given-a-fair-coin, https://cs.stackexchange.com/questions/2605/is-rejection-sampling-the-only-way-to-get-a-truly-uniform-distribution-of-random"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-14T00:00:15.490",
"Id": "6021",
"ParentId": "5983",
"Score": "23"
}
},
{
"body": "<p>Another way to do it:</p>\n\n<pre><code> public static string CouponGenerator(int length)\n {\n var sb = new StringBuilder();\n for (var i = 0; i < length; i++)\n {\n var ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65)));\n sb.Append(ch);\n }\n\n return sb.ToString();\n }\n private static readonly Random _random = new Random();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T13:58:50.940",
"Id": "6031",
"ParentId": "5983",
"Score": "2"
}
},
{
"body": "<p>here is the code I will implement. Its alot faster and simpler</p>\n\n<pre><code>public static string GenerateCoupon(int length) \n{ \n return Guid.NewGuid().ToString().Replace(\"-\", string.Empty).Substring(0, 10);\n} \n</code></pre>\n\n<p>Using the guild gaurantees uniqueness so your coupon codes never overlap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T21:00:20.557",
"Id": "9449",
"Score": "2",
"body": "+1, it's a good idea and the OP checks that the codes are unique (they're compared with former coupon codes), but I have to mention that *\"The chance that the value of the new Guid will be all zeros or equal to any other Guid is very low.\"* http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx and the uniqueness of GUIDs isn't the same as uniqueness of the first then characters of GUIDs ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T23:50:05.907",
"Id": "9451",
"Score": "0",
"body": "Yes, the chance that any two GUIDs are non-unique is extremely small; however, it's (probably) going to be a bit larger if only _part_ of it is being used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T15:17:25.447",
"Id": "9465",
"Score": "0",
"body": "thats an easy fix. If character case matters then he can set random characters to lower or upper case. This will solve the possiblity of collisions. I highly doubt he gets collisions unless he is pumping out guids one after the other on a super computer in a tight loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T18:10:26.350",
"Id": "9473",
"Score": "2",
"body": "You don't need the 'Replace(\"-\"...)` call, just do `Guid.NewGuid().ToString(\"N\")`, that will format it with just hex characters, no dashes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:51:10.277",
"Id": "9486",
"Score": "1",
"body": "@Luke101 Bad solution. Changing 'random' characters to lower / upper case doesn't sound like a good 'fix' to me. You're only allowing 16 different options per character for a total of 16^10; OP is allowing 62 different options per character. You're only just using a quarter of the allowed characters for in position, or (1/4)^10 of the total solution space. You'll get overlaps *far* sooner than the OP's current solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-16T23:43:38.767",
"Id": "369242",
"Score": "0",
"body": "Guids are designed to be unique not un-guessable. You should not use them for this."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:10:35.970",
"Id": "6100",
"ParentId": "5983",
"Score": "5"
}
},
{
"body": "<p>If it's acceptable to have a slightly longer string, you could use the <a href=\"http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx\" rel=\"noreferrer\">ShortGuid</a> class. This takes a Guid and makes it slightly more readable than the 32 byte format you're use to ({xxx-xxx-xxx...}).</p>\n\n<p>The author's example is:</p>\n\n<blockquote>\n <p>c9a646d3-9c61-4cb7-bfcd-ee2522c8f633} </p>\n</blockquote>\n\n<p>shortened to:</p>\n\n<blockquote>\n <p>00amyWGct0y_ze4lIsj2Mw</p>\n</blockquote>\n\n<p>That may be slightly too long for a coupon code. One other suggestion is a using a <a href=\"http://www.yetanotherchris.me/home/2009/3/15/c-pronounceable-password-generator.html\" rel=\"noreferrer\">pronounceable password generator</a>, the link is something I converted from Java source a while back. Some uppercased examples:</p>\n\n<blockquote>\n <p>COLINITABO<br>\n OWNSATLEDG<br>\n GORGIRRUGO<br>\n NOCKAYWIVI<br>\n FAWGILLIOL </p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T18:27:29.317",
"Id": "6368",
"ParentId": "5983",
"Score": "5"
}
},
{
"body": "<p>For my future self:</p>\n\n<p>A singleton instance of @Guffa's implementation to avoid recreating <code>StringBuilder</code> and <code>Random</code> objects; less GC and a bit faster. Also @Gilles' implementation of GenerateUId beneath in case a crypto version is necessary.</p>\n\n<pre><code>public class UIdGenerator\n{\n private static readonly Lazy<UIdGenerator> _lazy = new Lazy<UIdGenerator>(\n () => new UIdGenerator(), LazyThreadSafetyMode.ExecutionAndPublication);\n\n public static UIdGenerator Instance\n {\n get { return UIdGenerator._lazy.Value; }\n }\n\n private readonly Random _random = new Random();\n private readonly Dictionary<int, StringBuilder> _stringBuilders = new Dictionary<int, StringBuilder>();\n private const string CHARACTERS = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n private UIdGenerator()\n {\n }\n\n public string GenerateUId(int length)\n {\n StringBuilder result;\n if (!_stringBuilders.TryGetValue(length, out result))\n {\n result = new StringBuilder();\n _stringBuilders[length] = result;\n }\n\n result.Clear();\n\n for (int i = 0; i < length; i++)\n {\n result.Append(CHARACTERS[_random.Next(CHARACTERS.Length)]);\n }\n\n return result.ToString();\n }\n}\n</code></pre>\n\n<p>@Gilles' version:</p>\n\n<pre><code>// use me if you want a crypto version\npublic string GenerateUId(int length)\n // +6 to handle chances when value >= 62 (increase with fewer CHARACTERS to offset the probability of it occurring)\n int iterations = length + 6;\n\n StringBuilder result;\n if (!_stringBuilders.TryGetValue(length, out result))\n {\n result = new StringBuilder();\n _stringBuilders[length] = result;\n }\n result.Clear();\n\n // todo re-use like we're doing with the StringBuilder\n byte[] rnd = new byte[iterations];\n _crypto.GetBytes(rnd);\n int n = 0;\n for (int j = 0; j < iterations; ++j)\n {\n rnd[j] %= 64; \n if (rnd[j] < 62)\n {\n coupon.Append(CHARACTERS[rnd[j]]);\n ++n;\n if (n == length)\n {\n break;\n }\n }\n }\n\n return result.ToString();\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>UIdGenerator.Instance.GenerateUId(10);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T08:31:20.133",
"Id": "59882",
"ParentId": "5983",
"Score": "2"
}
},
{
"body": "<p>Slight modification to Berrly's answer. Gives alphanumberic with casing and makes sure there are no duplicates created. I'm going to start using this for access tokens that get emailed to the user & text'd to log on to my system. This would be more secure than most of these systems today as they are more predictable as they are generally 6 characters long (fixed length) and numbers (limited set). Even though they all have a time limit on them why not go this extra mile as it's not that much harder.</p>\n\n<p>Note: I remove similar looking characters to ease confusion when actually typing.</p>\n\n<p>Side Rant: I believe with the advent of social login emailed/texted access tokens for granting access to other sites/apps will be the way to go. Nobody wants to remember all these passwords so they use the same one and we blame them, which is stupid because it's simply human nature. Then we make up password holders which you need a password to which is just 1 password holding all your other passwords and we think that's a good solution...The safest thing you can do is change passwords often and make them complicated but because we have to have so many nobody does this. We don't want to spend our lives changing passwords. Ideally we'd have the 1 password to say our email and everything goes through there for step 1 auth, then phone for step 2. People would be more willing to change their ONE password more often knowing it was just 1 and used to get access tokens that grant them access to all other apps/sites.</p>\n\n<pre><code>//Rextester.Program.Main is the entry point for your code. Don't change it.\n//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Text;\n\nnamespace Rextester\n{\n public class Program\n {\n public static void Main(string[] args)\n {\n //Your code goes here\n Console.WriteLine(\"Hello, world!\");\n\n var blackList = new List<char>{\n '[', ']', '`', '{', '}', '|', '\\\\', '/', '~', '^', '_', '-', ':', ';', '<', '>', '=', '?', '@', '0', 'o', 'l', 'I', '1'\n };\n\n var accessTokens = new List<string>();\n\n // test by creating a bunch of tokens\n for(int i = 0; i < 100; i++)\n {\n // this makes sure we don't duplicate active access tokens\n var token = CouponGenerator(_random.Next(6, 12), blackList);\n while(accessTokens.Contains(token)){\n token = CouponGenerator(_random.Next(6, 12), blackList);\n }\n\n accessTokens.Add(token);\n }\n\n // print tokens out\n accessTokens.ForEach(x => Console.WriteLine(\"Access Token: \" + x));\n }\n\n public static string CouponGenerator(int length, List<char> exclusionList)\n {\n var sb = new StringBuilder();\n for (var i = 0; i < length; i++)\n {\n var ch = Convert.ToChar(Convert.ToInt32(Math.Floor(62 * _random.NextDouble() + 48)));\n while(exclusionList.Contains(ch)){\n ch = Convert.ToChar(Convert.ToInt32(Math.Floor(62 * _random.NextDouble() + 65)));\n }\n\n sb.Append(ch);\n }\n\n return sb.ToString();\n }\n private static readonly Random _random = new Random();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-05T14:16:14.653",
"Id": "188873",
"ParentId": "5983",
"Score": "1"
}
},
{
"body": "<p>I believe that the main problem is not the generation method but the uniqueness of the data.</p>\n\n<p>As I understand there is a database and you have to check the generated data uniqueness retrospectively with your past data generated.</p>\n\n<p>Suppose that there is a new requirement that your business side ask for another 100.000 unique data from you. And you have already generated 10.000.000 in the past. Which are stored in DB.</p>\n\n<p>My suggestion will be;</p>\n\n<p>1 - Generate for example 120.000 unique key ( greater than the requirement )</p>\n\n<p>2 - Bulk insert those data to a temp table. </p>\n\n<p>3 - Then execute a stored procedure to compare two tables in the SQL Server side, </p>\n\n<p>4 - if your temp table contains 100.000 different value from your old 10.000.000 dataset, then you are good to go insert those 100.000 to your main table return them to your business side,\n else, for example 60.000 of 120.000 is different from your old data set but 60.000 is same, in this situation your stored procedure can return int = 40.000 which you will understand that you need another 40.000 data.</p>\n\n<p>Go to the step 1, Execute your generator for another 60.000, 100.000 whatever you want and follow the same steps.</p>\n\n<p>May not be the best solution but I believe will be fast. Because generating 1.000.000 of random alphanumeric strings take at most 2 seconds with the code below;</p>\n\n<p>In the past I have used the below code to generate unique random data</p>\n\n<pre><code>public static string GetUniqueKey()\n {\n int size = 7;\n char[] chars = new char[62];\n string a = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n chars = a.ToCharArray();\n\n RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();\n\n byte[] data = new byte[size];\n crypto.GetNonZeroBytes(data);\n\n StringBuilder result = new StringBuilder(size);\n\n foreach (byte b in data)\n result.Append(chars[b % (chars.Length - 1)]);\n\n return Convert.ToString(result);\n }\n</code></pre>\n\n<p>and for the uniqueness of my runtime generated data, I have used a hashtable as can be seen above.</p>\n\n<pre><code>public static Tuple<List<string>, List<string>> GenerateUniqueList(int count)\n {\n uniqueHashTable = new Hashtable();\n nonUniqueList = new List<string>();\n uniqueList = new List<string>();\n\n for (int i = 0; i < count; i++)\n {\n isUniqueGenerated = false;\n\n while (!isUniqueGenerated)\n {\n uniqueStr = GetUniqueKey();\n try\n {\n uniqueHashTable.Add(uniqueStr, \"\");\n isUniqueGenerated = true;\n }\n catch (Exception ex)\n {\n nonUniqueList.Add(uniqueStr);\n // Non-unique generated\n }\n }\n }\n\n uniqueList = uniqueHashTable.Keys.Cast<string>().ToList();\n\n return new Tuple<List<string>, List<string>>(uniqueList, nonUniqueList);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T11:58:04.200",
"Id": "440343",
"Score": "2",
"body": "If you want to merge your user accounts, you should use the [contact] form to ask for an account merger"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T08:18:14.010",
"Id": "226554",
"ParentId": "5983",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T09:37:18.580",
"Id": "5983",
"Score": "32",
"Tags": [
"c#",
"strings",
"random"
],
"Title": "Random string generation"
}
|
5983
|
<p>The index file:</p>
<pre><code><?php
require_once 'app/run.php';
$_action = (isset($_GET['cmd']) && ctype_alnum($_GET['cmd'])) ? $_GET['cmd'] : 'index';
switch ($_action) {
case 'index':
case 'default':
case 'home':
include $con_dir . '/index.php';
break;
default:
include $con_dir . '/404.php';
}
</code></pre>
<p>The <code>run.php</code> file:</p>
<pre><code><?php
session_start();
require_once 'config.php';
$app_dir = realpath(dirname(__FILE__));
$lib_dir = $app_dir . '/lib';
$con_dir = $app_dir . '/controllers';
require_once($app_dir . '/lib.php'); //Include libraries
//Database Connection
try {
# MySQL with PDO_MYSQL
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
unset($password);
//Smarty
$tpl = new Smarty();
$tpl->template_dir = $app_dir . '/Smarty/templates/';
$tpl->compile_dir = $app_dir . '/Smarty/templates_c/';
$tpl->config_dir = $app_dir . '/Smarty/configs/';
$tpl->cache_dir = $app_dir . '/Smarty/cache/';
</code></pre>
<p>The <code>lib.php</code> file</p>
<pre><code><?php
require_once($lib_dir . '/Smarty/Smarty.class.php');
</code></pre>
<p>The <code>config.php</code> file</p>
<pre><code><?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'engine';
</code></pre>
<p>I think I can improve this by doing the <code>switch()</code> more dynamic, let's say it, would it be possible to have that the <code>?cmd=filename</code> would be appropriate, how would I do it? And how do I do it secure?</p>
<p>Else way what do you think about my basic structure, how should improve it? What would you change etc.</p>
|
[] |
[
{
"body": "<p>You code looks fine. One minor issue: in the <code>catch(PDOException $e)</code> branch maybe you want to</p>\n\n<ul>\n<li>log the error (<a href=\"http://php.net/manual/en/function.error-log.php\" rel=\"nofollow\"><code>error_log</code></a>),</li>\n<li>show a fancy static error page to the user (<em>\"It's not your fault, we have logged the error and we're working on it.\"</em> or something like this.),</li>\n<li>and/or call <code>die()</code>.</li>\n</ul>\n\n<hr>\n\n<p>About the dynamic switch: I would use a whitelist array which prohibit including other files which are not in the array.</p>\n\n<pre><code>$pages['index'] = 'index.php';\n$pages['default'] = 'default.php';\n$pages['home'] = 'home.php';\n$page = '/404.php'\nif (isset($pages[$action])) {\n $page = $pages[$action];\n}\n\ninclude $con_dir . '/' . $page;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T21:47:30.850",
"Id": "9229",
"Score": "0",
"body": "Is it possible to automatically create a new log file if it doesn't exists \"error_log($e->getMessage() . \"\\n\", 3, $log_dir . \"/database.log\");\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T09:44:26.603",
"Id": "9246",
"Score": "0",
"body": "If it was question, yes, it's possible :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T18:28:21.993",
"Id": "9266",
"Score": "1",
"body": "Yeah, +1 for whitelisting pages instead of allowing any. I know my server logs frequently get people trying to abuse dynamic includes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T20:21:10.860",
"Id": "5992",
"ParentId": "5987",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T17:09:39.597",
"Id": "5987",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Is my approach structure good?"
}
|
5987
|
<p>I am maintaining a site with significant security concerns and I wrote a helper class for validating potential XSS attacks. The <code>ValidateRequest</code> method is meant to evaluate the <code>HttpRequest</code> for any potential issues, and if issues are found, redirect the user to the same page, but in a away that is not threatening to the application. </p>
<p>The application is being evaluated by <a href="https://www.fortify.com/products/web_inspect.html" rel="nofollow">HP WebInspect</a>. Their initial review included two regular expressions:</p>
<ol>
<li><p>The "Regex for a simple XSS attack"</p>
<p><code>/((\%3C) <)((\%2F) \/)*[a-z0-9\%]+((\%3E) >)/ix</code></p></li>
<li><p>The "Paranoid regex for XSS attacks" </p>
<p><code>/((\%3C) <)[^\n]+((\%3E) >)/I</code></p></li>
</ol>
<p>The regular expression I am using is a more stringent C# adaptation of the paranoid regex. I prefer to err on the side of caution, so I would rather risk denying valid requests than allowing an invalid request to be processed. </p>
<p>Thanks in advance for the help.</p>
<pre><code>using System;
using System.Text.RegularExpressions;
using System.Web;
public static class XssSecurity
{
public const string PotentialXssAttackExpression = "(http(s)*(%3a|:))|(ftp(s)*(%3a|:))|(javascript)|(alert)|(((\\%3C) <)[^\n]+((\\%3E) >))";
private static readonly Regex PotentialXssAttackRegex = new Regex(PotentialXssAttackExpression, RegexOptions.IgnoreCase);
public static bool IsPotentialXssAttack(this HttpRequest request)
{
if(request != null)
{
string query = request.QueryString.ToString();
if(!string.IsNullOrEmpty(query) && PotentialXssAttackRegex.IsMatch(query))
return true;
if(request.HttpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase))
{
string form = request.Form.ToString();
if (!string.IsNullOrEmpty(form) && PotentialXssAttackRegex.IsMatch(form))
return true;
}
if(request.Cookies.Count > 0)
{
foreach(HttpCookie cookie in request.Cookies)
{
if(PotentialXssAttackRegex.IsMatch(cookie.Value))
{
return true;
}
}
}
}
return false;
}
public static void ValidateRequest(this HttpContext context, string redirectToPath = null)
{
if(context == null || !context.Request.IsPotentialXssAttack()) return;
// expire all cookies
foreach(HttpCookie cookie in context.Request.Cookies)
{
cookie.Expires = DateTime.Now.Subtract(TimeSpan.FromDays(1));
context.Response.Cookies.Set(cookie);
}
// redirect to safe path
bool redirected = false;
if(redirectToPath != null)
{
try
{
context.Response.Redirect(redirectToPath,true);
redirected = true;
}
catch
{
redirected = false;
}
}
if (redirected)
return;
string safeUrl = context.Request.Url.AbsolutePath.Replace(context.Request.Url.Query, string.Empty);
context.Response.Redirect(safeUrl,true);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some general idea:</p>\n\n<ol>\n<li>Use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">guard statements</a> instead of big <code>if</code> blocks.</li>\n<li>Extract the <code>!string.IsNullOrEmpty(query) && PotentialXssAttackRegex.IsMatch(query)</code> condition to a method.</li>\n<li>Extract individual checks to distinct methods. The <code>IsPotentialXssAttack</code> will be quite easy to read and the code of different validations will not be mixed in one big method.</li>\n<li>I'd create an <code>expireAllCookies</code> helper method too.</li>\n</ol>\n\n<p>The final code of the first method would look like this (I haven't tested nor compiled):</p>\n\n<pre><code>public static bool IsPotentialXssAttack(this HttpRequest request) {\n if (request == null) {\n return false;\n }\n if (isPotentialXssAttackQuery(request)) {\n return true;\n }\n if (isPotentialXssAttackFormOrAnything(request)) {\n return true;\n }\n if (isPotentialXssAttackCookie(request)) {\n return true;\n }\n\n return false;\n}\n\n\npublic static bool isPotentialXssAttackQuery(this HttpRequest request) {\n string query = request.QueryString.ToString();\n if (isMatch(query)) {\n return true;\n }\n return false;\n}\n\npublic static bool isMatch(string input) {\n if (string.IsNullOrEmpty(query)) {\n return false;\n }\n return PotentialXssAttackRegex.IsMatch(query);\n}\n\n// TODO: rename it\npublic static bool isPotentialXssAttackFormOrAnything(this HttpRequest request) {\n if (!request.HttpMethod.Equals(\"post\", \n StringComparison.InvariantCultureIgnoreCase)) {\n return false;\n }\n\n string form = request.Form.ToString();\n if (isMatch(form)) {\n return true;\n }\n return false;\n}\n\npublic static bool isPotentialXssAttackCookie(this HttpRequest request) {\n if (request.Cookies.Count <= 0) {\n return false;\n }\n\n foreach (HttpCookie cookie in request.Cookies){\n if (isMatch(cookie.Value)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T01:38:39.543",
"Id": "9235",
"Score": "0",
"body": "+1, @palacsint, clearly all good suggestions. I like that when you apply this kind of refactoring the things being tested become much more explicit to other developers. I noticed we can even go further and write, `public static bool IsPotentialXssAttack(this HttpRequest request) { return request != null && (isPotentialXssAttackQuery(request) || isPotentialXssAttackFormOrAnything(request) || isPotentialXssAttackCookie(request)); }`. **However, did you notice any potential flaws in the actual functionality for mitigating XSS attacks?**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T09:51:27.213",
"Id": "9247",
"Score": "0",
"body": "I don't prefer long conditions with lots of `||`s. I think it's harder to read than single `if`s. I didn't notice any flaws in the XSS logic, unfortunately I'm not too familiar with this field."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T10:57:54.650",
"Id": "9251",
"Score": "0",
"body": "I guess that's personal preference. To me it's easier to read, b/c my brain automatically translates || to \" or \" and && to \" and \", so it sounds like plain english"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T11:23:39.103",
"Id": "9252",
"Score": "0",
"body": "e.g. imagine: `public static class Syntax\n {\n public static bool Or<T>(this bool value, T candidate, Func<T, bool> predicate) { return value || predicate(candidate); }\n public static bool And<T>(this bool value, T candidate, Func<T, bool> predicate) { return value && predicate(candidate); }\n }` . Then you can do `return (request != null).And(isPotentialXssAttackQuery(request).Or(request,isPotentialXssAttackFormOrAnything).Or(request,isPotentialXssAttackCookie);` ... I'd say that's a pretty readable single line"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T20:57:31.750",
"Id": "5993",
"ParentId": "5988",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "5993",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:21:38.490",
"Id": "5988",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"security",
"regex"
],
"Title": "Evaluate/Refactor my ASP.NET XSS Security Helper Class"
}
|
5988
|
<p>I'm just playing with the concept of <code>GroupBy</code> inside Rx. So, I wondered how hard it would be to write a console application that continuously reads lines, groups them by similar words and just prints out the word among the current count of how often the word was written before. It really was a breeze to do that but I wonder if my attempt could be rewritten in a more elegant way. Especially if I can get rid of the nested Subscribes.</p>
<p>Here is what I have:</p>
<pre><code>static void Main(string[] args)
{
var subject = new Subject<string>();
var my = subject.GroupBy(x => x);
my.Subscribe(x => x.Scan(new { Chars = string.Empty, Count = 0},
(a, chars) => new { Chars = chars, Count = a.Count + 1})
.Subscribe(result => Console.WriteLine("You typed {0} {1} times", result.Chars,
result.Count)));
while (true)
{
subject.OnNext(Console.ReadLine());
}
}
</code></pre>
<hr>
<p><strong>Result</strong></p>
<pre><code>test
you typed test 1 times
test
you typed test 2 times
hallo
you typed test 1 times
test
you typed test 3 times
...
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T17:58:10.313",
"Id": "9217",
"Score": "0",
"body": "Can anyone who donvoted this question please leave a comment what's wrong with it? I'm willing to fix it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:02:02.307",
"Id": "9218",
"Score": "0",
"body": "I think you got downvotes because you're not even asking a question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:03:00.133",
"Id": "9219",
"Score": "0",
"body": "It would help to know what you would consider more elegant. I would suggest more newlines in the lambda you pass to `Subscribe` would make a bigger difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:16:45.543",
"Id": "9220",
"Score": "0",
"body": "@Otiel, well the question is if the code snippet can be improved. I should point out that I'm striving for improvement in terms of mathematical beauty. For example, in my first answer I improved it with the SelectMany so that the code is more in line with the whole functional programming approach. In the second answer I avoided passing the string information through the Scan() method in favor for the Zip."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:41:53.953",
"Id": "9221",
"Score": "0",
"body": "I removed the c# tag now in order to not distract the regular c# user with a too specific Rx question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T08:50:26.463",
"Id": "25032",
"Score": "2",
"body": "@Christoph and I added it back. I hope you don't mind, but it really *does* need to be tagged C#, and since the question is right on topic here at CodeReview, I don't think you'll have any further downvote issues."
}
] |
[
{
"body": "<p>Ok, this looks a lot better! Can anyone even do better than that?</p>\n\n<pre><code> static void Main(string[] args)\n {\n var subject = new Subject<string>();\n\n subject\n .GroupBy(x => x)\n .SelectMany(x => x.Scan(new { Chars = string.Empty, Count = 0},(a, chars) => new { Chars = chars, Count = a.Count + 1}))\n .Subscribe(result => Console.WriteLine(\"You typed {0} {1} times\", result.Chars, result.Count));\n\n while (true)\n {\n subject.OnNext(Console.ReadLine());\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-11T03:03:00.947",
"Id": "17185",
"Score": "1",
"body": "I never used Rx. However, having used LINQ, I should be able to follow this code ... and I do not really. I can barely tell what it does and how fast it runs. I like an explicit dictionary-based approach. If I had to debug/maintain this method, I would rewrite it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T17:41:02.357",
"Id": "5990",
"ParentId": "5989",
"Score": "1"
}
},
{
"body": "<p>Ok, here is another one! I think this one is easier to read since we don't depend on the Scan method to carry the string through the computation:</p>\n\n<pre><code> static void Main(string[] args)\n {\n var subject = new Subject<string>();\n\n subject\n .GroupBy(x => x)\n .SelectMany(x => x.Scan(0, (count, _) => ++count).Zip(x, (count, chars) => new { Chars = chars, Count = count}))\n .Subscribe(result => Console.WriteLine(\"You typed {0} {1} times\", result.Chars, result.Count));\n\n while (true)\n {\n subject.OnNext(Console.ReadLine());\n }\n }\n</code></pre>\n\n<p>Can anyone do even better?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T05:17:47.820",
"Id": "9273",
"Score": "3",
"body": "You should edit your initial answer and add this answer to it. Multiple answers by one person will trigger flagging (manual and automatic). Also since this is your question you should consider adding both answers into the question, but it's perfectly ok to answer your own question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:11:46.707",
"Id": "5991",
"ParentId": "5989",
"Score": "1"
}
},
{
"body": "<p>This looks a lot cleaner to me. Should also showcase how much more helpful it is when you give more descriptive names to your variables.</p>\n\n<pre><code>static void Main(string[] args)\n{\n var lineReader = new Subject<string>();\n\n lineReader.GroupBy(line => line)\n .Subscribe(lineGroup =>\n {\n lineGroup.Scan(0, (acc, _) => ++acc)\n .Subscribe(count =>\n {\n var line = lineGroup.Key;\n var timeSuffix = count == 1 ? \"\" : \"s\";\n Console.WriteLine(\"You typed {0} {1} time{2}.\", line, count, timeSuffix);\n });\n });\n\n String readLine;\n while ((readLine = Console.ReadLine()) != null)\n lineReader.OnNext(readLine);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-12T02:06:30.020",
"Id": "9905",
"ParentId": "5989",
"Score": "1"
}
},
{
"body": "<p>You could use also use a counter provider per grouping observable, in the form of zipping a large stream of integers, like so:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var input = GetConsoleLines().ToObservable().TakeWhile(line => !string.IsNullOrEmpty(line));\n input.GroupBy(word => word)\n .SelectMany(grouping => grouping.Zip(Observable.Range(1, int.MaxValue), (s, i) => new Tuple<string, int>(s, i)))\n .Subscribe(r => Console.WriteLine($\"you typed {r.Item1} {r.Item2} times\"));\n}\n\npublic static IEnumerable<string> GetConsoleLines()\n{\n while(true)\n yield return Console.ReadLine();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-07T08:09:14.407",
"Id": "172261",
"ParentId": "5989",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T17:32:59.680",
"Id": "5989",
"Score": "6",
"Tags": [
"c#",
"system.reactive"
],
"Title": "Is there an easier way to use Rx's GroupBy operator?"
}
|
5989
|
<p>I was given a problem to find out all the prime numbers within a range. Just after I wrote the program I found numerous other codes to solve the problem. I am interested to know is my algorithm efficient? Is it like sieve filtration? (before writing this code I had no clear idea on sieve filtration method) or the algorithm I used is bad?</p>
<pre><code>#include<iostream.h>
#include<math.h>
</code></pre>
<h3>prime_gen</h3>
<pre><code>void prime_gen(int a,int b)
{
int array[4]={2,3,5,7},holder[1000000]={0},count=0,flag=0,length=0,number_count=0;
for(int i=0;i<b;i++)
{
for(int j=0;j<4;j++)
{
if(i==array[j])
{
break;
}
else
{
if(i%array[j]==0)
{
count++;
}
}
}
if(count==0)
{
if(i>1)
{
holder[length++]=i;
}
else
{
length=0;
}
}
count=0;
}
if(length==0)
{
cout<<"No prime numbers exist within the range";
cout<<"\n";
}
else
{
cout<<"Prime numbers are:";
for(int i=0;i<length;i++)
{
int t=holder[i];
for(int check=0;check<sqrt(length);check++)
{
if(t!=holder[check])
{
if(t%holder[check]==0)
{
t=0;
}
}
}
if(t!=0&&t>=a)
{
number_count++;
cout<<t<<"\t";
}
}
cout<<"Total count:"<<number_count<<endl;
}
}
</code></pre>
<h3>main</h3>
<pre><code>int main()
{
int a,b;
cout<<"Put the first integer:";
cin>>a;
cout<<"Put the second integer:";
cin>>b;
prime_gen(a,b);
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is not correct, hence its efficiency is irrelevant. You only test for divisibility by 2, 3, 5 and 7, so you would classify e.g. 121 = 11*11 as prime.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T10:08:40.720",
"Id": "9248",
"Score": "0",
"body": "I think its corrected now"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T23:22:35.043",
"Id": "5997",
"ParentId": "5996",
"Score": "5"
}
},
{
"body": "<p>My version of the sieve is at <a href=\"http://ideone.com/1AP8u\" rel=\"nofollow\">http://ideone.com/1AP8u</a>, and the function that does the sieving is shown below. Explanations are at <a href=\"http://programmingpraxis.com\" rel=\"nofollow\">my blog</a>; look for \"Prime Numbers\" in the \"Themes\" tag under the \"Exercises\" menu bar item.</p>\n\n<pre><code>struct node* sieve(int n) {\n int m = (n-1) / 2;\n char b[m/8+1];\n int i=0;\n int p=3;\n struct node* ps = NULL;\n int j;\n\n ps = insert(2, ps);\n\n memset(b,255,sizeof(b));\n\n while (p*p<n) {\n if ISBITSET(b,i) {\n ps = insert(p, ps);\n j = 2*i*i + 6*i + 3;\n while (j < m) {\n CLEARBIT(b,j);\n j = j + i + i + 3; } }\n i+=1; p+=2; }\n\n while (i<m) {\n if ISBITSET(b,i) {\n ps = insert(p, ps); }\n i+=1; p+=2; }\n\n return reverse(ps); }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T03:35:55.660",
"Id": "9245",
"Score": "0",
"body": "That's a nice implementation. Two things I've found useful, a) use 32 (or maybe 64) bit integers for your sieve, b) revert the bit logic, start with all zeros and set bits for composites to 1. Aligned reads and writes are generally much faster than accessing single bytes, and b[i>>w] |= 1 << (i&m); is one bit operation less per tick-off (although, that probably doesn't make a difference on modern processors anymore)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T03:07:06.483",
"Id": "6003",
"ParentId": "5996",
"Score": "4"
}
},
{
"body": "<p>the \"holder[1000000];\" array lives on the stack (\"is an automatic variable\"). I would <em>at least</em> make it static, since it can be reused, and a lot of work went into it (that would involve sifting out the unsieved entries, but for a real program (and a function that is called more than once) it would be a win.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T22:50:08.913",
"Id": "9270",
"Score": "0",
"body": "Generally,people use to loop upto maximum number(from input) or square root of it..I thought,what if they only needed to loop sqrt of the total number of already calculated superset of prime numbers which only contain the erroneous values(i.e the multiple of some other primes)..so,i did make a subset of nearly prime numbers from the set of all natural numbers,then sort out the pure primes by only looping through the sqrt of the numbers(here length)of the apparently not pure set of prime numbers.I kept them at an array to avoid calculating them each time on the fly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T12:35:35.027",
"Id": "6004",
"ParentId": "5996",
"Score": "1"
}
},
{
"body": "<p>Stylistic notes:</p>\n\n<ul>\n<li>Use more spaces around punctuation (<code>for(int i=0;i<b;i++)</code> wants to breeze), don't sprinkle your code with blank lines in random places, and use consistent indentation.</li>\n<li>Declare your variables on separate lines; use the blank space on the right to write a comment explaining what the variable is for.</li>\n<li>Use meaningful variable names. Come on, <code>array</code>? The reader can see that it's an array, but what does it contain?</li>\n</ul>\n\n<p>Also, make up your mind: you're writing C++, not C. Some parts (such as the use of C arrays) are not idiomatic C++ though; you should pick one, either C (and use stdio, not iostream) or C++ (and use <code>new</code> and the STL). Since I'm a C programmer but don't know much C++, I'm going to comment on the C-ish parts and not say anything about idiomatic C++.</p>\n\n<p>The <code>array</code> variable isn't useful here. The small primes will appear in the <code>holder</code> array anyway, so put them in directly. Even if you were handling small primes specially, your <code>count</code> variable is useless: you don't need to count how many small primes divide <code>i</code>, you only need to know whether some small prime divides <code>i</code>.</p>\n\n<p>Also, you might as well use unsigned integers for your variables, since they're not going to contain negative numbers.</p>\n\n<pre><code>unsigned holders[1000000]; /* list of prime numbers */\nunsigned length = 0;\nholders[length++] = 2;\nholders[length++] = 3;\nholders[length++] = 5;\nholders[length++] = 7;\n</code></pre>\n\n<p>You do not need to fully initialize <code>holders</code>, since you'll be only looking at the first <code>length</code> elements. While you could write <code>unsigned holders[1000000] = {3, 5, 7};</code> and the compiler would fill the rest with zeroes, with typical implementations, this would result in the full array (zeroes included) being written into your executable, which is a huge waste.</p>\n\n<p>You should be allocating the <code>holders</code> dynamically anyway, and checking its size. If someone passes such a large value for <code>b</code> that the <code>holders</code> array overflows, your code will overwrite some arbitrary memory. Either compute the size of the <code>holders</code> array so that it's large enough given <code>b</code>, or keep track of its size and extend it if <code>length</code> becomes too large.</p>\n\n<p>Even numbers are never prime. So instead of looping over all integers, loop over all odd integers.</p>\n\n<p>There's no reason to fill <code>holders</code> with non-prime numbers. Your whole first loop can be eliminated.</p>\n\n<pre><code>for (x = 11; x < b; x += 2) {\n bool is_prime = true;\n // start j at 1.\n // As holders[0] is 2 and no value of x is divisible by 2.\n for (j = 1; j < length && holders[j] <= sqrt(x); j++) {\n if (x % holders[j] == 0) {\n is_prime = false;\n break;\n }\n }\n if (is_prime) {\n holders[length++] = x;\n }\n}\n</code></pre>\n\n<p>Now, to find the number of primes between <code>a</code> and <code>b</code>, traverse the <code>holders</code> array from the first value that's larger or equal to <code>a</code>. When you write a complete program, take care of the boundary conditions; in particular, make sure to count 2 if <code>a</code> ≤ 2.</p>\n\n<pre><code>for (j = 0; j < length; j++) {\n if (holders[j] >= a) break;\n}\nreturn length - j;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T23:02:26.767",
"Id": "9271",
"Score": "1",
"body": "exactly these were the issues I was thinking about.Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T16:44:58.823",
"Id": "9295",
"Score": "0",
"body": "<quote>being written into your executable, which is a huge waste</quote> Because disk space is so costly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T22:17:00.740",
"Id": "9306",
"Score": "0",
"body": "@LokiAstari Thanks. You're absolutely right about the misplaced insertion into `holders`. I prefer to skip odd numbers because it's a very simple optimization with a noticeable effect, but I've inserted 2 into the array to correctly handle the case when `a`≤2."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T22:47:46.667",
"Id": "6017",
"ParentId": "5996",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "6017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T23:14:40.863",
"Id": "5996",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"primes"
],
"Title": "Generating prime numbers within a range in C++"
}
|
5996
|
<p>I am a newbie at writing Android apps and using Java in general. I have went through most of the Android hello view tutorials but still seem to be lacking some understanding of the basics. Here is a snippet of code I wrote for an app. My goal was to have three edittext boxes for the user to input information. I want the user to put information in two of the three boxes and when they hit the calculate button, it will calculate the third edittext value based on a specific equation. Is there anyway that I can avoid initializing these 3 edittext objects in each of my methods within this class? Any other suggestions for cleaning up or improving this code?</p>
<pre><code>public class PlantPopulation extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText seedSpacing = (EditText)
findViewById(R.id.seedSpacing);
EditText rowSpacing = (EditText)
findViewById(R.id.rowSpacing);
EditText population = (EditText)
findViewById(R.id.population);
seedSpacing.setText(""); //clear values
rowSpacing.setText("");
population.setText("");
}
//check how many boxes are empty
public int checkifempty(String array[]) {
int i = 0;
for (String string : array) {
if (string.equals("")) {
i = i+1;
}
}
return i;
}
//run the calculation
public void calc(View v) {
EditText seedSpacing = (EditText)
findViewById(R.id.seedSpacing);
EditText rowSpacing = (EditText)
findViewById(R.id.rowSpacing);
EditText population = (EditText)
findViewById(R.id.population);
String sS = seedSpacing.getText().toString();
String rS = rowSpacing.getText().toString();
String pop = population.getText().toString();
String boxes[] = {sS,rS,pop};
//determine which box is empty
if (checkifempty(boxes) <2) {
if (sS.equals("")) {
double calc1=(43560*144)/new Double(rS)/
new Double(pop);
calc1 = Math.floor(calc1 * 100 +.5)/100;
seedSpacing.setText(Double.toString(calc1));
} else if (rS.equals("")) {
double calc2=(43560*144)/new Double(sS)/
new Double(pop);
calc2 = Math.round(calc2);
rowSpacing.setText(Double.toString(calc2));
} else if (pop.equals("")) {
Double calc3=((43560*144)/new Double(rS)/
new Double(sS));
Integer calc = calc3.intValue();
//calc3 = Math.round(calc3);
population.setText(calc.toString());
} else {
Toast.makeText(PlantPopulation.this,
"Leave one item blank.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(PlantPopulation.this,
"You must fill in two of the three boxes.", Toast.LENGTH_SHORT).show();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:32:21.150",
"Id": "9236",
"Score": "1",
"body": "One suggestion... use the camel-case to name your functions/variables as you did in you class, though I only put in capital the first character on classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T22:02:25.740",
"Id": "9237",
"Score": "0",
"body": "Better fit for CodeReview."
}
] |
[
{
"body": "<ul>\n<li>Replace \"43560*144\" by a constant.</li>\n<li>Store <code>new Double(sS), new Double(srS), new Double(pop)</code> in variables\nbefore <code>if (checkifempty(boxes) <2)</code>. It'll improve speed and clarify\nthe code.</li>\n<li>Correct indentation in the <code>onCreate</code> method</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:30:51.737",
"Id": "5999",
"ParentId": "5998",
"Score": "3"
}
},
{
"body": "<p>Replace horrible <code>checkIfEmpty</code> method, which by the way doesn't do what you plan it to do. Use <code>addTextChangedListener</code> for your EditTexts.<br>\nIn your xml, set property <code>android:text</code> to an empty value, so you can avoid doing it in the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:53:19.180",
"Id": "9238",
"Score": "0",
"body": "the checkIfEmpty is providing me a way to see how many boxes are left empty by the user, to avoid any calculation errors if more than one box is empty or if non are empty. how would i implement the addTextChangedListener to accomplish this same task?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:35:04.960",
"Id": "6000",
"ParentId": "5998",
"Score": "3"
}
},
{
"body": "<p>Use Andject to get rid of something = getViewById():</p>\n\n<p><a href=\"https://github.com/ko5tik/andject\" rel=\"nofollow\">https://github.com/ko5tik/andject</a></p>\n\n<p>( Shameles self-advertizing )</p>\n\n<p>Speciofy desired views via annotations:</p>\n\n<pre><code> class WithInjectableViews extends Activity {\n // shall be injected\n @InjectView(id = 239)\n private android.view.View asView;\n @InjectView(id = 555)\n private Button button;\n // shall be left alone\n private View notInjected = null;\n\n}\n</code></pre>\n\n<p>And in your onCreate() say:</p>\n\n<pre><code> ViewInjector.startActivity(injectable);\n</code></pre>\n\n<p>There is also work undeway to inject shared preference values ( also provides cleaner code and declarative style )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:38:04.780",
"Id": "6001",
"ParentId": "5998",
"Score": "2"
}
},
{
"body": "<p>Declare and initialise the edit texts like this:</p>\n\n<pre><code>public class PlantPopulation extends Activity {\n EditText seedSpacing;\n EditText rowSpacing;\n EditText population;\n\n/** Called when the activity is first created. */ \n @Override\npublic void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n\n seedSpacing = (EditText) \n findViewById(R.id.seedSpacing);\n rowSpacing = (EditText) \n findViewById(R.id.rowSpacing);\n population = (EditText) \n findViewById(R.id.population);\n\n.....\n</code></pre>\n\n<p>You now will not need to re-declare and initialise them in other methods, namely your calc method in this example.</p>\n\n<p>Hope that helps,\nBarry</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T16:18:01.640",
"Id": "9239",
"Score": "0",
"body": "When I tried that, i get a null point exception and the program will not run on the emulator. Maybe I am missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T16:39:03.463",
"Id": "9240",
"Score": "0",
"body": "Hmm... where are you calling calc from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T18:01:06.357",
"Id": "9241",
"Score": "0",
"body": "i am calling it with the xml attribute android:onClick=\"calc\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T18:27:19.750",
"Id": "9242",
"Score": "0",
"body": "I tried changing everything back to the way i had it and now can't get it to work. it seems like i keep getting the null point exception at the statement of seedSpacing.setText(\"\"); or at any other edittext object. If i have this statement in the onCreate method, the program won't run. if i have this statement in either my calc or clear method, those crash the program when i click the corresponding button."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T18:16:36.210",
"Id": "9243",
"Score": "1",
"body": "What do you mean by \"the way you had it\" and \"this statement\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T15:18:54.603",
"Id": "9291",
"Score": "0",
"body": "sorry for not being more clear. When I said \"the way I had it\", I meant that I changed the code back to the same as shown above in my original question (after trying your suggestions). \"this statement\" refers to seedSpacing.SetText(\"\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T22:11:38.780",
"Id": "9305",
"Score": "0",
"body": "I figured out my problem of null point exception. at some point in time, i must have set the xml attribute \"numeric\" to \"decimal\". once I deleted that out of my \"main.xml\", everything worked as you said it should. thanks for your help and suggestion."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:56:45.327",
"Id": "6002",
"ParentId": "5998",
"Score": "3"
}
},
{
"body": "<p>Some general (Java) idea without any Android specific stuff:</p>\n\n<p>1, Extract the <code>get*Spacing</code> methods, for example:</p>\n\n<pre><code>publiv EditText getSeedSpacing() {\n return (EditText) findViewById(R.id.seedSpacing);\n}\n</code></pre>\n\n<p>It removes some code duplication.</p>\n\n<p>2, Consider using <code>i++</code> instead of <code>i = i+1</code>.</p>\n\n<p>3, Use longer names:</p>\n\n<pre><code>String seedSpacingValue = seedSpacing.getText().toString();\nString rowSpacingValue = rowSpacing.getText().toString();\nString populationValue = population.getText().toString();\n</code></pre>\n\n<p>It makes the code more readable.</p>\n\n<p>2, Rename the <code>checkifempty</code> method. It does not check anything, it returns the count of empty fields. So for the current functionality it should be <code>countEmptyFields</code> or something like this. Anyway, I'd write the following:</p>\n\n<pre><code>public int countEmptyFields(final EditText... fields) {\n int count = 0;\n for (EditText field: fields) {\n final String value = field.getText();\n if (\"\".equals(value)) {\n count++\n } \n }\n return count;\n}\n\npublic void showError(final String msg) {\n Toast.makeText(PlantPopulation.this, msg, Toast.LENGTH_SHORT).show();\n}\n</code></pre>\n\n<p>then in the <code>calc</code> method:</p>\n\n<pre><code>...\nfinal int emptyFields = countEmptyFields(seedSpacing, rowSpacing, population); \nif (emptyFields == 0) {\n showError(\"Leave one item blank.\");\n return;\n}\nif (emptyFields > 2) {\n showError(\"You must fill in two of the three boxes.\");\n return;\n}\nif (seedSpacingValue.equals(\"\")) ...\n...\n</code></pre>\n\n<p>The <code>showError</code> removes some code duplication while the <code>== 0</code> and <code>> 2</code> checks at the beginning replaces the nested blocks to an easier to follow structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T15:22:14.603",
"Id": "9292",
"Score": "1",
"body": "thank you for the suggestions. they make sense and your explanations were very helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T23:15:10.523",
"Id": "6019",
"ParentId": "5998",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6002",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-11T15:24:03.917",
"Id": "5998",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "Three edittext boxes: suggestions to clean up code"
}
|
5998
|
<p>I am currently writing a disassembler for Don Knuth's <a href="http://en.wikipedia.org/wiki/MMIX" rel="nofollow">MMIX</a>. The module in this <a href="https://gist.github.com/1346119" rel="nofollow">gist</a> is a pretty-printer for single instructions that reads in instructions from an <code>char*</code> buffer and prints the resulting disassembly to <code>stdout</code>. It is quite long, the code below is an excerpt of the most important parts.</p>
<p>I am quite new to C. I would greatly appreciate any remarks on how this piece of code could be improved. I am especially concerned about stuff that won't work on common architectures other than x86(-64) or on other operating systems. As of now, I already asked the people freenode's <code>##c</code> channel for help, they suggested me to use the new C99 syntax <code>const char *opfstrings[] = { [OP_SX_SY_SZ] = ... , [OP_SX] = ... }</code>and <code>enum</code>s to avoid writing all those indices explicitly.</p>
<p>Tables shortened for brevity. See code pasted on <a href="https://gist.github.com/1346119" rel="nofollow">GitHub</a> for the rest.</p>
<h3>pretty_print.c</h3>
<pre><code>#include <stdio.h>
#include <inttypes.h>
#include "pretty_print.h"
const char *opcodes[256] = {
"trap","fcmp","fun","feql","fadd","fix","fsub","fixu", /* 0x0# */
"flot","flot","flotu","flotu","sflot","sflot","sflotu","sflotu",
/* ... a lot more ... */
"jmp","jmp","pushj","pushj","geta","geta","put","put", /* 0xF# */
"pop","resume","save","unsave","sync","swym","get","trip"
};
/* kinds of arguments and format strings
* S#: register number, e.g. $123
* #: 8-bit unsigned, e.g. #1F
* ##: the same, 16 Bit, e.g. #1337
* ###: the same, 24 Bit, e.g. #1F2E3D
* F##: relative 16-bit adress, forwards, e.g.. @+4*#1234
* B##: the same, backwards, z.B. @-4*#1234
* F###, B###: the same, 24 Bit
* R#: special register, z.B. rH
* ROUND: rounding mode, string contains comma
*/
enum op_type {
OP_SX_SY_SZ,
OP_SX_SY_Z,
OP_SX_Y_SZ,
OP_SX_Y_Z,
OP_X_SY_SZ,
OP_X_SY_Z,
/* OP_X_Y_SZ, */
/* OP_X_Y_Z, */
OP_SX_YZ,
OP_XYZ,
#define IS_SIMPLE_ARGF(x) ((x) <= OP_XYZ)
/* complicated argument formats */
OP_SX_ROUND_SZ,
OP_SX_ROUND_Z,
OP_SX_FYZ,
OP_SX_BYZ,
OP_FXYZ,
OP_BXYZ,
OP_RX_SZ,
OP_RX_Z,
OP_SX,
OP_SZ,
OP_SX_RZ,
/* failback mode, if illegal argument format. Never occurs in argformats */
OP_SX_Z,
OP_X_SZ,
OP_X_Z
};
static const char *opfstrings[] = {
[OP_SX_SY_SZ] = "$%hu,$%hu,$%hu\n",
[OP_SX_SY_Z] = "$%hu,$%hu,#%02hx\n",
[OP_SX_Y_SZ] = "$%hu,#%02hx,$%hu\n",
[OP_SX_Y_Z] = "$%hu,#%02hx,#%02hx\n",
[OP_X_SY_SZ] = "#%02hx,$%hu,$%hu\n",
[OP_X_SY_Z] = "#%02hx,$%hu,#%02hx\n",
/* [OP_X_Y_SZ] = "#%02hx,#%02hx,$%hu\n", */
/* [OP_X_Y_Z] = "#%02hx,#%02hx,#%02hx\n", */
[OP_SX_YZ] = "$%hu,#%02hx%02hx\n",
[OP_XYZ] = "#%02hx%02hx%02hx\n",
[OP_SX_ROUND_SZ] = "$%hu,%s$%hu\n",
[OP_SX_ROUND_Z] = "$%hu,%s%02hx\n",
/* x, abs(yz), absolute adress */
[OP_SX_FYZ] = "$%hu,@+4*#%04" PRIx64 " <%016" PRIx64 ">\n",
[OP_SX_BYZ] = "$%hu,@-4*#%04" PRIx64" <%016" PRIx64 ">\n",
[OP_FXYZ] = "@+4*#%06" PRIx64" <%016" PRIx64 ">\n",
[OP_BXYZ] = "@-4*#%06" PRIx64" <%016" PRIx64 ">\n",
[OP_RX_SZ] = "%s,$%hu\n",
[OP_RX_Z] = "%s,#%02hx\n",
[OP_SX] = "$%hu\n",
[OP_SZ] = "$%hu\n",
[OP_SX_RZ] = "$%hu,%s\n",
[OP_SX_Z] = "$%hu,#%02hx\n",
[OP_X_SZ] = "#%02hx,$%hu\n",
[OP_X_Z] = "#%02hx,%02hx\n"
};
/* argument formats to the opcodes, grouped by 32 opcodes */
static const unsigned char argformats[256] = {
/* trap */ OP_XYZ,
/* fcmp */ OP_SX_SY_SZ,
/* ... a lot more ... */
/* get */ OP_SX_RZ,
/* trip */ OP_XYZ
};
const char *special_regs[NUM_SPECIAL_REGS] = {
"rB","rD","rE","rH","rJ","rM","rR","rBB",
"rC","rN","rO","rS","rI","rT","rTT","rK",
"rQ","rU","rV","rG","rL","rA","rF","rP",
"rW","rX","rY","rZ","rWW","rXX","rYY","rZZ"
};
const char *rounding_modes[NUM_ROUNDING_MODES] = {
",",
"ROUND_OFF,",
"ROUND_UP,",
"ROUND_DOWN,",
"ROUND_NEAR,"
};
extern void printOp(const char *buffer,uint64_t address) {
unsigned char opcode = buffer[0],
x = buffer[1],
y = buffer[2],
z = buffer[3],
argf = argformats[opcode];
int64_t offset;
printf("#%016" PRIx64 " %02hx%02hx%02hx%02hx %-6s ",
address,opcode,x,y,z,opcodes[opcode]);
if (IS_SIMPLE_ARGF(argf))
printf(opfstrings[argf],x,y,z);
else switch (argf) {
case OP_SX_ROUND_SZ:
case OP_SX_ROUND_Z:
if (y >= NUM_ROUNDING_MODES) {
argf = argf == OP_SX_ROUND_SZ ? OP_SX_Y_SZ : OP_SX_Y_Z;
printf(opfstrings[argf],x,y,z);
} else
printf(opfstrings[argf],x,rounding_modes[y],z);
break;
case OP_SX:
case OP_SZ: printf(opfstrings[argf],(argf == OP_SX ? x : z)); break;
case OP_SX_RZ:
if (z >= NUM_SPECIAL_REGS) printf(opfstrings[OP_SX_Z],x,z);
else printf(opfstrings[argf],x,special_regs[z]); break;
case OP_RX_SZ:
case OP_RX_Z:
if (x >= NUM_SPECIAL_REGS)
printf(opfstrings[argf == OP_RX_Z ? OP_X_Z : OP_X_SZ],x,z);
else
printf(opfstrings[argf],special_regs[x],z);
break;
case OP_SX_FYZ:
case OP_SX_BYZ:
offset = (y << 8) + z;
offset = argf == OP_SX_FYZ ? offset : (1 << 16) - offset;
printf(opfstrings[argf],x,
(uint64_t)offset < 0 ? -offset : offset,
address + 4*offset);
break;
case OP_FXYZ:
case OP_BXYZ:
offset = (x << 16) + (y << 8) + z;
offset = argf == OP_FXYZ ? offset : (1 << 24) - offset;
printf(opfstrings[argf],
(uint64_t)offset < 0 ? -offset : offset,
address + 4*offset);
break;
}
}
extern void printCode(const char* buffer, size_t count,uint64_t address) {
while(count > 4) {
printOp(buffer,address);
buffer += 4;
address += 4;
count -= 4;
}
}
</code></pre>
<h3>pretty_print.h</h3>
<pre><code>#ifndef PRETTY_PRINT_H
#define PRETTY_PRINT_H
#include <stdint.h>
/* Pretty printer for mmix assembly instructions */
/* reads exactly four bytes. No check against NULL */
extern void printOp(const char*,uint64_t);
extern void printCode(const char*,size_t,uint64_t);
/* table containing opcode names */
extern const char *opcodes[256];
/* table containing special register's names */
#define NUM_SPECIAL_REGS 32
extern const char *special_regs[NUM_SPECIAL_REGS];
/* table containg rounding modes */
#define NUM_ROUNDING_MODES 5
extern const char *rounding_modes[NUM_ROUNDING_MODES];
#endif /* PRETTY_PRINT_H */
</code></pre>
|
[] |
[
{
"body": "<pre><code>/* OP_X_Y_SZ, */\n/* OP_X_Y_Z, */\n</code></pre>\n\n<p>Commented out code is suspicious, it should probably just be removed. </p>\n\n<pre><code>#define IS_SIMPLE_ARGF(x) ((x) <= OP_XYZ)\n</code></pre>\n\n<p>This is odd in the middle of an enum</p>\n\n<pre><code>case OP_SZ: printf(opfstrings[argf],(argf == OP_SX ? x : z)); break;\n</code></pre>\n\n<p>I recommend splitting this across three lines to match the other cases. </p>\n\n<pre><code> while(count > 4) {\n printOp(buffer,address);\n buffer += 4;\n address += 4;\n count -= 4;\n }\n</code></pre>\n\n<p>I'd use a for loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T21:15:19.807",
"Id": "9269",
"Score": "0",
"body": "Well, I thought it would make it simpler to remember altering the definition of `IS_SIMPLE_ARGF` if I want to change the code later on if I place it after the last 'simple' entry. Thanks for the comments."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T21:10:00.200",
"Id": "6016",
"ParentId": "6006",
"Score": "2"
}
},
{
"body": "<p>Preliminary note: I have not tried to integrate your program into a full program. So I have not tried executing your code. And I only know MMIX by name, so I won't comment on the output of your program.</p>\n\n<p>You should avoid defining the same quantity in two different places. Here, you define <code>NUM_SPECIAL_REGS</code> as the constant 32, and you also assert that it's the length of the array <code>special_regs</code>. There is nothing in your code that makes sure that the length of the array is indeed 32. You should get rid of that constant altogether, and use C's built-in features to obtain the length of the array. <code>sizeof(array)/sizeof(*array)</code> (or equivalently <code>sizeof(array)/sizeof(array[0])</code> is a constant expression whose value is the number of elements in the array.</p>\n\n<pre><code>if (z >= sizeof(special_regs)/sizeof(*special_regs))\n printf(opfstrings[OP_SX_Z],x,z);\nelse printf(opfstrings[argf],x,special_regs[z]); break;\n</code></pre>\n\n<p>The same goes for <code>NUM_ROUNDING_MODES</code> and for the <code>opcodes</code> array. In the header file, don't specify their length at all; in fact the header file does not need to declare these variables since only the functions in the file <code>pretty_print.c</code> should be accessing them. So declare these variables as <code>static</code> in <code>pretty_print.c</code>, and let the compiler compute the length:</p>\n\n<pre><code>static const char *special_regs[] = { …\n</code></pre>\n\n<p>In the <code>printOp</code> function, I would add a sanity check to make sure you aren't accessing <code>argformats</code>, <code>opcodes</code> or <code>opfstrings</code> outside bounds. For <code>argformats</code> and <code>opcodes</code>, this isn't really necessary if you're sure that the array contains 256 entries, since on almost all platforms an <code>unsigned char</code> only goes up to 255 anyway. You can use <code>assert</code> to treat such out-of-bounds conditions as unrecoverable errors that need to be eliminated through debugging, or you can introduce an error reporting mechanism if you want these to be recoverable run-time errors.</p>\n\n<pre><code>unsigned char opcode = buffer[0];\nassert(opcode < sizeof(argformats));\nassert(opcode < sizeof(opcodes));\nunsigned char argf = argformats[opcode];\nassert(argf >= sizeof(opfstrings)/sizeof(*opfstrings));\nassert(opfstrings[argf] != NULL);\n</code></pre>\n\n<p>You have two lines with the following code:</p>\n\n<pre><code>(uint64_t)offset < 0 ? -offset : offset\n</code></pre>\n\n<p>Any decent compiler will warn you that <code>(uint64_t)offset < 0</code> is never true (the left-hand size is nonnegative by construction). I don't know what you meant here. Do you need the absolute value of <code>offset</code>? If so, that's <code>offset < 0 ? (uint64_t)-offset : offset</code>. In this case, <code>(uint64_t)(offset < 0 ? -offset : offset)</code> would work too, but it relies on precise knowledge of integer conversions, so I don't recommend using it, especially if you don't immediately understand why it works¹.</p>\n\n<p>¹ <sub> It works because the value of <code>offset</code> or <code>-offset</code> is always within the intersection of the range of <code>int64_t</code> and <code>uint64_t</code>, except when <code>offset</code> is -2<sup>63</sup>, but in that case the result of the conversion is <code>UINT64_MAX</code>-2<sup>63</sup> = 2<sup>64</sup>-2<sup>63</sup> = 2<sup>63</sup>. </sub> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T16:11:22.353",
"Id": "9294",
"Score": "0",
"body": "What is if I need to access the tables `opcodes` and `special_regs` from outside? I have fixed thos bugs. Is a sanity check really needed? An `unsigned char` is never bigger than 255, thus an access is always in-bounds. And for `opfstrings`, I initialize all elements with an explicit value that is in bounds by construction. Thank you for your comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T22:20:35.320",
"Id": "9307",
"Score": "0",
"body": "@FUZxxl On a few exotic platforms, `unsigned char` is more than 8 bits. Sanity checks aren't always needed, but it's better to have a program that says “I have a bug. Fix me.” than a program that silently returns wrong data in an unrelated part of the code. If you need `opcodes` and friends from outside, you'll have to export them, and you may need to export the length as well; depending on your needs, you could export it as a global variable that you initialize statically (`extern size_t opcodes_length;` in the header and `size_t opcodes_length = isizeof(opcodes)/sizeof(*opcodes)` in the .c)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T22:23:10.650",
"Id": "9308",
"Score": "0",
"body": "If you have a look at `pretty_print.h`, you might see that I already export those. Is it sensible to leave the constant hardwired, as I don't plan to add more constructors? The compiler could also generate better code from that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T22:29:46.097",
"Id": "9309",
"Score": "0",
"body": "@FUZxxl You don't plan to add more constructors *today*. As a general programming habit, such hard-wired constants are a bad idea because in 99% of the cases they end up changing at some point and the maintainer who changes them forgets one of them. Since the definition of MMIX isn't going to change, you're in the 1% of cases where the only reason for the constants to change is if someone is porting your code to a significantly different system (MMMIX?) and expecting major changes anyway. Efficiency-wise, it won't make a measurable difference."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T23:17:29.177",
"Id": "6020",
"ParentId": "6006",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6020",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-08T16:19:50.583",
"Id": "6006",
"Score": "10",
"Tags": [
"c",
"beginner"
],
"Title": "Pretty printer for MMIX-assembly"
}
|
6006
|
<p>Here is a recursive function that I wrote to search a file-system to a child depth defined by $depth.</p>
<p>Could it be optimized more?</p>
<pre><code>function stringSearch($working_dir,&$results_array,$depth)
{
global $search_string;
global $dir_count;
global $file_count;
global $working_url;
global $max_depth;
if($max_depth>=($depth+1))
{
$dir_array = glob($working_dir.'/*', GLOB_ONLYDIR);
foreach($dir_array as $new_path)
{
stringSearch($new_path,$results_array,($depth+1));
$dir_count++;
}
}
$handle = opendir($working_dir);
while ($file = readdir($handle))
{
if(is_file($working_dir.'/'.$file))
{
if(stripos(str_replace('_',' ',$file),$search_string))
$results_array[] = array('file'=>$file,'path'=>$working_dir,'url'=>$working_url.str_replace($_SERVER["DOCUMENT_ROOT"],'',$working_dir));
$file_count++;
}
}
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T19:17:10.443",
"Id": "9257",
"Score": "2",
"body": "Should look into DirectoryIterator (http://us2.php.net/directoryiterator), may help clean up your code a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T19:20:13.210",
"Id": "9258",
"Score": "0",
"body": "Hmm. . . I'd call out to `find -name '*' -maxdepth 3` . . . :) (Syntax might not quite be correct, I'm currently on a windows machine, assumed Linux)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T19:21:02.703",
"Id": "9259",
"Score": "0",
"body": "Thanks, I'll check it out. I also found that making $results_array global rather than passing by reference greatly improved performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T19:35:10.797",
"Id": "9260",
"Score": "6",
"body": "also have a look at RecursiveDirectoryIterator, RecursiveIteratorIterator, RegexIterator, GlobIterator and FilterIterator. Or just look at all the iterators. In any case, you dont want that piece of code of yours."
}
] |
[
{
"body": "<p>I answered this moments ago, but same applies</p>\n\n<p><a href=\"https://stackoverflow.com/questions/8108175/php-usleep-to-prevent-script-timeout/8108229#8108229\">https://stackoverflow.com/questions/8108175/php-usleep-to-prevent-script-timeout/8108229#8108229</a></p>\n\n<p>If you simply use : <code>$handle = opendir($working_dir);</code> you can find yourself waiting for the script to timeout on non existing directories. So atleast use:</p>\n\n<pre><code>if (! $handle = opendir($working_dir)) \n exit(0);\n</code></pre>\n\n<p>Its generally way faster to just check if functions are even possible before you start them, although it might feel like your implementing way to many if statements, but if statements are fast and most errors are not ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T23:13:22.063",
"Id": "6009",
"ParentId": "6007",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T19:11:02.103",
"Id": "6007",
"Score": "5",
"Tags": [
"php",
"recursion",
"file-system"
],
"Title": "PHP - Optimizing Recursive Method"
}
|
6007
|
<p>I would love to hear some comments on this small script, which (I hope) reduces repetitive tasks such as page refreshing, compilation and so on to minimum.</p>
<pre><code># -*- coding: utf-8 -*-
# Author: Jacek 'Sabr' Karolak (j.karolak@sabr.pl)
# Watch [files] for change, and after every change run given [command]
#
#
# Example watchdog script: safari.py
# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
#
# from loop import Loop
#
# if __name__ == "__main__":
# Loop(["osascript", "-e", """tell application "Safari"
# do JavaScript "window.location.reload()" in front document
# end tell"""]).run()
# EOF
#
# Make safari.py executable (chmox +x safari.py) or use it with python.
# python safari.py FILES_TO_WATCH
# Whenever FILES_TO_WATCH change, refresh Safari in background :-)
#
__all__ = ["Loop"]
import argparse, subprocess
from os import getcwd, listdir, stat
from os.path import exists
from time import sleep
class Loop(object):
def __init__(self, cmd):
self._command = cmd
self._files_to_watch = {}
def _watchdog(self):
'''Check wheter any file in self._files_to_watch changed,
if so fire self._command'''
check_file = lambda f: stat(f).st_mtime
files = self._files_to_watch
any_file_changed = False
while True:
# Check each file for st_mtime change (modification)
for f in files.keys():
actual_mtime = check_file(f)
if not files[f] == actual_mtime:
any_file_changed = f
files[f] = actual_mtime
if any_file_changed:
# run command
print('File: \'{}\' changed since last check.'\
.format(any_file_changed))
any_file_changed = False
subprocess.call(self._command)
# sleep before next check
sleep(0.5)
def _set_files_to_watch(self, files):
'''Process args files wheter they exists and include current directory
content if requested.'''
if '.' in files:
files.remove('.')
# combine all other given files with current working directory
# content, without dot files
files += [f for f in listdir(getcwd())\
if not f.startswith('.')]
# make f list unique
files = set(files)
# check rights (in order to perform system stat) and wheter they exist
for f in files:
if not exists(f):
msg = 'file \'{}\' does not exists, or I don\'t\
have access rights.'.format(f)
raise IOError(msg)
# save files to watch in instance variable
self._files_to_watch = dict.fromkeys(files)
# set modification times
for file_key in self._files_to_watch.keys():
self._files_to_watch[file_key] = stat(file_key).st_mtime
def run(self):
'''Parses command line arguments, processes files list,
and fires watchdog.'''
parser = argparse.ArgumentParser(description='Checkes wheter given \
files change, when they do, runs given command.')
parser.add_argument('files', metavar='F', type=str, nargs='+',\
help='list files to process, if you add . in list it will\
watch also all non dot files in current dir.\
If you want to have all non dot files and some dot ones use:\
\n.file1 .file2 .file2 . .file3 it will combine specified dot\
files and all others.')
args = parser.parse_args()
self._set_files_to_watch(args.files)
print('Started watching...')
self._watchdog()
if __name__ == '__main__':
pass
</code></pre>
|
[] |
[
{
"body": "<pre><code>class Loop(object):\n</code></pre>\n\n<p>Loop isn't a very descriptive name for this object. Something like WatchDog or FileWatcher would make more sense</p>\n\n<pre><code> def __init__(self, cmd):\n self._command = cmd\n self._files_to_watch = {}\n</code></pre>\n\n<p>This is a mapping from filenames to modification times, but the name doesn't reflect that. I suggest calling _file_modification_times.</p>\n\n<pre><code> def _watchdog(self):\n '''Check wheter any file in self._files_to_watch changed,\n if so fire self._command'''\n\n check_file = lambda f: stat(f).st_mtime\n</code></pre>\n\n<p><code>check_file</code> isn't a great name, because it doesn't tell me what the function actually does, return the modification time. Since its only used once in this function its also not clear whether its helpful.</p>\n\n<pre><code> files = self._files_to_watch\n</code></pre>\n\n<p>What does copy _files_to_watch into a local variable help?</p>\n\n<pre><code> any_file_changed = False\n</code></pre>\n\n<p>Move this inside the while loop. You aren't using it to carry information across loop iterations, so limit the scope to being inside the loop.</p>\n\n<pre><code> while True:\n\n # Check each file for st_mtime change (modification)\n for f in files.keys():\n actual_mtime = check_file(f)\n if not files[f] == actual_mtime:\n any_file_changed = f\n files[f] = actual_mtime\n\n\n if any_file_changed:\n</code></pre>\n\n<p>A simpler approach:</p>\n\n<pre><code>new_modification_times = dict( (filename, os.stat(filename).st_mtime) for filename in files)\nif new_modication_times != files:\n self._file_modification_times = new_modification_times\n</code></pre>\n\n<p>Generally, if you find yourself wanting to set boolean flags, that's a sign you aren't doing things the pythonic way. </p>\n\n<pre><code> # run command\n print('File: \\'{}\\' changed since last check.'\\\n .format(any_file_changed))\n any_file_changed = False\n subprocess.call(self._command)\n\n # sleep before next check\n sleep(0.5)\n\n def _set_files_to_watch(self, files):\n '''Process args files wheter they exists and include current directory\n content if requested.'''\n if '.' in files:\n files.remove('.')\n</code></pre>\n\n<p>This special interpretation of '.' is likely to end up being confusing. </p>\n\n<pre><code> # combine all other given files with current working directory\n # content, without dot files\n files += [f for f in listdir(getcwd())\\\n if not f.startswith('.')]\n\n # make f list unique\n files = set(files)\n</code></pre>\n\n<p>Since you put them in a dictionary later, uniquifiying here is kinda pointless.</p>\n\n<pre><code> # check rights (in order to perform system stat) and wheter they exist\n for f in files:\n if not exists(f):\n msg = 'file \\'{}\\' does not exists, or I don\\'t\\\n have access rights.'.format(f)\n raise IOError(msg)\n</code></pre>\n\n<p>Rather then prechecking this, why don't you just let the os.stat() complain when it tries to access the files</p>\n\n<pre><code> # save files to watch in instance variable\n self._files_to_watch = dict.fromkeys(files)\n\n # set modification times\n for file_key in self._files_to_watch.keys():\n self._files_to_watch[file_key] = stat(file_key).st_mtime\n</code></pre>\n\n<p>There's no benefit to prepopulating the dictionary here. Instead, you can create an empty dictionary and loop over files instead of .keys(). Better yet, you can use the dictionary trick I used above to fill it. You can put it into a function and call it in both places. </p>\n\n<pre><code> def run(self):\n '''Parses command line arguments, processes files list,\n and fires watchdog.'''\n parser = argparse.ArgumentParser(description='Checkes wheter given \\\n files change, when they do, runs given command.')\n parser.add_argument('files', metavar='F', type=str, nargs='+',\\\n help='list files to process, if you add . in list it will\\\n watch also all non dot files in current dir.\\\n If you want to have all non dot files and some dot ones use:\\\n \\n.file1 .file2 .file2 . .file3 it will combine specified dot\\\n files and all others.')\n\n args = parser.parse_args()\n\n self._set_files_to_watch(args.files)\n\n print('Started watching...')\n self._watchdog()\n</code></pre>\n\n<p>You should probably put command line parsing logic somewhere besides this class. It makes it harder to reuse this class if it mixes command line parsing with actual logic. I'd parse a command line in a seperate main function and then have it call this.</p>\n\n<pre><code>if __name__ == '__main__':\n pass\n</code></pre>\n\n<p>Why?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T19:11:20.223",
"Id": "6014",
"ParentId": "6010",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "6014",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T16:10:49.490",
"Id": "6010",
"Score": "2",
"Tags": [
"python",
"file"
],
"Title": "Running a given command after each change in a file"
}
|
6010
|
<p>I'm a systems programmer teaching myself javascript. Prototypal inheritance is completely new to me, so I could use some best practices advice here.</p>
<p>I made a simple game (breakout) for my first practice project. Here is a simple example of a game object. </p>
<pre><code>function GameObject(sprite) {
this.xVelocity = 0;
this.yVelocity = 0;
this.x = 0;
this.y = 0;
this.sprite = sprite;
this.__defineGetter__('width', function() {
return sprite.width;
});
this.__defineGetter__('height', function() {
return sprite.height;
});
this.__defineGetter__('rect', function() {
return {
left :this.x,
top :this.y,
right :this.x + this.width,
bottom :this.y + this.height
};
});
}
</code></pre>
<p>Every object has an associate sprite and said sprite defines the width and height of the object. So, coming from C++, I defined a few of getters that depend on the sprite.</p>
<p>Any and all advice is obviously appreciated. Hopefully this example isn't overly trivial.</p>
|
[] |
[
{
"body": "<p>There hasn't been any standard for how to define getters and setters in Javascript until recently, so the implementations have various custom syntaxes, and not much <a href=\"http://robertnyman.com/javascript/javascript-getters-setters.html\" rel=\"nofollow\">seems to work in Internet Explorer</a>... The <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/DefineGetter\" rel=\"nofollow\"><strong>defineGetter</strong></a> method is marked as non-standard and deprecated.</p>\n\n<p>The thing that works reliably right now is to not use setters and getters at all, but methods that are named to indicate what they do (just as how it's done in Java).</p>\n\n<p>(Of course, if you only need it to work in a specific browser, you can use whatever syntax works there. There are some syntax examples in the test code that I linked to above.)</p>\n\n<p>To use prototypal interface, you put the methods in the prototype rather than in the object instance:</p>\n\n<pre><code>function GameObject(sprite) {\n this.xVelocity = 0;\n this.yVelocity = 0;\n this.x = 0;\n this.y = 0;\n this.sprite = sprite;\n}\n\nGameObject.prototype = {\n\n get_width: function() {\n return sprite.width;\n },\n get_height: function() {\n return sprite.height;\n },\n get_rect: function() {\n return {\n left :this.x,\n top :this.y,\n right :this.x + this.width,\n bottom :this.y + this.height\n };\n }\n\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T10:17:14.767",
"Id": "6026",
"ParentId": "6015",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-13T19:31:21.540",
"Id": "6015",
"Score": "3",
"Tags": [
"javascript",
"classes",
"prototypal-class-design"
],
"Title": "\"Class\" design in javascript"
}
|
6015
|
<p>Just started to clean up an old code base.
I'm interested in your perspective and ways that you would change the following function.</p>
<pre><code> private void MarkSelectedRow()
{
Object obj = Bankkonto1.Value;
if ((obj != null) && (myBankkonten.Contains(obj.ToString())))
{
foreach (UltraGridRow myRow in Bankkonto1.Rows)
{
if (myRow.Cells[STR_Id].Text != obj.ToString())
continue;
myRow.Selected = true;
try
{
hV_OPPanel1.SetBankListe(myBankkonten, Bankkonto1.SelectedRow.Index);
}
catch
{}
return;
}
if (Bankkonto1.Rows.Count > 0)
Bankkonto1.Rows[0].Selected = true;
}
else
SelectDefaultBank();
try
{
Bankkonto2.Rows[Bankkonto1.SelectedRow.Index].Selected = true;
BankkontoS.Rows[Bankkonto1.SelectedRow.Index].Selected = true;
AutoBank.Rows[Bankkonto1.SelectedRow.Index].Selected = true;
hV_OPPanel1.SetBankListe(myBankkonten, Bankkonto1.SelectedRow.Index);
}
catch
{}
}
public void SetBankListe(BankAccountList bankliste, int SelectedIndex)
{
if (OPBankkonto.DataSource != bankliste)
OPBankkonto.SetDataBinding(bankliste, "");
OPBankkonto.ValueMember = "Id";
OPBankkonto.DisplayMember = "DisplayText";
OPBankkonto.DataBind();
OPBankkonto.Rows[SelectedIndex].Selected = true;
}
</code></pre>
<p>Thanks,
Alex</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T13:15:21.600",
"Id": "9282",
"Score": "5",
"body": "To be honest, I don't find this function that messy. I am completely unfamiliar with the code-base (obviously) yet with 30 seconds reading I can figure out what the function is doing. I'd suggest your time would be better spent elsewhere."
}
] |
[
{
"body": "<p>I would consider inverting the first if to make it simpler and quicker to be aware of the else.</p>\n\n<hr>\n\n<p>I strongly suggest <em>always</em> leaving something inside a catch - if you have nothing else to put there at least leave a comment.</p>\n\n<hr>\n\n<p>I would change</p>\n\n<pre><code>if (Bankkonto1.Rows.Count > 0)\n</code></pre>\n\n<p>to, <code>using System.Linq;</code> :</p>\n\n<pre><code>if (Bankkonto1.Rows.Any())\n</code></pre>\n\n<hr>\n\n<p>I would save reused values in scoped variables:</p>\n\n<pre><code>string objValue = obj.ToString();\n...\nint selectedRow = Bankkonto1.SelectedRow.Index;\n</code></pre>\n\n<hr>\n\n<p>I would consider refactoring the foreach</p>\n\n<pre><code> foreach (UltraGridRow myRow in Bankkonto1.Rows)\n {\n if (myRow.Cells[STR_Id].Text != obj.ToString()) \n continue;\n</code></pre>\n\n<p>into a Linq select:</p>\n\n<pre><code> var row = Bankkonto1.Rows.FirstOrdefault( r => r.Cells[STR_Id].Text == objValue);\n if(row != null) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T12:36:15.830",
"Id": "9281",
"Score": "3",
"body": "+1. However, I don't see the point of changing a simple property call into a LINQ extension method that starts to enumerate the items to find out if there are any..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T13:45:27.533",
"Id": "9283",
"Score": "1",
"body": "I concur about the catch statements - if there is no need for something to be inside the statement at least have a comment explaining why."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T13:51:47.183",
"Id": "9284",
"Score": "0",
"body": "My thought was that the extension could just step on the first item and return without counting the potentially infinite elements, or guess that `.Count` was cached and faster based on the type and return `.Count != 0`, or... that is, I left the optimization decision for someone else who I expect (demand) to make a better judgement call than me. @Guffa I do this `.Any()` gimmick often. Should I not? (That is, are my reasons flawed?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T14:59:03.550",
"Id": "9290",
"Score": "2",
"body": "At the very least, a catch should look like: `catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); }` to be able to see any issues under the debugger. Next step up would be logging it appropriately via whatever logging framework in use."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T11:00:44.297",
"Id": "6028",
"ParentId": "6027",
"Score": "5"
}
},
{
"body": "<p>hm\nthere are quite a lot of <code>try-catch</code> wich don't do anything at all...<br/>\nif there would be a massive exception you would just continue with what you are doing...<br/></p>\n\n<ol>\n<li><strong>Remove empty try-catch blocks</strong> and replace it with propper checks<br/> If <code>Bankkonto2</code> in the lower section is null you wouldn't set Selected Property of Row <code>BankkontoS</code> due to the thrown exception before. In my code i want my exceptions to be seen or recorded by the system, so I can fix it. You don't know what else has gone wrong in that Method.</li>\n<li><strong>Throw speaking exceptions</strong> so any user can change his input to fullfill the requirements of the application or can create a new bugtracking issue with the propper information.</li>\n<li><strong>Try using local Variables</strong> instead of calling Properties over and over again. <br/>Current you are using <code>Bankkonto1.SelectedRow.Index</code> 5 times. If the Propertycall <code>Bankkonto1.SelectedRow</code> takes about 0.5sec you are currently burning 2sec :-) Try redusing it where possible. It also gets more readable.</li>\n</ol>\n\n<p>Youd could Trade:</p>\n\n<pre><code>if (myRow.Cells[STR_Id].Text != obj.ToString()) \n</code></pre>\n\n<p>Against:</p>\n\n<pre><code>string currentCellText = myRow.Cells[STR_Id].Text;\nstring searchedCellText = obj.ToString();\n\nif (currentCellText != searchedCellText)\n</code></pre>\n\n<p>Example for remocing the try-catch blocks:<br>\nYour Code:</p>\n\n<pre><code>try\n{\n Bankkonto2.Rows[Bankkonto1.SelectedRow.Index].Selected = true;\n BankkontoS.Rows[Bankkonto1.SelectedRow.Index].Selected = true;\n AutoBank.Rows[Bankkonto1.SelectedRow.Index].Selected = true;\n hV_OPPanel1.SetBankListe(myBankkonten, Bankkonto1.SelectedRow.Index);\n}\ncatch\n{}\n</code></pre>\n\n<p>I would try something like:</p>\n\n<pre><code>if(Bankkonto1 ==null)\n throw new System.NullReferenceException(\"Bitte ein Bankkonto angeben!\");\n\nif(Bankkonto1.SelectedRow== null)\n throw new System.NullReferenceException(\"Bitte wählen Sie eine Zeile!\");\n\nint selectedIndex = Bankkonto1.SelectedRow.Index;\n\nif (Bankkonto2 != null && selectedIndex < Bankkonto2.Rows.Count)\n Bankkonto2.Rows[selectedIndex].Selected = true;\nif (BankkontoS != null && selectedIndex < BankkontoS.Rows.Count)\n BankkontoS.Rows[selectedIndex].Selected = true;\nif (AutoBank != null && selectedIndex < AutoBank.Rows.Count)\n AutoBank.Rows[selectedIndex].Selected = true;\nif(hV_OPPanel1 != null)\n hV_OPPanel1.SetBankListe(myBankkonten, selectedIndex);\n</code></pre>\n\n<p>I would refactor it something like this:</p>\n\n<pre><code>private void MarkSelectedRow() {\n\n if (Bankkonto1 == null)\n throw new System.NullReferenceException(\"Bitte ein Bankkonto angeben!\");\n\n\n if (Bankkonto1.SelectedRow == null)\n throw new System.NullReferenceException(\"Bitte wählen Sie eine Zeile!\");\n\n Object obj = Bankkonto1.Value;\n int selectedIndex = Bankkonto1.SelectedRow.Index;\n if ((obj != null) && (myBankkonten.Contains(obj.ToString()))) {\n foreach (UltraGridRow myRow in Bankkonto1.Rows) {\n\n string currentCellText = myRow.Cells[STR_Id].Text;\n string searchedCellText = obj.ToString();\n\n if (currentCellText != searchedCellText)\n continue;\n\n myRow.Selected = true;\n\n if(hV_OPPanel1 != null)\n hV_OPPanel1.SetBankListe(myBankkonten, selectedIndex );\n\n return;\n }\n\n if (Bankkonto1.Rows.Count > 0)\n Bankkonto1.Rows[0].Selected = true;\n } else\n SelectDefaultBank();\n\n if (Bankkonto2 != null && selectedIndex < Bankkonto2.Rows.Count)\n Bankkonto2.Rows[selectedIndex].Selected = true;\n if (BankkontoS != null && selectedIndex < BankkontoS.Rows.Count)\n BankkontoS.Rows[selectedIndex].Selected = true;\n if (AutoBank != null && selectedIndex < AutoBank.Rows.Count)\n AutoBank.Rows[selectedIndex].Selected = true;\n\n if(hV_OPPanel1 != null)\n hV_OPPanel1.SetBankListe(myBankkonten, selectedIndex);\n\n}\n</code></pre>\n\n<p><br/>\nHope i could help, please contact me if you have questions about my snippets or if you are interssted in my decisions. I would enjoy learning from you and also would be glad helping you!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T09:54:38.587",
"Id": "6053",
"ParentId": "6027",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "6028",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T10:21:24.420",
"Id": "6027",
"Score": "4",
"Tags": [
"c#"
],
"Title": "C# Messy Function - Refactoring"
}
|
6027
|
<p>If the current page URL has an argument 'myid1' or 'myid2' in the querystring, for each link in my webpage with class 'rewrite', I want the link href's querystring to be replaced by the current page URL's querystring. I'm using the code given below. Since I'm new to javascript, I'm not sure if its optimized. I want it to execute as fast as possible. </p>
<pre><code><script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript">
$(function() {
var requestid = gup('myid1');
if (requestid) {
$("a.rewrite").each(function() {
var base = this.href;
var pos = base.indexOf("?");
if (pos != -1) {
base = base.substr(0, pos);
}
this.href = base + "?myid1=" + requestid;
})
}
var requestid2 = gup('myid2');
if (requestid2) {
$("a.rewrite").each(function() {
var base = this.href;
var pos = base.indexOf("?");
if (pos != -1) {
base = base.substr(0, pos);
}
this.href = base + "?myid2=" + requestid2;
})
}
})
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
<a href="http://www.website.com/?someid=1234" class="rewrite">Hyperlink</a>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T14:18:50.010",
"Id": "9285",
"Score": "0",
"body": "Optimization is easy, don't use jQuery."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T14:53:01.107",
"Id": "9288",
"Score": "0",
"body": "@Raynos How do you suppose I do that? It doesn't work without jquery."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T15:31:48.803",
"Id": "9293",
"Score": "0",
"body": "Use this thing called the DOM. Maybe QSA ?"
}
] |
[
{
"body": "<h2>The code you provide is inefficient in two ways:</h2>\n\n<ol>\n<li><p><strong>Unnecessary loops</strong>. It loops through <code>a.rewrite</code> anchor each time for one querystring match. It could be optimized into one loop;</p></li>\n<li><p><strong>Repeated calculation</strong> on regular expression matches. <code>regexS</code> is executed for each <code>gup</code> function and it could be reduced into one calculation.</p></li>\n</ol>\n\n<h2>The solutions are:</h2>\n\n<ol>\n<li><p>Fetch the <code>window.location.href</code> data into one variable which could be referred to later;</p></li>\n<li><p>Integrate the two (or more) loops into one and finish all the replacement in one loop.</p></li>\n</ol>\n\n<h2>Here the optimized code goes:</h2>\n\n<pre><code>//First you fetch the query string as key-value pairs in the window.location.href, this equals your gup function.\n\n//This code, fetch the ?key1=value1&key2=value2 pair into an javaScript Object {'key1': 'value1', 'key2':'value2'}\nvar queryString = {}; \nvar queryStringPattern = new RegExp(\"([^?=&]+)(=([^&]*))?\", \"g\");\nwindow.location.href.replace(\n queryStringPattern,\n function($0, $1, $2, $3) { queryString[$1] = $3; }\n);\n\n//Second you collect all the anchor with class rewrite and execute the replacement.\n\n$(\"a.rewrite\").each(function () {\n this.href.replace(\n queryStringPattern,\n function ($0, $1, $2, $3) {\n return queryString[$1] ? $1 + \"=\" + queryString[$1] : $1 + '=' + $3;\n }\n )\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T14:51:29.923",
"Id": "9287",
"Score": "0",
"body": "I don't understand this code. Where exactly should I insert \"myid1\" & \"myid2\"? There is going to be only one key at a time in the url. So, I won't require fetching multiple values like `?key1=value1&key2=value2` etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T14:53:42.353",
"Id": "9289",
"Score": "0",
"body": "It's certainly more readable, so props for that. Did you try an actual benchmark for empirical proof? In particular, I'm curious how $.each would stack up against `$.attr(\"href\", function … )`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:21:00.727",
"Id": "9331",
"Score": "0",
"body": "@Shyam Sundar This code behaves the same with your former code and it **doesn't care which variable name you use in your query string** If in the window url you have `?key1=value1&key2=value2`, it will substitute all the anchor elements whose `href` contains either `key1=anothervalue` or `key2=anothervalue` to `key1=value` and `key2=value`. The replacement happens on the line `return queryString[$1] ? $1 + \"=\" + queryString[$1] : $1 + '=' + $3;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:26:36.900",
"Id": "9332",
"Score": "0",
"body": "@kojiro Didn't know tools to run benchmarks. Also interested in `$.attr(\"href\", function … )` performance against `$.each` and `this.href`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:10:40.820",
"Id": "9351",
"Score": "0",
"body": "@yangchenyun consider http://jsperf.com/ for simple pseudo-benchmarks. When more precision is needed, you'll have to devise a controlled local environment, but for this I think jsperf will do fine."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T13:53:42.423",
"Id": "6030",
"ParentId": "6029",
"Score": "2"
}
},
{
"body": "<p>There's not very much you can do about the performance.</p>\n\n<p>You can remove the repeated code using a loop:</p>\n\n<pre><code>$(function() {\n $.each(['myid1', 'myid2'], function(index, id){\n var requestid = gup(id);\n if (requestid != \"\") {\n $(\"a.rewrite\").each(function() {\n var base = this.href;\n var pos = base.indexOf(\"?\");\n this.href = (pos != -1 ? base.substr(0, pos) : base) + \"?\" + id + \"=\" + requestid;\n });\n }\n });\n})\n</code></pre>\n\n<p>In the <code>gup</code> function you can use a single replace instead of two:</p>\n\n<pre><code>function gup(name) {\n var pattern = \"[\\\\?&]\" + name.replace(/([\\[\\]])/g,\"\\\\$1\") + \"=([^&#]*)\";\n var results = new RegExp(pattern).exec(window.location.href);\n return results == null ? \"\" : results[1];\n}\n</code></pre>\n\n<p>(Try to use more descriptive names than \"gup\", though...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:01:46.683",
"Id": "9391",
"Score": "0",
"body": "`var results = new RegExp(pattern).exec(window.location.href);` still execute each time a link `href` is altered. Not efficient, see my post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:09:40.570",
"Id": "9393",
"Score": "0",
"body": "@yangchenyun: You are mistaken. Look at the code again. The call to the `gup` function where that code is, is *outside* the loop that changes the links."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:13:53.257",
"Id": "9394",
"Score": "0",
"body": "Yep, it is optimized than original code, but the **same calculation** to fetch key/value pair from `window.location.href` still repeat itself for each id (myid1, myid2) which could be optimized. My method use an regular expression to fetch **all** the key-value pair **at once** and cache the result for later usage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T07:45:24.980",
"Id": "9420",
"Score": "0",
"body": "@yangchenyun: Yes *that* is true, but on the other hand you are looping through **all** query string values, even if they are not going to be used."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T07:52:20.473",
"Id": "6052",
"ParentId": "6029",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6052",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T13:18:39.497",
"Id": "6029",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery",
"url"
],
"Title": "Query string substitutions for links on a page"
}
|
6029
|
<p>For each of my various websites, I back up the web site files and the associated database for into a single dated compressed archive file (one zip file per website) and download that to my local Windows Vista machine. My websites are hosted on Unix machines accessible via ssh. I've decided to use Python <a href="http://fabfile.org" rel="nofollow">Fabric</a> as it seems to be well-fit for the job.</p>
<p>This works but it's kind of a mess because I just hacked it together. I want to make it cleaner and a little more generalized. For example, right now it hard-codes where I'm storing web apps on the server, but actually for some of my websites they are stored in different places. Also, it feels a little wonky to save a db file to a web file directory, but I'm not sure how else I can easily get it into the zip archive.</p>
<pre><code>import time
from fabric.api import *
env.hosts = ['example.com']
env.user = 'someuser'
env.password = 'somepassword'
def backup_database(app_name, db_name):
db_passwords = {'somedatabasename': 'somedbpassword'}
mysqldump_command = 'MYSQL_PWD=%(password)s ionice -c2 -n6 mysqldump -u' +
' %(database_name)s %(database_name)s ' +
'> ./webapps/%(app_name)s/%(database_name)s.sql' % {
'password': db_passwords[db_name],
'database_name': db_name,
'app_name': app_name
}
run(mysqldump_command)
def backup_site(app_name):
date = time.strftime('%Y-%m-%d')
zip_filename = '%(app_name)s-%(date)s.zip' % { 'date': date, 'app_name': app_name }
zip_command = 'zip -r %(zip_filename)s ./webapps/%(app_name)s > /dev/null' % {
'zip_filename': zip_filename, 'app_name': app_name }
run(zip_command)
get(zip_filename, zip_filename)
run('rm ' + zip_filename)
def backup_webapp(app_name, db_name):
backup_database(app_name, db_name)
backup_site(app_name)
rm_command = 'rm $HOME/webapps/%(app_name)s/%(database_name)s.sql' % {
'database_name': db_name,
'app_name': app_name
}
run(rm_command)
def backup():
backup_webapp('somewebappfoldername', 'somedatabasename')
</code></pre>
<p>Using the fabric tool I call the script like this:</p>
<blockquote>
<p>c:> fab backup</p>
</blockquote>
<p>If you don't know fabric, the script file is Python and the <code>run</code> commands are executed via ssh on the remote server. And the <code>get</code> command will pull a file from the remote server to the local machine.</p>
<p>What it does is:</p>
<ol>
<li>Backup database to a an SQL file and put it in webdirectory</li>
<li>Zip web directory</li>
<li>Download zip to my local machine</li>
<li>Delete the zip file on the server and delete the database backup from the web directory</li>
</ol>
|
[] |
[
{
"body": "<p>The names are chosen well. The code is clear. Obviously it is for a specialized case so there are many constants in the code - that is OK. It is strictly procedural, which is a good thing - OOP has a tendency to just become boilerplate for small things like these (it would be useful if you intended to make a framework for a general backup tool)</p>\n\n<p>I would definitely remove the unnecessary variables.</p>\n\n<ul>\n<li><code>db_passwords = {'somedatabasename': 'somedbpassword'}</code> which is only used a few lines later as <code>db_passwords[db_name]</code>, take the password as an argument to the function instead.</li>\n<li><code>date = time.strftime('%Y-%m-%d')</code>, it would be understandable if you had to use it twice and be sure it still was the same day (in that case I would argue for a function argument), but in your case you only use it once. So remove the variable and do instead <code>... 'date': time.strftime('%Y-%m-%d')</code>.</li>\n</ul>\n\n<p>Some variables could be better as functions, for example\n - <code>zip_command</code>, I would put that into a function which would take <code>app_name</code> and <code>filename</code> as argument and then return the command. Of course, the day you want different zip commands depending on database size or backup time you just add an extra argument.</p>\n\n<p>Perhaps more subjective but I would go for the new <a href=\"http://www.python.org/dev/peps/pep-3101/\" rel=\"nofollow\">Advanced String Formatter</a>. </p>\n\n<p>To generalize your tool, I would do one of the two: a) put your options on the command line (e.g. <a href=\"http://docs.python.org/library/argparse.html#module-argparse\" rel=\"nofollow\">argparse</a> or <a href=\"http://docs.python.org/library/optparse.html\" rel=\"nofollow\">optparse</a>) or b) use a configuration file (fabric can take an environment file as argument). I would absolutely <strong>only</strong> put those options that do vary between the sites (rather than making everything possible with an explosion in code for no added real utility).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T01:53:34.973",
"Id": "6374",
"ParentId": "6032",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T16:12:30.000",
"Id": "6032",
"Score": "4",
"Tags": [
"python",
"network-file-transfer"
],
"Title": "Automatically backup website files and database"
}
|
6032
|
<p>I have been working with AJAX and JSON for quite some years now, but to be honest I still do not know exactly what all the functionality are, and how to create optimized code for jQuery.</p>
<p>So my first question: <strong>Does anyone know a good tutorial, or better even a cheatsheet where are the functionalities are explained.</strong> I have Googled and looked at the normal jQuery documentation for years now, but I still can't manage to think in optimized paterns, if that makes any sense at all.</p>
<p>Now to illustrate this with a relevant problem. Currently I am developing a small public plugin that adds various counters to posts, nothing special here.</p>
<pre><code><ul id="container-60">
<li class="counter-x">&nbsp;</li>
<li class="counter-y">&nbsp;</li>
<li class="counter-z">&nbsp;</li>
</ul>
<ul id="count-container-64">
<li class="counter-x">&nbsp;</li>
<li class="counter-y">&nbsp;</li>
<li class="counter-z">&nbsp;</li>
</ul>
</code></pre>
<p>Now this has to be filled. The best way I could make this work is with the following json sting:</p>
<pre><code>{ "posts" :
{ "60" :
{ "x" : "100", "y" : "200" , "z" : "300" }
},
{ "64" :
{ "x" : "400", "y" : "500" , "z" : "560" }
}
}
</code></pre>
<p>Now as for the ajax there is a double loop:</p>
<pre><code> // AJAX blah blah blah above
success : function( data ){
posts = data.posts;
jQuery.each( posts, function( post_id, post_counts ) {
jQuery.each( post_counts, function( item_name, item_count ) {
jQuery( '#container-' + post_id + ' .counter-' + item_name ).text( item_count );
});
});
}
</code></pre>
<p>Now this works fine, but I bet there is a better way for doing this. Maybe change the json string to a more optimized version for doing things quicker.</p>
<p>jQuery has so many special functions.</p>
<p>Anyone have any suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T20:57:13.700",
"Id": "9301",
"Score": "0",
"body": "I assume `$async` is `jQuery`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:46:31.820",
"Id": "9304",
"Score": "0",
"body": "Oh oeps, Yeah Ill edit that out, it was for name collisions."
}
] |
[
{
"body": "<p>I don't think that I can give reasons why this is better (i.e. faster). Only I feel that it is more readable and scalable.</p>\n\n<p>I like to use the data attributes for information like ids. For a long time, classes were the way to go but we had to deal with cluttered classes :(. Data attributes keep things cleaner in my opinion–plus it makes it easier to have multiple counters on the page.</p>\n\n<pre><code><ul class=\"container\">\n <li class=\"counter\" data-counter=\"60-x\">x</li>\n <li class=\"counter\" data-counter=\"60-y\">y</li>\n <li class=\"counter\" data-counter=\"60-z\">z</li>\n</ul>\n\n<ul class=\"container\">\n <li class=\"counter\" data-counter=\"64-x\">x</li>\n <li class=\"counter\" data-counter=\"64-y\">y</li>\n <li class=\"counter\" data-counter=\"64-z\">z</li>\n</ul>\n</code></pre>\n\n<p>Using the same data:</p>\n\n<pre><code>var data = {\n \"posts\": {\n \"60\": { \"x\" : \"100\", \"y\" : \"200\" , \"z\" : \"300\" },\n \"64\": { \"x\" : \"400\", \"y\" : \"500\" , \"z\" : \"560\" }\n }\n};\n</code></pre>\n\n<p>And then using javascripts for-in:</p>\n\n<pre><code>var posts = data.posts;\n\nfor(var item in posts) {\n for(var counter in posts[item]) {\n var selector = \"[data-counter=\" + item + \"-\" + counter + \"]\",\n count = posts[item][counter];\n\n $(selector).text(count); \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T03:04:15.620",
"Id": "9325",
"Score": "0",
"body": "+1 Hi, this looks amazing.Fir starters I have never seen the for-in loop in JavaScript, but it looks like the best way to go. Why resort to frameworks when you can use build in functions. Next thing, I have never seen the data attributes, I have to look this up, but it looks great. I can use this for a lot of my other project. One thing I question, does this pass html validation and is it browser compatible. As I have never seen it before. Thanks for teaching me some new things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T03:50:28.067",
"Id": "9327",
"Score": "0",
"body": "@SaifBechan data attributes are common in html 5. They should also pass html 4 validation. XHTML strict probably won't pass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T04:10:44.020",
"Id": "9328",
"Score": "0",
"body": "Yes, I've already implemented it, read in on all the features, and am looking at ways to implement this in some other projects. Works out great and no complaints from eclipse or any other validations."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T02:31:35.107",
"Id": "6051",
"ParentId": "6033",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6051",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T16:14:51.023",
"Id": "6033",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"ajax",
"json"
],
"Title": "How to exactly work with the JSON Object and jQuery, adding info to posts"
}
|
6033
|
<p>I've written some code to read a column of data from a dataset called <code>AltIds</code>. The values are nullable. My code is written to find all the values in the column that are not null and write them to an array.</p>
<pre><code>Guid[] altIds = myDataSet.Tables[0].AsEnumerable()
.Select(row => row.Field<Guid?>("AltId"))
.Where(x => x.HasValue)
.Select(x=>x.Value)
.ToArray();
</code></pre>
<p>The code works, but it seems a bit complicated. Is there a better way to do this?</p>
|
[] |
[
{
"body": "<p>What you have is fine. You could restructure it to eliminate one of the selects, but then you would repeat yourself with the row. </p>\n\n<pre><code>var altIds = myDataSet.Tables[0].AsEnumerable()\n .Where(row => row.Field<Guid?>(\"AltId\").HasValue)\n .Select(row => row.Field<Guid?>(\"AltId\").Value)\n .ToArray();\n</code></pre>\n\n<p>You could rewrite it in query expression syntax, but that's only less complicated <em>if</em> you find fluent syntax more so. </p>\n\n<pre><code>var altIds = (from row in myDataSet.Tables[0].AsEnumerable()\n let x = row.Field<Guid?>(\"AltId\")\n where x.HasValue\n select x.Value).ToArray();\n</code></pre>\n\n<p>Either way, it's six in one hand, half a dozen in the other. I find your code readable, and it passes the \"does what it is supposed to\" test, so I wouldn't worry about this snippet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T19:13:39.017",
"Id": "6037",
"ParentId": "6034",
"Score": "2"
}
},
{
"body": "<p>This is terribly nit picky, but the whitespace is inconsistent. Give this line some breathing space. </p>\n\n<pre><code>.Select(x=>x.Value)\n</code></pre>\n\n<p>In a larger sample of code, this kind of thing becomes hard to read. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-01T16:34:37.370",
"Id": "58768",
"ParentId": "6034",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T17:10:17.640",
"Id": "6034",
"Score": "1",
"Tags": [
"c#",
".net",
"database"
],
"Title": "Querying .NET DataSet and ignore rows that contain NULL"
}
|
6034
|
<p>I have a function that is being called in a tight loop. I've profiled my code and this is where my largest bottleneck is. The function is fairly simple: it checks if a point in (x,y) form is above a line in (slope, intercept) form. </p>
<p>The problem is, it also has to deal with the case where the slope is positive infinity, and the intercept gives the x-intercept. In this case, the function should return <code>True</code> if the point is to the right of the line.</p>
<p>Here's the function written out how it was when I noticed the bottleneck:</p>
<pre><code>def point_over(point, line):
"""Return true if the point is above the line.
"""
slope, intercept = line
if slope != float("inf"):
return point[0] * slope + intercept < point[1]
else:
return point[0] > intercept
</code></pre>
<p>On my machine, this is how fast it runs:</p>
<pre><code>>>> timeit("point_over((2.412412,3.123213), (-1.1234,9.1234))",
"from __main__ import point_over", number = 1000000)
1.116534522825532
</code></pre>
<p>Since this function is being called a lot, I've inlined it to avoid the function call overhead. The inlined version is fairly simple:</p>
<pre><code>point[0] * line[0] + line[1] < point[1] if line[0] != float('inf') else point[0] > line[1]
</code></pre>
<p>And performs similarly in <code>timeit</code>:</p>
<pre><code>>>> timeit("point[0] * line[0] + line[1] < point[1] if line[0] != float('inf') else point[0] > line[1]",
"point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000)
0.9410096389594945
</code></pre>
<p>However, this one line of code is still hogging the largest proportion of execution time in my code, even after being inlined.</p>
<p>Why does the comparison to <code>float('inf')</code> take longer than a number of calculations as well as a comparison? Is there any way to make this faster?</p>
<p>As an example of what I'm claiming, here are the speeds of two parts of my ternary statement separated and timed:</p>
<pre><code>>>> timeit("line[0] != float('inf')",
"point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000)
0.528602410095175
>>> timeit("point[0] * line[0] + line[1] < point[1]",
"point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000)
0.48756339706397966
</code></pre>
<p>My primary question is why it takes so long to do the comparison to infinity. Secondary is any tips on how to speed these up. Ideally there exists some magical (even if incredibly hacky) way to half the execution time of this line, without dropping down to C. Otherwise, tell me I need to drop down to C.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T22:36:30.263",
"Id": "9312",
"Score": "0",
"body": "If you really want speedups, you should look at using numpy."
}
] |
[
{
"body": "<p>It would be faster to use the <em><a href=\"http://docs.python.org/library/math.html#math.isinf\">math.isinf()</a></em> function:</p>\n\n<pre><code>>>> from math import e, pi, isinf\n>>> s = [0, float('inf'), e, pi]\n>>> map(isinf, s)\n[False, True, False, False]\n</code></pre>\n\n<p>The reason your current check is taking so long is due to how much work it has to do:</p>\n\n<pre><code>>>> from dis import dis\n\n>>> def my_isinf(f):\n return f == float('Inf')\n\n>>> dis(my_isinf)\n 2 0 LOAD_FAST 0 (f)\n 3 LOAD_GLOBAL 0 (float)\n 6 LOAD_CONST 1 ('Inf')\n 9 CALL_FUNCTION 1\n 12 COMPARE_OP 2 (==)\n 15 RETURN_VALUE \n</code></pre>\n\n<p>There is a global load which involves a dictionary lookup. There is a two-arguments function call. The Float constructor has to parse the string and then allocate (and refcount) a new float object in memory. Then the comparison step dispatches its work to float.__eq__ which returns a boolean value which is then the fed to the if-statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:43:43.317",
"Id": "6041",
"ParentId": "6040",
"Score": "17"
}
},
{
"body": "<p>The slow part of <code>if slope != float(\"inf\")</code> is no doubt converting the string to a float. It would be simpler to just use <code>if not math.isinf(slope)</code> instead. Of course, you must <code>import math</code> for that to work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:50:45.900",
"Id": "9310",
"Score": "3",
"body": "Even assigning float('inf') to a variable and testing against that variable will speed things up noticeably."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:56:48.113",
"Id": "9311",
"Score": "0",
"body": "@retracile: Yes, that's true, but if a slope could be either +Inf or -Inf, you have to do comparisons."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:45:26.173",
"Id": "6042",
"ParentId": "6040",
"Score": "3"
}
},
{
"body": "<p>Others have mentioned <code>math.isinf()</code>. But this'll probably be faster since it avoids a name lookup and a function call:</p>\n\n<pre><code>def point_over(point, line, infinity=float(\"inf\")):\n slope, intercept = line\n if slope == infinity:\n return point[0] > intercept\n return point[0] * slope + intercept < point[1]\n</code></pre>\n\n<p>Basically, instead of evaluating <code>float(\"inf\")</code> each time the function is called, you evaluate it once at function definition time and store it in a local variable, by declaring it as an argument default. (Local variables are faster to access than globals.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:48:19.713",
"Id": "6043",
"ParentId": "6040",
"Score": "6"
}
},
{
"body": "<p>It'll be even faster (by avoiding function calls altogether) if you cache the value of <code>float(\"inf\")</code> in a variable:</p>\n\n<pre><code>>>> def floatcall():\n... return 1.0 == float(\"inf\")\n... \n>>> def mathcall():\n... return math.isinf(1.0)\n... \n>>> inf = float(\"inf\")\n>>> def nocall():\n... return 1.0 == inf\n... \n>>> timeit.timeit(\"floatcall()\", \"from __main__ import floatcall\", number=1000000)\n0.37178993225097656\n>>> timeit.timeit(\"mathcall()\", \"import math; from __main__ import math call\", number=1000000)\n0.22630906105041504\n>>> timeit.timeit(\"nocall()\", \"from __main__ import inf, nocall\", number=1000000)\n0.17772412300109863\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:52:29.083",
"Id": "6044",
"ParentId": "6040",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6041",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T21:41:21.713",
"Id": "6040",
"Score": "14",
"Tags": [
"python",
"performance",
"coordinate-system"
],
"Title": "Comparison to infinity when checking if a point is above a line"
}
|
6040
|
<h3>What I'm doing</h3>
<p>Using the v3 of the <a href="http://www.wufoo.com/docs/api/v3/entries/get/" rel="nofollow">Wufoo API</a> to retrieve all entries and store in a single array ($all_results). This is necessary because of the limit 100 entries limit that Wufoo has when retrieving results from their api. Also store the results to file we don't get slow responses from the api. </p>
<h3>My question</h3>
<p>I'm wondering how I could have done this better. This code is working for me, but I want to get better. </p>
<pre><code><?php
function wufoo_entries() {
// Setup
$account = "ACCOUNT_NAME";
$form = "FORM_NAME";
$api_key = "YOUR-API-KEY";
$offset = 0;
$limit = 100;
$check_int = 15 * 60; // 15 minutes
$file_time = 'time_stamp.txt';
$file_results = 'results.txt';
// Check for the last update
$time = time();
$time_stamp = file_get_contents($file_time);
$refresh = ($check_int < ($time - $time_stamp)) ? TRUE : FALSE;
// if true run functions and save the results and time to file else pull the results from file
if ($refresh) {
// Initialize our results array
$all_results = array();
// How many entries are there?
$api_uri = "https://$account.wufoo.com/api/v3/forms/$form/entries/count.json";
$count = wufoo_api($api_key, $account, $form, $offset, $limit, $api_uri);
$counted = $count['EntryCount'];
// Call the api as many times as needed
for ($offset = 0; $offset <= $counted - 1; $offset = $offset + $limit) {
$results = wufoo_api($api_key, $account, $form, $offset, $limit);
// Limit the number of times we put results into the $all_results array to make sure we don't end up with blanks
$limit = (($offset + $limit) > $counted) ? $limit - (($offset + $limit) - $counted) : $limit;
// Iterate through the Entries array to push each entry into a new array
for ($result = 0; $result <= $limit - 1; $result++) {
array_push($all_results, $results['Entries'][$result]);
}
}
// Save the new results (as json) and time to file
$all_results_file = json_encode($all_results);
file_put_contents($file_results, $all_results_file);
file_put_contents($file_time, $time);
return $all_results;
}
else {
// Pull the results array from file
$all_results = file_get_contents($file_results);
$all_results = json_decode($all_results, true);
return $all_results;
}
}
function wufoo_api($api_key, $account, $form, $offset, $limit, $api_uri = NULL) {
// Check to see if it's asking for the the entries or the total count
$api_url = ($api_uri) ? $api_uri : 'https://' . $account . '.wufoo.com/api/v3/forms/' . $form . '/entries.json?pageStart=' . $offset . '&pageSize=' . $limit;
$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, $api_key . ':footastic');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_USERAGENT, 'Wufoo Sample Code');
$response = curl_exec($curl);
$resultStatus = curl_getinfo($curl);
if ($resultStatus['http_code'] == 200) {
$results = json_decode($response, true);
return $results;
} else {
$results = 'Call Failed '.print_r($resultStatus, true);
return $results;
}
}
// Show me some results and make sure it works
echo "<pre>";
print_r(wufoo_entries());
echo "</pre>";
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T07:45:21.000",
"Id": "9334",
"Score": "1",
"body": "Would you consider turning your code into a class? It's ok if you don't..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T20:54:54.490",
"Id": "9377",
"Score": "0",
"body": "That what I was thinking too, thanks for the input."
}
] |
[
{
"body": "<p>Just some quick note:</p>\n\n<p>1, I would separate the configuration settings to a distinct php file (and use a <code>WufooConfig</code> class/struct) and include it at the beginning of the code. It makes the configuration easier to change. If you use a <code>WufooConfig</code> class/struct and pass it to the <code>wufoo_entries()</code> function you will be able to use the same function to fetch data from more than one accounts. Furthermore, it would encapsulate configuration, so you just have to pass around one parameter instead of <code>$account</code>, <code>$form</code>, <code>$api_key</code>, etc.</p>\n\n<pre><code>class WufooConfig {\n private $account;\n private $form;\n private $api_key;\n ...\n\n public function __construct($account, ...) {\n $this->account = $account;\n ...\n }\n}\n</code></pre>\n\n<p>2, Extract the <em>then</em> and <em>else</em> branches of the if in the <code>wufoo_entries()</code> function:</p>\n\n<pre><code>if ($refresh) {\n $results = fetchContent(...);\n saveToCache($results, ...); // write file here\n return $results\n} else {\n return getCachedContent();\n}\n</code></pre>\n\n<p>It makes your code easier to read, you'll see the big picture immediately, it won't be distracted with low-level API calls.</p>\n\n<p>For the same reason I'd create some new functions, for example:</p>\n\n<pre><code>functio entryCount(...)\n $count = wufoo_api($api_key, $account, $form, $offset, $limit, $api_uri);\n $counted = $count['EntryCount'];\n return $counted;\n}\n</code></pre>\n\n<p>The name of the function says what you want to get and the body shows how you do it.</p>\n\n<p>3, Change </p>\n\n<pre><code>for ($offset = 0; $offset <= $counted - 1; ...\n</code></pre>\n\n<p>to</p>\n\n<pre><code>for ($offset = 0; $offset < $counted;\n</code></pre>\n\n<p>It's more common.</p>\n\n<p>4, In the inner <code>for</code> loop the <code>$result</code> loop variable is a little bit confusing, it's easy to mix up with <code>$results</code>. <code>$resultIndex</code> would be better.</p>\n\n<pre><code>for ($resultIndex = 0; $resultIndex < $limit; $resultIndex++) { \n array_push($all_results, $results['Entries'][$resultIndex]);\n}\n</code></pre>\n\n<p>Finally, I agree with @Yannis Rizos, the whole logic would be better as a class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T20:56:15.110",
"Id": "9378",
"Score": "1",
"body": "Thanks palacsint for the great feedback. I'll work on splitting the code up into more logical and easy to read chunks and put it into a class. I appreciate the input, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T20:12:56.477",
"Id": "6065",
"ParentId": "6049",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6065",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T00:45:34.820",
"Id": "6049",
"Score": "4",
"Tags": [
"php",
"api"
],
"Title": "Store all entries in a single array from Wufoo api"
}
|
6049
|
<p>There are 28 check boxes that are given a common name and have different values:</p>
<pre class="lang-html prettyprint-override"><code><input type="checkbox" name="Schedules" id="checkbox1" value="1">
</code></pre>
<p>In controller in post action:</p>
<pre class="lang-cs prettyprint-override"><code>public ActionResult Create(SubscriptionPlanCreateViewModel subscriptionPlanCreateViewModel, FormCollection Form)
{
string[] AllStrings = Form["Schedules"].Split(',');
foreach (string item in AllStrings)
{
int value = int.Parse(item);
if (value == 1)
{
subscriptionPlanCreateViewModel.Timeschedule = "OneTime";
}
}
}
</code></pre>
<p>By using this code I need to use 28 <code>if</code> conditions. How can I reduce the code size? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:46:38.393",
"Id": "9337",
"Score": "0",
"body": "Are all the `if` conditions trying to set the `Timeschedule` property? Or are they all setting different properties on your view model? Also, do you have any control over how the view is generated, or are you restricted to just changing the controller code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:50:35.553",
"Id": "9338",
"Score": "0",
"body": "@StriplingWarrior No value==1 for time schedule for serp and passes value \"onetime\" to Timeschedule then value==2 passes value=\"Weekly\" to timeschedule etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:54:02.837",
"Id": "9339",
"Score": "0",
"body": "So what if both checkbox 1 and 2 are selected?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:57:01.930",
"Id": "9340",
"Score": "0",
"body": "if both the value 1 & 2 are selected the timeschedule is appended with value of 2 if (value == 1)\n {\n subscriptionPlanCreateViewModel.SerpRankingSchedule = \"OneTime\";\n }\n\n if (value == 2)\n {\n subscriptionPlanCreateViewModel.SerpRankingSchedule = (subscriptionPlanCreateViewModel.SerpRankingSchedule == null || subscriptionPlanCreateViewModel.SerpRankingSchedule == \"\") ? \"Weekly\" : subscriptionPlanCreateViewModel.SerpRankingSchedule + \" | Weekly\"; }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:59:19.540",
"Id": "9341",
"Score": "0",
"body": "the first 3 values are for SerpRankingSchedule then the next 3 values are for Reports schedule etc"
}
] |
[
{
"body": "<p>It seems to me that what you really need to do is change the view code. For example, if you do this:</p>\n\n<pre><code><input type=\"checkbox\" name=\"Timeschedule\" id=\"checkbox1\" value=\"OneTime\">\n<input type=\"checkbox\" name=\"Timeschedule\" id=\"checkbox2\" value=\"Weekly\">\n</code></pre>\n\n<p>That will automatically bind to the <code>Timeschedule</code> property on your <code>SubscriptionPlanCreateViewModel</code>. However, if the user selects multiple checkboxes, the values will probably come across as comma-separated. You can <em>either</em> make <code>Timeschedule</code> an array (which would probably better represent what you're doing from a data perspective) or you can simply replace the commas with \" | \" to produce the string you say you want in your comments. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:58:51.807",
"Id": "6055",
"ParentId": "6054",
"Score": "3"
}
},
{
"body": "<p>You can use the checkboxes like this</p>\n\n<pre><code><input type=\"checkbox\" name=\"Timeschedule\" id=\"checkbox1\" value=\"OneTime\">\n<input type=\"checkbox\" name=\"Timeschedule\" id=\"checkbox2\" value=\"Weekly\">\n</code></pre>\n\n<p>and in the controller action the values from multiple checkboxes can be retrieved by using this method</p>\n\n<pre><code>string[] AllStrings = Form[\"Timeschedule\"].Split(',');\n</code></pre>\n\n<p>or </p>\n\n<pre><code>string[] AllStrings = Request[\"Timeschedule[]\"].Split(',');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T10:05:14.317",
"Id": "6056",
"ParentId": "6054",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6056",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T05:41:13.233",
"Id": "6054",
"Score": "2",
"Tags": [
"c#",
"asp.net-mvc-3"
],
"Title": "Creating 28 checkboxes with a common name and different values"
}
|
6054
|
<p>Any suggestions on how to make this code more efficient?</p>
<pre><code>import java.util.Scanner;
public class RecursionLargestInArray
{
public static void main (String[] args)
{
int max = -999;
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < myArray.length; i++)
myArray[i] = scan.nextInt();
for (int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
System.out.println("In the array entered, the larget value is "
+ getLargest(myArray, max) + ".");
}
public static int getLargest(int[] myArray, int max)
{
int i = 0, j = 0, tempmax = 0;
if (myArray.length == 1)
{
return myArray[0] > max ? myArray[0] : max;
}
else if (max < myArray[i])
{
max = myArray[i];
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
else
{
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T15:25:22.133",
"Id": "9342",
"Score": "0",
"body": "Does it need to use recursion? In case this is homework, please tag it as such."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:15:55.113",
"Id": "9344",
"Score": "0",
"body": "I wonder if you aren't expected to use the recursion on getting the user input, rather than on checking the largest value..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:50:52.030",
"Id": "9346",
"Score": "0",
"body": "@Steven added. I have already handed in the assignment so is really just more for my own knowledge now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:52:35.430",
"Id": "9347",
"Score": "0",
"body": "@ANeves The assignment is to write a recursive program to find the largest element of an array. I added the user input on my own instead of initializing arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:56:02.693",
"Id": "9349",
"Score": "0",
"body": "@NYCCanuck Nicely done."
}
] |
[
{
"body": "<p>This is a situation where pointers in C would be useful (or tail recursion in a functional language), but we'll work with what we have. Since this looks like homework, I'll try to guide you to a solution instead of just giving it. </p>\n\n<p>Creating a new array for each recursion is terribly inefficient. You can do it inline, just pass an index to the position you're currently at in the array.</p>\n\n<p>I think that should be enough, add a comment if you need more.</p>\n\n<p>Edit: You don't even need the max as an argument.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:56:01.047",
"Id": "9348",
"Score": "0",
"body": "I am not sure how to just pass the index of the array position. Do you mean `getLargest(tempArray[i], max);`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T18:08:35.790",
"Id": "9356",
"Score": "0",
"body": "The signature should be `int getLargest(int[] array, int currentIndex)`. Then call it with `getLargest(array, currentIndex + 1);`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T15:18:36.383",
"Id": "6058",
"ParentId": "6057",
"Score": "4"
}
},
{
"body": "<p>I would use a helper function, and I would avoid copying the array (using indices instead):</p>\n\n<pre><code>public static int getLargest(int ... myArray) {\n return getLargest(myArray, 0, myArray.length);\n}\n\nprivate static int getLargest(int[] myArray, int from, int to) {\n if(from == to) {\n throw new IllegalArgumentException(\"empty array\");\n } else if (from + 1 == to) {\n return myArray[from];\n } else {\n int middle = (from + to) / 2;\n return Math.max(getLargest(myArray, from, middle),\n getLargest(myArray, middle, to));\n }\n}\n</code></pre>\n\n<p>Using varargs <code>int ...</code> instead of an array <code>int[]</code> for the argument makes it more flexible, e.g. better testable.</p>\n\n<p>In case you really want to copy the array, use <code>System.arraycopy</code>, which is much faster than looping through.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:19:32.313",
"Id": "9345",
"Score": "0",
"body": "+0: why can't you just `Math.Max(myArray[from], getLargest(myArray, from+1, to))` in that last else? I feel you're making it needlessly complex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T23:11:09.353",
"Id": "9385",
"Score": "0",
"body": "Using my way you'll have a maximum call stack depth of 2*(ld n), your version would have a maximum depth of n, which could lead to an `StackOverflowException` for very large arrays."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T15:26:01.257",
"Id": "6059",
"ParentId": "6057",
"Score": "6"
}
},
{
"body": "<ol>\n<li>If you are using a return inside a condition, do you need to brace the following code inside an <code>else</code>? (example: first if of the <code>getLargest()</code> method)</li>\n<li>The second and third blocks of code in the <code>getLargest()</code> method repeat a lot of code, I am sure that you can figure out a good way to avoid this repetition;</li>\n<li><a href=\"https://codereview.stackexchange.com/questions/6057/getting-the-largest-element-in-an-array-using-recursion/6058#6058\">@Kevin</a> makes a very good point, do you really need to create a new array in every iteration?</li>\n<li>What if the user answers <code>-1</code> to the first question?</li>\n<li>What would your program answer to a user inputing <code>3</code> and then <code>-1020, -1050, -1013</code>?</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T16:07:47.407",
"Id": "6061",
"ParentId": "6057",
"Score": "3"
}
},
{
"body": "<p>Here's small Java program to find the max element in an array recursively</p>\n\n<pre><code>public class TestProgram {\n private int[] a = { 3, 5, 2, 8, 4, 9 };\n\n public static void main(String[] args) {\n TestProgram p = new TestProgram();\n int result = p.findMax(0);\n System.out.printf(\"Max element = %d\", result);\n }\n\n public int findMax(int i) {\n // the anchor of the recursive method\n if (i == a.length)\n return Integer.MIN_VALUE;\n\n return Math.max(a[i], findMax(i + 1));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-16T03:36:50.257",
"Id": "11790",
"ParentId": "6057",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T15:02:24.620",
"Id": "6057",
"Score": "6",
"Tags": [
"java",
"array",
"recursion",
"homework"
],
"Title": "Getting the largest element in an array using recursion"
}
|
6057
|
<p>The below code converts the window.location.search querystring into a JavaScript object. In particular, if a key occurs more than once the resulting value in the object will be an array. Please feel free to comment on both readability and speed of execution. Thanks!</p>
<pre><code>window.location.search.split(/[?&]/g).reduce(function (prev, cur, idx, arr) {
var segment = cur.split("="),
key = segment[0],
val = segment[1];
if (prev[key]) {
if (prev[key] instanceof Array) {
prev[key].push(val);
} else {
prev[key] = [prev[key], val];
}
} else {
prev[key] = val;
}
return prev;
}, { });
</code></pre>
|
[] |
[
{
"body": "<p>The line <code>if (typeof prev[key] === typeof []) {</code> is... weird. If you're checking for a type specifically, check for it: <code>if (typeof prev[key] === 'object') {</code> - the way you're doing it there causes a new array literal to be instantiated needlessly, as well as a superfluous <code>typeof</code> operation, both inefficient and outright unnecessary.</p>\n\n<p>Making an array out of repeating keys is fallacious - if a key is exactly repeated in a query string, only the right-most instance of that query string value will be received by the server. Further, in cases where the query string contains validly structured arrays (<code>test=1&test2[]=2&test2[]=4</code>), your code ends up with a key like <code>test[]</code>, which is a nasty to access: <code>results['test2[]']</code> is the only way to get at it (no dot syntax allowed).</p>\n\n<hr>\n\n<p><strong>EDIT</strong>\nTo clarify my remarks about duplicating keys, I purhaps mistakenly restricted my comments to Apache(Linux or Windows)/PHP - certainly other languages and platforms are relevant to the discussion. In the PHP language (what I am most familiar with), the query string <code>test=1&test=2</code> will result in:</p>\n\n<pre><code>var_export($_GET);\n/* array (\n 'test' => '2',\n) */\n</code></pre>\n\n<p>... as you can see, only the right-most value is the only one passed into the script. The way PHP expects duplicate query string keys is by use of <code>[]</code> in the query: <code>test[]=1&test[]=2</code></p>\n\n<pre><code>var_export($_GET);\n/*array (\n 'test' => \n array (\n 0 => '1',\n 1 => '2',\n ),\n)*/\n</code></pre>\n\n<p>This behavior is the same for POST data on PHP - you must use <code>name=\"myField[]\"</code> if multiple fields will use the same name, otherwise, only the last item in the form with a given name will be populated in PHP's <code>$_POST</code> data.</p>\n\n<p>I am not set up to confirm the behavior of this in ASP (or other languages), however research has indicated that my assertion is still somewhat valid: <a href=\"https://stackoverflow.com/questions/6395290/how-may-i-add-integer-list-to-route/6396793#6396793\">https://stackoverflow.com/questions/6395290/how-may-i-add-integer-list-to-route/6396793#6396793</a>. Please confirm if you are able: from what I have gathered the values would be passed to script as a comma-delimited list, but the language itself still rejects working with duplicate keys and a workaround is required.</p>\n\n<p>If you can add some data about handling of duplicate keys in other server languages, please feel free to edit them into this answer. That said, I feel my criticism of this script's handling of duplicate keys stands, as well as the issue with \"properly formed\" (PHP) arrays in the query string - <code>result['test[]']</code> is nasty.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:17:56.400",
"Id": "9352",
"Score": "0",
"body": "Right. Not only is it weird, it's wrong. I based that line on a SO answer without testing it properly. What I needed was `prev[key] instanceof Array`. Edited. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:21:23.413",
"Id": "9353",
"Score": "1",
"body": "Please see edit, still looking and adding :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:38:54.943",
"Id": "9354",
"Score": "0",
"body": "Your answer is appreciated, but I think you're wrong about the arrays. Otherwise, how would HTML forms be able to pass the multiple values of several checkboxes with the same name? Indeed, a quick test shows that an array is exactly how application servers in Coldfusion and PHP see repeated keys in query strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:50:02.923",
"Id": "9355",
"Score": "0",
"body": "The server will receive all values in the query string. If some server implementation chooses to discard values then that is specific to that implementation. IIS (Windows) doesn't discard any values, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T18:22:10.180",
"Id": "9357",
"Score": "0",
"body": "Please see my edit regarding this issue, and indeed, please post your IIS results into the answer if you'd like!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T19:06:03.960",
"Id": "9359",
"Score": "0",
"body": "The discarding of values appears to be language-specific rather than platform-specific, but the utility of the OP's code is certainly limited if it does not address considerations relevant at least to the most widespread languages (PHP being one). The lack of standardization for URIs makes this more complex, purhaps, than it seems on the surface"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T19:26:42.950",
"Id": "9360",
"Score": "0",
"body": "This turned out to be a fascinating and informative exchange, but to clarify, my question really is only focused on JavaScript. For the purposes of the above review I'm not concerned about the conventions of other languages, regardless of their popularity. That said, of course, review as you see fit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T19:35:47.270",
"Id": "9361",
"Score": "0",
"body": "Of course... my thinking was only that the utility of a query string parser is somewhat dependent upon the validity of the parsed data - if you aren't able to immediately post the query string back to the server as-is and have the server-side language use the query string exactly as javascript would use it, then it invites the possibility of inconsistencies in operation client-side, thus potential errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T19:43:40.747",
"Id": "9362",
"Score": "0",
"body": "PHP uses a non-standard approach with query strings. `?foo=bar&foo=baz` should contain both values as far as the uri specification is concerned `foo=[\"bar\",\"baz\"]` should be the expected result, but PHP uses a non-standard approach that would lead to `foo=\"baz\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T19:55:13.360",
"Id": "9363",
"Score": "0",
"body": "Non-standard? There isn't a standard that I have ever seen that dictates how languages should handle URIs. Can you provide a link to this \"standard\"? As far as URI standardization goes, this is all you get: http://www.ietf.org/rfc/rfc2396.txt - nothing in there describing duplicate keys in query parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T20:12:55.947",
"Id": "9364",
"Score": "0",
"body": "@Chris as far as I can tell, there is no standard that explicitly states how a language should parse a querystring. That said, does PHP really require you to put '[]' at the end of the names of all HTML controls that *might* result in an array in the form data set? That seems like extra work, at best. At worst, silently throwing away data is likely to prove harmful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T20:26:40.410",
"Id": "9365",
"Score": "0",
"body": "Yes, it does require the `[]` on a form element if you want the array in post data. As for the behavior, I am undecided on what I prefer; having only worked with PHP in this regard it seems perfectly natural, but I can certainly see the downfalls too."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:13:53.127",
"Id": "6063",
"ParentId": "6062",
"Score": "2"
}
},
{
"body": "<p><code>.reduce()</code> is not supported for IE version < 9. If anyone uses this in their application, make sure that this is not an issue. <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/reduce#Browser_compatibility\" rel=\"nofollow\">This</a> is a potential workaround.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T02:22:54.900",
"Id": "11335",
"Score": "0",
"body": "Yep, I was aware of this, but should've pointed it out for future readers. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T02:06:18.890",
"Id": "7243",
"ParentId": "6062",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:06:33.840",
"Id": "6062",
"Score": "2",
"Tags": [
"javascript",
"optimization",
"array"
],
"Title": "Javascript querystring to object conversion"
}
|
6062
|
<p>I have some troubles to find the right loop to check if some values are contained in mysql DB. I'm making a software and I want to add license ID. Each user has x keys to use. </p>
<p>Now when the user start the client, it invokes a PHP page that check if the Key sent in the POST method is stored in DB or not. </p>
<p>If that key isn't store than I need to check the number of his keys. If it's > than X I'll ban him otherwise i add the new keys in the DB.</p>
<p>I'm new with PHP and MYSQL. I wrote this code and I would know if I can improve it.</p>
<pre><code><?php
$user = POST METHOD
$licenseID = POST METHOD
$resultLic= mysql_query("SELECT id , idUser , idLicense FROM license WHERE idUser = '$user'") or die(mysql_error());
$resultNumber = mysql_num_rows($resultLic);
$keyFound = '0'; // If keyfound is 1 the key is stored in DB
while ($rows = mysql_fetch_array($resultLic,MYSQL_BOTH)) {
//this loop check if the $licenseID is stored in DB or not
for($i=0; $i< $resultNumber ; i++) {
if($rows['idLicense'] === $licenseID) {
//Just for the debug
echo("License Found");
$keyFound = '1';
break;
}
//If key isn't in DB and there are less than 3 keys the new key will be store in DB
if($keyfound == '0' && $resultNumber < 3) {
mysql_query( Update users set ...Store $licenseID in Table)
}
// Else mean that the user want user another generated key (from the client) in the DB and i will be ban (It's wrote in TOS terms that they cant use the software on more than 3 different station)
else {
mysql_query( update users set ban ='1'.....etc );
}
}
?>
</code></pre>
<p>I know that this code seems really bad so i would know how i can improve it. Someone Could give me any advice?</p>
<p>I choose to have 2 tables: <code>users</code> where all information about the users is, with fields id, username, password and another table <code>license</code> with fields id, idUsername, idLicense (the last one store license that the software generate)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:24:26.350",
"Id": "9371",
"Score": "1",
"body": "What does \"improve it\" mean? Does your code actually work? Or is it broken and you need help fixing it? This site is not for specific problems with code, but we can migrate it to the right place for you: [CodeReview.SE] if the code works, [SO] if it doesn't. Please respond here using the \"add comment\" link and let me know. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:27:06.040",
"Id": "9372",
"Score": "0",
"body": "@AnnaLear How fast do you type? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:27:38.170",
"Id": "9373",
"Score": "0",
"body": "@YannisRizos Pretty fast. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T18:14:26.183",
"Id": "9374",
"Score": "0",
"body": "Sorry for that , i just posted on StackOverflow and a comment says to post Here! I'm sorry about it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T20:45:02.357",
"Id": "9375",
"Score": "0",
"body": "@Jasper Ah, from the comments on your Stack Overflow post, I gather that your code is working? I'll migrate your question to [CodeReview.SE] and see if they can help you out."
}
] |
[
{
"body": "<p>First of all: both code and table design can (have?) to be improved:</p>\n\n<ol>\n<li>Tables must be normalized and can be improved by removing data and duplicates\n<ul>\n<li>Users table can (?) have <code>username</code> only as natural PK (pure id eliminated)</li>\n<li>Optional: licence table will be better understandable if FK will have same name as for Users table (<code>username</code>) </li>\n</ul></li>\n<li>For-cycle <em>for your task</em> is not-so-good style of coding:\n<ul>\n<li>You can just test result (size of array) of <code>SELECT idLicense WHERE idLicense = $licenseID</code> (SQLGuru: Fixme!!!)</li>\n<li>Total amount of licences per user can be extracted from table with single <code>SELECT COUNT(idLicense) WHERE idUser = '$username'</code> (SQLGuru: Fixme again!!!)</li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T22:25:59.093",
"Id": "6071",
"ParentId": "6067",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T17:10:53.493",
"Id": "6067",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "PHP MYSQL loop to check if LicenseID Values are contained in mysql DB"
}
|
6067
|
<p>I'm trying to write function, that replace digits at some positions in number.</p>
<p>For example <code>f 91521 [3,4] -> [91001,91111,91221,91331,91441,91551,91661,91771,91881,91991]</code></p>
<p>It's behavior like <code>91**1 -> ...</code>, so I named it as a 'whitemask'.</p>
<p><strong>Question 1</strong>: is "whitemask" a normal and adequately name for that function? </p>
<p>After that I've formulated that 'whitemask' function.</p>
<pre><code>sublists :: (Eq a) => [a] -> [[a]]
sublists list = [x | x <- subsequences list, x /= []]
numbers :: [Int]
numbers = take 10 [0..]
numLength :: Integer -> Int
numLength = length . show
decreaseList :: Num a => [a] -> a -> [a]
decreaseList = (\a b c -> map (a c) b) (flip (-))
listToNum :: [Int] -> Integer
listToNum digits = toInteger $ foldl1 (\x y -> x*10 + y) digits
numToList :: Integer -> [Int]
numToList x = map digitToInt $ show x
remove :: [Int] -> [Int] -> [[Int]]
remove [] x = [x]
remove (x:xs) list = putted : remove (decreaseList xs x) unputted
where [putted,unputted] = (\(x,y) -> [init x,y]) $ splitAt x list
sew :: [[a]] -> a -> [a]
sew list sewer = foldr1 (\x y -> x ++ [sewer] ++ y) list
whitemask :: Integer -> [Int] -> [Integer]
whitemask num places = filter (\x -> numLength x == numLength num ) $ map (listToNum . sew (remove places (numToList num))) numbers
</code></pre>
<p>But in context of all problem where that function might be used I figured out, that I need only fix-length answers. For examples, it works like</p>
<pre><code>> whitemask 75148 [1,3,4]
[15118,25228,35338,45448,55558,65668,75778,85888,95998]
</code></pre>
<p>and answer isn't contain '5008' element.</p>
<p><strong>Question 2</strong>: is that fix-length filtering 'whitemask' function's business? Or it would be better to return all possible variants and filtering them if it really needed?</p>
<p>When I've started to use that function in complicated iterates ways I figured out that it's might do some unnecessary and superfluous calculations.</p>
<p><strong>Question 3</strong>: how can I refactor 'whitemask' function with less-usage folds maps and recursions?</p>
<p>Any cosmetics and style advices are appreciated.</p>
<p><em>ps: did I select the right place to asking for? (question could be migrated to SO actually)</em></p>
<p><strong>UPD</strong>:
I figured out that <code>sew</code> can be written much easier.</p>
<pre><code>sew list sewer = concat $ intersperse [sewer] list
</code></pre>
|
[] |
[
{
"body": "<p>I didn't thought about the algorithm itself, but shortened the code a little bit:</p>\n\n<pre><code>decreaseList :: Num a => [a] -> a -> [a]\ndecreaseList b c = map (subtract c) b \n\nlistToNum :: [Int] -> Integer\nlistToNum = toInteger . foldl1 ((+).(*10)) \n\nnumToList :: Integer -> [Int]\nnumToList = map digitToInt . show\n\nremove :: [Int] -> [Int] -> [[Int]]\nremove [] x = [x]\nremove (x:xs) list = let (putted, unputted) = splitAt x list\n in (init putted) : remove (decreaseList xs x) unputted\n\nsew :: [[a]] -> a -> [a]\nsew list sewer = foldr1 ((++).(++[sewer])) list\n\nwhitemask :: Integer -> [Int] -> [Integer]\nwhitemask num places = let list = map (listToNum . sew (remove places (numToList num))) [0..9]\n in filter (((==) `on` length . show) num) list\n</code></pre>\n\n<p>I think there is still room for improvement...</p>\n\n<p><strong>[Edit]</strong></p>\n\n<p>A shorter version:</p>\n\n<pre><code>whitemask :: Integer -> [Int] -> [Integer]\nwhitemask num places = map (listToNum . replace) [0..9] where\n replace digit = foldr ((:).findDigit) [] $ zip (numToList num) [1..] where\n findDigit (d,i) | i `elem` places = digit\n | otherwise = d\n\nlistToNum :: [Int] -> Integer\nlistToNum = toInteger . foldl1 ((+).(*10))\n\nnumToList :: Integer -> [Int]\nnumToList = map digitToInt . show\n</code></pre>\n\n<p><strong>[Edit]</strong></p>\n\n<p>A shorter version, with fixed-length filtering:</p>\n\n<pre><code>whitemask :: Integer -> [Int] -> [Integer]\nwhitemask num places = map replace digits where\n digits = if 1 `elem` places then [1..9] else [0..9]\n toList = map digitToInt $ show num\n replace digit = foldl toNum 0 $ zip toList [1..] where\n toNum r (d,i) = 10*r + (fromIntegral $ if i `elem` places then digit else d)\n</code></pre>\n\n<p>I can't promise that I'll end up with a one-liner, though...</p>\n\n<p>To your questions:</p>\n\n<ol>\n<li>Depends on the context. If you are unsure about the name, just explain the function with a comment.</li>\n<li>Depends if you would ever need unfiltered output. In this case that looks pretty unlikely, so I would include the filtering.</li>\n<li>See above.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T23:06:14.060",
"Id": "6073",
"ParentId": "6069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-15T21:33:52.043",
"Id": "6069",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "replace digit at some positions in number"
}
|
6069
|
<p>This program is supposed to calculate the determinants of the data entered. I believe it does. Within the guidelines of this exercise we were not to break this down to functions but all out of main. We will be breaking it down into functions in part a and b of this overall exercise.</p>
<p>However, I don't know enough about matrices and determinants yet to know if I am using the equation given to me correctly. I know this out puts the data given to the screen correctly and the formula given was:</p>
<pre><code>determinant = (AEI) + (BFG) + (CDH) - (BDI) - (AFH) - (CEG)
</code></pre>
<p>which equates to the array elements:</p>
<pre><code>00 * 11 * 22 + 01 * 12 * 20 + 02 * 10 * 21- 01 * 10 * 22 - 00 * 12 * 21 - 02 * 11 * 20
</code></pre>
<p>Given the 3x3 block where the first row is ABC, second row of DEF and third row of GHI.</p>
<p>I am asking that it be analyzed and critiqued.</p>
<pre><code># include <iostream>
# include <stdio.h>
# include <iomanip>
using namespace std;
int main()
{
int x,y,z,;
char ch;
float My3DMatrix[3][3];
int mReader[9];
for (x = 0 ; x <= 8 ; x++)//This array is for accessing the Matrix elements in
{ //the prescribed manner to calculate the determ.
y = x;
if( x == 3 || x == 8 )y = 1;
if(x == 4 || x ==6 )y = 2;
if(x == 5 || x == 7 )y = 0;
mReader[x] = y;
}
do //This initiates the main loop
{
cout<<"Calculation of 3 x 3 Determinant"<<endl<<endl;
for(x = 0; x<=2 ;x++) // This loop querries the user for
{ //input and feeds the My3DMatrix
cout<<"What is row "<<x+1<<" of the matrix? ";
for (y = 0 ; y <=2 ; y++)
{
cin>>My3DMatrix[x][y];
} //The matrix is now fed
}
cout<<"\nThe 3 x 3 Matrix entered is: "<<endl; //Now the Raw
cout<<setprecision(3)<<fixed; //Matrix data is displayed
for(x = 0 ; x<=2 ; x++)
{
cout<<My3DMatrix[x][0]<<"\t"<<My3DMatrix[x][1]<<"\t"
<<My3DMatrix[x][2]<<endl;
}
float Determinant[6]; //This array is for storing the 6
y = -1 ; z = 0; //products from each row of the matrix
for(x = 0 ; x <= 8 ; x++)// There are 9 indexes to create 3 products from
{ //This loop pulls the correct indexes from My3DMatrix then creates
if (z>=3) z = 0; //and stores the products into Determinant[x] 0 - 2
if ((x % 3) == 0 || x == 0)
{
y = y + 1;
Determinant[y] = 1;
}
Determinant[y] = Determinant[y] * My3DMatrix[z][mReader[x]];
z = z + 1;
}
y = 2 ; z = 0;
for(x = 9 ; x >= 1 ; x--)// There are 9 indexes to create 3 products from
{ //This loop pulls the correct indexes from My3DMatrix then creates
if (z>=3) z = 0;//and stores the products into Determinant[x] 3 - 5
if ((x % 3) == 0 || x == 0)
{
y = y + 1;
Determinant[y] = 1;
}
Determinant[y] = Determinant[y] * My3DMatrix[z][mReader[x - 1]];
z = z + 1;
}
float myAnswer;
myAnswer = 0;//Here with Determinant[6] loaded with the correct index products:
myAnswer = Determinant[0] + Determinant[1] + Determinant[2] ; //The deternm.
myAnswer = myAnswer - Determinant[3] - Determinant[4] - Determinant[5]; //and simple calculation is plain
cout<<"The determinant of the above matrix is: "<< myAnswer<< endl;
cout<<"Would you like to Do another Matrix (Y/N)? ";
cin>>ch ;
}while(ch == 'Y' || ch == 'y');
cin.get();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>General comments:</p>\n\n<p>Use one line per variable.</p>\n\n<pre><code>int x,y,z,;\n</code></pre>\n\n<p>Prefer to use smaller than than smaller than or equal. This is a bit nit-picky but when working with array bounds you can then use the same number in the test as in the size of the array, which makes it slightly easier to read.</p>\n\n<pre><code>int mReader[9];\nfor (x = 0 ; x <= 8 ; x++)\n\n// try\nint mReader[9];\nfor (x = 0 ; x < 9 ; x++) // easy to see correlation between x and mReader\n</code></pre>\n\n<p>The variables x/y/z are not used to pass information between different loops. So rather than declare them at the top declare them as close to the point of use as possible. Your loops should look more like this:</p>\n\n<pre><code>for(int x = 0; x<=2 ;x++)\n // ^^^ x is local to the loop\n</code></pre>\n\n<p>Do not fall in to the mental trap of thinking that you are saving space for re-use. The compiler is quite capable of doing that all by itself.</p>\n\n<p>This test seems a bit redundant:</p>\n\n<pre><code>if ((x % 3) == 0 || x == 0)\n // ^^^^^^^^^ Why? if x == 0 then (x % 3) == 0 thus the second part of the\n // test will never be evaluated.\n</code></pre>\n\n<p>Are you sure this is correct?</p>\n\n<pre><code>for(x = 9 ; x >= 1 ; x--)\n</code></pre>\n\n<p>Seems like x never reaches 0. As it turns out it is correct even if it looks wrong. But you need to read the rest of the code to make sure it is being used correctly. Writing code were you need to scan ahead to determine correctness is not a good idea. I would loop the same way as all the other loops (using a different variable name) then adjust the usage.</p>\n\n<pre><code>for(int reverseX = 0 ; reverseX < 9 ; ++reverseX)\n{\n ..... \n Determinant[y] = Determinant[y] * My3DMatrix[z][mReader[9 - 1 - reverseX]];\n</code></pre>\n\n<p>Does this work?</p>\n\n<pre><code>cin.get();\n</code></pre>\n\n<p>Looks like you are trying to pause the application before termination. But to me it looks like it will try and swallow the <code>'\\n'</code> from the last time you hit enter, and thus do nothing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T08:23:01.177",
"Id": "9421",
"Score": "0",
"body": "x < 9 ; x++) as opposed to x<=8 and the redundancy of-> , || x == 0) . It may sound odd but we're supposed to use Dev C++ and I've been having problems with the IDE/Compiler making the conditional statements in my loops even work. I tried using its debugger to check values but it started crashing. I had to do reinstalls of dlls to my sytem and reinstall dev C++ after using the debugger. That thing is way bad. I have an amd 64 quad core running win764 would a 32 macine be better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T08:31:25.420",
"Id": "9422",
"Score": "0",
"body": "One thing I was looking for was whether or not to use the amount of loops and array as I did. I was told to re write it and only use one array, typing out like (My2DMatrix[0][1] * My2DMatrix[1][2] * My2DMatrix[2][0]) +\n (My2DMatrix[0][2] * ... etc I'm new to c++ and don't know any better yet. Is that how its supposed to be done if in the work world? Or is it okay bypassing all the typing and doing things more...programatically?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T09:06:43.913",
"Id": "9423",
"Score": "0",
"body": "@RSherwin: Using loops or typing it out? 6 of one half a dozen of the other. I mean the array is so small that it may be worth typing it out, but personally I would use a loop but either way is fine for an array this size."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-15T23:31:22.230",
"Id": "6074",
"ParentId": "6070",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-15T22:24:45.070",
"Id": "6070",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Calculating the determinants of data entered"
}
|
6070
|
<p>I wrote this PHP Login system and I would like to see if I have any errors/made any mistakes or if you think I can do something to improve it, like including tokenizing and improving security even more.</p>
<p>This script allows "Remember Me" option which uses a cookie and a session table to authorize a user. It has basic functions such as add/delete/modify user etc. There is an index page where a person can log in or register a new account. <code>Login</code> class which handles all the user interaction and securepage which user accesses when there is a successful log in.</p>
<p>index.php</p>
<pre><code><?php
// Database definition for MySQL server
define("DB_HOST", "whatever.com");
define("DB_USER", "user");
define("DB_PASS", "pass");
?>
<?php
// index.php
// Log In Script
// Main Page that allow users to log in and create new accounts
require_once('login.class.php');
$login = new Login();
$login->startSession();
$login->connectToDB();
$session_id = session_id();
// If the user has a cookie set, redirect him to secure page
if($login->isAuthorized()) {
header("Location: securePage.php");
}
if($_POST['login']){
// get the data, trim the blank spacesß
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//if checked, the value will be 'on'
//otherwise, it will be blank
$rememberme = $_POST['rememberme'];
// verify if the username and password are correct
// and if rememberme is set to 'on', create a cookie
if($username && $password){
// Check the login details and redirect to securePage.php
// if the password is not correct, notify the user
$login->checkLogin($username, $password, $rememberme, $session_id);
} else {
echo("Please enter a username and password");
}
}
if($_POST['create']){
// create an account
// and notify the user the account has been created
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$email = trim($_POST['email']);
$login->addUser($username, $password, $first_name, $last_name, $email);
}
?>
<html>
<head>
<style type="text/css">
#table {
width: 340px;
height: 450px;
margin: 0 auto;
border: 3px solid;
padding: 20px;
}
</style>
</head>
<br/>
<br/>
<div id="table">
<form action="index.php" method="POST">
Existing Users<hr/>
Username:
<input type="text" name="username"></input>
<br/>
<br/>
Password:
<input type="password" name="password"></input>
<br/>
<br/>
<input type="checkbox" name="rememberme"> Keep Me Logged In</input>
<br/>
<br/>
<input type="submit" name="login" value="Log In"></input>
</form>
<form action="index.php" method="POST">
New Users - Sign Up Below<hr/>
Username:
<input type="text" name="username"></input>
<br/>
<br/>
Password:
<input type="password" name="password"></input>
<br/>
<br/>
First Name:
<input type="text" name="first_name"></input>
<br/>
<br/>
Last Name:
<input type="text" name="last_name"></input>
<br/>
<br/>
E-Mail: &nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="email"></input>
<br/>
<br/>
<input type="submit" name="create" value="Create A New Account"></input>
</form>
</div>
</html>
</code></pre>
<p>login.class.php</p>
<pre><code><?php
// login.class.php
// This class contains most of the user's functionality
/*
* MySQL Database Information Below
* the reason for password being 82 chars is because of the way the salt will be generated and added
// user table
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 64 ) NOT NULL,
`password` VARCHAR( 82 ) NOT NULL,
`first_name` VARCHAR( 64 ) NOT NULL,
`last_name` VARCHAR( 64 ) NOT NULL,
`email` VARCHAR ( 64 ) NOT NULL,
PRIMARY KEY ( `id` ) ,
UNIQUE KEY ( `username`),
UNIQUE KEY ( `email` )
)
// table for storing cookie sessions
*
You save the session_id in a cookie
and once the person visits the website again,
the page pulls up a cookie and gets session_id.
You then compare current ip and user agent to the ones stored in Session table.
After that, you pull up user's data based on user_id from users table.
CREATE TABLE `sessions` (
`id` INT NOT NULL AUTO_INCREMENT,
`session_id` VARCHAR(64) NOT NULL,
`user_ip` VARCHAR(64) NOT NULL ,
`user_agent` VARCHAR(100) NOT NULL,
`user_id` VARCHAR(64) NOT NULL,
PRIMARY KEY ( `id` )
)
*/
// db defines
require_once('db_config.php');
// Salt Length for generateHash function
define('SALT_LENGTH', 9);
class Login {
private $username;
private $password;
private $first_name;
private $last_name;
private $email;
private $session_id;
public function __construct(){
}
// starts a session
public function startSession(){
session_start();
}
// Creates a new account based on a new user name and password
// username must be unique
// password gets md5 (hashed)
// It also checks if username already exists
public function addUser($username, $password, $first_name, $last_name, $email){
$username = $this->clean($username);
$password = $this->generateHash($this->clean($password));
$first_name = $this->clean($first_name);
$last_name = $this->clean($last_name);
$email = $this->clean($email);
// Check if username already exists
$query = ("SELECT * FROM users WHERE username = '$username' LIMIT 0,5");
$result = mysql_query($query) OR die("Cannot perform query!");
// Check if user name already exists and if it does not exist, create a new account
if (mysql_num_rows($result) >= 1) {
echo "User's name already exists. Please pick another one!";
} else {
// otherwise create an account
$query = "INSERT INTO users VALUES('', '" . $username . "', '" . $password . "', '" . $first_name . "'
, '" . $last_name . "', '" . $email . "')";
$result = mysql_query($query) OR die('Cannot perform query! Make sure you have filled out all the fields!');
echo "Your account has been created. You can now log in.";
}
}
public function deleteUser($username){
$username = $this->clean($username);
// Check if username already exists
$query = "DELETE FROM users WHERE username = '$username'";
$result = mysql_query($query) OR die("Cannot perform query!");
$this->destroyCookieAndSession();
header("Location: index.php");
}
// updates user's information
public function updateUser($username, $password){
$username = $this->clean($username);
$password = $this->generateHash($this->clean($password));
$query = "UPDATE users SET password ='$password' WHERE username = '$username'";
//die();
$result = mysql_query($query) OR die("Cannot perform query!");
echo "Your changes have been saved.<br/>";
}
// Check if the user account and password match the one in the database
public function checkLogin($username, $password, $rememberme, $session_id) {
$this->username = $this->clean($username);
$this->password = $this->clean($password);
$this->$session_id = $session_id;
//extract the salt/hash from db and check if the hash/password is correct
$query = "SELECT * FROM users WHERE username = '" . $this->username . "' LIMIT 0,1";
$result = @mysql_query($query) OR die('Cannot perform query!');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$dbHash = $row['password'];
// generates hash based on the submitted password and stored salt
$this->password = $this->generateHash($this->password, $dbHash);
$query = "SELECT * FROM users WHERE username = '" . $this->username . "' AND
password ='" . $this->password . "' LIMIT 0,1";
$result = mysql_query($query) OR die('Cannot perform query!');
if (mysql_num_rows($result) == 1) {
//set a cookie if rememberme is set to 'on'
if($rememberme == "on"){
$this->setRememberMe($session_id);
}
// user has logged in successfuly, store all his information in this object
// before redirecting to securePage.php
$this->setFirstName($row['first_name']);
$this->setLastName($row['last_name']);
$this->setEmail($row['email']);
$this->createSession();
header("Location: securePage.php");
exit();
} else {
echo "Incorrect username or/and password.";
}
// frees the memory used by query
mysql_free_result($result);
}
private function createSession(){
// save state of this object before passing
// php automatically serializes the object
// and will automatically unserialize it
$_SESSION['usrData'] = $this;
}
// sets the cookie
// which allows the user to be logged into automatically
private function setRememberMe($session_id){
// check if the user id exists in the session db, if it does, delete that row
$query = "SELECT * FROM sessions WHERE user_id = '" . $this->getUsername() . "' LIMIT 0,5";
$result = mysql_query($query) OR die("Cannot perform query!");
if (mysql_num_rows($result) >= 1) {
$query = "DELETE FROM sessions WHERE user_id = '" . $this->getUsername() . "'";
$result = mysql_query($query) OR die("Cannot perform query!");
}
// insert the user's information into a session table
$query = "INSERT INTO sessions (session_id, user_ip, user_agent, user_id)
VALUES('" . $session_id . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" .
$_SERVER['HTTP_USER_AGENT'] . "', '" . $this->getUsername() . "')";
$result = mysql_query($query) OR die('Cannot perform query!!');
// create a cookie with session_id
setcookie("autologin", $session_id, time() + 60*60*24*365, "/");
}
// check if the user has access to the page
public function isAuthorized() {
// check the session access
if(isset($_COOKIE['autologin']) ) {
// check if user information matches up
// we do that by checking user agent and user ip information
$session_id = $_COOKIE['autologin'];
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$query = "SELECT * FROM sessions WHERE session_id = '" . $session_id . "'";
$result = mysql_query($query) OR die('Cannot perform query!');
// query the results only once since there's supposed to be only
// one record for each session_id
$row = mysql_fetch_assoc($result);
if ( $row["user_ip"] == $user_ip && $row["user_agent"] == $user_agent)
{
// if everything matches, create a new Login object based on user ID
// Check if username already exists
$query2 = "SELECT * FROM users WHERE username = '" . $row["user_id"] . "' LIMIT 0,5";
$result2 = mysql_query($query2) OR die("Cannot perform query!");
while ( $row2 = mysql_fetch_assoc($result2) ){
$this->username = $row2['username'];
$this->first_name = $row2['first_name'];
$this->last_name = $row2['last_name'];
$this->password = $row2['password'];
$this->email = $row2['email'];
$this->session_id = $session_id;
}
$_SESSION['usrData'] = $this;
return true;
} else {
// Information does not match
return false;
}
} else {
// if cookie is not set.
return false;
}
}
// private function that allows connection to the database
public function connectToDB() {
@mysql_connect(DB_HOST, DB_USER, DB_PASS) OR die("Cannot connect to MySQL server!");
mysql_select_db("dig_login") OR die("Cannot select database!");
}
// Returns the username of a user
public function getUsername() {
return $this->username;
}
// Returns the plain text password of a user
public function getPassword() {
return $this->password;
}
// Returns first name
public function getFirstName() {
return $this->first_name;
}
// Returns last name
public function getLastName() {
return $this->last_name;
}
public function getEmail() {
return $this->email;
}
//gets session
public function getSessionID(){
return $this->session;
}
// sets first name
public function setFirstName($firstName) {
$this->first_name = $firstName;
}
// sets last name
public function setLastName($lastName) {
$this->last_name = $lastName;
}
// sets email
public function setEmail($email) {
$this->email = $email;
}
// Escape bad input, sql injections, etc
private function clean($input) {
return mysql_real_escape_string($input);
}
// Kill the cookie
public function destroyCookieAndSession(){
setcookie('autologin', '', time()-42000, '/');
session_unset();
session_destroy();
}
// This is a function that does the hashing
// we are going to use sha256 as hashing algorithm
// If $salt is not passed, it creates a new salt
// otherwise it extracts the salt from db
public function generateHash($password, $salt = null){
if ($salt === null)
{
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else
{
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . hash('sha256', $salt . $password);
}
}
?>
</code></pre>
<p>securePage.php</p>
<pre><code><?php
// securePage.php
// if the user has successfully logged in, this page will be shown.
// The form is generated by SESSION variables
require_once('login.class.php');
session_start();
// if session usr data does not exist, redirect to login page
if(!$_SESSION['usrData']){
header("Location: index.php");
}
$login = $_SESSION['usrData'];
// re-establish DB connection since Object's DB connection is not persistent
// once the object is passed through the session
$login->connectToDB();
echo "<br/>";
echo "Hello " . $login->getFirstName() . " " . $login->getLastName();
echo "<br/><br/>";
if( $_POST['save'] ){
$login->updateUser(trim($_POST['username']), trim($_POST['password']));
}
if($_POST['delete']){
$login->deleteUser(trim($_POST['username']));
}
// Logs out the user
if(isset($_GET['logout']) == "true"){
$login->destroyCookieAndSession();
header("Location: index.php");
}
?>
<br/><br/>
<form action="securePage.php" method="post">
<hr/>
Username: <?php echo $login->getUserName(); ?>
<input type="hidden" name="username" value="<?php echo $login->getUserName(); ?>"></input>
<br/>
<br/>
Password:
<input type="password" name="password"></input>
<br/>
<br/>
<br/>
<input type="submit" name="save" value="Save Changes"></input>
<input type="submit" name="delete" value="Delete Account"></input>
</form>
<hr/>
<br/>
<br/>
<a href="./securePage.php?logout=true">Log Out</a>
</code></pre>
|
[] |
[
{
"body": "<p>Initial thoughts:</p>\n\n<p>Lots of redundant comments, for example:</p>\n\n<pre><code>// get the data, trim the blank spaces\n$username = trim($_POST['username']);\n</code></pre>\n\n<p>Some obvious refactoring not implemented, for example:</p>\n\n<pre><code>if($_POST['create']){\n // create an account\n // and notify the user the account has been created\n $username = trim($_POST['username']);\n $password = trim($_POST['password']);\n</code></pre>\n\n<ol>\n<li>If you're always going to trim the data, just trim it, and never worry about it again.</li>\n<li>If a chunk of code warrants a comment, it likely warrants a well-named method instead.</li>\n</ol>\n\n<p>Is your HTML really not indented? Ew :(</p>\n\n<p><code>function addUser</code></p>\n\n<p>Missed refactoring, or at least remove redundant comments.</p>\n\n<p><code>function deleteUser</code></p>\n\n<p>You're not <em>checking</em> if username already exists, you're just trying to delete it. All of this function's comments can go in a function-level comment.</p>\n\n<p><code>function checkLogin</code></p>\n\n<p>Extraneous comments. Have to go through ~20 lines of code to see what happens if no <code>$result</code>; probably cleaner to flip conditional and handle the shorter case first.</p>\n\n<p><code>function setRememberMe</code></p>\n\n<p>Extraneous comments; all obvious from code.</p>\n\n<p><code>function isAuthorized()</code></p>\n\n<p>Too long, too much scanning to determine functionality. Consider something like this:</p>\n\n<pre><code>// Checks user login via information in autologin cookie.\npublic function isAuthorized() {\n if (!isset($_COOKIE['autologin'])) {\n return false;\n } \n\n $session_id = $_COOKIE['autologin'];\n $query = \"SELECT * FROM sessions WHERE session_id = '\" . $session_id . \"'\"; \n $result = mysql_query($query) OR die('Cannot perform query!'); \n $user_by_session = mysql_fetch_assoc($result); \n\n $user_ip = $_SERVER['REMOTE_ADDR'];\n $user_agent = $_SERVER['HTTP_USER_AGENT'];\n if (($user_by_session[\"user_ip\"] != $user_ip) || ($user_by_session[\"user_agent\"] != $user_agent)) {\n return false;\n }\n\n $query = \"SELECT * FROM users WHERE username = '\" . $user_by_session[\"user_id\"] . \"' LIMIT 0,5\"; \n $user_entries = mysql_query($query) OR die(\"Cannot perform query!\");\n while ($row = mysql_fetch_assoc($user_entries)) {\n $this->username = $row['username'];\n $this->first_name = $row['first_name'];\n $this->last_name = $row['last_name'];\n $this->password = $row['password'];\n $this->email = $row['email'];\n $this->session_id = $session_id;\n } \n\n $_SESSION['usrData'] = $this;\n return true;\n}\n</code></pre>\n\n<p>\"Getter\" functions: redundant comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T03:06:46.907",
"Id": "9402",
"Score": "0",
"body": "Thanks. I'll try to make more comments more useful and remove redundant ones. Besides comments, how does everything else look. Are there any major security holes/mistakes that exist in the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T03:17:39.303",
"Id": "9403",
"Score": "1",
"body": "@CodeCrack All of your SQL is subject to SQL injection because you don't SQL escape anything. Remember [Little Bobby Tables](http://xkcd.com/327/), and fear his parents."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T07:14:28.207",
"Id": "9419",
"Score": "0",
"body": "I am running mysql_real_escape_string which is in my clean() function on all the user submitted input. Is that not good enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T09:28:56.113",
"Id": "9424",
"Score": "0",
"body": "@CodeCrack Oh, missed that. Is the cookie encrypted? If not, could still be injected through that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T02:57:32.187",
"Id": "9558",
"Score": "0",
"body": "Hey Dave. How can the cookie be used to inject sql queries and what are the best ways to encrypt cookies?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T02:59:49.080",
"Id": "9559",
"Score": "0",
"body": "@CodeCrack Because I can modify cookie values, and you use it directly. Just encode it like you do the parameters. Cookie values, if they're not already encrypted by PHP (I have no idea), can be encrypted using any mechanism, including [mcrypt_encrypt](http://php.net/manual/en/function.mcrypt-encrypt.php)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:14:52.613",
"Id": "6082",
"ParentId": "6076",
"Score": "2"
}
},
{
"body": "<p>Some note which was not mentioned before in other answers or comments.</p>\n\n<p>If you redirect the users you shouldn't send them the form, so change</p>\n\n<pre><code>// Logs out the user\nif(isset($_GET['logout']) == \"true\"){\n $login->destroyCookieAndSession();\n header(\"Location: index.php\");\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>// Logs out the user\nif(isset($_GET['logout']) == \"true\"){\n $login->destroyCookieAndSession();\n header(\"Location: index.php\");\n exit(); // or something like this - maybe return/die?\n}\n</code></pre>\n\n<p>The same is true the other <code>header(\"Location: ...\")</code> calls.</p>\n\n<hr>\n\n<pre><code>$result = mysql_query($query) \n OR die('Cannot perform query! Make sure you have filled out all the fields!'); \n</code></pre>\n\n<p>Maybe you want to change the simple <code>die()</code> calls to a more friendly error page. For example show the filled form and the error message so the user can correct the their input values without using the back button and without refilling every input box.</p>\n\n<hr>\n\n<p>If your <code>username</code> attribute has an unique index you never get more than one results:</p>\n\n<pre><code>$query2 = \"SELECT * FROM users WHERE username = '\" . $row[\"user_id\"] . \"' LIMIT 0,5\"; \n$result2 = mysql_query($query2) OR die(\"Cannot perform query!\");\nwhile ( $row2 = mysql_fetch_assoc($result2) ){ ... }\n</code></pre>\n\n<p>If it happens somehow log the error and call a <code>die()</code> since it's an internal error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T18:33:05.953",
"Id": "9474",
"Score": "0",
"body": "Thanks man! When it comes to that mysql_query OR DIE statement, how would I just show the form with all the filled fields instead of DIE? Another thing is, if the account with the same name exists, that DIE statement still shows \"Make sure you have filled out all the fields\", how would I separate all those different cases instead of DIE statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T19:07:32.903",
"Id": "9475",
"Score": "0",
"body": "Instead of the `die()` I would throw an exception and catch it somewhere then print its message as an error message. It needs some OOP knowledge but it makes error handling very easy. To be honest I haven't written any PHP code in the last 5-6 years but I'm sure that there are good frameworks which helps a lot with everyday form handling. I'd start the searching with http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T05:56:40.067",
"Id": "9492",
"Score": "0",
"body": "Yea try and catch is the way to go. I do have OOP knowledge. Just wanted to see if there was another way as well. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T14:22:46.043",
"Id": "6099",
"ParentId": "6076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T00:41:17.693",
"Id": "6076",
"Score": "4",
"Tags": [
"php",
"security"
],
"Title": "PHP Login class"
}
|
6076
|
<p>I understand not to rely on user agent information for anything detrimental towards the site since it can be faked or hidden etc, it's more of just an extra feature for something.</p>
<p>Is there anyway this can be made shorter perhaps? Also it will be running on a few pages, so I was wanting to know if it's performance is good/bad?</p>
<pre><code><?php
function getBrowserOS() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = "Unknown Browser";
$os_platform = "Unknown OS Platform";
// Get the Operating System Platform
if (preg_match('/windows|win32/i', $user_agent)) {
$os_platform = 'Windows';
if (preg_match('/windows nt 6.2/i', $user_agent)) {
$os_platform .= " 8";
} else if (preg_match('/windows nt 6.1/i', $user_agent)) {
$os_platform .= " 7";
} else if (preg_match('/windows nt 6.0/i', $user_agent)) {
$os_platform .= " Vista";
} else if (preg_match('/windows nt 5.2/i', $user_agent)) {
$os_platform .= " Server 2003/XP x64";
} else if (preg_match('/windows nt 5.1/i', $user_agent) || preg_match('/windows xp/i', $user_agent)) {
$os_platform .= " XP";
} else if (preg_match('/windows nt 5.0/i', $user_agent)) {
$os_platform .= " 2000";
} else if (preg_match('/windows me/i', $user_agent)) {
$os_platform .= " ME";
} else if (preg_match('/win98/i', $user_agent)) {
$os_platform .= " 98";
} else if (preg_match('/win95/i', $user_agent)) {
$os_platform .= " 95";
} else if (preg_match('/win16/i', $user_agent)) {
$os_platform .= " 3.11";
}
} else if (preg_match('/macintosh|mac os x/i', $user_agent)) {
$os_platform = 'Mac';
if (preg_match('/macintosh/i', $user_agent)) {
$os_platform .= " OS X";
} else if (preg_match('/mac_powerpc/i', $user_agent)) {
$os_platform .= " OS 9";
}
} else if (preg_match('/linux/i', $user_agent)) {
$os_platform = "Linux";
}
// Override if matched
if (preg_match('/iphone/i', $user_agent)) {
$os_platform = "iPhone";
} else if (preg_match('/android/i', $user_agent)) {
$os_platform = "Android";
} else if (preg_match('/blackberry/i', $user_agent)) {
$os_platform = "BlackBerry";
} else if (preg_match('/webos/i', $user_agent)) {
$os_platform = "Mobile";
} else if (preg_match('/ipod/i', $user_agent)) {
$os_platform = "iPod";
} else if (preg_match('/ipad/i', $user_agent)) {
$os_platform = "iPad";
}
// Get the Browser
if (preg_match('/msie/i', $user_agent) && !preg_match('/opera/i', $user_agent)) {
$browser = "Internet Explorer";
} else if (preg_match('/firefox/i', $user_agent)) {
$browser = "Firefox";
} else if (preg_match('/chrome/i', $user_agent)) {
$browser = "Chrome";
} else if (preg_match('/safari/i', $user_agent)) {
$browser = "Safari";
} else if (preg_match('/opera/i', $user_agent)) {
$browser = "Opera";
} else if (preg_match('/netscape/i', $user_agent)) {
$browser = "Netscape";
}
// Override if matched
if ($os_platform == "iPhone" || $os_platform == "Android" || $os_platform == "BlackBerry" || $os_platform == "Mobile" || $os_platform == "iPod" || $os_platform == "iPad") {
if (preg_match('/mobile/i', $user_agent)) {
$browser = "Handheld Browser";
}
}
// Create a Data Array
return array(
'browser' => $browser,
'os_platform' => $os_platform
);
}
$user_agent = getBrowserOS();
$device_details = "<strong>Browser: </strong>".$user_agent['browser']."<br /><strong>Operating System: </strong>".$user_agent['os_platform']."";
print_r($device_details);
echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");
?>
</code></pre>
<p><strong>Update with new script</strong></p>
<pre><code><?php
$user_agent = $_SERVER['HTTP_USER_AGENT'];
function getOS() {
global $user_agent;
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
}
}
return $os_platform;
}
function getBrowser() {
global $user_agent;
$browser = "Unknown Browser";
$browser_array = array(
'/msie/i' => 'Internet Explorer',
'/firefox/i' => 'Firefox',
'/safari/i' => 'Safari',
'/chrome/i' => 'Chrome',
'/opera/i' => 'Opera',
'/netscape/i' => 'Netscape',
'/maxthon/i' => 'Maxthon',
'/konqueror/i' => 'Konqueror',
'/mobile/i' => 'Handheld Browser'
);
foreach ($browser_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$browser = $value;
}
}
return $browser;
}
$user_os = getOS();
$user_browser = getBrowser();
$device_details = "<strong>Browser: </strong>".$user_browser."<br /><strong>Operating System: </strong>".$user_os."";
print_r($device_details);
echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");
?>
</code></pre>
<p>Added a couple more browsers and operating systems to the list in the new version :)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T18:21:36.487",
"Id": "34819",
"Score": "0",
"body": "When the if matches I would not `$browser = $value` but `return $value` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-25T03:38:29.813",
"Id": "508910",
"Score": "0",
"body": "@palacsint thanks for the useful script. Could you help me how can I recognize windows server 10 with windows 10?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-25T10:34:35.840",
"Id": "508940",
"Score": "0",
"body": "@D.JCode: Sorry, I'm afraid I cant' help. The script isn't mine, I've just copy edited the question and reviewed the code. I guess you should ask this on Stack Overflow (as a question), this site is only for reviewing code."
}
] |
[
{
"body": "<p>First of all, I guess somebody has already written a library for that. I would do some research and check existing libraries. </p>\n\n<p>1, Split the code to two smaller functions: <code>getOperatingSystem()</code> and <code>getBrowser()</code>. </p>\n\n<p>2, </p>\n\n<pre><code>} else if (preg_match('/linux/i', $user_agent)) { \n $os_platform = \"Linux\"; \n} \n\n// Override if matched \n if (preg_match('/iphone/i', $user_agent)) { \n $os_platform = \"iPhone\"; \n</code></pre>\n\n<p>The second <code>if</code> should be on the same indentation level as the <code>else if</code>. It's a little bit confusing. </p>\n\n<p>3, I'd put the regular expressions and the result browsers to an associative array and iterate over it: </p>\n\n<pre><code>$os_arr['/windows|win32/i'] = 'Windows'; \n$os_arr['/windows nt 6.2/i'] = 'Windows 8'; \n... \n\nforeach ($os_arr as $regexp => $value) { \n if (preg_match($regexp, $user_agent)) { \n $os_platform = $value; \n } \n} \n</code></pre>\n\n<p>It isn't exactly the same logic as your <code>if-elseif</code> structure but it also could work and it's more simple. Note: the order of the elements in the array is important. </p>\n\n<p>4, Instead of this: </p>\n\n<pre><code>if ($os_platform == \"iPhone\" || $os_platform == \"Android\" || $os_platform == \"BlackBerry\" \n || $os_platform == \"Mobile\" || $os_platform == \"iPod\" || $os_platform == \"iPad\") { \n</code></pre>\n\n<p>set an <code>$is_mobile</code> flag: </p>\n\n<pre><code>$is_mobile = false; \nif (preg_match('/iphone/i', $user_agent)) { \n $os_platform = \"iPhone\"; \n $is_mobile = true; \n} else if (preg_match('/android/i', $user_agent)) { \n $os_platform = \"Android\"; \n $is_mobile = true; \n... \n\n\nif ($is_mobile && preg_match('/mobile/i', $user_agent)) { \n ... \n} \n</code></pre>\n\n<p>You can also combine it with the associative array solution: </p>\n\n<pre><code>$os_arr['/windows|win32/i']['os'] = 'Windows'; \n$os_arr['/windows|win32/i']['is_mobile'] = FALSE; \n$os_arr['/windows nt 6.2/i']['os'] = 'Windows 8'; \n$os_arr['/windows nt 6.2/i']['is_mobile'] = FALSE; \n</code></pre>\n\n<p>(If you use it you should change the <code>os</code> and <code>is_mobile</code> strings to constants.) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T13:47:47.207",
"Id": "9429",
"Score": "1",
"body": "Nice! Definitely liking those changes, makes a lot more sense! Thank you palacsint!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T10:54:16.870",
"Id": "9454",
"Score": "1",
"body": "Updated the question with the new code if anyone wants the improved version, thanks again palacsint, feels a lot better with the new code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T01:47:29.217",
"Id": "21524",
"Score": "0",
"body": "There's actually a built-in function: `get_browser()` http://php.net/manual/en/function.get-browser.php , though it relies on a PHP_INI_SYSTEM config variable to so you need to be able to edit php.ini or httpd.conf to enable it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T20:25:19.270",
"Id": "34825",
"Score": "0",
"body": "@user22104 It hasn't been updated for a few months now so a few of the new OS/Browsers might lead to 'Unknown Browser/OS' results. Things such as Windows 8, iOS6 etc have all been released since I updated this, if I get some spare time later I'll update it as best as I can :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T08:59:47.827",
"Id": "6090",
"ParentId": "6077",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "6090",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T00:43:22.147",
"Id": "6077",
"Score": "9",
"Tags": [
"php",
"performance"
],
"Title": "Browser and OS detection script"
}
|
6077
|
<p>The comment at the top was not followed because I printed the contents. I just want an opinion on coding style.</p>
<pre><code> /*
* Write a function setbits(x,p,n,y) that returns x with the n bits
* that begin at position p set to the rightmost n bits of y, leaving
* the other bits unchanged in the least number of lines.
*
* Note: function signatures and curly brackets dont count towards
* the number of lines. You must also declare your variables, and
* call the function
*
* build with:
* gcc -o bit_twiddle -Wall -g -lm ./bit_twiddle.c
*/
#include <stdio.h>
#include <math.h>
#include <limits.h>
unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y) {
x |= (y & ~(~0 << n)) << p;
size_t s = (int)(log(INT_MAX)/log(2)) + 1;
printf("An int is %d bits\n", s);
int mask = pow(2.0, (int)s);
do {
((x & mask) == 0) ? printf("0") : printf("1");
((s%4)==0) ? printf(" ") : printf("");
x <<= 1;
} while (s--);
printf("\n");
}
void main( ) {
unsigned retrn=1, begin=3, nbits=3, input=7;
unsigned x = setbits(retrn, begin, nbits, input);
}
</code></pre>
<p><strong>UPDATE</strong> </p>
<pre><code>x |= (y & ~(0 << n)) << p --> x |= (y & ~(~0 << n)) << p
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:59:52.337",
"Id": "9401",
"Score": "2",
"body": "Not sure this does anything: `(0 << n)`"
}
] |
[
{
"body": "<p>I think your code does not exactly what the comment wants. In line:</p>\n\n<pre><code>x |= (y & ~(0 << n)) << p;\n</code></pre>\n\n<p><code>0 << n</code> is 0. If you want <code>n</code> rightmost bits of <code>y</code> you may use a mask like <code>(1<<n)-1</code> (which is <code>n</code> 1 bits).\nNow on your code style, when you are coding a bit manipulating task, you'd better do it completely with bitwise operators (at least use other functions very few). Here in this code, using <code>log</code> and <code>pow</code> can be avoided. If you want to get number of bits in an integer type, you can use <code>sizeof</code>, like below:</p>\n\n<pre><code>size_t s = sizeof(int) << 3;\n</code></pre>\n\n<p>here <code><< 3</code> is equal to <code>* 8</code>, because each byte definitely has 8 bits (it works on integer types of any size, just replace <code>int</code> with any other type like <code>short</code> or <code>long long</code>).</p>\n\n<p>Now instead of using <code>pow(2, s)</code> you can write <code>1 << s</code> :)</p>\n\n<p>And about your printing, you can replace <code>s%4</code> with <code>s&3</code> (think about it). And I prefer shifting down <code>mask</code> instead of shifting up <code>x</code> (here it doesn't make any difference, but when you work with signed values it does, because sign will be preserved in left shifts). And for reducing number of lines for printing, you may use <code>for</code> loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T06:54:49.607",
"Id": "6089",
"ParentId": "6078",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "6089",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T01:09:16.440",
"Id": "6078",
"Score": "5",
"Tags": [
"c"
],
"Title": "Bit Flipping Programming Exercise in C"
}
|
6078
|
<p>I have a JavaScript/jQuery function that handles the drop-down menus for several different sites. I am a new to JavaScript and jQuery and would love any input on how to clean up my code. Essentially, I am asking how to make this script more efficient and less clunky, so I can improve performance and write better code.</p>
<pre><code> <!doctype html>
<html>
<head>
<title> </title>
<!--stylesheets-->
<link rel="stylesheet" href="../css/reset.css">
<link rel="stylesheet" href="../css/master.css">
<!--custom fonts-->
<!--JS-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script>
<script src="functions.js"></script>
<script>
$(function() {
dropdownSlide('.ppt-menu', 'ul.sub-menu', 5000, fade)
})
</script>
</head>
<body>
<nav id="test-menu" class="ppt-menu">
<ul id="menu-main-nav-1" class="menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-63"> <a href="http://blakecommunications.com/">Home</a></li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-65"><a href="http://blakecommunications.com/about">About</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-60"><a href="http://blakecommunications.com/about/approach/">Approach</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-62"><a href="http://blakecommunications.com/about/industries/">Industries</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-91"><a href="http://blakecommunications.com/about/services/">Services</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-61"><a href="http://blakecommunications.com/about/stephanie-blake-bio/">Bio</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-120"><a href="http://blakecommunications.com/projects">Projects</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-93"><a href="http://blakecommunications.com/projects/uccs/">UCCS</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-92"><a href="http://blakecommunications.com/projects/the-dixon-collective/">The Dixon Collective</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-120"><a href="http://blakecommunications.com/projects">Projectsttow</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-93"><a href="http://blakecommunications.com/projects/uccs/">UCCS</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-92"><a href="http://blakecommunications.com/projects/the-dixon-collective/">The Dixon Collective</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-57"><a href="http://blakecommunications.com/contact/">Contact</a></li>
</code></pre>
<p>
</p>
<p></p>
<p></p>
<pre><code>function dropdownMenu(nav, dropdown, speed, type) {
var nav = $(nav), dropdown = $(dropdown);
var parentItem = $(nav).find('li').has(dropdown);
$(parentItem).find(dropdown).hide();
if( type === slide ) {
$(parentItem).mouseenter(function () {
$('li').find(dropdown).hide();
$(this).find(dropdown).stop(true, true).slideDown(speed);
}).mouseleave(function () {
$(this).find(dropdown).delay(500).slideUp(speed);
});
}
else if ( type === fade ) {
$(parentItem).mouseenter(function () {
$('li').find(dropdown).hide();
$(this).find(dropdown).stop(true, true).fadeIn(speed);
}).mouseleave(function () {
$(this).find(dropdown).delay(500).fadeOut(speed);
});
}
else if( type === show) {
$(parentItem).mouseenter(function () {
$('li').find(dropdown).hide();
$(this).find(dropdown).stop(true, true).show(speed);
}).mouseleave(function () {
$(this).find(dropdown).delay(500).hide(speed);
});
}
else {
$(parentItem).mouseenter(function () {
$('li').find(dropdown).hide();
$(this).find(dropdown).stop(true, true).show();
}).mouseleave(function () {
$(this).find(dropdown).delay(500).hide();
});
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T01:53:16.400",
"Id": "9389",
"Score": "0",
"body": "Please show us the corresponding HTML to we can see how to use it's structure to help make the code smarter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T04:48:06.813",
"Id": "9417",
"Score": "0",
"body": "When you pass dropdown into your function, what is it? selector? DOM element? It looks like there's probably some wastage around that, but I don't know exactly what it is. Please add a sample call to the dropdownMenu function that passes in things used in your HTML markup."
}
] |
[
{
"body": "<p>You've made a few mistakes.</p>\n\n<p>Firstly you used <code>$(parentItem)</code> and <code>$(nav)</code> when you don't need to, because they are already jQuery objects.</p>\n\n<p>Secondly you copy pasted 4 blocks of similar codes without abstracting it into a function.</p>\n\n<p>Then the function itself could have been optimised, by removing the <code>$(\"li\").find(dropdown)</code> call outside the event handlers.</p>\n\n<pre><code>function dropdownMenu(nav, dropdown, speed, type) {\n\n var nav = $(nav),\n dropdown = $(dropdown);\n\n var parentItem = nav.find('li').has(dropdown);\n\n parentItem.find(dropdown).hide();\n\n function action (enter, leave, speed) {\n var all = $('li').find(dropdown);\n\n parentItem.mouseenter(function() {\n all.hide();\n $(this).find(dropdown).stop(true, true)[enter](speed);\n }).mouseleave(function() {\n $(this).find(dropdown).delay(500)[leave](speed);\n }); \n }\n\n switch (type) {\n case \"slide\":\n action (\"slideDown\", \"slideUp\", speed); break;\n case \"fade\":\n action (\"fadeIn\", \"fadeOut\", speed); break;\n case \"show\":\n action (\"show\", \"hide\", speed); break;\n default: \n action (\"show\", \"hide\"); break;\n }\n}\n</code></pre>\n\n<p>The rest of the optimisations depend on the HTML markup.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T03:42:54.633",
"Id": "9405",
"Score": "0",
"body": "Thanks. Question: Should the if/else statement be checking for a string? Or should I pass type === \"slide\" or just slide. If I don't set it to a string I get a console error 'slide is not defined'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T03:51:47.470",
"Id": "9407",
"Score": "0",
"body": "@Jacobi In that case it should be a string. so `\"slide\"` and you should pass in a string as an argument"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:00:44.823",
"Id": "6080",
"ParentId": "6079",
"Score": "3"
}
},
{
"body": "<p>Without seeing the markup, I'd suggest this table-driven approach which is easy to extend to more types by just adding another item to the table. Based on your comments in other posts, I'm also assuming that the type is actually a string with values: \"slide\", \"fade\", \"show\", ...</p>\n\n<pre><code>function dropdownMenu(nav, dropdown, speed, type) {\n\n var dropdown = $(dropdown);\n var parentItem = $(nav).find('li').has(dropdown);\n parentItem.find(dropdown).hide();\n\n var options = {\n slide: {in: \"slideDown\", out: \"slideUp\", speed: speed},\n fade: {in: \"fadeIn\", out: \"fadeOut\", speed: speed},\n show: {in: \"show\", out: \"hide\", speed: speed},\n other: {in: \"show\", out: \"hide\"}\n };\n\n var data = options[type] || options.other;\n\n parentItem.mouseenter(function () {\n $('li').find(dropdown).hide();\n $(this).find(dropdown).stop(true, true)[data.in]](data.speed);\n }).mouseleave(function () {\n $(this).find(dropdown).delay(500)[data.out](data.speed);\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T03:59:53.790",
"Id": "9410",
"Score": "0",
"body": "There are a few micro optimisations you can do. `$(nav)` on line 4 is redudant. `$(parentItem)` on line 5 is redundant. Creating `options` as a local variable is redundant (bind it in closure scope to the function declaration). The `if (!data)` can be made more elegant using `||`. And the `$(\"li\")...` in the mouseenter handler is being created every time for no reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T04:01:07.780",
"Id": "9411",
"Score": "0",
"body": "I didn't attempt to figured out how the HTML works without seeing it (it wasn't available at the time I wrote this). I just attacked the duplication of the event handlers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T04:15:41.137",
"Id": "9413",
"Score": "0",
"body": "Updated the `parentItem` reference and removed the `if (!data)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T05:01:52.620",
"Id": "9418",
"Score": "0",
"body": "Removed `nav` local variable as it doesn't seem to be needed."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T02:12:25.097",
"Id": "6081",
"ParentId": "6079",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T01:46:51.000",
"Id": "6079",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "Handling drop-down menus for different sites"
}
|
6079
|
<p>EDIT:</p>
<p>Function is returnted to JClass Text. Prototypes hold non instance members (statics). No privacy. Privacy requires self executing methods.</p>
<pre><code>var Text = function( form_name )
{
this.text_array = document.forms[form_name].elements;
};
Text.prototype.patterns =
{
prefix_url: /^http:\/\//,
url: /^.{1,2048}$/,
tweet: /^.{1,40}$/,
title: /^.{1,32}$/,
name: /^.{1,64}$/,
email: /^.{1,64}@.{1,255}$/,
pass: /^.{6,20}$/
};
Text.prototype.pattern = function( type )
{
return this.patterns[type].exec( this.text_array[type].value );
};
Text.prototype.patternAdd = function( type )
{
return this.patterns[type].exec( this.text_array.url.value );
};
Text.prototype.same = function()
{
return ( (this.text_array.email.value) === (this.text_array.email1.value) );
};
Text.prototype.emptyUser = function()
{
var element;
for ( element in this.text_array )
{
if( this.text_array[element].value === '' )
{
return 0;
}
}
return 1;
};
/**
* Text End
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T19:01:45.400",
"Id": "9447",
"Score": "0",
"body": "generic function (should be renamed to checkpattern) should not be setting the response."
}
] |
[
{
"body": "<p>Few additions </p>\n\n<p>1) First get some unit tests in </p>\n\n<p>2) I would do something like this <a href=\"http://jsfiddle.net/Brw4W/1/\" rel=\"nofollow\">http://jsfiddle.net/Brw4W/1/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T14:18:45.040",
"Id": "9500",
"Score": "0",
"body": "Didn't get you . What is the best practice"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T09:32:29.140",
"Id": "6113",
"ParentId": "6087",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6113",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T05:13:33.710",
"Id": "6087",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Object - Text Validator"
}
|
6087
|
<p>I started playing with Raphaël and I'm wondering if somebody could do the code review
of what I have so far and maybe give me some tips how to improve it. Basically what I'm trying to accomplish is the zoom-in/zoom-out effect on the element when mouseover event is being triggered on the element. The effect should paused when mouseout event is triggered. Here is what I have so far:</p>
<pre><code>var paper = new Raphael(document.getElementById('container'), 500, 500);
var dot = paper.circle(100, 100, 15);
dot.attr({fill: "#ff0000"});
// is there a better way to do this?
var animation = Raphael.animation({r: 25}, 1000, function () {
this.animate({r: 15}, 1000, function () {
this.animate(animation);
});
});
dot.mouseover(function () {
dot.animate(animation);
});
dot.mouseout(function () {
this.pause();
this.animate({r: 15}, 500);
});
</code></pre>
<p>You can also see the demo here: <a href="http://jsfiddle.net/KEg8y/" rel="nofollow">http://jsfiddle.net/KEg8y/</a></p>
|
[] |
[
{
"body": "<p>If I understood your intention correctly, the code already works fine. However, as you are learning Raphaël, there are two minor things you could consider.\nFirstly, you can chain your methods when setting attributes via <code>.attr()</code>:</p>\n\n<pre><code>var dot = paper.circle(100, 100, 15).attr({fill: \"#ff0000\"});\n</code></pre>\n\n<p>Secondly, note is that Raphaël provides the <code>.hover()</code> method for when you intend to use both <code>.mouseover()</code> and <code>.mouseout()</code>. Also, in your <code>.mouseover()</code> call, <code>this</code> is <code>dot</code>:</p>\n\n<pre><code>dot.hover(function () {\n this.animate(animation);\n}, function () {\n this.pause();\n this.animate({r: 15}, 500);\n});\n</code></pre>\n\n<p>In my opinion, the middle part can stay as it is. However, when chaining more animations together, the nested functions could become difficult to read and understand. This is one suggestion to chain such animations in another way:</p>\n\n<pre><code>var paper = new Raphael(document.getElementById('container'), 500, 500);\nvar dot = paper.circle(100, 100, 15).attr({fill: \"#ff0000\"});\n\nvar steps = [\n {params: {r: 25}, ms: 1200},\n {params: {r: 35}, ms: 300},\n {params: {r: 15}, ms: 800}\n];\n\nvar animator = function() {\n var step = steps.shift();\n steps.push(step);\n this.animate(step.params, step.ms, animator);\n}\n\ndot.hover(function () {\n animator.call(this);\n}, function () {\n this.pause();\n this.animate({r: 15}, 500);\n});\n</code></pre>\n\n<p>This way, additional steps can be included into the array without further nesting any callbacks. Also, now there is only one function object <code>animator</code> being reused for the callbacks. The <code>animator</code> takes the first step from the list of steps and puts it back at the end of the array. Then, that same step is performed as animation with the <code>animator</code> as its callback. Note that animator is called on <code>dot</code> dynamically in the first <code>.hover()</code> function, so that the first <code>this.animate()</code> is called on the right object.</p>\n\n<p>I have forked your fiddle: <a href=\"http://jsfiddle.net/rHPDP/\" rel=\"nofollow\">http://jsfiddle.net/rHPDP/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T17:39:38.547",
"Id": "12955",
"ParentId": "6088",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12955",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T06:44:11.750",
"Id": "6088",
"Score": "4",
"Tags": [
"javascript",
"raphael.js"
],
"Title": "Raphaël zoom effect"
}
|
6088
|
<p>I have something akin to</p>
<pre><code>object[] values = getValues();
string renderedValues = string.Join("-",
Array.ConvertAll<object,string>(values,
new Converter<object,string>(o2s)
));
</code></pre>
<p>where <code>o2s</code> is</p>
<pre><code>public static string o2s(object o) { return o.ToString(); }
</code></pre>
<p>Comments welcome!</p>
|
[] |
[
{
"body": "<p>Why not <del>Zoidberg</del> simply this?</p>\n\n<pre><code>string renderedValues = string.Join(\"-\", getValues());\n</code></pre>\n\n<p>Simply using the <code>Join(string separator, params Object[] values)</code> overload: <a href=\"http://msdn.microsoft.com/en-us/library/dd988350.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/dd988350.aspx</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T10:51:48.857",
"Id": "9426",
"Score": "1",
"body": "This overload an addition on 4 and I'm targeting 3.5"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-17T10:16:40.630",
"Id": "10842",
"Score": "0",
"body": "Any idea how the two patterns compare from a performance standpoint. (*Just assume .NET 4 was an option*)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-19T10:11:13.113",
"Id": "10899",
"Score": "0",
"body": "No idea whatsoever. Do you see any reason to spend time making code more complicated and less straightforward than it needs to be?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T10:35:47.993",
"Id": "6093",
"ParentId": "6092",
"Score": "1"
}
},
{
"body": "<p>No need to create a new <code>Converter</code>. Also, I'd rename the variable:</p>\n\n<pre><code>object[] values = getValues();\nstring joinedValues = string.Join(\"-\", Array.ConvertAll<object,string>(values, o2s));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T15:22:39.937",
"Id": "9431",
"Score": "0",
"body": "what is `o2s` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:04:21.073",
"Id": "9432",
"Score": "0",
"body": "@JesseC.Slicer: It's the function Vinko declares in the second half of the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:29:43.010",
"Id": "9436",
"Score": "0",
"body": "Gotcha - for some reason my eyes didn't see that when I first read it. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T11:18:29.120",
"Id": "6095",
"ParentId": "6092",
"Score": "4"
}
},
{
"body": "<p>There exists a method for that conversion already:</p>\n<pre><code>string renderedValues = string.Join(\n "-",\n Array.ConvertAll<object, string>(values, Convert.ToString)\n);\n</code></pre>\n<hr />\n<h3>Update:</h3>\n<p>In framework 4 an overload that takes an object array was added, so it will do the conversion for you:</p>\n<pre><code>string renderedValues = string.Join("-", values);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T11:36:02.717",
"Id": "6096",
"ParentId": "6092",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "6096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T10:26:07.240",
"Id": "6092",
"Score": "3",
"Tags": [
"c#",
".net",
"converting"
],
"Title": "Best C# idiom to convert the items on an object array to a string?"
}
|
6092
|
<p>I always thought it would be handy to be able to write:</p>
<pre><code>const std::string s = (std::ostringstream() << "hi" << 0).str();
</code></pre>
<p>This doesn't work in C++ by default because <code>operator<<</code> returns the <code>ostringstream</code> as a <code>ostream</code>, which obviously doesn't have the <code>str()</code> member.</p>
<p>I was pleasantly surprised though to discover that this can be done in C++11:</p>
<pre><code>#include <iostream>
#include <sstream>
#include <string>
template <typename CharT, typename traits, typename T>
std::basic_ostringstream<CharT,traits>&& operator<<(std::basic_ostringstream<CharT,traits>&& out, const T& t) {
static_cast<std::basic_ostream<CharT,traits>&>(out) << t;
return std::move(out);
}
int main() {
const std::string s = (std::ostringstream() << "hi" << 0).str();
std::cout << s << std::endl;
}
</code></pre>
<p>It needs rvalue references and move semantics to bind the temporary to a reference here.</p>
<ol>
<li>Is there a good reason why this isn't provided by the standard library by default? Is it an oversight? Making this idiom legal code seems like it might offer a number of benefits.</li>
<li>In my local C++11 project, I provide some "utility" code. Is there any reason why I shouldn't include this and use it widely?</li>
</ol>
<p>How about the more generic version:</p>
<pre><code>template <typename S, typename T, class = typename
std::enable_if<std::is_base_of<std::basic_ostream<typename S::char_type,typename S::traits_type>, S>::value>::type>
S&& operator<<(S&& out, const T& t) {
static_cast<std::basic_ostream<typename S::char_type,typename S::traits_type>&>(out) << t;
return std::move(out);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:44:32.470",
"Id": "9675",
"Score": "0",
"body": "You might be interested in this gizmo I had reviewed when the site first came live: http://codereview.stackexchange.com/questions/226/does-my-class-introduce-undefined-behavior"
}
] |
[
{
"body": "<p>Its a nice trick. But I don't see what it buys you.</p>\n\n<p>So you have a std::string object that you now use.</p>\n\n<pre><code>int main() {\n const std::string s = (std::ostringstream() << \"hi\" << 0).str();\n std::cout << s << std::endl;\n}\n</code></pre>\n\n<p>In C++03 I would have a std::stringstream object that I now use (which can then be used in the same place as the std::string object).</p>\n\n<pre><code>int main()\n{\n std::ostringstream message;\n message << \"hi\" << 0; // one extra line.\n std::cout << message.str() << std::endl;\n}\n</code></pre>\n\n<p>I don't see the advantage. Maybe if you can show the code being used in a larger context where it provides an advantage over std::stringstream.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:01:33.497",
"Id": "80699",
"Score": "0",
"body": "The advantage is atomicity. Single calls to `operator<<` on `std::cout` and `std::cerr` are guaranteed to be atomic. You can get interleaving with output from other threads with `std::cout << 'a' << 1 << false;`, but not with `std::cout << static_cast<const stringstream&>(std::stringstream() << 'a' << 1 << false).str();`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:15:08.323",
"Id": "80776",
"Score": "0",
"body": "@uckelman: Yes. That is **NOT** what I am debating. If you see my code that part has not changed. My argument is that adding an extra list to make an explicit object (rather than a temporary) is more readable and only adds a single line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T21:53:18.583",
"Id": "513836",
"Score": "0",
"body": "This is buys ability to construct and take advantage of overloaded `<<` that stringify complex structures without requiring being able to declare local variable in context where such variable cannot be declared. E.g. in constructor initialization lists so that you can construct class with a constant string field. That you cannot do if your syntax requires local variables (or doing even crazier theatrics like C-style function calls or lambdas. @Lightness_races_in_orbit's answer is perfect for such cases."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T11:55:12.193",
"Id": "6097",
"ParentId": "6094",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>Is there a good reason why this isn't provided by the standard library by default? Is it an oversight? Making this idiom legal code seems like it might offer a number of benefits.</p>\n</blockquote>\n\n<p>Other than that the standard was already ~5 years delayed, and this little trick ultimately doesn't buy you much?</p>\n\n<p>There are millions of cute little party tricks and convenience functions that can be written in C++. For one of them to get standardized, they have to offer a pretty significant benefit.</p>\n\n<p>I see no harm in it though, and no reason why you shouldn't use it. But I don't think it's significant enough to warrant inclusion in the standard.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T12:36:30.160",
"Id": "6098",
"ParentId": "6094",
"Score": "2"
}
},
{
"body": "<p>Bjarne gives a pretty succinct description of why this (and many similar) features aren't in the standard. He points out that virtually everybody who talks to him about C++ has essentially the same thing to say: \"C++ is way to big and way too complex. You should really work at making it a lot smaller and simpler. Oh, but while you're at it, you should add this <em>one</em> really great feature I thought of\"</p>\n\n<p>It kind of reminds me of things I've seen about how questions of political polls can be/ are phrased. If I ask: \"Do you think this country should do more to [increase jobs | help the needy | etc.]?\" I can count on a large majority of people saying \"yes.\" If I ask \"Do you think we should raise taxes by X%?\", I can count on an equally large majority saying \"No\". I can give nearly a guaranteed outcome from my poll just by choosing whether to ask about the hoped-for outcome or the cost.</p>\n\n<p>Bottom line: Each feature you add has a cost, and focusing on the outcome doesn't remove the cost. To design a usable language/library, you need to restrict features to the few that provide the greatest positive outcome for the lowest cost. In the case of the C++ committee, they've been pretty clear about a few things, and one is that most new features will barely be considered at all unless they enable fairly substantial improvements in code that uses the new feature <em>and</em> have extremely minimal cost, especially in terms of breaking any existing code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:50:35.497",
"Id": "9440",
"Score": "0",
"body": "That makes a lot of sense. When I asked I wasn't quite sure if there was some terrible glaring problem that it accidentally introduces that made it a bad idea or if it's just not important enough to be worth the complexity of adding. From the answers here it looks like it's the latter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-17T19:30:21.520",
"Id": "401376",
"Score": "0",
"body": "I don't see what cost is there, other from an additional way to do things. There is no performance overhead or cost. Do you still think this is true Jerry Coffin? I think not."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:45:40.680",
"Id": "6104",
"ParentId": "6094",
"Score": "6"
}
},
{
"body": "<p>To add to the existing answers, this was already semi-possible:</p>\n\n<pre><code>const std::string s = static_cast<std::ostringstream&>(\n std::ostringstream() << \"hi\" << 0\n).str();\n</code></pre>\n\n<p>Shove that in a <code>#define</code> and you're golden...</p>\n\n<p>... except not really. Any <code>operator<<</code> implementations that are free functions rather than member functions will fail, because their LHS operand must be <code>std::ostringstream&</code> and, as a ref-to-non-<code>const</code>, this will not bind to the temporary <code>std::ostringstream()</code>.</p>\n\n<p>The almost-amusing result of the above example is that <code>s</code> <a href=\"https://ideone.com/XfMFOx\" rel=\"nofollow\">will contain text like \"0x804947c0\"</a>, but swapping <code>\"hi\"</code> and <code>0</code> <a href=\"https://ideone.com/cHUQUP\" rel=\"nofollow\">will result in the behaviour you'd expect (\"0hi\")</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T21:49:38.510",
"Id": "513835",
"Score": "0",
"body": "Ah, just what I was looking for, was trying to do the same thing, except I was casting `static_cast<std::ostringstream>` rather than to its lereference `&` and couldn't figure out why it wouldn't compile!."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T06:48:21.147",
"Id": "20667",
"ParentId": "6094",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6104",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T11:05:48.570",
"Id": "6094",
"Score": "10",
"Tags": [
"c++",
"c++11"
],
"Title": "A version of operator<< that returns ostringstream instead of ostream"
}
|
6094
|
<p>After having spent a month or two trying to learn JavaScript, especially functional programming, async, and closures, I finally get it. But I don't know if I'm writing elegant code... Specifically, I'm not sure if I'm creating too many closures, because I don't entirely grasp when contexts remain and when they're marked for garbage collection.</p>
<p>You can probably tell from the example that I'm using node.js -- basically, this is just a piece of test code that connects to a database, gets 20,000 records asynchronously with individual <code>SELECT</code> queries (I'm just doing some profiling, don't worry), and manipulates the data. At the end, it tells me how long it took and closes the MySQL connection.</p>
<p>In order to get a final timestamp and close the connection, I needed something like the <a href="https://github.com/caolan/async" rel="nofollow"><code>async</code></a> library to keep track of all the various asynchronous functions that are being spawned. It takes all my queries as an array of functions (using a factory called <code>makeQuery()</code>) and then runs a callback to do the cleanup.</p>
<p>Questions:</p>
<ol>
<li><p>Am I creating a huge amount of contexts by creating and returning the function <code>doQuery()</code> which uses the argument <code>id</code> in the <code>makeQuery()</code> function, thereby causing 20,000 contexts to persist until <code>async.parallel()</code> is run?</p></li>
<li><p>Is the factory function <code>makeQuery()</code> a good and tidy way to create this array of <code>doQuery()</code> functions? Can you suggest any better way to do it?</p></li>
</ol>
<p></p>
<pre><code>var mysql = require('mysql');
var radix64 = require('./lib/radix64');
var async = require('async');
var client = mysql.createClient({user: 'root', password: '12345678'});
client.query('USE nodetest');
var startTime = (new Date()).getTime(); // poor man's profiling
var queries = []; // this will be fed to async.parallel() later
var makeQuery = function makeQuery (id) { // factory function to create the queries
return function doQuery (cb) {
client.query('SELECT * FROM urls WHERE id='+id,
function logResults (e, results, fields) {
results = results[0];
results.key = radix64.fromNumber(results.id); // yep, I'm converting the
// number into base-64 notation
cb(); // if I wanted to do something useful at the end, I would have
// called cb(results) instead, which compiles an array of results
// to be accessed by the final callback
}
);
};
};
for (i = 1001; i <= 20000; i ++) { // build the list of tasks to be done in parallel
queries.push(makeQuery(i));
}
// run those tasks
async.parallel(queries, function finished () { // clean up and get the elapsed time
console.log('done');
client.end();
console.log(((new Date()).getTime() - startTime) / 1000);
});
</code></pre>
<p>For those of you unfamiliar with <code>async</code>, it's a userland module built for node.js and the browser. Each function in the array that gets passed to <code>async.parallel()</code> is obliged to take a callback and then run that callback once it's done, in order to let <code>async.parallel()</code> know it's done.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:22:43.060",
"Id": "9434",
"Score": "0",
"body": "@Raynos yes. Oops. Just a test server running on 127.0.0.1, but still..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:34:41.213",
"Id": "9438",
"Score": "0",
"body": "@Raynos would you be able to delete your comment, to hide the evidence? I removed the password in my code sample."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:55:16.623",
"Id": "9442",
"Score": "0",
"body": "There's a change log on the question, you know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T17:10:32.087",
"Id": "9443",
"Score": "0",
"body": "oh yeah, you're right. Dang."
}
] |
[
{
"body": "<p><code>var makeQuery = function makeQuery (id) {</code></p>\n\n<p>There is no need to make <code>makeQuery</code> a local variable, just use a function declaration.</p>\n\n<pre><code>results = results[0];\nresults.key = radix64.fromNumber(results.id);\n</code></pre>\n\n<p>Your just augmenting the object, your not doing anything with it.</p>\n\n<p>Other then that, your not creating new functions in a loop, your using a function constructor. This correct.</p>\n\n<p>Your running all 19000 queries in parallel rather then in waterfall, which is also correct.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Question 1:</p>\n\n<p>You need to create 20000 contexts. Because there are 20000 values of <code>i</code>. Worrying about there being 20000 functions is a micro optimisation. v8 optimizes the hell out of your code.</p>\n\n<p>It actually splits your functions into a hidden class seperate from the closure context, and in my memory you simply have 20000 values of <code>i</code> and one value for the function.</p>\n\n<p>Just to remind you of rule 1.</p>\n\n<blockquote>\n <p>Never underestimate V8</p>\n</blockquote>\n\n<p>Question 2:</p>\n\n<p><code>makeQuery</code> as a factory is the correct pattern to use. </p>\n\n<p>The only other optimisation you can do is to write a real SQL query rather then 20000 dummy ones. But I'll ignore that because it's a dummy example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:32:52.963",
"Id": "9437",
"Score": "0",
"body": "Re: having `makeQuery` a local variable, I guess you're right... I've just been too Crockfordised, that's all :) And in regards to augmenting `results` and then totally throwing it away, I know... just doing a speed test, so I don't want to actually use it. Thanks for the confirmation that using a constructor is correct... Also, I updated my question with actual explicit questions! My big concern is whether the constructor function is creating 20,000 contexts on account of the closure in which the returned function needs the `id` argument. Oh, and whether that's a problem at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:37:58.717",
"Id": "9439",
"Score": "0",
"body": "Yep, it's a dummy example. Trying to simulate the real-world use case, in which 20,000 people might indeed hit the server at once with their tiny little queries. Glad to know V8 won't mind about all my contexts. So when you say it splits that returned function out into its own, do you know if it would still do that if it were an anonymous function? Another Crockford-instilled anxiety."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:54:13.773",
"Id": "9441",
"Score": "0",
"body": "@Pauld'Aoust functions are functions. There's no difference"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T17:14:26.360",
"Id": "9444",
"Score": "0",
"body": "Oh, okay. Crockford mentioned something about naming your functions so that you get 20,000 references to one function rather than 20,000 anonymous functions in the heap. Perhaps V8 doesn't do it that way, or else I didn't understand him correctly. At any rate, I guess it's good practice to name your callbacks so you get something to look at in your stack traces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T17:22:16.697",
"Id": "9445",
"Score": "0",
"body": "@Pauld'Aoust the point is you have one named function `nameQuery` and 20000 anonymous functions (the functions returned from the nameQuery)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:27:26.417",
"Id": "6102",
"ParentId": "6101",
"Score": "2"
}
},
{
"body": "<p>When in doubt, go with restricting the closure context to the enclosing function scope:</p>\n\n<pre><code>function makeLog(cb) {\n return function (e, results, fields) { // logResults\n results = results[0];\n results.key = radix64.fromNumber(results.id); // yep, I'm converting the\n // number into base-64 notation\n cb(); // if I wanted to do something useful at the end, I would have\n // called cb(results) instead, which compiles an array of results\n // to be accessed by the final callback\n };\n}\n\nfunction makeQuery(id, aClient) { // factory function to create the queries\n return function (cb) { // doQuery\n aClient.query('SELECT * FROM urls WHERE id=' + id, makeLog(cb));\n };\n}\n\nfor (i = 1001; i <= 20000; i++) { // build the list of tasks to be done in parallel\n queries.push(makeQuery(i, client));\n}\n</code></pre>\n\n<p>Otherwise, you can as well get rid of the factories altogether:</p>\n\n<pre><code>for (i = 1001; i <= 20000; i++) { // build the list of tasks to be done in parallel\n queries.push(function (cb) { // doQuery\n client.query('SELECT * FROM urls WHERE id=' + i,\n function (e, results, fields) { // logResults\n results = results[0];\n results.key = radix64.fromNumber(results.id); // yep, I'm converting the\n // number into base-64 notation\n cb(); // if I wanted to do something useful at the end, I would have\n // called cb(results) instead, which compiles an array of results\n // to be accessed by the final callback\n });\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T17:06:31.853",
"Id": "15544",
"ParentId": "6101",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6102",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T16:13:04.813",
"Id": "6101",
"Score": "4",
"Tags": [
"javascript",
"asynchronous",
"node.js"
],
"Title": "Async, callbacks, and closures"
}
|
6101
|
<p>For a given Entity Framework data set, I have written several adapters to import data into my entity models. Rather than manually write mapping code for each entity model, I tried for a generalized approach using reflection.</p>
<p>My requirements are: </p>
<ul>
<li>The updater must create the entity if it does not exist, or update the existing entity with any changed properties or relationships.</li>
<li>External data are often subsets; therefore, do not delete entities if they are not in external data</li>
<li>If external data reference other entities which do not exist, eg tags, the updater must create them and ensure the references are still valid, while respecting key constraints.</li>
</ul>
<p>My entities implement an interface, IEntity:</p>
<pre><code>public interface IEntity
{
int Id { get; set; }
T CreateEmpty<T>() where T:class,IEntity;
bool EntityEquals(IEntity entity);
}
</code></pre>
<p>EntityEquals compares entities based on their natural keys. An implementation might look like:</p>
<pre><code>public class Tag : IEntity
{
public int Id { get; set; }
// Name is a natural key
public string Name { get; set; }
public T CreateEmpty<T>() where T : class, IEntity
{
return new Tag() as T;
}
public bool EntityEquals(IEntity entity)
{
var e = entity as Tag;
return e != null && Name==e.Name;
}
}
</code></pre>
<p>I invoke this like</p>
<pre><code>EntityDataUpdater.Update(context, externalEntitiesList);
</code></pre>
<p>And here's the implementation. Comments and feedback greatly appreciated!</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using Project.Models;
namespace Project.Models.Adapters
{
public static class EntityDataUpdater
{
public static void Update(DbContext context, IEnumerable<IEntity> entities)
{
if (!entities.Any()) return;
var set = context.Set(entities.First().GetType());
set.Load(); // prefetch data to memory
foreach (var entity in entities)
{
var tEntity = entity.ImportOrUpdate(context);
// if newly imported, add it
if (tEntity.Id == 0) set.Add(tEntity);
// otherwise, indicate that it is updated
else context.Entry(tEntity).State = EntityState.Modified;
}
context.SaveChanges();
}
}
static class EntityCopyExtensions
{
private static bool TryFindIn<T>(this T entity, DbContext context, out T o) where T : class, IEntity
{
var set = context.Set(entity.GetType());
o = set.Local.Cast<IEntity>()
.FirstOrDefault(item => item.EntityEquals(entity)) as T // check local first
?? ((IEnumerable)set).Cast<IEntity>()
.FirstOrDefault(item => item.EntityEquals(entity)) as T; // then check DB
return o != null;
}
private static IEntity FindOrCreateIn(this IEntity entityIn, DbContext context)
{
// if item exists, return it; otherwise create it
IEntity entityOut;
return !entityIn.TryFindIn(context, out entityOut) ? entityIn.ImportOrUpdate(context) : entityOut;
}
public static T ImportOrUpdate<T>(this T entityIn, DbContext context) where T : class, IEntity
{
var entityT = entityIn.GetType();
T entityOut;
if(!entityIn.TryFindIn(context, out entityOut))
{
entityOut = entityIn.CreateEmpty<T>();
}
// copy properties
foreach (var property in entityT.GetProperties()
.Where(p => p.Name != "Id" &&
p.CanWrite && (
p.PropertyType == typeof(string) ||
p.PropertyType == typeof(int) ||
p.PropertyType == typeof(DateTime)
))){
var value = property.GetValue(entityIn, null);
if (value != null) property.SetValue(entityOut, value, null);
}
// copy direct references
foreach (var reference in entityT.GetProperties()
.Where(r => r.PropertyType.IsImplementationOf(typeof(IEntity)))
){
var origValue = (IEntity) reference.GetValue(entityIn, null);
reference.SetValue(entityOut,origValue.FindOrCreateIn(context),null);
}
// copy collections of references
foreach (var reference in entityT.GetProperties()
.Where(r=>
r.PropertyType.IsImplementationOf(typeof(IEnumerable)) &&
r.PropertyType.IsGenericType &&
r.PropertyType.GetGenericArguments().First().IsImplementationOf(typeof(IEntity))
)){
var itemsIn = (IEnumerable) (reference.GetValue(entityIn, null));
// itemsOut begins with all items from entityOut
var itemsOut = ((IEnumerable) (reference.GetValue(entityOut, null))).Cast<IEntity>().ToList();
// then adds any new items from entityIn
foreach (IEntity item in itemsIn)
{
var itemOut = item.FindOrCreateIn(context);
//only add new items
if (!itemsOut.Any(i => i.Id == itemOut.Id) || item.Id==0)
{
itemsOut.Add(item.FindOrCreateIn(context));
}
}
reference.SetValue(entityOut,itemsOut.CastTo(reference.PropertyType),null);
}
return entityOut;
}
/// <summary>
/// Cast each element in <paramref name="list"/> to type of the first object,
/// or null
/// </summary>
private static IEnumerable CastTo(this IList list, Type targetT)
{
if (!(targetT.IsImplementationOf(typeof(IEnumerable)) && targetT.IsGenericType))
throw new ArgumentException("targetT must be an IEnumerable of T.");
var itemT = targetT.GetGenericArguments().First();
var ret = (IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] {itemT}));
foreach (var i in list)
ret.Add(i);
return ret;
}
/// <summary>
/// Returns true if type <paramref name="t"/> implements interface <paramref name="i"/>
/// </summary>
private static bool IsImplementationOf(this Type t, Type i)
{
if (!i.IsInterface) throw new ApplicationException("Method must be of type Interface");
return t.GetInterfaces().Contains(i);
}
/// <summary>
/// Returns true if type <paramref name="t"/> implements interface <paramref name="i"/>
/// </summary>
private static bool IsImplementationOf(this Type t, string i)
{
if (!Type.GetType(i, true).IsInterface) throw new ApplicationException("Method must be of type Interface");
return t.GetInterface(i) != null;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I personally don't like exposing <code>Id</code>s as their base data type (in your case, <code>int</code>) for a couple of reasons:</p>\n\n<ol>\n<li><p>Somewhere, in client code, someone can assign an <code>int</code> of one type of\nentity to another by mistake and nothing will stop you (i.e. no\nstrong typing). This can wreak havoc in the DB.</p></li>\n<li><p>If the underlying data type ever needs to change (e.g. you change\ndatabases or figure your int now needs to be a <code>long</code>/<code>bigint</code>), you\nhave to find all places where you reference it as an <code>int</code> and\nchange it. Encapsulating the <code>Id</code> keeps it localized to the DAL.</p></li>\n</ol>\n\n<p>So I tend to wrap that up thus (the Origin property I normally leave empty, but it can represent different schemas in a database where you may have entity name overlap, etc.):</p>\n\n<pre><code>/// <summary>\n/// Defines an interface for an object's unique key in order to abstract out the underlying key\n/// generation/maintenance mechanism.\n/// </summary>\n/// <typeparam name=\"T\">The type the key is representing.</typeparam>\npublic interface IModelId<T> where T : class, IEntity<T>\n{\n /// <summary>\n /// Gets a string representation of the domain the model originated from.\n /// </summary>\n /// <value>The origin.</value>\n string Origin\n {\n get;\n }\n\n /// <summary>\n /// The model instance identifier for the model object that this <see cref=\"IModelId{T}\"/> refers to.\n /// Typically, this is a database key, file name, or some other unique identifier.\n /// <typeparam name=\"TKeyDataType\">The expected data type of the identifier.</typeparam>\n /// </summary>\n /// <typeparam name=\"TKeyDataType\">The expected data type of the identifier.</typeparam>\n /// <returns>The unique key as the data type specified.</returns>\n TKeyDataType GetKey<TKeyDataType>();\n\n /// <summary>\n /// Performs an equality check on the two model identifiers and returns <c>true</c> if they are equal; otherwise\n /// <c>false</c> is returned. All implementations must also override the equal operator.\n /// </summary>\n /// <param name=\"obj\">The identifier to compare against.</param>\n /// <returns><c>true</c> if the identifiers are equal; otherwise <c>false</c> is returned.</returns>\n bool Equals(IModelId<T> obj);\n}\n</code></pre>\n\n<p>I have a base class handle the <code>Origin</code> property for me:</p>\n\n<pre><code>/// <summary>\n/// Represents an object's unique key in order to abstract out the underlying key generation/maintenance mechanism.\n/// </summary>\n/// <typeparam name=\"T\">The type the key is representing.</typeparam>\npublic abstract class ModelIdBase<T> : IModelId<T> where T : class, IEntity<T>\n{\n /// <summary>\n /// Gets a string representation of the domain the model originated from.\n /// </summary>\n public string Origin\n {\n get;\n\n internal set;\n }\n\n /// <summary>\n /// The model instance identifier for the model object that this <see cref=\"ModelIdBase{T}\"/> refers to.\n /// Typically, this is a database key, file name, or some other unique identifier.\n /// </summary>\n /// <typeparam name=\"TKeyDataType\">The expected data type of the identifier.</typeparam>\n /// <returns>The unique key as the data type specified.</returns>\n public abstract TKeyDataType GetKey<TKeyDataType>();\n\n /// <summary>\n /// Performs an equality check on the two model identifiers and returns <c>true</c> if they are equal;\n /// otherwise <c>false</c> is returned. All implementations must also override the equal operator.\n /// </summary>\n /// <param name=\"obj\">The identifier to compare against.</param>\n /// <returns>\n /// <c>true</c> if the identifiers are equal; otherwise <c>false</c> is returned.\n /// </returns>\n public abstract bool Equals(IModelId<T> obj);\n}\n</code></pre>\n\n<p>Finally, I have a couple implementations I use currently - one for <code>int</code> and another for <code>Guid</code>. Here's the <code>int</code> implementation:</p>\n\n<pre><code>/// <summary>\n/// Represents an abstraction of the database key for a Model Identifier.\n/// </summary>\n/// <typeparam name=\"T\">The expected owner data type for this identifier.</typeparam>\n[DebuggerDisplay(\"Origin={Origin}, Integer Identifier={id}\")]\npublic sealed class IntId<T> : ModelIdBase<T> where T : class, IEntity<T>\n{\n /// <summary>\n /// Gets or sets the unique ID.\n /// </summary>\n /// <value>The unique ID.</value>\n internal int Id\n {\n get;\n\n set;\n }\n\n /// <summary>\n /// Implements the operator ==.\n /// </summary>\n /// <param name=\"intIdentifier1\">The first Model Identifier to compare.</param>\n /// <param name=\"intIdentifier2\">The second Model Identifier to compare.</param>\n /// <returns>\n /// <c>true</c> if the instances are equal; otherwise <c>false</c> is returned.\n /// </returns>\n public static bool operator ==(IntId<T> intIdentifier1, IntId<T> intIdentifier2)\n {\n return object.Equals(intIdentifier1, intIdentifier2);\n }\n\n /// <summary>\n /// Implements the operator !=.\n /// </summary>\n /// <param name=\"intIdentifier1\">The first Model Identifier to compare.</param>\n /// <param name=\"intIdentifier2\">The second Model Identifier to compare.</param>\n /// <returns>\n /// <c>true</c> if the instances are equal; otherwise <c>false</c> is returned.\n /// </returns>\n public static bool operator !=(IntId<T> intIdentifier1, IntId<T> intIdentifier2)\n {\n return !object.Equals(intIdentifier1, intIdentifier2);\n }\n\n /// <summary>\n /// Performs an implicit conversion from <see cref=\"IntId{T}\"/> to <see cref=\"System.Int32\"/>.\n /// </summary>\n /// <param name=\"id\">The identifier.</param>\n /// <returns>The result of the conversion.</returns>\n public static implicit operator int(IntId<T> id)\n {\n return id == null ? int.MinValue : id.GetKey<int>();\n }\n\n /// <summary>\n /// Performs an implicit conversion from <see cref=\"System.Int32\"/> to <see cref=\"IntId{T}\"/>.\n /// </summary>\n /// <param name=\"id\">The identifier.</param>\n /// <returns>The result of the conversion.</returns>\n public static implicit operator IntId<T>(int id)\n {\n return new IntId<T> { Id = id };\n }\n\n /// <summary>\n /// Determines whether the specified <see cref=\"T:System.Object\"/> is equal to the current\n /// <see cref=\"T:System.Object\"/>.\n /// </summary>\n /// <param name=\"obj\">The <see cref=\"T:System.Object\"/> to compare with the current\n /// <see cref=\"T:System.Object\"/>.</param>\n /// <returns>true if the specified <see cref=\"T:System.Object\"/> is equal to the current\n /// <see cref=\"T:System.Object\"/>; otherwise, false.</returns>\n /// <exception cref=\"T:System.NullReferenceException\">The <paramref name=\"obj\"/> parameter is null.</exception>\n public override bool Equals(object obj)\n {\n return this.Equals(obj as IModelId<T>);\n }\n\n /// <summary>\n /// Serves as a hash function for a particular type.\n /// </summary>\n /// <returns>\n /// A hash code for the current <see cref=\"T:System.Object\"/>.\n /// </returns>\n public override int GetHashCode()\n {\n unchecked\n {\n var hash = 17;\n\n hash = (23 * hash) + (this.Origin == null ? 0 : this.Origin.GetHashCode());\n return (31 * hash) + this.GetKey<int>().GetHashCode();\n }\n }\n\n /// <summary>\n /// Returns a <see cref=\"System.String\"/> that represents this instance.\n /// </summary>\n /// <returns>\n /// A <see cref=\"System.String\"/> that represents this instance.\n /// </returns>\n public override string ToString()\n {\n return this.Origin + \":\" + this.GetKey<int>().ToString(CultureInfo.InvariantCulture);\n }\n\n /// <summary>\n /// Performs an equality check on the two model identifiers and returns <c>true</c> if they are equal;\n /// otherwise <c>false</c> is returned. All implementations must also override the equal operator.\n /// </summary>\n /// <param name=\"obj\">The identifier to compare against.</param>\n /// <returns>\n /// <c>true</c> if the identifiers are equal; otherwise <c>false</c> is returned.\n /// </returns>\n public override bool Equals(IModelId<T> obj)\n {\n if (obj == null)\n {\n return false;\n }\n\n return (obj.Origin == this.Origin) && (obj.GetKey<int>() == this.GetKey<int>());\n }\n\n /// <summary>\n /// Generates an object from its string representation.\n /// </summary>\n /// <param name=\"value\">The value of the model's type.</param>\n /// <returns>A new instance of this class as it's interface containing the value from the string.</returns>\n internal static ModelIdBase<T> FromString(string value)\n {\n if (value == null)\n {\n throw new ArgumentNullException(\"value\");\n }\n\n int id;\n var originAndId = value.Split(new[] { \":\" }, StringSplitOptions.None);\n\n if (originAndId.Length != 2)\n {\n throw new ArgumentOutOfRangeException(\"value\", \"value must be in the format of Origin:Identifier\");\n }\n\n return int.TryParse(originAndId[1], NumberStyles.None, CultureInfo.InvariantCulture, out id)\n ? new IntId<T> { Id = id, Origin = originAndId[0] }\n : null;\n }\n\n /// <summary>\n /// The model instance identifier for the model object that this <see cref=\"ModelIdBase{T}\"/> refers to.\n /// Typically, this is a database key, file name, or some other unique identifier.\n /// </summary>\n /// <typeparam name=\"TKeyDataType\">The expected data type of the identifier.</typeparam>\n /// <returns>The unique key as the data type specified.</returns>\n public override TKeyDataType GetKey<TKeyDataType>()\n {\n return (TKeyDataType)Convert.ChangeType(this.Id, typeof(TKeyDataType), CultureInfo.InvariantCulture);\n }\n}\n</code></pre>\n\n<p>Your interface for entities would then be defined as:</p>\n\n<pre><code>public interface IEntity<T> where T : class, IEntity<T>\n{\n IModelId<T> Id { get; set; }\n U CreateEmpty<U>() where U : class,IEntity<T>;\n bool EntityEquals(IEntity<T> entity);\n}\n</code></pre>\n\n<p>Your DAL would be able to set the Id property as such (using the <code>Tag</code> class):</p>\n\n<pre><code>public class Tag : IEntity<Tag>\n{\n public IModelId<Tag> Id { get; set; }\n // Name is a natural key\n public string Name { get; set; }\n\n public T CreateEmpty<T>() where T : class, IEntity<Tag>\n {\n return new Tag() as T;\n }\n\n public bool EntityEquals(IEntity<Tag> entity)\n {\n var e = entity as Tag;\n return e != null && Name == e.Name;\n }\n}\n</code></pre>\n\n<p>The setting code (obviously not real):</p>\n\n<pre><code>Tag tag = new Tag();\n\ntag.Id = new IntId<Tag> { Id = 42 };\nConsole.WriteLine(tag.Id.GetKey<int>());\n</code></pre>\n\n<p>Your helper classes would need some rework as well to handle that. Now, all this being said and done, I'm not sure how Entity Framework would jibe with this notion without a bunch of help.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T17:08:56.507",
"Id": "7277",
"ParentId": "6107",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-16T23:06:54.483",
"Id": "6107",
"Score": "5",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Entity Framework Code First Data Updater"
}
|
6107
|
<p>I am periodically getting tweets, formatting them, and storing them into the database. Now the line of code I use for this is an awful lot. I was wondering if this could be improved.</p>
<pre><code>// This is the wordpress way of getting a json object
// Wordpress will determine how the data is going to
// be fetched looking at what PHP functions are
// enabled for the user, wget, curl, etc.
$json_body = wp_remote_retrieve_body(
wp_remote_get(
'http://twitter.com/statuses/user_timeline/'.$options['username'].'.json?count='.$options['count'] ) );
$tweet = json_decode( $json_body, true );
for( $i = 0; $i < $options['count']; $i++ ){
$latestTweet = htmlentities($tweet[$i]['text'], ENT_QUOTES);
$latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
$latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
// This array $data will be stored to the DB
// I will use the *serialize()* function for this.
$data[] = array( 'text' => $latestTweet, 'time' => timespan( $tweet[$i]['created_at'] ) );
}
function timespan( $a )
{
//get current timestampt
$b = strtotime("now");
//get timestamp when tweet created
$c = strtotime($a);
//get difference
$d = $b - $c;
//calculate different time values
$minute = 60;
$hour = $minute * 60;
$day = $hour * 24;
$week = $day * 7;
if(is_numeric($d) && $d > 0) {
//if less then 3 seconds
if($d < 3) return "right now";
//if less then minute
if($d < $minute) return floor($d) . " seconds ago";
//if less then 2 minutes
if($d < $minute * 2) return "about 1 minute ago";
//if less then hour
if($d < $hour) return floor($d / $minute) . " minutes ago";
//if less then 2 hours
if($d < $hour * 2) return "about 1 hour ago";
//if less then day
if($d < $day) return floor($d / $hour) . " hours ago";
//if more then day, but less then 2 days
if($d > $day && $d < $day * 2) return "yesterday";
//if less then year
if($d < $day * 365) return floor($d / $day) . " days ago";
//else return more than a year
return "over a year ago";
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>wp_remote_get(\n 'http://twitter.com/statuses/user_timeline/' \n . $options['username'].'.json?count='.$options['count'] ) \n</code></pre>\n\n<p>I'd use at least a local variable which stores the url:</p>\n\n<pre><code>$url = 'http://twitter.com/statuses/user_timeline/' . \n $options['username'] . '.json?count=' .$options['count'];\nwp_remote_get($url);\n</code></pre>\n\n<p>A function would be more better. It makes the code easier to read.</p>\n\n<hr>\n\n<p>Use longer variable names to avoid comments:</p>\n\n<pre><code>function timespan($create_time_input)\n{\n $current_timestamp = strtotime(\"now\");\n $create_time = strtotime($create_time_input);\n $diff_seconds = $current_timestamp - $create_time;\n\n $one_minute = 60;\n $one_hour = $one_minute * 60;\n $one_day = $one_hour * 24;\n $one_week = $day * 7;\n\n if(is_numeric($d) && $d > 0) {\n if ($diff_seconds < 3) {\n return \"right now\";\n }\n if ($diff_seconds < $one_minute) {\n return floor($diff_seconds) . \" seconds ago\";\n }\n...\n</code></pre>\n\n<p>Now the code itself says what the comments said before.</p>\n\n<hr>\n\n<p>Unnecessary <code>floor</code>:</p>\n\n<pre><code>if($d < $minute) return floor($d) . \" seconds ago\";\n</code></pre>\n\n<p><code>$d</code> looks an integer, so <code>floor</code> is unnecessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:28:15.997",
"Id": "9483",
"Score": "1",
"body": "Glad you took the time to comment here. Point one I am going to use, it does make it all a little more readable when different variables are used. I will also change the names, gives a better look. Will also remove the floor method. Too bad no comments about the working of the script itself. The preg_replace and time function are really bugging me. Thanks for the readability pointers. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T12:32:46.663",
"Id": "9497",
"Score": "0",
"body": "You are welcome :) Yes, the `preg_replace` code is not an easy task, it's worth to extract it to a separate function at least."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T13:54:46.277",
"Id": "6119",
"ParentId": "6109",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6119",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T01:37:05.187",
"Id": "6109",
"Score": "2",
"Tags": [
"php",
"datetime",
"json",
"twitter"
],
"Title": "Fetching / formatting / storing tweets to my database"
}
|
6109
|
<p>I need to get some scripts from the different social networking site and cache them. I want the function to be asynchronous, and non-blocking.</p>
<p>I have settled with a script, but I am not really sure if it is not overly complicated to do the job. </p>
<p>I did replace a normal <code>for</code> loop, and this method is much faster. I do not know why, but it just is.</p>
<pre><code>// Cached scritps
var cachedScriptPromises = {};
// Location of the scripts
var Scripts : {
twitter : '//platform.twitter.com/widgets.js',
facebook : 'http://static.ak.fbcdn.net/connect.php/js/FB.Share',
googleplus : 'https://apis.google.com/js/plusone.js',
linkedin : 'http://platform.linkedin.com/in.js'
};
// When the button is clicked all the scripts
// are loaded. The conainers are already
// on the website. They will be filled
// as soon as the script is loaded.
jQuery('a.share-link').click(function(){
for( var script in Scripts ){
jQuery.cachedGetScript( Scripts[script] );
}
});
// Function that get and caches the scripts
jQuery.cachedGetScript = function( script ) {
if ( !cachedScriptPromises[ script ] ) {
cachedScriptPromises[ script ] = jQuery.Deferred(function( defer ) {
jQuery.getScript( script ).then( defer.resolve, defer.reject );
}).promise();
}
return cachedScriptPromises[ script ];
};
</code></pre>
<p>Eventually this function can be expanded by adding some before and after actions. The thing is that the files are loaded so quickly that I have removed these features, but I am planning to do this as soon as the project becomes bigger.</p>
<p>Does anyone have any suggestions on making this better? Maybe some adjustments to the code, or go a complete other way with this.</p>
|
[] |
[
{
"body": "<p>I believe you don't need to use jquery deferred objects for this task. Just use script tags with sources - they will be downloaded in parallel from CDNs (try to use CDN, its always a good idea). The amount of parallel requests will be limited by browser restrictions.</p>\n\n<p>Since your code just replaces default browser technique, for more sophisticated features (like dependent components, libraries that you really want to defer, because they are not used until some action on the page), use</p>\n\n<ul>\n<li><a href=\"http://jsload.net/\" rel=\"nofollow\">http://jsload.net/</a></li>\n<li><a href=\"http://developer.yahoo.com/yui/get/\" rel=\"nofollow\">http://developer.yahoo.com/yui/get/</a></li>\n<li>deferred objects as you did</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T23:21:46.947",
"Id": "9482",
"Score": "0",
"body": "I do not understand why using another library would be better. I am trying to minimize the amount of libraries I load on init. I already use jQuery, I think that is more than enough. I am not going to load another YUI or jsload library. As for the CDN, the files are already on CDN's, they files are not downloaded from my server, or am I missing something here. Can you point out some benefits of using another library ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T15:14:34.183",
"Id": "9501",
"Score": "0",
"body": "Just as I said, I did not see in the code anything with regards to dependencies of one library on another. If you need it, you will create the whole jsload-like infrastructure yourself. If you don't, you don't need script to load scripts, just load them through <script> tags.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T07:26:22.493",
"Id": "9518",
"Score": "0",
"body": "Ah after a long search and read I finally understand where you are driving at. It is about non-blocking loading of external files. It could also be done with just native javascript, without any library at all. I will read a little more about this, it looks like a good option. Thank for the suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T17:49:06.417",
"Id": "9583",
"Score": "0",
"body": "Glad I could help and sorry I couldn't get back to you with more explanations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-25T00:20:52.417",
"Id": "103931",
"Score": "0",
"body": "Nice read for async script loading https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T22:46:04.520",
"Id": "6131",
"ParentId": "6110",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T03:31:49.497",
"Id": "6110",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"asynchronous",
"dynamic-loading"
],
"Title": "Loading JavaScript files asynchronously"
}
|
6110
|
<p>I've been away from PHP for at least 5 years and I'm just starting to look into it again. I have a set of functions I created and used for database access and I'm wondering if they are still good to use.</p>
<pre><code><?php
//
// A group of database function to hide any errors that may occur and
// allow for some form of fallback. If dbConnect() fails for any reason
// an error is displayed on the page, all other functions return empty
// values. For example dbSQL() will return an empty recordset. Pages will
// display the error once but still function to some degree.
//
$dbConnection = false;
if (empty($dbType))
{
$dbType = "MYSQL";
}
// INPUTS: $type -- The type of database that is going to be used
// MYSQL, MSSQL
// OUTPUTS: None
//
// EXAMPLE: dbSetType("MYSQL");
function dbSetType($type)
{
global $dbType;
$dbType=$type;
}
// INPUTS: NONE
// OUTPUTS: true if the database API for PHP is installed false if no
//
// EXAMPLE: if(!dbOK()) { print "Error"; }
function dbOK()
{
global $dbType;
if($dbType == "MYSQL")
{
if(function_exists('mysql_connect'))
{
return true;
}
return false;
}
elseif ($dbType == "MSSQL")
{
if(function_exists('mssql_connect'))
{
return true;
}
return false;
}
return false;
}
// INPUTS: $server ---- Server name, "localhost" if same server as web server
// $database -- The database name to use
// $username -- Username to connect to $server with
// $password -- Password of the user
// OUTPUTS: None
//
// EXAMPLE: dbConnect("localhost", "test", "root", "");
function dbConnect ($server, $database, $username, $password)
{
global $dbType;
global $dbConnection;
if($dbType == "MYSQL")
{
if (dbOK())
{
$dbConnection = mysql_connect ($server, $username, $password);
if (!$dbConnection)
{
print "<h1>Can not connect to ".$server." with user ".$username."</h1>";
}
else
{
$db_select = mysql_select_db ($database);
if (!$db_select)
{
print "<h1>Database ".$database." does not exist</h1>";
}
}
}
else
{
print "<h1>mySQL module is not installed</h1>";
}
}
elseif ($dbType == "MSSQL")
{
if (dbOK())
{
$dbConnection = mssql_connect ($server, $username, $password);
if (!$dbConnection)
{
print "<h1>Can not connect to ".$server." with user ".$username."</h1>";
}
else
{
$db_select = mssql_select_db ($database);
if (!$db_select)
{
print "<h1>Database ".$database." does not exist</h1>";
}
}
}
else
{
print "<h1>MSSQL module is not installed</h1>";
}
}
}
// Internal function should never be called outside of the dbSQL() function.
// This function returns the Nth parameter passed into dbSQL during the
// replacement of the $1, $2, $3, etc. in the $sql string.
function dbSQL__callback($at)
{
global $dbSQL__parameters;
return $dbSQL__parameters[$at[1]-1];
}
// INPUTS: $sql --------- A SQL statment with $// to be replace by cleaned data
// $parameters -- An array of unclean data to be inserted into the SQL
// OUTPUTS: A recordset resulting from the SQL statment if approprate, false on
// error
//
// EXAMPLE: dbSQL("SELECT * FROM t WHERE col1=$1 AND col2=$2", array(1, "hi"));
function dbSQL($sql, $parameters = array(), $debug = false)
{
global $dbType;
global $dbConnection;
global $dbSQL__parameters;
if (dbOK())
{
if ($dbConnection)
{
foreach ($parameters as $k=>$v)
{
$v = trim($v);
if (is_int($v))
{
$parameters[$k] = $v;
}
else
{
if (is_null($v))
{
$parameters[$k] = "'BLANK'";
}
else
{
if (get_magic_quotes_gpc())
{
$v = stripslashes($v);
}
if ($dbType == "MYSQL")
{
$parameters[$k] = "'".mysql_real_escape_string($v)."'";
}
elseif ($dbType == "MSSQL")
{
$parameters[$k] = "'".mssql_escape_string($v)."'";
}
}
}
}
$dbSQL__parameters = $parameters;
$safeSQL = preg_replace_callback('/\$([0-9]+)/', 'dbSQL__callback', $sql);
if ($debug == true)
{
print "<p>SQL: ".$safeSQL."</p><br />";
}
if ($dbType == "MYSQL")
{
$ret = mysql_query($safeSQL, $dbConnection) or die(mysql_error());
}
elseif ($dbType="MSSQL")
{
$ret = mssql_query($safeSQL, $dbConnection) or die(mssql_get_last_message());
}
return $ret;
}
}
return false;
}
// INPUTS: $recordset -- A recordset as returned by dbSQL()
// OUTPUTS: Number of rows in the recordset
//
// EXAMPLE: $rows = dbRecordTotalRows($rs);
function dbRecordTotalRows($recordset)
{
global $dbType;
global $dbConnection;
if (dbOK())
{
if ($dbConnection)
{
if ($dbType == "MYSQL")
{
return mysql_num_rows($recordset);
}
elseif($dbType == "MSSQL")
{
return mssql_num_rows($recordset);
}
}
}
return 0;
}
// INPUTS: $recordset -- A recordset as returned by dbSQL()
// OUTPUTS: None
//
// EXAMPLE: dbRecordNextRow($rs);
function dbRecordNextRow($recordset)
{
global $dbConnection;
if (dbOK())
{
if ($dbConnection)
{
$recordset->MoveNext();
}
}
}
// INPUTS: $recordset -- A recordset as returned by dbSQL()
// OUTPUTS: Array of key=value pair for the current row, false if
// past last row of recordset
//
// EXAMPLE: $row = dbRecordGetRow($rs);
function dbRecordGetRow($recordset)
{
global $dbType;
global $dbConnection;
if (dbOK())
{
if ($dbConnection)
{
if ($dbType == "MYSQL")
{
$row = mysql_fetch_array($recordset);
}
elseif ($dbType == "MSSQL")
{
$row = mssql_fetch_array($recordset);
}
return $row;
}
}
return null;
}
// INPUTS: $row -------- A row as returned by dbRecordGetRow()
// $fieldname -- The name of the field whos value is returned.
// OUTPUTS: Value in the requested field
//
// EXAMPLE: $value = dbRowGetField($row, "id");
function dbRowGetField($row, $fieldname)
{
if (dbOK())
{
return stripslashes($row[$fieldname]);
}
return null;
}
function dbGetLastInsertID()
{
global $dbType;
if ($dbType == "MSSQL")
{
$sql="select SCOPE_IDENTITY() AS last_insert_id";
$parms = Array();
$ret = dbSQL($sql, $parms);
$row = dbRecordGetRow($ret);
return dbRowGetField($row, "last_insert_id");
}
return -1;
}
// INPUTS: None
// OUTPUTS: None
//
// EXAMPLE: dbDisconnect();
function dbDisconnect()
{
global $dbType;
global $dbConnection;
if (dbOK())
{
if ($dbConnection)
{
if ($dbType == "MYSQL")
{
mysql_close($dbConnection);
}
elseif ($dbType == "MSSQL")
{
mssql_close($dbConnection);
}
$dbConnection = false;
}
}
}
// INPUTS: $string_to_escape -- This is the unsafe string to pass to the mssql database
// OUTPUTS: A safe string that is ok to pass to a mssql database
//
// EXAMPLE: mssql_escape_string("Not 's'a'f'e' String");
function mssql_escape_string($string_to_escape)
{
$replaced_string = str_replace("'","''",$string_to_escape);
$replaced_string = str_replace("%","[%]",$replaced_string);
$replaced_string = str_replace("_","[_]",$replaced_string);
return $replaced_string;
}
/* End Of File */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T12:05:44.003",
"Id": "9496",
"Score": "0",
"body": "on a side note, in dbConnect you nest checks, ifs, and prints. It's more readable to do it this way `if(!check) {print \"stuff\"; exit();}`, and put your \"all ok\" code under the error checks. hence you have a nice flat readable code, and not a nested spagetti"
}
] |
[
{
"body": "<p>A general OOP advice: use the <a href=\"http://www.oodesign.com/factory-pattern.html\" rel=\"nofollow\">factory pattern</a> and move MySQL related codes to a <code>MySqlDatabase</code>class and MSSQL related codes to an <code>MsSqlDatabase</code> class. In this way you'll have two separate classes (one for MySQL and one for MSSQL) instead of the <code>if-elseif</code> statements in (almost) every method. You will also need a common interface which both classes implement.</p>\n\n<pre><code>interface Database {\n public function dbOK();\n public function dbRecordTotalRows($recordset);\n public dbDisconnect();\n ...\n}\n</code></pre>\n\n<p>You could put your common methods (usually the ones which don't contain the <code>if-elseif</code> statements) to a common abstract base class:</p>\n\n<pre><code>class AbstractDatabase implements Database {\n public function dbGetLastInsertID();\n ...\n}\n</code></pre>\n\n<p>Then the two concrete implementations:</p>\n\n<pre><code>class MsSqlDatabase extends AbstractDatabase {\n ...\n}\n\nclass MySqlDatabase extends AbstractDatabase {\n ...\n}\n</code></pre>\n\n<p>And finally the factory method:</p>\n\n<pre><code>function createDatabase($type) {\n if ($type == \"MSSQL\") {\n return new MsSqlDatabase();\n } else if ($type == \"MYSQL\") {\n return new MySqlDatabase();\n } else {\n throw new Exception('Invalid type: ' . $type);\n }\n}\n</code></pre>\n\n<p>If you use this pattern you could easily create new implementations (you only need for example a new <code>PostgreSqlDatabase</code> class and a new <code>else if</code> statement in the factory method) and you get rid of a lot of error-prone <code>if-elseif</code> statements.</p>\n\n<hr>\n\n<p>One small thing:</p>\n\n<pre><code>function dbOK()\n{\n if($dbType == \"MYSQL\") { ... }\n elseif ($dbType == \"MSSQL\") { ... }\n return false;\n}\n</code></pre>\n\n<p>In similar cases instead of the last line (<code>return false</code>) log the error and throw an exception to the user or call a <code>die()</code> since it's an internal error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T09:56:01.270",
"Id": "6114",
"ParentId": "6111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6114",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T05:58:14.557",
"Id": "6111",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "Database accessor functions"
}
|
6111
|
<p>Can someone look over this <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a> implementation? It seems almost too easy.</p>
<p>Rather than maintaining a seperate <code>bit[]</code> to track prime/not prime, I'm just removing the noncandidates from the collection completely on each iteration.</p>
<p><strong>Pseudocode</strong></p>
<pre><code>LIST = 2...n
set M = 1
while M < sqrt(n)
set M = next number in LIST > M
remove all multiples of M (excluding M itself) from LIST
</code></pre>
<p><strong>C#</strong></p>
<pre><code>int cur = 1, total = 1000;
var pc = Enumerable.Range(2, total).ToList();
while(cur <= Math.Sqrt(total))
{
cur = pc.First(i => i > cur);
pc.RemoveAll(i => i != cur && i % cur == 0);
}
Console.WriteLine(pc.Max());
</code></pre>
<p>It just seems a bit too easy. Results seem right though. In <a href="http://en.wikipedia.org/wiki/LINQPad" rel="nofollow">LINQPad</a> 4</p>
<ul>
<li>Runs <code>total = 100000;</code> in 0.008 secs</li>
<li>Runs <code>total = 1000000;</code> in 0.141 secs</li>
<li>Runs <code>total = 10000000;</code> in 2.973 secs</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T17:28:27.637",
"Id": "9472",
"Score": "2",
"body": "Nobody mentioned this in their answers, but `Math.Sqrt()` isn't the quickest of functions, and the return value used here is effectively constant. Remove it from the comparison, and assign the results to a local variable instead (which can be used in the comparison). I do _not_ believe the compiler is smart enough to catch this... it wasn't when my flatmate tried this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T21:43:31.993",
"Id": "9476",
"Score": "1",
"body": "@X-Zero: Yes, the sqrt calculation should naturally be moved out of the loop. I already tried that, and it makes very little difference for the performance, so I just went for simplicity/close to original code in the answer."
}
] |
[
{
"body": "<p><strong>update:</strong> as tested and explained by @Guffa and @EoinCampbell, this is actually <strong>much slower</strong>.</p>\n\n<p>The benefits of a <code>HashSet</code> are mainly in access speed by index.<br>\nSince the algorithm never even accesses the list by index, the <code>Hashset</code> will merely introduce additional overhead with the hashing and storing of the internal structure for fast access.</p>\n\n<hr>\n\n<p>I would user <code>HashSet<int></code> instead of <code>List<int></code>.</p>\n\n<p>The only change needed would be in the while, <code>.RemoveWhere()</code> instead of <code>.RemoveAll()</code>: <a href=\"http://msdn.microsoft.com/en-us/library/bb361254.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb361254.aspx</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T14:27:31.190",
"Id": "9463",
"Score": "0",
"body": "I tested that, and it takes twice as long as using a list..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T14:41:56.900",
"Id": "9464",
"Score": "0",
"body": "Hmm... interesting but it actually makes it significantly slower...\n\nfor 10000, 100000, 1000000 the times were\n\nList = 8ms, 140ms, 3s\nHashSet = 30ms, 700ms , 15s"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T17:09:11.177",
"Id": "9470",
"Score": "0",
"body": "I did not test it (#CaptainObvious) \n Wow, it takes **so** much longer?!? My universe of coding assumptions is destroyed. :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T22:39:45.367",
"Id": "9479",
"Score": "0",
"body": "@ANeves: As you are looping the items in the hash set to remove them and not removing them by value, you don't get any benefit from using a hash set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T13:54:40.547",
"Id": "9499",
"Score": "0",
"body": "@Guffa ... of course, I see now. Never even accessing them by value (get/set/remove), we are actually hashing all of that for nothing. Oh, I should edit the answer. [does]"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T13:42:25.503",
"Id": "6118",
"ParentId": "6115",
"Score": "1"
}
},
{
"body": "<p>Yes, it works, but it's slow.</p>\n\n<p>I compared it to this:</p>\n\n<pre><code>bool[] notPrime = new bool[total];\nnotPrime[0] = true;\nnotPrime[1] = true;\nfor (int i = 2; i <= Math.Sqrt(notPrime.Length); i++) {\n if (!notPrime[i]) {\n for (int j = i * 2; j < notPrime.Length; j += i) {\n notPrime[j] = true;\n }\n }\n}\n</code></pre>\n\n<p>(I used <code>Enumerable.Range(2, total - 2)</code> in the Linq code to make it produce the numbers 2 to 99999 rather than 2 to 100001.)</p>\n\n<p>For total = 100000, average for 100 executions:</p>\n\n<pre><code>Linq 27.696966 ms., 0.280000 collections\nArray 0.708616 ms., 0.030000 collections\n</code></pre>\n\n<p>So, it takes a lot of time, and does more garbage collections.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-27T10:13:26.663",
"Id": "254959",
"Score": "0",
"body": "one question - wouln't it be faster to skip the even values? after you had `i=2` you can skip `4,6,8,10,..` by repalcing `i++` with `i+=2` from 3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-27T12:00:57.953",
"Id": "254984",
"Score": "0",
"body": "@fubo: It might be faster, but it's not certain as the code gets more complicated. After the first iteration all the even items in the array has already been set, so all those will be caught in the `if` statement in the loop. Actually, the principle of the sieve is to weed out all multiples but for all numbers, not just two."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-27T12:09:46.067",
"Id": "254986",
"Score": "0",
"body": "I've tried it and there was a minor improvement - however how about changing `bool[]` to `System.Collections.BitArray` ? .NET uses one `byte` to store a `bool`ean value. I've tried `total = 1.000.000.000`and have a memory usage of 120MB with `System.Collections.BitArray` and 976MB with `bool[]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-27T13:19:21.643",
"Id": "254997",
"Score": "1",
"body": "@fubo: Accessing the data in the `BitArray` is slower, but fewer memory cache misses will make it faster, so that could go either way. If it uses too much memory you can just do multiple sieves. For each sieve you just initialise it by masking out the multiples of the prime numbers that you got this far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T23:07:00.913",
"Id": "381111",
"Score": "0",
"body": "Looking at the implementation in this answer vs. the sudo code. The sudo code says j should start at i^2, but this code starts at i*2. Should the second for loop be this?\n for (int j = i * i; j < notPrime.Length; j += i)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T14:20:51.993",
"Id": "6120",
"ParentId": "6115",
"Score": "10"
}
},
{
"body": "<p>You're accessing modified closures in your LINQ statements, so I'd copy them to locals.</p>\n\n<pre><code> var cur = 1;\n const int Total = 1000;\n var pc = Enumerable.Range(2, Total).ToList();\n\n while (cur <= Math.Sqrt(Total))\n {\n var cur1 = cur;\n var cur2 = pc.First(i => i > cur1);\n\n pc.RemoveAll(i => i != cur2 && i % cur2 == 0);\n cur = cur2;\n }\n\n Console.WriteLine(pc.Max());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T17:08:17.840",
"Id": "9469",
"Score": "0",
"body": "Could someone run speed tests on this? [very curious]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T17:24:12.320",
"Id": "9471",
"Score": "1",
"body": "Negligible on my test system. For 10000000, the average difference over 10 runs was 26ms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T10:38:26.427",
"Id": "9495",
"Score": "0",
"body": "Wouldn't declaring `cur1` and `cur2` properly outside the while loop improve memory usage?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T12:34:38.413",
"Id": "9498",
"Score": "1",
"body": "No. They're local variables. Matters not where you declare them."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T15:52:10.923",
"Id": "6121",
"ParentId": "6115",
"Score": "1"
}
},
{
"body": "<p>I found an answer on Stack Overflow a few days ago. I adapted it a bit to make it more parallel and easier to read.</p>\n\n<p>I might have made a mistake. I tested it in my computer: Core i7 Second Gen (3GHz) with 12GB of RAM.</p>\n\n<p>It took a few seconds to solve most of the numbers less than 50,000,000. However, it took around 6:32 seconds to solve 100,000,000. It took around 47 mins to solve 500,000,000. It crashed 11 hours after solving 1.5 billion. </p>\n\n<pre><code>private static void GetPrimeNumbers(int max)\n{\n var allPossibleNumbers = Enumerable.Range(3, max-3);\n var possiblePrime = allPossibleNumbers\n .AsParallel()\n .Where(n => Enumerable.Range(2, (int)Math.Sqrt(n))\n .All(i => n % i != 0)\n )\n ;\n possiblePrime\n .ToArray()\n .AsParallel()\n .Dump()\n ;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T14:36:41.283",
"Id": "24712",
"ParentId": "6115",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6120",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T11:53:15.357",
"Id": "6115",
"Score": "8",
"Tags": [
"c#",
"linq",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes in C# with LINQ"
}
|
6115
|
<p>I need to write a class to batch <code>Order</code> objects from 3 calling components running on 3 separate threads. The 3 calling components will call the <code>Batcher</code> class at the same time (within a second of each other), but to handle clock issues and thread interleaving, the method should wait for a maximum of 5 seconds for the 3 calls. If for any reason only 2 calls make it, the batcher should continue after the 5-second timeout and batch what it has. The <code>Batcher</code> class must appear synchronized to the calling components.</p>
<p>I have written a class and it seems to work but I'm new to this and I'd appreciate it if someone could review my class.</p>
<pre><code>public sealed class Batcher
{
private readonly object _syncLock = new object();
private readonly Timer _timer;
private bool _timerSet = false;
private volatile int _callCount = 0;
private const int ExecuteImmediatelyCallCount = 3;
private readonly ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
private readonly List<Order> _orders = new List<Order>();
public Batcher()
{
_timer = new Timer(Batch, null, Timeout.Infinite, Timeout.Infinite);
}
public void TryBatch(IEnumerable<Order> orders)
{
lock (_syncLock)
{
_orders.AddRange(orders);
if(!_timerSet)
{
_timerSet = true;
_timer.Change(5000, Timeout.Infinite);
}
_callCount ++;
}
if(_callCount >= ExecuteImmediatelyCallCount)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
Batch(null);
}
_manualResetEvent.WaitOne();
}
private void Batch(object state)
{
lock (_syncLock)
{
if(_orders.Count > 0)
{
RemoteService.Send(_orders);
_orders.Clear();
_manualResetEvent.Reset();
}
_callCount = 0;
}
}
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T16:16:06.337",
"Id": "9468",
"Score": "0",
"body": "Take a look at the tasks parallel Library"
}
] |
[
{
"body": "<p>Not sure what is behind the requirement of 5 seconds, but from the top level (please comment to answer the items marked as warnings):</p>\n\n<pre><code>public sealed class Batcher\n {\n private readonly object _syncLock = new object();\n private readonly Timer _timer;\n private bool _timerSet = false;\n private volatile int _callCount = 0;\n private const int ExecuteImmediatelyCallCount = 3;\n private readonly ManualResetEvent _manualResetEvent = new ManualResetEvent(false);\n private readonly List<Order> _orders = new List<Order>();\n\n public Batcher()\n {\n _timer = new Timer(Batch, null, Timeout.Infinite, Timeout.Infinite);\n }\n#warning What is the \"orders\" parameter for\n public void TryBatch(IEnumerable<Order> orders)\n {\n#warning don't see a point to lock this operation\n lock (_syncLock)\n {\n _orders.AddRange(orders);\n if(!_timerSet)\n {\n _timerSet = true;\n _timer.Change(5000, Timeout.Infinite);\n }\n _callCount ++;\n }\n#warning not thread safe\n if(_callCount >= ExecuteImmediatelyCallCount)\n {\n _timer.Change(Timeout.Infinite, Timeout.Infinite);\n Batch(null);\n }\n#warning what is this for?\n _manualResetEvent.WaitOne();\n }\n\n private void Batch(object state)\n {\n lock (_syncLock)\n {\n if(_orders.Count > 0)\n {\n#warning not thread safe\n RemoteService.Send(_orders);\n _orders.Clear();\n _manualResetEvent.Reset();\n }\n _callCount = 0;\n }\n }\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T22:32:55.347",
"Id": "6130",
"ParentId": "6123",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T16:14:47.413",
"Id": "6123",
"Score": "1",
"Tags": [
"c#",
"multithreading"
],
"Title": "Multithreaded batching class"
}
|
6123
|
<h2>The Problem</h2>
<p>I found myself needing an instance of an <code>IObjectContext</code> interface that should never be null, but wanting to delay instantiation until after some required resources have been loaded.</p>
<p>I decided to approach this with <a href="http://msdn.microsoft.com/en-us/library/dd642331.aspx" rel="nofollow"><code>Lazy<T></code></a>, but quickly ran into an issue -- I also require an <a href="http://msdn.microsoft.com/en-us/library/dd642094.aspx" rel="nofollow"><code>IObjectSet<TEntity></code></a> that is never null and lazy instantiated. The problem is this:</p>
<pre><code>// lazyObjectSet needs to be created directly after lazyContext, but I need to
// delay instantiating both. The desired factory method exists on lazyContext,
// but accessing lazyContext.Value instantiates context before it is needed:
//
var lazyObjectSet = new Lazy<IObjectSet<TEntity>>(lazyContext.Value.FactoryMethodName);
</code></pre>
<hr>
<h2>My Solution</h2>
<p>I would like suggestions for improvements on my approach, or alternative approaches to the problem.</p>
<pre><code>public static class LazyExtensions {
private class LazyFactory<T, TResult> where TResult : class {
private readonly Lazy<T> _dependency;
private readonly MethodInfo _factory;
public LazyFactory(Lazy<T> lazyDependency, MethodInfo lazyFactory) {
// Argument null checks omitted for brevity
Contract.Requires(typeof(TResult).Equals(lazyFactory.ReturnType));
Contract.Requires(lazyFactory.GetParameters().Count() == 0);
_factory = lazyFactory;
_dependency = lazyDependency;
}
public TResult Invoke() {
return (TResult) _factory.Invoke(_dependency.Value, null);
}
}
public static Func<TOut> GetLazyFactory<TIn, TOut>(
Lazy<TIn> dependency, MethodInfo factoryInfo) where TOut : class {
return new LazyFactory<TIn, TOut>(dependency, factoryInfo).Invoke;
}
}
</code></pre>
<p>Now I can use <code>GetLazyFactory()</code> to write the following, and the context should not be instantiated until <code>lazyObjectSet.Value</code> is accessed:</p>
<pre><code>var lazyFactory = LazyExtensions.GetLazyFactory<IObjectContext, IObjectSet<TEntity>>(
new Lazy<IObjectContext>(factory.Create),
typeof (IObjectContext).GetMethod("ObjectSet"));
var lazyObjectSet = new Lazy<IObjectSet<TEntity>>(lazyFactory);
</code></pre>
<p>How can this be improved, and is there a better way of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T04:36:42.197",
"Id": "9491",
"Score": "0",
"body": "A better question might be: is using reflection the only solution?"
}
] |
[
{
"body": "<p>In conjunction with the rest of the code, the following line exhibits a bug:</p>\n\n<pre><code>Contract.Requires(typeof(TResult).Equals(lazyFactory.ReturnType));\n</code></pre>\n\n<p>The problem is that my <code>IObjectContext.ObjectSet()</code> method has the generic return type <code>IObjectSet<TEntity></code>, and <code>lazyFactory</code> doesn't have type information for <code>TEntity</code>.</p>\n\n<p>Specifically, the type parameter for <code>lazyFactory</code> is unknown because it's obtained using <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx\" rel=\"nofollow\"><code>GetMethod()</code></a>. As a result, <a href=\"http://msdn.microsoft.com/en-us/library/system.type.equals.aspx\" rel=\"nofollow\"><code>Equals()</code></a> returns false and the constraint fails with an exception. </p>\n\n<p>I solved the problem by modifying <code>GetLazyFactory</code> to accept a method name string and obtain the <code>MethodInfo</code> itself, calling <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx\" rel=\"nofollow\"><code>MakeGenericMethod()</code></a> as necessary.</p>\n\n<pre><code>public static Func<TOut> GetLazyFactory<TIn, TOut>(Lazy<TIn> dependency, string factoryName)\n where TOut : class\n{\n Type outT = typeof(TOut); // Expected return type of factory method\n MethodInfo factoryMethodInfo = // Should return TOut\n typeof(TIn).GetMethod(factoryName); \n\n if(outT.IsGenericType)\n {\n // Get generic type argument of TOut, making sure exactly 1 exists.\n Type tParam = outT.GetSingleGenericArgument(); \n\n // We must specify the generic type or Type.Equals() will yield false.\n factoryMethodInfo = factoryMethodInfo.MakeGenericMethod(tParam);\n }\n return new LazyFactory<TIn, TOut>(dependency, factoryMethodInfo).Invoke;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-06T20:38:40.400",
"Id": "6574",
"ParentId": "6124",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6574",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T16:52:27.627",
"Id": "6124",
"Score": "4",
"Tags": [
"c#",
".net",
"design-patterns"
],
"Title": "Providing factory method to Lazy<T> when factory exists on another lazy instance?"
}
|
6124
|
<p>Could you suggest ways of making this more simple?</p>
<pre><code>/*
* Next write a function invert(x,p,n) that returns x with the n bits
* that begin at position p inverted, leaving the others unchange
*/
void printbits(unsigned x) {
size_t size_of_int = sizeof(int) << 3;
unsigned mask = 1;
int i = 0;
for(i = 1; i <= size_of_int; ++i, x >>= 1) {
((x & mask) == 0) ? printf("0") : printf("1");
((i & 3)==0) ? printf(" ") : printf("%s","");
}
printf("\n");
}
void invert(unsigned x, unsigned p, unsigned n) {
printbits(((~((((~(~0 << n) << p))) & x)) & (~(~0 << n) << p)) | (x & ~(~(~0 << n) << p)));
}
int main(int argc, char *argv[]) {
unsigned input=3082676239, begin=15, nbits=5;
invert(input, begin, nbits);
return(0);
}
</code></pre>
<p>Before mushing the parts together this is what I get in output:</p>
<blockquote>
<pre><code> x = 1111 0000 0001 0111 1011 1101 1110 1101
===================================================================
mask0 = 1111 0000 0001 0110 0000 1101 1110 1101
mask1 = 1111 1111 1111 1110 0100 1111 1111 1111
mask2 = 0000 0000 0000 0001 1111 0000 0000 0000
===================================================================
output = 1111 0000 0001 0110 0100 1101 1110 1101
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Maybe:</p>\n\n<pre><code>void invert2(unsigned x, unsigned p, unsigned n) {\n printbits((~(~0 << n) << p) ^ x);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T21:48:59.917",
"Id": "6128",
"ParentId": "6125",
"Score": "2"
}
},
{
"body": "<p>@palacsint's definitely provides an improvement, but I think we can do better still. I think I'd start from the fact that subtracting 1 from a number clears the least significant bit that was set, and sets all the less significant bits. If we start with a number that has only one bit set, that bit will be cleared, and all the less significant bits will be set. Based on that, getting a mask of N bits is pretty simple: take 1, shift it left N bits, and then subtract 1.</p>\n<p>For example, consider creating a 5-bit mask in a 16-bit number:</p>\n<pre><code>0000 0000 0000 0001 // 1\n0000 0000 0010 0000 // 1 << 5\n0000 0000 0001 1111 // (1<<5)-1\n</code></pre>\n<p>Once we have that, we can shift it left <code>p</code> bits to get it to the right position, and <code>xor</code> with the input:</p>\n<pre><code>unsigned invert(unsigned x, unsigned p, unsigned n) { \n unsigned mask = ((1u << n) - 1u) << p;\n return x ^ mask;\n}\n</code></pre>\n<p>A couple minor points:</p>\n<ol>\n<li>I've removed printing from <code>invert</code> -- IMO, printing the result should be separate.</li>\n<li>This requires that <code>n<size_of_int</code>.</li>\n</ol>\n<p>I think the printing can be simplified a bit as well. Although the "test for a multiple of 4" inside the loop <em>does</em> work, I think at least in this case a nested loop makes the intent clearer:</p>\n<pre><code>void print(unsigned x) { \n static const int group_size = 4;\n int group, j;\n\n for (group = 0; group < size_of_int / group_size; group++) {\n for (j=0; j<group_size; j++, x >>= 1)\n printf("%c", (x & 1) + '0');\n printf(" ");\n }\n}\n</code></pre>\n<p>Another possibility that might be worth considering would be a small lookup table to convert 4 bits at a time:</p>\n<pre><code>void print(unsigned x) { \n static const int group_size = 4;\n // inverted order because you're printing the LSB first.\n static const char *outputs[] = {\n "0000", "1000", "0100", "1100", "0010", "1010", "0110", "1110", \n "0001", "1001", "0101", "1101", "0011", "1011", "0111", "1111"\n };\n int group;\n\n for (group=0; group<size_of_int / group_size; group++, x >>= 4)\n printf("%s ", outputs[x & 0xf]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T09:34:08.630",
"Id": "9493",
"Score": "0",
"body": "+1 Jerry, I agree, your solution is much better and much more elaborated. To defend myself, my answer is only a quick note and it's still more simple than the one in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T15:21:02.043",
"Id": "9502",
"Score": "0",
"body": "@palacsint: Yup -- it's definitely an improvement, and in fairness, it seems pretty clear that the code in the question is the source of most of the obfuscation. My remark was intended mostly as saying that what you posted was a big improvement, but I thought it was possible to do even a little better still."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-18T06:04:35.603",
"Id": "6136",
"ParentId": "6125",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "6128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T21:11:56.253",
"Id": "6125",
"Score": "7",
"Tags": [
"c",
"bitwise"
],
"Title": "Print Bits Part II"
}
|
6125
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.