• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 08:14
CEST 14:14
KST 21:14
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
Team TLMC #5 - Finalists & Open Tournaments1[ASL20] Ro16 Preview Pt2: Turbulence10Classic Games #3: Rogue vs Serral at BlizzCon9[ASL20] Ro16 Preview Pt1: Ascent10Maestros of the Game: Week 1/Play-in Preview12
Community News
StarCraft II 5.0.15 PTR Patch Notes146BSL 2025 Warsaw LAN + Legends Showmatch2Weekly Cups (Sept 8-14): herO & MaxPax split cups4WardiTV TL Team Map Contest #5 Tournaments1SC4ALL $6,000 Open LAN in Philadelphia8
StarCraft 2
General
StarCraft II 5.0.15 PTR Patch Notes Why Storm Should NOT Be Nerfed – A Core Part of Pr #1: Maru - Greatest Players of All Time Team TLMC #5 - Finalists & Open Tournaments Team Liquid Map Contest #21 - Presented by Monster Energy
Tourneys
RSL: Revival, a new crowdfunded tournament series Stellar Fest KSL Week 80 StarCraft Evolution League (SC Evo Biweekly) SC2's Safe House 2 - October 18 & 19
Strategy
Custom Maps
External Content
Mutation # 491 Night Drive Mutation # 490 Masters of Midnight Mutation # 489 Bannable Offense Mutation # 488 What Goes Around
Brood War
General
Soulkey on ASL S20 ASL20 General Discussion BW General Discussion Diplomacy, Cosmonarchy Edition ASL TICKET LIVE help! :D
Tourneys
[ASL20] Ro16 Group D BSL 2025 Warsaw LAN + Legends Showmatch [ASL20] Ro16 Group C Small VOD Thread 2.0
Strategy
Simple Questions, Simple Answers Muta micro map competition Fighting Spirit mining rates [G] Mineral Boosting
Other Games
General Games
Stormgate/Frost Giant Megathread Path of Exile Borderlands 3 Nintendo Switch Thread General RTS Discussion Thread
Dota 2
Official 'what is Dota anymore' discussion LiquidDota to reintegrate into TL.net
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread
Community
General
US Politics Mega-thread The Big Programming Thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread UK Politics Mega-thread
Fan Clubs
The Happy Fan Club!
Media & Entertainment
Movie Discussion! [Manga] One Piece Anime Discussion Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion MLB/Baseball 2023
World Cup 2022
Tech Support
Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread High temperatures on bridge(s)
TL Community
BarCraft in Tokyo Japan for ASL Season5 Final The Automated Ban List
Blogs
Too Many LANs? Tournament Ov…
TrAiDoS
i'm really bored guys
Peanutsc
I <=> 9
KrillinFromwales
A very expensive lesson on ma…
Garnet
hello world
radishsoup
Lemme tell you a thing o…
JoinTheRain
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1583 users

The Big Programming Thread - Page 117

Forum Index > General Forum
Post a Reply
Prev 1 115 116 117 118 119 1031 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
tec27
Profile Blog Joined June 2004
United States3701 Posts
February 19 2012 15:15 GMT
#2321
On February 19 2012 18:36 BottleAbuser wrote:
My concern isn't so much with the code taking a lot of bandwidth, it's maintainability and readability.

For example, I have a page that serves as a drag & drop HTML editor. It takes a bunch of content from the DB and loads it into hidden divs, with a list of titles representing them, which are then made draggable. I have a few templates which have droppable zones, and are loaded into the editor area upon menu clicks. Saving edits is done with ajax.

With visual effects and all, this amounts to about 70 lines of code on the $.onload() function, each initializing something different, and something like 15 different function declarations that each do their own thing (showBusy(), hideBusy(), save(), initDroppable(), ...). Right now, I can make sense of it but the next person who comes along, or me in a few months, will have a bitch of a time navigating this whole "everything is in this one file here, hope you can read my English comments" deal.

I guess what I'm looking for is some way of logically dividing this stuff up so it's easier to look at. I don't have a problem with compiling everything into one file for production use, but I'd really like to have readable source.

(Also, I'm sure there has got to be a better way of displaying javascript code than what Eclipse does. I end up with lines that are rarely over 40 characters long, and so I end up with this column of code that uses 1/5 of what my widescreen offers and forces me to scroll like a madman when I'm looking for that one piece of code that does this or that.)

Ah, okay. Well, I actually started typing a response with that in mind, but then I figured that wasn't what you were asking

You should try to write stuff in a more modular style. What you're describing is what I had to deal with at work, where over the years we somehow ended up with a 3000 line 'utility.js' that is nothing more than random functions thrown everywhere. Now that I've gotten rid of that, I guess I can give you some tips on how to avoid that

1) Avoid global scope unless absolutely necessary. This includes functions. Its really easy in JavaScript to end up with everything hanging off window, and this *really bad* for maintainability. Instead, write your stuff as some sort of "class" (using whatever method you prefer) and use those objects to perform your task. You can even write jQuery plugins that utilize those classes, making everything easier.

2) Use closures for each module. (That is, surround your code with a (function() { ... })(); ). This makes it so you have to be extra-explicit in creating globals, and will make your life easier in the long run. While we're at it, this also means you can split each module up into a separate file, and programmatically compile them back together without problems.

3) Use jQuery events to your advantage (if you're using jQuery). Whether it means creating your own custom events or using the ones already built into the browser, you can often ease the modularization of your code by using events and handlers instead of calling the handler functions directly. For instance, at work we have this concept of choosing values for an input from a modal dialog. The old code would call a pre-defined function, and this function would handle setting the input value. Each page would re-define this function for its purposes. This sucked. So when I re-wrote it, I wrote a class specifically for dealing with dialogs, and whenever you go to close the dialog it emits a custom event with data about the value that was chosen (yes, jQuery can also emit events on objects, its super-useful ). Handlers subscribed to that event can either utilize the value information they just received, or preventDefault() and stop the dialog from even closing. And now I don't have to modify my dialog code at all to add new close handling functionality, and I don't have to throw more things into global scope.

4) Use JSHint extensively. I have a plugin for vim that lets me run JSHint on a file at the touch of a button, and it is wonderful. Highly necessary for pretty much any javascript project, imo.

If you want an example of a project that handles this stuff well, I'd look at jQuery-UI. Their widget stuff is pretty nice and a lot of the stuff I've written for my job is modeled after that. It makes it very easy to go from element -> javascript component or vice versa, which makes stuff really clean.
Can you jam with the console cowboys in cyberspace?
lolmlg
Profile Joined November 2011
619 Posts
February 19 2012 15:55 GMT
#2322
On February 18 2012 13:36 mmp wrote:
Show nested quote +
On February 17 2012 19:04 aksfjh wrote:
On February 17 2012 10:31 mmp wrote:
On February 17 2012 05:55 aksfjh wrote:
Not really a question, but a frustrating observation. I'm currently attemtping to teach myself C++, and it's going alright. However, when I browse problems on forums, I see a frustrating amount of, "I'm not going to help with your problem, just point out that line 7 out of 96 is bad coding practice! <insert 3 paragraph rant>." 75% of the time, they don't even tell you that their useless advice won't help you solve the problem. Ugh!

Your problems are boring. From the point of view of someone who knows the answer but isn't responding, a newbie is born every minute, so why should they waste their time doing your thinking for you? Read the fucking manual.

They also might not know the answer (most forums have a lot of bad answers), but want to say something anyway.

It's not necessarily my problem anyways. I'm not the one posting. Anyways, here's a good example:

Creating a program that requires a "while" or "do while" loop to gather a set of numbers. There is a number terminator (like -1). However, when you input a character or string instead of an int with the "cin" function, it spits out the previous prompt in a rapid infinite loop, which must be aborted. The actual solution to this problem relies on some very unintuitive programming, but without somebody teaching you, you'll try exception handling, "if" statements, etc. When looking for an answer to this issue, the #1 response was the improper use of "throw" from the submitted program. However, when he fixed that "issue," he still had the same cin problem as before.

Yeah that sounds terribly boring.

Those websites are designed to help people with their boring beginner problems. There's no other reason for StackOverflow to exist. There are a lot of guys on there who are really helpful and know their stuff, so it can be a great resource. But it's Yahoo Answers for programming. The people who leave dumb answers to questions do so because they simply don't know the answer. They don't know but they still want to demonstrate that they know something, so tell you to fix other parts of the code. Or that your whole approach was bad, even if it wasn't your approach in the first place.

It's pretty common. There are tons of responses where people say things like "why would you do that, you should do this instead" without answering the question, which just forces the poster to respond with all the reasons why they can't do that.

On February 17 2012 09:57 Pawsom wrote:
Show nested quote +
On February 17 2012 05:55 aksfjh wrote:
Not really a question, but a frustrating observation. I'm currently attemtping to teach myself C++, and it's going alright. However, when I browse problems on forums, I see a frustrating amount of, "I'm not going to help with your problem, just point out that line 7 out of 96 is bad coding practice! <insert 3 paragraph rant>." 75% of the time, they don't even tell you that their useless advice won't help you solve the problem. Ugh!



This is probably because most if not all of your problems can be solved with proper use of google.

You know what comes up on Google a lot of the time? Yeah, StackOverflow pages.

Icx
Profile Blog Joined November 2009
Belgium853 Posts
Last Edited: 2012-02-19 21:07:03
February 19 2012 20:39 GMT
#2323
Just posting in case anyone would be able to help me:

I'm trying to write a basic raycaster to make a wolfenstein3D like game (just basic testing code, this is just to make it work, and then go from there to write the actual final thing, so it's a bit messy).

But it's just kicking my ass like no other code has done before, and I'm just banging my head against the wall trying to fix it, usually I don't just post code, and say "hey help me", but in this case, there must be something that I'm not seeing, or something silly and I just can't find it.

The degrees are in the unit circle (0 degrees = right, 90 = up, 180 = left, etc).
The coordinate system, the usual screen coordinates (so the positive Y-axis going down).

Initialization:
+ Show Spoiler +



