Advertisement
Guest User

Untitled

a guest
May 15th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.58 KB | None | 0 0
  1. ## JavaScript
  2.  
  3. Hey mentor,
  4.  
  5. I was working through an assignment last night and came across a bug. I'm so confused!
  6.  
  7. The text in the alert is showing up as "undefined" instead of either "A Unicorn", "A hug", or "Fresh Laundry" and
  8. I'm not quite sure what's going on. Can you point me in the right direction?
  9.  
  10. -Student
  11.  
  12. ```js
  13. <button id="btn-0">Button 1!</button>
  14. <button id="btn-1">Button 2!</button>
  15. <button id="btn-2">Button 3!</button>
  16.  
  17. <script type="text/javascript">
  18. var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
  19. for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
  20. // for each of our buttons, when the user clicks it...
  21. document.getElementById('btn-' + btnNum).onclick = function() {
  22. // tell her what she's won!
  23. alert(prizes[btnNum]);
  24. };
  25. }
  26. </script>
  27. ```
  28.  
  29. ```
  30. Can you run the program for me. Lets put a couple of console.logs inside the for loop
  31.  
  32. for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
  33. // for each of our buttons, when the user clicks it...
  34. console.log(btnNum);
  35. document.getElementById('btn-' + btnNum).onclick = function() {
  36. // tell her what she's won!
  37. console.log(btnNum)
  38. alert(prizes[btnNum]);
  39. };
  40. }
  41.  
  42. Wow! you just found a real JS quirk! Lets start by using our friend the "console.log". First thing you notice is that the
  43. console.log(btnNum) inside the for loop, when you run it see 0,1,2 being logged. Alsoconsole.log(btnNum) inside the function
  44. returns a 3. This means the for loop is looping over all the btnNum before running the function associated with the onclick.
  45. Remember when we talked about JavaScript closures? can you tell me what a closure is[at this point I will try and gauge how
  46. comfortable the student is with closures].
  47. A closure, is a function in JavaScript, can simply be described as a retained scope. The benefit of a closure is in
  48. the fact that it retains the scope of the outer or “parent execution context. The looping problem occurs when you
  49. create a function within a loop and expect the current value of a variable to retain itself within that new function
  50. even though it changes in the loops context before your new function is called. That is the reason when we see that
  51. the two console.logs are returning values that have already been run by the for loop, the only thing that is being
  52. passed to the onclick is the final value of 3.
  53. Now lets change stuff around. How about if we create a function outside of the for loop and extract the closure
  54. from the loop and put it in that function, lets try that[I would do this step-by-step explainng each step]
  55.  
  56. var callThisFunction = function(arr, index) {
  57. document.getElementById('btn-' + btnNum).onclick = function() {
  58. alert(arr[index]);
  59. }
  60. };
  61.  
  62. var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
  63.  
  64. for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
  65. // for each of our buttons, when the user clicks it...
  66. callThisFunction(prizes, btnNum)
  67. }
  68.  
  69. As you see, this problem can be solved by creating a function and calling it on each iteration of the loop,
  70. while passing the btnNum on each call; calling the function will form a brand new execution context where the
  71. value of btnNum is retained and can be used in any way within that context, including within the returned function.
  72. ```
  73. Rails
  74.  
  75. Hey mentor,
  76.  
  77. I am starting to understand associations, but I'm still confused about through. What's the practical difference between a has_many and a has_many :through? What about has_one :through? When do I use them?
  78.  
  79. -Student
  80.  
  81. ```
  82. Good Question, and a really important one! Lets jog our memories back to associations between two models. In general, Why do
  83. we need associations between models?[I would wait for the students response]. Correct! because they make common operations
  84. simpler and easier in your code. There are different type of associations between two models, has_many one of those associations.
  85. A has_many association indicates a one-to-many connection with another model.his association indicates that each instance of
  86. the model has zero or more instances of another model. For example, in an application containing authors and books, the author
  87. model could be declared like this:
  88.  
  89. class Author < ApplicationRecord
  90. has_many :books
  91. end
  92.  
  93. This one is easy right! Now say we are running a medical practice, with many patients, and everytime a patient needs to see us
  94. they need to make an appointment. Now can you tell me how many models would be needed here? Thats correct, three models: patients,
  95. physician, appointments. So if we put it in plain English, a physician has many appointments with many patients, and a
  96. patient can have a lot of physicians. What kind of relationship does this depict? a has_many:through, do you see it?
  97. [see if the student is following along]. A has_many :through association is often used to set up a many-to-many connection
  98. with another model. This association indicates that the declaring model can be matched with zero or more instances of another
  99. model by proceeding through a third model. In our example it would look something like this[I would probably draw some form
  100. of a diagram while explaining this]
  101.  
  102. class Physician < ApplicationRecord
  103. has_many :appointments
  104. has_many :patients, through: :appointments
  105. end
  106.  
  107. class Appointment < ApplicationRecord
  108. belongs_to :physician
  109. belongs_to :patient
  110. end
  111.  
  112. class Patient < ApplicationRecord
  113. has_many :appointments
  114. has_many :physicians, through: :appointments
  115. end
  116.  
  117. I would suggest that you thoroguhly practice these association, the only way of doing this is by coming up with some examples.
  118. why don't you think of an examples for both has_many and has_many :through. Once you are done we can discuss this further.
  119. Also, lets discuss has_one :through once you finish practicing has_many. Once you are able to come with some example for
  120. has_many, has_one will become clearer.
  121. ```
  122. ### SQL
  123.  
  124. Hey mentor,
  125.  
  126. Thanks for the lecture yesterday, it really helped me get motivated again. I've been working through this assignment about databases and I'm confused about "SQL injection." What does that mean and how does it work? How do I prevent it in my apps?
  127.  
  128. Thanks!
  129.  
  130. -Student
  131.  
  132. ```
  133. Databases, one of my favorite topics! Thank you for bringing up 'SQL injection' it is really important, to understand what it
  134. is and how to secure your databases from it. Since a SQL Injection vulnerability could possibly affect any website or web
  135. application that makes use of an SQL-based database, the vulnerability is one of the oldest, most prevalent and most dangerous
  136. of web application vulnerabilities.
  137. SQL Injection refers to an injection attack wherein an attacker can execute malicious SQL statements that control a web
  138. application’s database server. In order to, run malicious SQL queries against a database server, an attacker must first find
  139. an input within the web application that is included inside of an SQL query. In order for, an SQL Injection attack to take
  140. place, the vulnerable website needs to directly include user input within an SQL statement. An attacker can then insert a
  141. payload that will be included as part of the SQL query and run against the database server.
  142. Look at the following pseudocode:
  143.  
  144. # Define POST variables
  145. uname = request.POST['username']
  146. passwd = request.POST['password']
  147.  
  148. # SQL query vulnerable to SQLi
  149. sql = “SELECT id FROM users WHERE username=’” + uname + “’ AND password=’” + passwd + “’”
  150.  
  151. # Execute the SQL statement
  152. database.execute(sql)
  153.  
  154. The above script is a simple example of authenticating a user with a username and a password against a database with a table
  155. named users, and a username and password column. The above script is vulnerable to SQL Injection because an attacker could
  156. submit malicious input in such a way that would alter the SQL statement being executed by the database server.A simple
  157. example of an SQL Injection payload could be something as simple as setting the password field to password’ OR 1=1.
  158.  
  159. This would result in the following SQL query being run against the database server.
  160.  
  161. SELECT id FROM users WHERE username=’username’ AND password=’password’ OR 1=1’
  162.  
  163. Once the query executes, the result is returned to the application to be processed, is could lead to an authentication bypass. In the event of authentication bypass being possible, the application will most likely log the attacker in with the first account from the query result — the first account in a database is usually of an administrative user. So this is pretty serious stuff.
  164.  
  165. Now how how do we prevent this from happening? So there are many ways of doing this, in diffrent frameworks, but lets
  166. specifically talk about Rails application. Most Rails applications interact with a database through ActiveRecord, the
  167. default and convenient Object Relational Mapping (ORM) layer which comes with Rails. Generally, use of ORMs is safer
  168. than not. They can provide abstraction and safety and allow developers to avoid manually building SQL queries.
  169. They can embody best practices and prevent careless handling of external input.
  170.  
  171. Instead of unsafe code like
  172.  
  173. query = "SELECT * FROM users WHERE name = '#{name}' AND password = '#{password'} LIMIT 1"
  174. results = DB.execute(query)
  175.  
  176. You can have safer, simpler code like
  177.  
  178. User.where(:name => name, :password => :password).first
  179. ```
  180. ### Angular/jQuery
  181.  
  182. Hey mentor,
  183.  
  184. I'm really excited about starting on learning Angular. I'm having a problem understanding what angular is.
  185. Up until this point we've used jQuery, which we've called a library. Now we are using Angular, which is a framework.
  186. What's the difference? What are the drawbacks/benefits of using a framework like Angular vs a library like jQuery?
  187.  
  188. ```
  189. Really good question, you just hit the nail in the head between age old question between when does a library become a
  190. framework? what are the differences? lets tackle this one at a time.
  191. Lets start with difference between library and a framework. A library is a reusable piece of code which you use as it comes
  192. i.e it does not provide any hooks for you to extend it. A library will usually focus on a single piece of functionality,
  193. which you access. A framework is a piece of code which dictates the architecture your project will follow. Once you choose
  194. a framework to work with, you have to follow the framework's code and design methodologies. Why is jQuery called a library?
  195. because it is good at one thing; DOM manipulation, that makes it easier to use JavaScript on your website. JavaScript is
  196. the language of choice for making webpages dynamic and interactive. jQuery takes the complex code that would be required '
  197. to make AJAX calls or manipulate the DOM and wraps them into simple methods you can call with a single line of JavaScript.
  198. While AngularJS is a JavaScript framework that was specifically designed to help developers build Single Page Applications
  199. aka SPAs[more on this once we get into Angular] in accordance with best practices for web development. By providing a
  200. structured environment for building SPAs, the risk of producing “spaghetti code” is greatly reduced.
  201. YOU SHOULD USE JQUERY IF…
  202. You’re seeking a lightweight and powerful tool for DOM manipulation. jQuery is a library of code designed to do one thing,
  203. as I mentioned earlier—help you manipulate the DOM with JavaScript.
  204. YOU SHOULD USE ANGULARJS IF…
  205. You require a full-featured framework for developing web applications from scratch. AngularJS gives you everything you need
  206. to build the client-side of an application. It will also make it easier to keep your web project organized and modular to
  207. avoid repeating code.
  208. I am going to list some drawbacks/benefits of using a framework like Angular vs a library like jQuery, because you asked,
  209. but remember before I do that; you I have to tell you. Once you start exploring these tools further, you will develop your
  210. own opinions on which one you prefer. So take anything I say with a grain of salt.
  211. jQuery is very easy to get a handle on and continues to be an amazing way to delegate events(learn more as you get into JS)
  212. and normalize them. It simplified DOM manipulation and Ajax calls before it became a thing. If jQuery is classy, Angular
  213. is the cool kid in JS code-town.
  214. Angular is an open-source structural framework for web apps brought to us by Google, so it’s pretty solid on credentials.
  215. It aims to simplify single-page applications by making development and testing phases easier. How does it do that?
  216. It brings “server-side development tools and capabilities to web client” turf. It is OK if you do not understand all the
  217. terminology here, once you start working with these frameworks all this technical jargon will become second nature.
  218.  
  219. Drawing Some Comparisons here
  220. Advantages of jQuery:
  221. Easy to learn, easy to use
  222. Community:Popularity practically equates to scores of developers actively coding, experimenting and improving upon the base.
  223. Disadvantages of jQuery:
  224. Not built for larger apps
  225.  
  226. Advantages of AngularJS:
  227. Automatic DOM manipulation
  228. MVVW Principle: You ask what the heck is that? For now just know that it is a design paradigm that stands for model, view,
  229. viewmodel. There are others, we will talk more about these as we go along. These paradigms are like a set of rules that
  230. shape applications...thats all you need to know for now.
  231. Disadvantages of AngularJS:
  232. Steep learning curve: You need to apply yourself to learning this framework for a while before you get the hang of it.
  233. jQuery is easier to learn.
  234. ```
  235. ### Algorithms
  236.  
  237. Hey mentor,
  238.  
  239. I hope you're doing well. I'm really enjoying learning algorithms, but I'm pretty confused by this Big O Notation thing. Can you explain how I'm supposed to figure out which notation my algorithm uses?
  240.  
  241. -Student
  242.  
  243. ```
  244. Thats is a tricky one! Lets start by a simple definition of what the Big O notation is Big O notation is used in Computer
  245. Science to describe the performance or complexity of an algorithm. Big O specifically describes the worst-case scenario,
  246. and can be used to describe the execution time required or the space used (e.g. in memory or on disk) by an algorithm.
  247. The relationship between the time it takes and the data increase in Big O has different measurements.
  248. As you can see, O(1) is constant complexity, which basically means that it will take the same time to run the algorithm,
  249. regardless of the length of the data set. (for example, it takes the same time to find the first element or the last in a
  250. sorted data set).
  251. O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set.
  252. The example below also demonstrates how Big O favours the worst-case performance scenario; a matching string could be found
  253. during any iteration of the for loop and the function would return early, but Big O notation will always assume the upper
  254. limit where the algorithm will perform the maximum number of iterations.
  255. bool ContainsValue(IList<string> elements, string value)
  256. {
  257. foreach (var element in elements)
  258. {
  259. if (element == value) return true;
  260. }
  261.  
  262. return false;
  263. }
  264. O(N2) represents an algorithm whose performance is directly proportional to the square of the size of the input data set.
  265. This is common with algorithms that involve nested iterations over the data set. Deeper nested iterations will result in
  266. O(N3), O(N4) etc.
  267. Logarithms are slightly trickier to explain so I'll use a common example:
  268. Binary search is a technique used to search sorted data sets. It works by selecting the middle element of the data set,
  269. essentially the median, and compares it against a target value. If the values match it will return success. If the target
  270. value is higher than the value of the probe element it will take the upper half of the data set and perform the same
  271. operation against it. Likewise, if the target value is lower than the value of the probe element it will perform the
  272. operation against the lower half. It will continue to halve the data set with each iteration until the value has been
  273. found or until it can no longer split the data set.
  274. This type of algorithm is described as O(log N). The iterative halving of data sets described in the binary search example
  275. produces a growth curve that peaks at the beginning and slowly flattens out as the size of the data sets increase e.g.
  276. an input data set containing 10 items takes one second to complete, a data set containing 100 items takes two seconds,
  277. and a data set containing 1000 items will take three seconds. Doubling the size of the input data set has little effect
  278. on its growth as after a single iteration of the algorithm the data set will be halved and therefore on a par with an
  279. input data set half the size. This makes algorithms like binary search extremely efficient when dealing with large data sets.
  280. It is Ok if this all seems too complicated, a key to understanding Big O is writing programs, and actually thinking about
  281. what kind of time and complexity you think they work in. In this case, practice makes perfect.
  282. ```
  283. ### CSS
  284.  
  285. Hey mentor,
  286.  
  287. I'm having a really hard time with some CSS. I've been given a PSD in an assignment. I know what the document should look
  288. like, but I'm getting this instead.
  289.  
  290. Can you help me with this? Here is my code!
  291.  
  292. -Student
  293. ```css
  294. <header>
  295.  
  296. </header>
  297. <section class="pricing">
  298. <div class="pricing-tiers">
  299. <div class="tier">
  300. <h1>The plan</h1>
  301. <ul>
  302. <li>You get all the things</li>
  303. <li>plus more!!</li>
  304. </ul>
  305. </div>
  306.  
  307. <div class="tier">
  308. <h1>The plan</h1>
  309. <ul>
  310. <li>You get all the things</li>
  311. <li>plus more!!</li>
  312. </ul>
  313. </div>
  314.  
  315. <div class="tier">
  316. <h1>The plan</h1>
  317. <ul>
  318. <li>You get all the things</li>
  319. <li>plus more!!</li>
  320. </ul>
  321. </div>
  322. </div>
  323. </section>
  324. header {
  325. width: 100%;
  326. height: 60px;
  327. background-color: #333;
  328. }
  329.  
  330. .pricing {
  331. width: 100%;
  332. padding: 20px;
  333. background-color: tomato;
  334. }
  335.  
  336. .pricing-tiers {
  337. width: 960px;
  338. margin: 0px auto;
  339. background-color: #ddd;
  340. }
  341.  
  342. .pricing-tiers .tier {
  343. width: 260px;
  344. margin: 20px;
  345. padding: 10px;
  346. background-color: white;
  347. float: left;
  348. }
  349.  
  350. .tier h1 {
  351. font-family: "Helvetica", sans-serif;
  352. font-weight: bold;
  353. font-size: 2em;
  354. margin-bottom: 20px;
  355. text-align: center;
  356. }
  357.  
  358. .pricing-tiers > .tier:last-child {
  359. margin-right: 0px;
  360. }
  361. ```
  362. ```
  363. CSS can be tricky sometimes. There are a few small changes that we need to make to fix this layout. I encourage you to open
  364. the chrome dev tools and make the changes one by one so you can see the effect. Once you get it how you like, you can make
  365. the same changes to your CSS.
  366. The first thing we’d like to have is the orange and gray outlines to stretch around our three boxes. This can be fixed by
  367. adding display: inline-block; to the .pricing-tiers selector. This has to do with the fact that inline-block elements and 
  368. block (what it was before) elements handle height differently. Essentially, as a block element, it sees no direct text in
  369. the div, so it assumes a height of zero. It should work well for this application though. Now the heights look right, but
  370. it is no longer centered. We can fix this by adding text-align: center; to the .pricing selector. The text inside the smaller
  371. boxes is centered, but we want them aligned left. For this, we’ll use text-align: left;. We could add this as a property to
  372. each box, but instead, we can add it to the .pricing-tiers selector and the boxes will all inherit it. Lastly, lets get rid
  373. of those ul bullets. We can do this with list-style-type: none;. Instead of applying it to ul, lets apply it to .tier ul in
  374. case we decide we need the bullets elsewhere on the page.
  375. The best way to work with CSS, is to play around with it using the inspector tools, and once you have it the way you like,
  376. to make the changes in the CSS file.
  377.  
  378.  
  379. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement