Niklaus Wirth

Niklaus Wirth

Translate

Show the Local Weather

35-ый день #100DaysOfCode

http://codepen.io/YaroslavW/full/egKYRa/

HTML


<div class="info">
  <h1 ="title">Local Weather</h1>
  <h2 id="city"></h2>
  <button id="convert" class="btn btn-info">Convert to Celsius</button> 
  <h2 id="temp"></h2>
  <img id="icon"></img>
</div>


CSS


@import url(https://fonts.googleapis.com/css?family=Lato);

body {
  text-align: center;
  font-family: 'Lato', sans-serif;
}

.info {
  margin: 5px auto;
 width: 60vw;
 padding: 10px 5px 10px 5px;
 background: linear-gradient(rgba(179, 168, 211, .9), rgba(222, 199, 182, 0.9));
 border-radius: 10px;
}

@media screen and (max-width: 600px) {
  .info {
    width: 100%;
  }
}
#convert{
   border: 1px solid;
   border-radius: 5px;
   padding: .5em 2em;
}



JS


$.getJSON('http://ip-api.com/json', function (position) {
  var lat = position.lat;
  var lon = position.lon;
  console.log('https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=imperial&APPID=a391588e176db8c353dcb74504141cf5')
  $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=imperial&APPID=a391588e176db8c353dcb74504141cf5', function (data) {
        
    console.log(data);
    var city = data.name;
    var f = Math.round(data.main.temp);
    var c = Math.round((data.main.temp - 32) * 5/9);
    var temp = f;
    var condition = data.weather[0].id;
    $('#city').text(city);
    $('#temp').text(temp  + "\u00B0 F");
    $('#icon').attr('src', 'http://openweathermap.org/img/w/' + data.weather[0].icon + '.png')

     if (condition >= 800 && condition <= 804) {
    $('body').css('background', 'url(https://oboi.ws//wallpapers/27_2145_oboi_solnechnaja_pustynja_2560x2048.jpg)' + 'no-repeat center center fixed');
   }
    if (condition >= 200 && condition <= 531) {
    $('body').css('background', 'url(http://hq-oboi.ru/photo/solnce_skvoz_oblaka_skachat_krasivye_1920x1200.jpg)' + 'no-repeat center center fixed');
    }
    if (condition >= 600 && condition <= 622) {
    $('body').css('background', 'url(http://www.jr1.ru/i/orig/10628-1600x1200.jpg)' + 'no-repeat center center fixed');
    }       
    $('body').css('background-size', 'cover')

    $('#convert').click(function() {
      if (temp === f) {
        temp = c;
        $('#convert').text("Convert to Fahrenheit");
        $('#temp').text(temp + "\u00B0 C");
      }
      else {
        temp = f;
        $('#temp').text(temp + "\u00B0 F");
        $('#convert').text("Convert to Celsius");
      }
    });
      
  });  
});




See the Pen Show the Local Weather(1) by YaroslavW (@YaroslavW) on CodePen.


(34)Build a Random Quote Machine

34D #100DaysOfCode


HTML


<div class="container">
  <div class="transbox">
    
   <p class="quote" id="response">Programming is usually taught by examples.
~Niklaus Wirth</p> <button id="getTweet" class=" btn-custom"> <i class="fa fa-twitter"></i> Tweet This</button> <button id="getMessage" class="btn-custom pull-right">New Quote</button> </div> <div class="footer hline text-center"> <p> Built by Yaroslav Kolesnikov.</p> </div> </div>


SCSS


@import url(https://fonts.googleapis.com/css?family=Tangerine:400,500);



body {
  background-image: url(http://www.wallpapers13.com/wp-content/uploads/2016/04/New-Zealand-view-from-the-hill-sea-empty-beach-ocean-waves-HD-Wallpapers-for-Desktop-1920x1080.jpg);
  background-repeat: no repeat;
}

.quote {
  padding-top: 50px;
  font-family:Tangerine,serif;
  font-size: 52px;
  font-weight: bold;
  color: #003333;
  line-height: 40px;
  text-align: center;
}

.btn-custom {
  margin-top: 5%;
  padding: 15px;
  background: #006666;
  color: white;
  font-weight: bold;
  border: #003333;
  border-radius: 5px;
}

.btn-custom:active {
  background: #003333;
}

.btn-custom:hover {
  background: #003333;
}

.transbox {
  margin: 10%;
  padding: 5px;
  background-color: #ffffff;
  border: 1px solid #003333;
  border-radius:5px;
  opacity: 0.6;
  filter: alpha(opacity=60);
}

.hline {
  width: 100%;
  height: 1px;
  background: #003333;
  margin-top: 20%;
  margin-bottom: 15px;
  font-weight: bold;
  color: #003333;
   
}


JS




$(document).ready(function() {
  $("#getMessage").on("click", function() {
    $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?", function(data) {
      if(data.quoteAuthor == "") {
        data.quoteAuthor = "Anonymous";
      }
      $("#response").html( data.quoteText + "
" + "~" + data.quoteAuthor); }); }); $("#getTweet").on("click", function() { window.open("https://twitter.com/intent/tweet?text=" + $("#response").text()); }); });


See the Pen Build a Random Quote Machine(1) by YaroslavW (@YaroslavW) on CodePen.



I prefer second version of solutions




See the Pen Build a Random Quote Machine(2) by YaroslavW (@YaroslavW) on CodePen.


(33)Arguments Optional

Arguments Optional
33-ий день программы "#100 Days Of Code"

Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.

Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = addTogether(2);

sumTwoAnd(3) returns 5.

If either argument isn't a valid number, return undefined.


function addTogether() {
  var results;
  if(arguments.length <=3){
    var a1 = arguments[0];
    var a2 = arguments[1];
    if(typeof(a2)==='number'){
      if(typeof(a1) ==='number'){
      
        results = a1 +a2;
      }
    } else if(a2===undefined && typeof(a1)==='number'){
      return function(a2){
        if(typeof(a2)==='number'){
          return a1 + a2;
        }
        else return results;
      };
    }
  }
  return results;
}

addTogether(2,3);


Ответы:

addTogether(2, 3)
return 5.

addTogether(2)(3)
return 5.

addTogether("http://bit.ly/IqT6zt")
return undefined.

addTogether(2, "3")
return undefined.

addTogether(2)([3])
return undefined.


(32)Everything Be True

Everything Be True
32-ой день программы "#100 Days Of Code"

Check if the predicate (second argument) is truthy on all elements of a collection (first argument).

Remember, you can access object properties through either dot notation or [] notation.



function truthCheck(collection, pre) {

  for(var i = 0; i < collection.length; i++){
    if(!collection[i][pre])
      return false;
  }
  return true;
}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");



Ответы:

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")
return true.

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")
return false.

truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")
return false.

truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat")
return false

truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat")
return true

truthCheck([{"single": "yes"}], "single")
return true

truthCheck([{"single": ""}, {"single": "double"}], "single")
return false

truthCheck([{"single": "double"}, {"single": undefined}], "single")
return false

truthCheck([{"single": "double"}, {"single": NaN}], "single")
return false


Функция с функцией, как аргумент (31)Drop it

Drop it
31-ый день программы "#100 Days Of Code"

Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.

The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not.

Return the rest of the array, otherwise return an empty array.

Функцию можно описать так: Пока есть аргумент в виде массива, то будет выполняться, полученная вторым аргументом, функция, которая добавит в массив только те элементы, которые подойдут под условие заданное полученной функцией.

Here are some helpful links:



function dropElements(arr, func) {
  
  
    while(!func(arr[0])){
       arr.shift();
    }
  
  return arr;
}

dropElements([1, 2, 3], function(n) {return n < 3; });


Ответы:

dropElements([1, 2, 3, 4], function(n) {return n >= 3;})
return [3, 4].

dropElements([0, 1, 0, 1], function(n) {return n === 1;})
return [1, 0, 1].

dropElements([1, 2, 3], function(n) {return n > 0;})
return [1, 2, 3].

dropElements([1, 2, 3, 4], function(n) {return n > 5;})
return [].

dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})
return [7, 4].

dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})
return [3, 9, 2].


(30)Pairwise

Pairwise
30-ый день программы "#100 Days Of Code"

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.



Index01234
Value79111315


Below we'll take their corresponding indices and add them.

7 + 13 = 20 → Indices 0 + 3 = 3

9 + 11 = 20 → Indices 1 + 2 = 3

3 + 3 = 6 → Return 6



Создали пустой массив, куда будем добавлять наши номера. Отдельно создал переменную ответ

Исключили те случаи, когда наша функция должна вернуть 0 -пустой массив на входе pairwise([], 100) should return 0.

Два цикла перебора массива находят варианты при которых сумма двух чисел будет равна аргументу и добавлять их позиции в новый массив. Чтобы избежать повторов, мы в условие прописываем, что данных чисел там еще не должно быть

(arr[i]+arr[j]===arg&& sum.indexOf(i) ==-1 && sum.indexOf(j) ==-1)

В конце мы получаем сумму всех значений массива.

sum = answers.reduce(function(a,b){
    return a+b;
  });

И вернуть именно это значение!

Вообще то, я думаю, что переменная sum здесь лишняя. Можно было вполне обойтись и без нее. Но ... пока что я учусь и потому, оставил для наглядности :-) !

Here are some helpful links:



function pairwise(arr, arg) {
  var answers = [];
  var sum = 0;
  if(arr.length < 1){return 0;}
  for(var i = 0; i < arr.length; i++){
    for(var j = i + 1; j < arr.length; j++){
      if(arr[i] + arr[j]===arg && answers.indexOf(i)== -1 && answers.indexOf(j)== -1){
        answers.push(i,j);
      }
    }
  }
  sum = answers.reduce(function(a,b){
    return a + b;
  });
  return sum;
}

pairwise([1,4,2,3,0,5], 7);

Ответы:

pairwise([1, 4, 2, 3, 0, 5], 7)
return 11.

pairwise([1, 3, 2, 4], 4)
return 1.

pairwise([1, 1, 1], 2)
return 1.

pairwise([0, 0, 0, 0, 1, 1], 1)
return 10.

pairwise([], 100)
return 0.


(29)Map the Debris


день программы "#100 Days Of Code"
Return a new array that transforms the element's average altitude into their orbital periods.
The array will contain objects in the format {name: 'name', avgAlt: avgAlt}.
You can read about orbital periods on wikipedia.
The values should be rounded to the nearest whole number. The body being orbited is Earth.
The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418 km3s-2.



Here are some helpful links:

function orbitalPeriod(arr) {
 var GM = 398600.4418;
  var earthRadius = 6367.4447;
var answer =[];

  var radius;
  
  for (var i = 0; i < arr.length; i++){
    answer[i]= {};
   answer[i].name = arr[i].name;
    
    radius =earthRadius + arr[i].avgAlt;
    answer[i].orbitalPeriod = Math.round(2 * Math.PI *Math.sqrt((Math.pow(radius,3))/GM));

}
return answer;

}

orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);



Ответы:
orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])
return [{name: "sputnik", orbitalPeriod: 86400}].

orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])
return [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}].