raycast::raycast(): m_playerFOV(ToRad(60)), m_PlayerViewAngle(ToRad(90)), m_PlayerHeight(BLOCK_DIM/2), m_PlayerPos(8*BLOCK_DIM,11*BLOCK_DIM), m_ProjPlaneDim(800,600)
{
//Find the center of the projection plane
m_ProjPlaneCenter.x = m_ProjPlaneDim.x/2;
m_ProjPlaneCenter.y = m_ProjPlaneDim.y/2;

//Find the distance from the player to the projection plane
m_ProjPlaneDistance = m_ProjPlaneCenter.x / tan(m_playerFOV/2);

//Find the player direction vector, only used for movement purposes
m_PlayerDirection.x = cos(m_PlayerViewAngle);
m_PlayerDirection.y = sin(m_PlayerViewAngle);

m_PlayerDirection = m_PlayerDirection + m_PlayerPos;

//Find the offset for each ray
m_RayAngles = ToRad(m_playerFOV / ToRad(m_ProjPlaneDim.x));

//Initialize the map
InitMap();
}



Tick:
+ Show Spoiler +


void raycast::Tick()
{
//Add half of the player FOV to get the angel of the first ray
double rayToCastAngle = m_PlayerViewAngle + (m_playerFOV /2);

//Cast rays equal to the width of the projection plane
for(int rayCounter = 0; rayCounter < int(m_ProjPlaneDim.x); ++rayCounter)
{
//Find the horizontal intersection
DOUBLE2 HorizontalIntersect = HorizontalInterSection(rayToCastAngle);

//Find the vertical Intersection
DOUBLE2 VerticalIntersect = VerticalInterSection(rayToCastAngle);


//Calculate the distances of the rays if the ray has hit a wall
double horizontalRayDist = 0;

if(HorizontalIntersect.x != std::numeric_limits<double>::max() && HorizontalIntersect.y != std::numeric_limits<double>::max())
{
horizontalRayDist = sqrt((m_PlayerPos.x - HorizontalIntersect.x)*(m_PlayerPos.x - HorizontalIntersect.x))+((m_PlayerPos.y - HorizontalIntersect.y)*(m_PlayerPos.y - HorizontalIntersect.y));

//Correct the distance (fishbowl effect)
double angleOffset = rayToCastAngle - m_PlayerViewAngle;
horizontalRayDist *= cos(angleOffset);
}
else
{
horizontalRayDist = std::numeric_limits<double>::max();
}

double verticalRayDist = 0;

if(VerticalIntersect.x != std::numeric_limits<double>::max() && VerticalIntersect.y != std::numeric_limits<double>::max())
{
verticalRayDist = sqrt((m_PlayerPos.x - VerticalIntersect.x)*(m_PlayerPos.x - VerticalIntersect.x))+((m_PlayerPos.y - VerticalIntersect.y)*(m_PlayerPos.y - VerticalIntersect.y));

//Correct the distance (fishbowl effect)
double angleOffset = rayToCastAngle - m_PlayerViewAngle;
verticalRayDist *= cos(angleOffset);
}
else
{
verticalRayDist = std::numeric_limits<double>::max();
}


//Find the smaller of the 2 distances
if(verticalRayDist < horizontalRayDist)
{
m_RayDistances[rayCounter] = double(BLOCK_DIM) / verticalRayDist * m_ProjPlaneDistance;
}
else
{
if(horizontalRayDist < verticalRayDist)
{
m_RayDistances[rayCounter] = double(BLOCK_DIM) / horizontalRayDist * m_ProjPlaneDistance;
}
}

//subtract angle of 1 ray from the angle
rayToCastAngle -= m_RayAngles;

if(rayToCastAngle > ToRad(360))
rayToCastAngle = 0;

if(rayToCastAngle < 0)
rayToCastAngle = ToRad(360);
}
}



Horizontal and vertical rays
+ Show Spoiler +



DOUBLE2 raycast::HorizontalInterSection(double rayAngle)
{
//If the ray is 0 or 180 degrees there will be no horizontal Intersection
if(rayAngle == 0 || rayAngle == ToRad(180))
return DOUBLE2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());

//Find the coordinate of the first intersection
DOUBLE2 intersection(0,0);

if(rayAngle < ToRad(180))
{
//ray is facing up
intersection.y = floor(m_PlayerPos.x / BLOCK_DIM) * BLOCK_DIM - 1;
}
else
{
//ray is facing down
intersection.y = floor(m_PlayerPos.x / BLOCK_DIM) * BLOCK_DIM + BLOCK_DIM;
}

intersection.x = m_PlayerPos.x + (m_PlayerPos.x - intersection.y) / tan(rayAngle);

//Check if the ray is outside of the grid
if(intersection.x < 0 || (intersection.x > double(NUM_ROWS*BLOCK_DIM)) || intersection.y < 0 || (intersection.y > double(NUM_ROWS*BLOCK_DIM)))
{
return DOUBLE2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
}

//Check if there is a wall on the coordinate
if(m_WorldMapArr[int(intersection.x/BLOCK_DIM)][int(intersection.y/BLOCK_DIM)] > 0)
{
return intersection;
}
else
{
//Find the Offsets
DOUBLE2 offSet(double((BLOCK_DIM)/tan(rayAngle)),BLOCK_DIM);

//if the ray is facing up
if(rayAngle < ToRad(180))
offSet.y = BLOCK_DIM*-1;


//loop until intersection is found or the ray goes outside of the grid
while(true)
{
intersection.x += offSet.x;
intersection.y += offSet.y;

//Check if the ray is outside of the grid
if(intersection.x < 0 || (intersection.x > double(NUM_ROWS*BLOCK_DIM)) || intersection.y < 0 || (intersection.y > double(NUM_ROWS*BLOCK_DIM)))
{
return DOUBLE2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
}

//Check if there is a wall on the coordinate
if(m_WorldMapArr[int(intersection.x/BLOCK_DIM)][int(intersection.y/BLOCK_DIM)] > 0)
{
return intersection;
}
}
}
}

DOUBLE2 raycast::VerticalInterSection(double rayAngle)
{
//if the ray is 90 or 270 degrees we can't find a vertical intersection
if(rayAngle == ToRad(90) || rayAngle == ToRad(270))
{
return DOUBLE2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
}

//Find the first Intersection
DOUBLE2 intersection(0,0);

if(rayAngle > ToRad(90) && rayAngle < ToRad(270))
{
//ray is facing left
intersection.x = floor(m_PlayerPos.x / double(BLOCK_DIM)) * BLOCK_DIM -1;
}
else
{
//ray is facing right
intersection.x = floor(m_PlayerPos.x / double(BLOCK_DIM)) * BLOCK_DIM + BLOCK_DIM;
}

intersection.y = m_PlayerPos.y + (m_PlayerPos.x - intersection.x) * tan(rayAngle);

//Check if the ray is withing the grid
if(intersection.x < 0 || (intersection.x > double(NUM_ROWS*BLOCK_DIM)) || intersection.y < 0 || (intersection.y > double(NUM_ROWS*BLOCK_DIM)))
{
return DOUBLE2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
}

//check if the ray has hit a wall
if(m_WorldMapArr[int(intersection.x/BLOCK_DIM)][int(intersection.y/BLOCK_DIM)] > 0)
{
return intersection;
}
else
{
//find the offsets
DOUBLE2 offset(BLOCK_DIM, (m_PlayerPos.y + (m_PlayerPos.x - intersection.x) * tan(rayAngle)));

//Check if the ray is facing right
if(rayAngle > ToRad(90) && rayAngle < ToRad(270))
offset.x = BLOCK_DIM * -1;

//loop untill a wall has found or the ray is outside the grid
while(true)
{
intersection.x += offset.x;
intersection.y += offset.y;

//Check if the ray is outside of the grid
if(intersection.x < 0 || (intersection.x > double(NUM_ROWS*BLOCK_DIM)) || intersection.y < 0 || (intersection.y > double(NUM_ROWS*BLOCK_DIM)))
{
return DOUBLE2(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
}

//Check if there is a wall on the coordinate
if(m_WorldMapArr[int(intersection.x/BLOCK_DIM)][int(intersection.y/BLOCK_DIM)] > 0)
{
return intersection;
}
}
}
}



edit: sorry if it's a bit hard to read, since some lines don't fit, if it is a problem let me know and i'll see if I can fix it.
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-02-20 01:00:09
February 20 2012 00:34 GMT
#2324
On February 19 2012 12:01 tec27 wrote:
Show nested quote +
On February 18 2012 13:33 mmp wrote:
On February 17 2012 22:58 BottleAbuser wrote:
I've been doing this project that's supposed to be all flashy so I'm using a lot of javascript (jQuery). I've been having trouble keeping my code clean. Any resources that might help?

So far, I've been identifying blocks of code that are similar, generalizing them into library functions, and including a lib.js in my common header. Of course, this means we're loading code that's unneeded for a sizable chunk of the pages on the site.

I'm starting to wonder if there are better ways such as dynamically calling javascript resources (maybe with ajax). Is this a good idea? I'm thinking I'd need to eval() the returned script, but that seems like a big no-no.

(1) How large is your lib.js? It's probably trivially small.
(2) Do not use eval. Do what jQuery does, append a <script> element into the document.

Post a link to your source for detailed comments.

(2) is pretty bad advice, considering jQuery uses eval() on scripts you try to insert into the DOM through it. There are things you don't want to eval, such as data that comes from domains you do not control, but people need to stop being so irrationally fearful of it. It has valid uses.

Sorry, I mistook jQuery's cross domain script behavior (which relies on the src attribute of <script>) for it's text/[foobar]script mimetype handling, which does use eval in global context (on par with <script>).

Other libraries (e.g. require.js) use <script>. I'm actually not sure why jQuery prefers eval. Probably convenience to users that want to execute the script synchronously (as opposed to gathering it alongside other scripts & sync-ing before manually exec-ing), but <script> is a little bit cleaner (if nothing else, you give the user agent a chance to handle it like a normal script -- maybe you have a plugin like NoScript that doesn't want to worry about every XHR being eval-ed as script), and therefore slightly preferable, to me anyway.

Both are frightfully insecure by nature, of course, unless your code is delivered over TLS or signed or checksumed. But unless you need a Javascript REPL in your page, I don't think eval is ever preferable to <script>, except as a convenience.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
tec27
Profile Blog Joined June 2004
United States3701 Posts
February 20 2012 01:52 GMT
#2325
On February 20 2012 09:34 mmp wrote:
Show nested quote +
On February 19 2012 12:01 tec27 wrote:
On February 18 2012 13:33 mmp wrote:
On February 17 2012 22:58 BottleAbuser wrote:
I've been doing this project that's supposed to be all flashy so I'm using a lot of javascript (jQuery). I've been having trouble keeping my code clean. Any resources that might help?

So far, I've been identifying blocks of code that are similar, generalizing them into library functions, and including a lib.js in my common header. Of course, this means we're loading code that's unneeded for a sizable chunk of the pages on the site.

I'm starting to wonder if there are better ways such as dynamically calling javascript resources (maybe with ajax). Is this a good idea? I'm thinking I'd need to eval() the returned script, but that seems like a big no-no.

(1) How large is your lib.js? It's probably trivially small.
(2) Do not use eval. Do what jQuery does, append a <script> element into the document.

Post a link to your source for detailed comments.

(2) is pretty bad advice, considering jQuery uses eval() on scripts you try to insert into the DOM through it. There are things you don't want to eval, such as data that comes from domains you do not control, but people need to stop being so irrationally fearful of it. It has valid uses.

Sorry, I mistook jQuery's cross domain script behavior (which relies on the src attribute of <script>) for it's text/[foobar]script mimetype handling, which does use eval in global context (on par with <script>).

Other libraries (e.g. require.js) use <script>. I'm actually not sure why jQuery prefers eval. Probably convenience to users that want to execute the script synchronously (as opposed to gathering it alongside other scripts & sync-ing before manually exec-ing), but <script> is a little bit cleaner (if nothing else, you give the user agent a chance to handle it like a normal script -- maybe you have a plugin like NoScript that doesn't want to worry about every XHR being eval-ed as script), and therefore slightly preferable, to me anyway.

Both are frightfully insecure by nature, of course, unless your code is delivered over TLS or signed or checksumed. But unless you need a Javascript REPL in your page, I don't think eval is ever preferable to <script>, except as a convenience.

Its mostly a compatibility thing, I think. Older versions of IE like to throw exceptions if you insert a script tag along with a bunch of other HTML. Also, I don't quite see how eval'ing a script file you download is less preferrable to inserting script tags. The end result is the same: the code from the script is executed in global scope.
Can you jam with the console cowboys in cyberspace?
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-02-20 03:48:37
February 20 2012 03:25 GMT
#2326
On February 20 2012 10:52 tec27 wrote:
Show nested quote +
On February 20 2012 09:34 mmp wrote:
On February 19 2012 12:01 tec27 wrote:
On February 18 2012 13:33 mmp wrote:
On February 17 2012 22:58 BottleAbuser wrote:
I've been doing this project that's supposed to be all flashy so I'm using a lot of javascript (jQuery). I've been having trouble keeping my code clean. Any resources that might help?

So far, I've been identifying blocks of code that are similar, generalizing them into library functions, and including a lib.js in my common header. Of course, this means we're loading code that's unneeded for a sizable chunk of the pages on the site.

I'm starting to wonder if there are better ways such as dynamically calling javascript resources (maybe with ajax). Is this a good idea? I'm thinking I'd need to eval() the returned script, but that seems like a big no-no.

(1) How large is your lib.js? It's probably trivially small.
(2) Do not use eval. Do what jQuery does, append a <script> element into the document.

Post a link to your source for detailed comments.

(2) is pretty bad advice, considering jQuery uses eval() on scripts you try to insert into the DOM through it. There are things you don't want to eval, such as data that comes from domains you do not control, but people need to stop being so irrationally fearful of it. It has valid uses.

Sorry, I mistook jQuery's cross domain script behavior (which relies on the src attribute of <script>) for it's text/[foobar]script mimetype handling, which does use eval in global context (on par with <script>).

Other libraries (e.g. require.js) use <script>. I'm actually not sure why jQuery prefers eval. Probably convenience to users that want to execute the script synchronously (as opposed to gathering it alongside other scripts & sync-ing before manually exec-ing), but <script> is a little bit cleaner (if nothing else, you give the user agent a chance to handle it like a normal script -- maybe you have a plugin like NoScript that doesn't want to worry about every XHR being eval-ed as script), and therefore slightly preferable, to me anyway.

Both are frightfully insecure by nature, of course, unless your code is delivered over TLS or signed or checksumed. But unless you need a Javascript REPL in your page, I don't think eval is ever preferable to <script>, except as a convenience.

Its mostly a compatibility thing, I think. Older versions of IE like to throw exceptions if you insert a script tag along with a bunch of other HTML. Also, I don't quite see how eval'ing a script file you download is less preferrable to inserting script tags. The end result is the same: the code from the script is executed in global scope.

It's mostly just bias against eval, but not without good reason. Even in a global context, it's still not a totally independent script. Strict mode affects the evaluated code (which definitely breaks a lot of popular libraries), strict eval differs from non-strict eval in that the calling context's variable environment is or is not inherited (it is set to the lexical environment instead), and I'm not even convinced that my up-to-date Chrome does the correct thing with regards to the thisArg (+ Show Spoiler +
Shouldn't these be equivalent contexts? (strict mode)
(function() {
alert(eval("this"))
alert(eval.call(this, "this"))
}).call({})
See Ecma-262, 10.4.2 for details.
).

Use <script> and you don't have to worry about anything (except code injection :p).
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
mmp
Profile Blog Joined April 2009
United States2130 Posts
February 20 2012 03:37 GMT
#2327
^ Maybe you can help clear up my confusion with the thisArg & variable environment. Unless I'm overlooking something in the spec, I think browser vendors are breaking spec in the hope of making eval safer.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
Weson
Profile Blog Joined December 2010
Iceland1032 Posts
February 20 2012 19:48 GMT
#2328
I need help with SQL. The thing i wanna do is to format a date so it appears as follows "23 - Jan - 2003". Anyone know how to acheive this? The data is stored in a table.
"!@€#" - as some guy said
Nutwagon
Profile Joined September 2011
Canada10 Posts
February 20 2012 20:17 GMT
#2329
I recently started my course in java, and there's one thing that's been bugging me for a couple days now. When I see a line like

System.out.println(" 5 + 3 * 2 = \t " + (5 + 3 * 2));

What is the \t for??

There's been other lines that I've seen that have multiple \t 's in a row (eg. \t\t\t ->)

Not sure if I missed something or if I'm looking too much into this..

Thanks for any help guys! Long live this thread.
zzdd
Profile Joined December 2010
United States484 Posts
February 20 2012 20:20 GMT
#2330
On February 21 2012 05:17 Nutwagon wrote:
I recently started my course in java, and there's one thing that's been bugging me for a couple days now. When I see a line like

System.out.println(" 5 + 3 * 2 = \t " + (5 + 3 * 2));

What is the \t for??

There's been other lines that I've seen that have multiple \t 's in a row (eg. \t\t\t ->)

Not sure if I missed something or if I'm looking too much into this..

Thanks for any help guys! Long live this thread.

Tab
frogmelter
Profile Blog Joined April 2009
United States971 Posts
February 20 2012 20:22 GMT
#2331
On February 21 2012 05:17 Nutwagon wrote:
I recently started my course in java, and there's one thing that's been bugging me for a couple days now. When I see a line like

System.out.println(" 5 + 3 * 2 = \t " + (5 + 3 * 2));

What is the \t for??

There's been other lines that I've seen that have multiple \t 's in a row (eg. \t\t\t ->)

Not sure if I missed something or if I'm looking too much into this..

Thanks for any help guys! Long live this thread.


I'm pretty sure this would have been found within 20 seconds of Googling, but the \t character is a tab character. Meaning it will be replaced with a tab inside of a formatted string.
TL+ Member
amazingxkcd
Profile Blog Joined September 2010
GRAND OLD AMERICA16375 Posts
February 20 2012 20:32 GMT
#2332
Hey guys.
This is my first post in this thread.

I have a project that I want to work on, being a python app that plays sound when sent strings from a server connection, but my main issue is the motivation to do it. How do you guys motivate yourselves to start a project and to finish that project when it is just for fun?
The world is burning and you rather be on this terrible website discussing video games and your shallow feelings
alwinuz
Profile Joined September 2011
Netherlands77 Posts
February 20 2012 20:50 GMT
#2333
I can't help you with that, the reason I'm reading this thread is because I'm not motivated for development work
Kasha_Not_Kesha
Profile Blog Joined October 2011
United States71 Posts
February 20 2012 20:56 GMT
#2334
Assembly question for ya'all.

I'm working with the IJVM instruction set for the MIC-1 processor for my Comp. Architechture class, and one of my homework problems is inadvertantly giving me a headache.

I'm just supposed to write some microcode for three new instructions: IPUSH1, IPUSH0, and IPUSHN1, which push a 1, 0 or -1 onto the stack respectively.

For the IPUSH1, I've got the following:

1: SP = MAR = SP + 1
2: PC = PC + 1; fetch
3: MDR = TOS = 1; wr; goto Main1

My question is, do I need the underlined fetch command, or is the following a valid optomization of the above code:

1: SP = MAR = SP + 1
2: PC = PC + 1; MDR = TOS = 1; wr; goto Main1

Also, regardless of whether or not this is a valid replacement, am I correct in assuming that the removal of the fetch command would speed up the instruction (i.e. would the second code be faster than the first code?)

Thanks!
Human beings are literally made up of potential more than anything else.
Badjas
Profile Blog Joined October 2008
Netherlands2038 Posts
February 20 2012 21:06 GMT
#2335
On February 21 2012 04:48 Weson wrote:
I need help with SQL. The thing i wanna do is to format a date so it appears as follows "23 - Jan - 2003". Anyone know how to acheive this? The data is stored in a table.

CONVERT(VARCHAR(255), YourDateField, "Format"), depending on database engine. You should look at the reference manual. (From memory, it's been a month ago that I had to do this.) Not sure if this only allows predefined formats, otherwise you have to convert parts of date, likely with a datepart function, and concatenate strings.

Oh, point in general, a decent database engine (any that you'll want to use) has a good reference manual, that must answer questions such as those. Do not continue without one, it's a waste of time otherwise.
I <3 the internet, I <3 you
Badjas
Profile Blog Joined October 2008
Netherlands2038 Posts
February 20 2012 21:10 GMT
#2336
On February 21 2012 05:32 amazingxkcd wrote:
Hey guys.
This is my first post in this thread.

I have a project that I want to work on, being a python app that plays sound when sent strings from a server connection, but my main issue is the motivation to do it. How do you guys motivate yourselves to start a project and to finish that project when it is just for fun?

Without motivation it won't be fun, would it?

I would start by writing down what you want. Then I'd write down which problems there are to tackle. Then write apps that tackle the problems one by one, or expand a single demo. Try to write it in a modular way so you don't have to rewrite a lot. At the end, tie up the stuff in a neat bundle, perhaps rewriting a user interface.

Don't stay up late You program better when you're awake.
I <3 the internet, I <3 you
Essbee
Profile Blog Joined August 2008
Canada2371 Posts
February 20 2012 21:12 GMT
#2337
On February 21 2012 05:32 amazingxkcd wrote:
Hey guys.
This is my first post in this thread.

I have a project that I want to work on, being a python app that plays sound when sent strings from a server connection, but my main issue is the motivation to do it. How do you guys motivate yourselves to start a project and to finish that project when it is just for fun?


The bolded part is my motivation. I really have fun programming little cool projects. I don't know about you but maybe programming isn't really for you if you don't enjoy it. It may seem harsh being said like this but I have a lot of people I know that just can't start their own little project because they don't find any joy in programming. That's sad because meanwhile I'm programming games, little applications, etc, and it really helps me getting better at programming and I enjoy it even more.

Start it and see it how it goes. If you think it'll be a cool program, why don't you want to start it? It sure asks for some patience and thinking but that's what programming is all about.
Weson
Profile Blog Joined December 2010
Iceland1032 Posts
February 20 2012 22:00 GMT
#2338
On February 21 2012 06:06 Badjas wrote:
Show nested quote +
On February 21 2012 04:48 Weson wrote:
I need help with SQL. The thing i wanna do is to format a date so it appears as follows "23 - Jan - 2003". Anyone know how to acheive this? The data is stored in a table.

CONVERT(VARCHAR(255), YourDateField, "Format"), depending on database engine. You should look at the reference manual. (From memory, it's been a month ago that I had to do this.) Not sure if this only allows predefined formats, otherwise you have to convert parts of date, likely with a datepart function, and concatenate strings.

Oh, point in general, a decent database engine (any that you'll want to use) has a good reference manual, that must answer questions such as those. Do not continue without one, it's a waste of time otherwise.

You saved me from going bald. Thank you =)
I'm totally green when it comes to SQL and server management. Im using MYSQL and this did the trick DATE_FORMAT( date, "%d-%b-%y" ).
"!@€#" - as some guy said
tec27
Profile Blog Joined June 2004
United States3701 Posts
Last Edited: 2012-02-21 00:07:23
February 20 2012 23:55 GMT
#2339
On February 20 2012 12:37 mmp wrote:
^ Maybe you can help clear up my confusion with the thisArg & variable environment. Unless I'm overlooking something in the spec, I think browser vendors are breaking spec in the hope of making eval safer.

I played around with this a bit, and I agree its confusing as hell I had no idea that strict mode affected evals though, thanks for bringing that to my attention. Anyway, here was my testing code:


(function() {
"use strict";
console.dir(this);
console.log('regular eval:');
eval('console.dir(this); var a = 5;')
//console.log('after: ' + a); // ReferenceError: a is not defined
console.log('eval.call:');
eval.call(this, 'console.dir(this); var b = 5;');
console.log('after: ' + b);
console.log('eval.bind:');
var ev = eval.bind(this, 'console.dir(this); var c = 5;');
ev();
console.log('after: ' + c);
}).call({myObj: 'yes'});

This results in the following output:

Object
myObj: "yes"
__proto__: Object

regular eval:
Object
myObj: "yes"
__proto__: Object

eval.call:
DOMWindow
after: 5

eval.bind:
DOMWindow
after: 5


Seems rather strange, but after reading the specs, I *think* this might be to spec. See #1 under 10.4.2:

1. If there is no calling context or if the eval code is not being evaluated by a direct call (15.1.2.1.1) to the eval
function then,
a. Initialise the execution context as if it was a global execution context using the eval code as C as
described in 10.4.1.1.

Those steps describe initializing the context to window within a browser, essentially. From my reading, it seems a direct call is basically eval() only, not eval.call(), eval.bind(), or eval.apply(). So I think this makes sense according to the specs. Now whether the specs make sense there, I don't know, but there's probably some reason for it

Edit: Yeah, I was correct on that: http://perfectionkills.com/global-eval-what-are-the-options/#indirect_eval_call_theory

I think the change for direct calls is more of an optimization thing than a safety thing, which is why its probably so easy to still use the fully global version.
Can you jam with the console cowboys in cyberspace?
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-02-21 02:36:10
February 21 2012 02:35 GMT
#2340
On February 21 2012 08:55 tec27 wrote:
Show nested quote +
On February 20 2012 12:37 mmp wrote:
^ Maybe you can help clear up my confusion with the thisArg & variable environment. Unless I'm overlooking something in the spec, I think browser vendors are breaking spec in the hope of making eval safer.

I played around with this a bit, and I agree its confusing as hell I had no idea that strict mode affected evals though, thanks for bringing that to my attention. Anyway, here was my testing code:


(function() {
"use strict";
console.dir(this);
console.log('regular eval:');
eval('console.dir(this); var a = 5;')
//console.log('after: ' + a); // ReferenceError: a is not defined
console.log('eval.call:');
eval.call(this, 'console.dir(this); var b = 5;');
console.log('after: ' + b);
console.log('eval.bind:');
var ev = eval.bind(this, 'console.dir(this); var c = 5;');
ev();
console.log('after: ' + c);
}).call({myObj: 'yes'});

This results in the following output:

Object
myObj: "yes"
__proto__: Object

regular eval:
Object
myObj: "yes"
__proto__: Object

eval.call:
DOMWindow
after: 5

eval.bind:
DOMWindow
after: 5


Seems rather strange, but after reading the specs, I *think* this might be to spec. See #1 under 10.4.2:
Show nested quote +

1. If there is no calling context or if the eval code is not being evaluated by a direct call (15.1.2.1.1) to the eval
function then,
a. Initialise the execution context as if it was a global execution context using the eval code as C as
described in 10.4.1.1.

Those steps describe initializing the context to window within a browser, essentially. From my reading, it seems a direct call is basically eval() only, not eval.call(), eval.bind(), or eval.apply(). So I think this makes sense according to the specs. Now whether the specs make sense there, I don't know, but there's probably some reason for it

Edit: Yeah, I was correct on that: http://perfectionkills.com/global-eval-what-are-the-options/#indirect_eval_call_theory

I think the change for direct calls is more of an optimization thing than a safety thing, which is why its probably so easy to still use the fully global version.

Oh wow that is far more complicated than I feared (kangax ftw). Thanks for pointing that out, I didn't even bother to look up ES indirect calls.

What about the issue of strict mode affecting the variable environment vs lexical environment? Do we know the effects of that?
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
Prev 1 115 116 117 118 119 1031 Next
Please log in or register to reply.
Live Events Refresh
RSL Revival
10:00
Season 2: Playoffs Day 7
Cure vs ZounLIVE!
Tasteless1253
Crank 1116
IndyStarCraft 228
CranKy Ducklings104
Rex103
3DClanTV 46
IntoTheiNu 19
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Tasteless 1253
Crank 1116
IndyStarCraft 228
Rex 103
MindelVK 38
Railgan 26
StarCraft: Brood War
Britney 44101
Calm 7883
Rain 2649
Horang2 2266
Flash 2062
GuemChi 1160
EffOrt 818
Larva 536
BeSt 467
actioN 423
[ Show more ]
Hyuk 315
Hyun 286
Zeus 206
Last 193
firebathero 182
Soma 114
Rush 113
ZZZero.O 92
Aegong 90
Light 85
Soulkey 69
sSak 67
Sharp 65
Free 58
ajuk12(nOOB) 56
Nal_rA 46
Movie 41
Mong 39
soO 34
sas.Sziky 31
Sacsri 29
Sexy 27
ivOry 21
Icarus 17
Hm[arnc] 10
Terrorterran 4
Noble 3
Dota 2
singsing2890
Gorgc2340
qojqva1380
Dendi1218
XcaliburYe734
Fuzer 207
Counter-Strike
allub268
Heroes of the Storm
Khaldor183
Other Games
B2W.Neo1050
DeMusliM495
crisheroes374
Lowko175
Hui .144
NeuroSwarm45
Trikslyr24
Organizations
Other Games
gamesdonequick713
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 13 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Jankos1883
• Stunt552
Other Games
• WagamamaTV269
Upcoming Events
BSL Open LAN 2025 - War…
2h 46m
OSC
8h 46m
BSL Open LAN 2025 - War…
19h 46m
RSL Revival
21h 46m
Classic vs TBD
WardiTV Invitational
22h 46m
Online Event
1d 3h
Wardi Open
1d 22h
Monday Night Weeklies
2 days
Sparkling Tuna Cup
2 days
LiuLi Cup
3 days
[ Show More ]
The PondCast
4 days
CranKy Ducklings
5 days
Liquipedia Results

Completed

Proleague 2025-09-10
Chzzk MurlocKing SC1 vs SC2 Cup #2
HCC Europe

Ongoing

BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Points
ASL Season 20
CSL 2025 AUTUMN (S18)
LASL Season 20
2025 Chongqing Offline CUP
BSL World Championship of Poland 2025
RSL Revival: Season 2
Maestros of the Game
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1

Upcoming

IPSL Winter 2025-26
BSL Season 21
SC4ALL: Brood War
BSL 21 Team A
Stellar Fest
SC4ALL: StarCraft II
EC S1
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.