<commit_before>var articulos, carrito, total;

function mostrarArticulos(){
       var contador = 0;
       var categoria = $(this).attr('id');
       var nombreCategoria = $(this).text();
       $.ajax({
           url:'articulos.php',
           type: 'POST',
           dataType: 'json',
           data: {categoria},
           success: function(data){
               $('#productos').html(null);
               $('
'+nombreCategoria+'
').appendTo('#productos');
               $('

').appendTo('#productos');
               $.each(data,function(){
                 var articulo = new Articulo(this.id,this.nombre,this.descripcion,this.precio,this.imagen,this.categoria,0);
                 articulos.push(articulo);
                 var idArticulo = "articulo"+articulo.id;
                 var imagen = "./img/"+articulo.imagen;
                 var imagenHTML = ''+'';
                 $('
').appendTo('#articulos').append('
'+ imagenHTML +'
').append('
'+articulo.nombre+'
').append('
'+articulo.descripcion+'
').append('
Precio: '+articulo.precio+'€'+'
').append('<button class="botonCarrito btn btn-success" idArticulo='+articulo.id+'> AÑADIR AL CARRITO</button>');
                 contador++;
                 if (contador == 3){
                   $('

').appendTo('#articulos');
                   contador = 0;
                 }
               });

              /*Modificando
              --------------------------------------------------------------*/
              $('.botonCarrito').on('click', function(){

                $('.anyadir').attr('idarticulo',$(this).attr('idArticulo'));
                texto="";
                texto+="" + $(this).parent().find('.titulo').text() + "
";
                texto+="" + $(this).parent().find('.precio').text() + "

";
                texto+="Descripcion: " + $(this).parent().find('.descripcion').text();
                $('#modalArticulo').modal('show');
                $('.modal-body').html(texto);
              });
            },
            error:function(data){
              console.log(data.responseText);
            }
          });
   }

   function mostrarCarrito(){
   	var carritoHTML = "";
    carritoHTML += "
";
    carritoHTML += "

Producto	Cantidad	Precio	Total

";
    carritoHTML += "
"
   	total = 0;
   	$.each(carrito.articulos,function(){
      /*    --------->>>  MEJORANDO ASPECTO DEL CARRITO*/
      //

      carritoHTML += "

";
      carritoHTML += "

"+this.nombre+"

	";
      carritoHTML += "<button class='btn btn-danger botonBorrarCarrito' idarticulo="+this.id +"> - </button> <input readonly class='text-center' type='text' size='3' value='"+this.cantidad+"'> <button class='btn btn-info botonAgregarCarrito' idarticulo="+this.id+"> + </button>	";
      carritoHTML += ""+this.precio+"€	";
      carritoHTML += ""+(this.precio * this.cantidad)+"€	";
      carritoHTML += "<button class='btn btn-danger botonBorrarArticuloCarrito' idarticulo="+this.id+"> Borrar</button>
";
    });
   	for(var i = 0; i < carrito.articulos.length; i++){
   		total += carrito.articulos[i].precio * carrito.articulos[i].cantidad;
   	}
    //carritoHTML += "
" + "Total: " + total + "€
";
    carritoHTML += "

Total:

"+total+"€

";
    carritoHTML += "

";

   	$('#modalCarrito').modal('show');
    $('#cuerpoCarrito').html(carritoHTML);
    $('.botonBorrarCarrito').on('click',borrarFromCarrito);
    $('.botonAgregarCarrito').on('click',sumarFromCarrito);
    $('.botonBorrarArticuloCarrito').on('click',borrarArticuloCarrito);
  }

   function borrarFromCarrito(){
   	var index = $(this).attr('idarticulo');
   	for(var i=0; i < carrito.articulos.length; i++){
   		if(carrito.articulos[i].id == index){
			  carrito.articulos[i].cantidad--;
  			if (carrito.articulos[i].cantidad < 1) {
          carrito.articulos.splice(i,1);
  			}
      }
   	}
   	mostrarCarrito();
   }

   function borrarArticuloCarrito(){
     var index = $(this).attr('idarticulo');
     for (var i = 0; i < carrito.articulos.length; i++) {
       if (carrito.articulos[i].id == index) {
         carrito.articulos.splice(i,1);
       }
     }
     mostrarCarrito();
   }

   function sumarFromCarrito(){
   	var index = $(this).attr('idarticulo');
   	for(var i = 0;i < carrito.articulos.length; i++){
   		if(carrito.articulos[i].id == index) {
        carrito.articulos[i].cantidad++;
      };
    }
   	mostrarCarrito();
   }

   function toCarrito(){
     var articulo;
     var existe = false;
     var indice;

     for(var i = 0; i < articulos.length; i++){
       if(articulos[i].id == $(this).attr('idarticulo')){
         articulo = articulos[i];
       }
     }
     for(var i = 0;i<carrito.articulos.length;i++){
       if(carrito.articulos[i].id == articulo.id){
         existe = true;
         indice = i;
       }
     }
     if(existe) {
       carrito.articulos[indice].cantidad++;
     } else{
     	articulo.cantidad = 1;
      carrito.addArticulo(articulo);
    }
   }

   function procesarCarrito() {
     // Añadimos el precio total y pasamos el carrito al servidor.
     carrito.total = total;
     var carritoJson = JSON.stringify(carrito);
     if (carrito.articulos.length < 1) {
       alert("Por favor, seleccione algún producto para comprar.");
     }
     else {
       $.ajax({
       url:'carrito.php',
       type: 'POST',
       data: {'carrito':carritoJson},
       success: function(data) {
         alert("Compra realizada satisfactoriamente.");
       }, error: function(data) {
         $("body").html(data.responseText);
       }
     });}
     carrito = new Carrito(1);
   }

function mostrarLogin(){

  $('#modalLogin').modal('show');
  $('#loginBT').on('click',login);
}

function login(){

  var email = $('#emailTF').val();
  var contrasenya = $('#passTF').val();
  var credencial = new Credencial(email,contrasenya);
  var credencialJson = credencial.toJson();
     $.ajax({
       url: 'login.php',
       type: 'POST',
       data: {'credencial':credencialJson},
       success: function(data){
          alert("Login OK" + data);
          actualizarModalLogin();

       },
       error: function(data){
          alert("Login incorrecto.");
       }
     });

}

function actualizarModalLogin(){
  $.ajax({
       url: 'session.php',
       type: 'GET',
       success: function(data){
          var sesion = JSON.parse(data);
          $('.login-modal').html("
 Has iniciado sesión como "+sesion.email);
          $('.login-modal-footer').html("<button type='button' class='btn btn-info' data-dismiss='modal'>Vale</button> <button class='btn btn-success' id='logoutBT'> Logout </button>");
          $('#logoutBT').on('click',logout);
          if (sesion.empleado == "true") {
              $('.login-modal-footer').append("Panel de Administración");
          };
       },
       error: function(data){
          console.log("Ha fallado la petición HTTP. "+data.responseText);
       }
     });
}

function logout(){
  $.ajax({
       url: 'logout.php',
       type: 'GET',
       success: function(data){
        alert("Logout OK");
        location.reload();
},
       error: function(data){
          console.log("Ha fallado la petición HTTP. "+data.responseText);
       }
     });
}

function logged(){
   $.ajax({
       url: 'autorizacion.php',
       type: 'GET',
       success: function(data){
        actualizarModalLogin();
},
       error: function(data){
        console.log("La sesión no está iniciada.");
       }
     });
}

function mostrarRegistro(){
  //seguir
}

   $(document).ready(function(){
     carrito = new Carrito(1);
     articulos = new Array();
     $.ajax({
       url: 'categorias.php',
       dataType: 'json',
       success: function(data){
         $.each(data, function(){
           $('' + this.nombre + '').appendTo('#categorias');
         });
       }
     });
     $('.anyadir').on("click", toCarrito);

     $('.comprar').on("click", procesarCarrito);

     $('#categorias').on("click",'.list-group-item',mostrarArticulos);

     $('#productos').html(null); //mostrar productos top.

     $('#verCarritoBT').on('click',mostrarCarrito);

     $('#verLoginBT').on('click',mostrarLogin);
     $('#registroBT').on('click',mostrarRegistro);
     logged();

  });
<commit_msg>feat: añadida validacion login carrito<commit_after>var articulos, carrito, total;

function mostrarArticulos(){
       var contador = 0;
       var categoria = $(this).attr('id');
       var nombreCategoria = $(this).text();
       $.ajax({
           url:'articulos.php',
           type: 'POST',
           dataType: 'json',
           data: {categoria},
           success: function(data){
               $('#productos').html(null);
               $('
'+nombreCategoria+'
').appendTo('#productos');
               $('

').appendTo('#productos');
               $.each(data,function(){
                 var articulo = new Articulo(this.id,this.nombre,this.descripcion,this.precio,this.imagen,this.categoria,0);
                 articulos.push(articulo);
                 var idArticulo = "articulo"+articulo.id;
                 var imagen = "./img/"+articulo.imagen;
                 var imagenHTML = ''+'';
                 $('
').appendTo('#articulos').append('
'+ imagenHTML +'
').append('
'+articulo.nombre+'
').append('
'+articulo.descripcion+'
').append('
Precio: '+articulo.precio+'€'+'
').append('<button class="botonCarrito btn btn-success" idArticulo='+articulo.id+'> AÑADIR AL CARRITO</button>');
                 contador++;
                 if (contador == 3){
                   $('

').appendTo('#articulos');
                   contador = 0;
                 }
               });

              /*Modificando
              --------------------------------------------------------------*/
              $('.botonCarrito').on('click', function(){

                $('.anyadir').attr('idarticulo',$(this).attr('idArticulo'));
                texto="";
                texto+="" + $(this).parent().find('.titulo').text() + "
";
                texto+="" + $(this).parent().find('.precio').text() + "

";
                texto+="Descripcion: " + $(this).parent().find('.descripcion').text();
                $('#modalArticulo').modal('show');
                $('.modal-body').html(texto);
              });
            },
            error:function(data){
              console.log(data.responseText);
            }
          });
   }

   function mostrarCarrito(){
   	var carritoHTML = "";
    carritoHTML += "
";
    carritoHTML += "

Producto	Cantidad	Precio	Total

";
    carritoHTML += "
"
   	total = 0;
   	$.each(carrito.articulos,function(){
      /*    --------->>>  MEJORANDO ASPECTO DEL CARRITO*/
      //

      carritoHTML += "

";
      carritoHTML += "

"+this.nombre+"

	";
      carritoHTML += "<button class='btn btn-danger botonBorrarCarrito' idarticulo="+this.id +"> - </button> <input readonly class='text-center' type='text' size='3' value='"+this.cantidad+"'> <button class='btn btn-info botonAgregarCarrito' idarticulo="+this.id+"> + </button>	";
      carritoHTML += ""+this.precio+"€	";
      carritoHTML += ""+(this.precio * this.cantidad)+"€	";
      carritoHTML += "<button class='btn btn-danger botonBorrarArticuloCarrito' idarticulo="+this.id+"> Borrar</button>
";
    });
   	for(var i = 0; i < carrito.articulos.length; i++){
   		total += carrito.articulos[i].precio * carrito.articulos[i].cantidad;
   	}
    //carritoHTML += "
" + "Total: " + total + "€
";
    carritoHTML += "

Total:

"+total+"€

";
    carritoHTML += "

";

   	$('#modalCarrito').modal('show');
    $('#cuerpoCarrito').html(carritoHTML);
    $('.botonBorrarCarrito').on('click',borrarFromCarrito);
    $('.botonAgregarCarrito').on('click',sumarFromCarrito);
    $('.botonBorrarArticuloCarrito').on('click',borrarArticuloCarrito);
  }

   function borrarFromCarrito(){
   	var index = $(this).attr('idarticulo');
   	for(var i=0; i < carrito.articulos.length; i++){
   		if(carrito.articulos[i].id == index){
			  carrito.articulos[i].cantidad--;
  			if (carrito.articulos[i].cantidad < 1) {
          carrito.articulos.splice(i,1);
  			}
      }
   	}
   	mostrarCarrito();
   }

   function borrarArticuloCarrito(){
     var index = $(this).attr('idarticulo');
     for (var i = 0; i < carrito.articulos.length; i++) {
       if (carrito.articulos[i].id == index) {
         carrito.articulos.splice(i,1);
       }
     }
     mostrarCarrito();
   }

   function sumarFromCarrito(){
   	var index = $(this).attr('idarticulo');
   	for(var i = 0;i < carrito.articulos.length; i++){
   		if(carrito.articulos[i].id == index) {
        carrito.articulos[i].cantidad++;
      };
    }
   	mostrarCarrito();
   }

   function toCarrito(){
     var articulo;
     var existe = false;
     var indice;

     for(var i = 0; i < articulos.length; i++){
       if(articulos[i].id == $(this).attr('idarticulo')){
         articulo = articulos[i];
       }
     }
     for(var i = 0;i<carrito.articulos.length;i++){
       if(carrito.articulos[i].id == articulo.id){
         existe = true;
         indice = i;
       }
     }
     if(existe) {
       carrito.articulos[indice].cantidad++;
     } else{
     	articulo.cantidad = 1;
      carrito.addArticulo(articulo);
    }
   }

   function procesarCarrito() {
     // Añadimos el precio total y pasamos el carrito al servidor.
     carrito.total = total;
     var carritoJson = JSON.stringify(carrito);
     if (carrito.articulos.length < 1) {
       alert("Por favor, seleccione algún producto para comprar.");
     }
     else {
      if (typeof sesion === 'undefined') {
          alert("Por favor, inicia sesión para poder comprar.");
}else{
  $.ajax({
       url:'carrito.php',
       type: 'POST',
       data: {'carrito':carritoJson},
       success: function(data) {
         alert("Compra realizada satisfactoriamente.");
         carrito = new Carrito(1);

       }, error: function(data) {
         $("body").html(data.responseText);
       }
     });}
}

   }

function mostrarLogin(){

  $('#modalLogin').modal('show');
  $('#loginBT').on('click',login);
}

function login(){

  var email = $('#emailTF').val();
  var contrasenya = $('#passTF').val();
  var credencial = new Credencial(email,contrasenya);
  var credencialJson = credencial.toJson();
     $.ajax({
       url: 'login.php',
       type: 'POST',
       data: {'credencial':credencialJson},
       success: function(data){
          alert("Login OK" + data);
          actualizarModalLogin();

       },
       error: function(data){
          alert("Login incorrecto.");
       }
     });

}

function actualizarModalLogin(){
  $.ajax({
       url: 'session.php',
       type: 'GET',
       success: function(data){
          sesion = JSON.parse(data);
          $('.login-modal').html("
 Has iniciado sesión como "+sesion.email);
          $('.login-modal-footer').html("<button type='button' class='btn btn-info' data-dismiss='modal'>Vale</button> <button class='btn btn-success' id='logoutBT'> Logout </button>");
          $('#logoutBT').on('click',logout);
          if (sesion.empleado == "true") {
              $('.login-modal-footer').append("Panel de Administración");
          };
       },
       error: function(data){
          console.log("Ha fallado la petición HTTP. "+data.responseText);
       }
     });
}

function logout(){
  $.ajax({
       url: 'logout.php',
       type: 'GET',
       success: function(data){
        alert("Logout OK");
        location.reload();
},
       error: function(data){
          console.log("Ha fallado la petición HTTP. "+data.responseText);
       }
     });
}

function logged(){
   $.ajax({
       url: 'autorizacion.php',
       type: 'GET',
       success: function(data){
        actualizarModalLogin();
},
       error: function(data){
        console.log("La sesión no está iniciada.");
       }
     });
}

function mostrarRegistro(){
  //seguir
}

   $(document).ready(function(){
     carrito = new Carrito(1);
     articulos = new Array();
     $.ajax({
       url: 'categorias.php',
       dataType: 'json',
       success: function(data){
         $.each(data, function(){
           $('' + this.nombre + '').appendTo('#categorias');
         });
       }
     });
     $('.anyadir').on("click", toCarrito);

     $('.comprar').on("click", procesarCarrito);

     $('#categorias').on("click",'.list-group-item',mostrarArticulos);

     $('#productos').html(null); //mostrar productos top.

     $('#verCarritoBT').on('click',mostrarCarrito);

     $('#verLoginBT').on('click',mostrarLogin);
     $('#registroBT').on('click',mostrarRegistro);
     logged();

  });
<|endoftext|>


<commit_before>/**
 * @fileoverview PQR related 3Dmol manipulations
 * @author JoshJRogan@gmail.com (Josh Rogan)
 * @author ritwikg2004@live.com (Ritwik Gupta)
 */

pqr.threeDMole = {
	all_viewers: [],
	rotation_timers: [],
	data_type: 'mol2',
	default_style: 'stick',
	backgroundColor: 0xffffff,
	backgroundOpacity: 1.0,
	rotationTime: 9,
	rotationXDegree: 1, //How many degrees to move every rotationTime
	rotationYDegree: 1,
	showSurface: true
};

/**
 * Update viewers
 *
 * @param  {Object} config optional config to override default settings
 */
pqr.threeDMole.initViewers = function(config) {
	this.all_viewers = $3Dmol.viewers;

	$.each(this.all_viewers, function(index, viewer) {
		pqr.threeDMole.clearBackgrounds(viewer);
		// pqr.threeDMole.rotate(viewer);
	});
};

/**
 * Set all of the background color alpha channel to 0. Cannot be done
 * with data attributes.
 *
 * @param  {GLviewer}
 */
pqr.threeDMole.clearBackgrounds = function(viewer) {
	viewer.setBackgroundColor(this.backgroundColor, 0);
	viewer.resize();
	viewer.render();

	if (pqr.debug) console.log("Clearing Background: ", viewer);
};

/**
 * Rotate a molecule viewer
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.rotate = function(viewer) {
	var rotation_timers = window.setInterval(function() {
		viewer.rotate(pqr.threeDMole.rotationYDegree, 'y');
		viewer.rotate(pqr.threeDMole.rotationXDegree, 'x');
		viewer.render();
	}, this.rotationTime, viewer);

	this.rotation_timers.push(rotation_timers);

	if (pqr.debug) console.log("Adding Rotation: ", viewer);
};

/**
 * Toggle the rotation of the viewer. Only hanldes one viewer.
 *
 * @param  {GLViewer} the viewer to toggle the rotation
 */
pqr.threeDMole.toggleRotation = function(viewer) {
	var rotation_timer = this.rotation_timers.pop();
	if (pqr.debug) console.log("The rotation time is: ", rotation_timer);
	if (rotation_timer !== undefined) {
		if (pqr.debug) console.log("Rotation timer not null. Clearing interval");
		clearInterval(rotation_timer);
	} else {
		if (pqr.debug) console.log("Rotation timer is null. Restarting rotation");
		this.rotate(this.all_viewers[0]);
	}
};

/**
 * Update the surface color to the correct value
 *
 * @param  {GLViewer} the viewer to set the surfaceColor on
 */
pqr.threeDMole.setSurfaceColor = function(viewer) {

};

/**
 * Toggle the surface of this viewer.
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.toggleSurface = function(viewer) {
	viewer = typeof viewer !== 'undefined' ? viewer : this.all_viewers[0];

	if (pqr.debug) console.log("Toggling the surface of ", viewer);

	this.removeSurface(viewer);
};

/**
 * Remove all of the surfaces for this viewere
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.removeSurface = function(viewer) {
	viewer.removeAllSurfaces();
	viewer.render();
	if (pqr.debug) console.log("Surface Removed");
};

/**
 * Reset the viewer to the default zoom level
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.resetView = function(viewer) {
	pqr.threeDMole.all_viewers[0].zoomTo();
};

pqr.threeDMole.addArrow = function(viewer, x, y, z) {
	pqr.threeDMole.all_viewers[0].addArrow({end: new $3Dmol.Vector3(x, y, z), color: "black", wireframe: false});
    pqr.threeDMole.all_viewers[0].render();
};

/**
 * Change the layout style of the selected viewer
 *
 * @param  {String} newStyle - the type of style to change this viewer to
 */
pqr.threeDMole.changeStyle = function(newStyle) {
	var viewer = this.all_viewers[0]; //Currently only getting the first viewer that exists
	if (viewer) {
		if (newStyle == "sphere") {
			viewer.setStyle({}, {
				sphere: {}
			});
		} else if (newStyle == "stick") {
			viewer.setStyle({}, {
				stick: {}
			});
		} else if (newStyle == "cross") {
			viewer.setStyle({}, {
				cross: {}
			});
		} else if (newStyle == "line") {
			viewer.setStyle({}, {
				line: {}
			});
		} else if (newStyle == "ballstick") {
            viewer.setStyle({}, {
                stick: {radius: 0.15},
                sphere: {radius: 0.40}
            });
        }

		viewer.render();
	}
};
<commit_msg>Change hard tabs to 4 spaces<commit_after>/**
 * @fileoverview PQR related 3Dmol manipulations
 * @author JoshJRogan@gmail.com (Josh Rogan)
 * @author ritwikg2004@live.com (Ritwik Gupta)
 */

pqr.threeDMole = {
    all_viewers: [],
    rotation_timers: [],
    data_type: 'mol2',
    default_style: 'stick',
    backgroundColor: 0xffffff,
    backgroundOpacity: 1.0,
    rotationTime: 9,
    rotationXDegree: 1, //How many degrees to move every rotationTime
    rotationYDegree: 1,
    showSurface: true
};

/**
 * Update viewers
 *
 * @param  {Object} config optional config to override default settings
 */
pqr.threeDMole.initViewers = function(config) {
    this.all_viewers = $3Dmol.viewers;

    $.each(this.all_viewers, function(index, viewer) {
        pqr.threeDMole.clearBackgrounds(viewer);
        // pqr.threeDMole.rotate(viewer);
    });
};

/**
 * Set all of the background color alpha channel to 0. Cannot be done
 * with data attributes.
 *
 * @param  {GLviewer}
 */
pqr.threeDMole.clearBackgrounds = function(viewer) {
    viewer.setBackgroundColor(this.backgroundColor, 0);
    viewer.resize();
    viewer.render();

    if (pqr.debug) console.log("Clearing Background: ", viewer);
};

/**
 * Rotate a molecule viewer
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.rotate = function(viewer) {
    var rotation_timers = window.setInterval(function() {
        viewer.rotate(pqr.threeDMole.rotationYDegree, 'y');
        viewer.rotate(pqr.threeDMole.rotationXDegree, 'x');
        viewer.render();
    }, this.rotationTime, viewer);

    this.rotation_timers.push(rotation_timers);

    if (pqr.debug) console.log("Adding Rotation: ", viewer);
};

/**
 * Toggle the rotation of the viewer. Only hanldes one viewer.
 *
 * @param  {GLViewer} the viewer to toggle the rotation
 */
pqr.threeDMole.toggleRotation = function(viewer) {
    var rotation_timer = this.rotation_timers.pop();
    if (pqr.debug) console.log("The rotation time is: ", rotation_timer);
    if (rotation_timer !== undefined) {
        if (pqr.debug) console.log("Rotation timer not null. Clearing interval");
        clearInterval(rotation_timer);
    } else {
        if (pqr.debug) console.log("Rotation timer is null. Restarting rotation");
        this.rotate(this.all_viewers[0]);
    }
};

/**
 * Update the surface color to the correct value
 *
 * @param  {GLViewer} the viewer to set the surfaceColor on
 */
pqr.threeDMole.setSurfaceColor = function(viewer) {

};

/**
 * Toggle the surface of this viewer.
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.toggleSurface = function(viewer) {
    viewer = typeof viewer !== 'undefined' ? viewer : this.all_viewers[0];

    if (pqr.debug) console.log("Toggling the surface of ", viewer);

    this.removeSurface(viewer);
};

/**
 * Remove all of the surfaces for this viewere
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.removeSurface = function(viewer) {
    viewer.removeAllSurfaces();
    viewer.render();
    if (pqr.debug) console.log("Surface Removed");
};

/**
 * Reset the viewer to the default zoom level
 *
 * @param  {GLViewer}
 */
pqr.threeDMole.resetView = function(viewer) {
    pqr.threeDMole.all_viewers[0].zoomTo();
};

pqr.threeDMole.addArrow = function(viewer, x, y, z) {
    pqr.threeDMole.all_viewers[0].addArrow({end: new $3Dmol.Vector3(x, y, z), color: "black", wireframe: false});
    pqr.threeDMole.all_viewers[0].render();
};

/**
 * Change the layout style of the selected viewer
 *
 * @param  {String} newStyle - the type of style to change this viewer to
 */
pqr.threeDMole.changeStyle = function(newStyle) {
    var viewer = this.all_viewers[0]; //Currently only getting the first viewer that exists
    if (viewer) {
        if (newStyle == "sphere") {
            viewer.setStyle({}, {
                sphere: {}
            });
        } else if (newStyle == "stick") {
            viewer.setStyle({}, {
                stick: {}
            });
        } else if (newStyle == "cross") {
            viewer.setStyle({}, {
                cross: {}
            });
        } else if (newStyle == "line") {
            viewer.setStyle({}, {
                line: {}
            });
        } else if (newStyle == "ballstick") {
            viewer.setStyle({}, {
                stick: {radius: 0.15},
                sphere: {radius: 0.40}
            });
        }

        viewer.render();
    }
};
<|endoftext|>


<commit_before>import { addTypes, wrapComponent } from './utils'

import Autocomplete from './components/form/autocomplete'
import Datepicker from './components/form/datepicker'
import Field from './components/form/field'
import Input from './components/form/input'
import Checkbox from './components/form/checkbox'
import Radio from './components/form/radio'
import Select from './components/form/select'
import Switch from './components/form/switch'
import Taginput from './components/form/taginput'
import Timepicker from './components/form/timepicker'
import Upload from './components/form/upload'

const VueFormlyBuefy = {
  install (Vue, options) {
    addTypes(Vue.$formly, {
      'autocomplete': Autocomplete,
      'autocomplete-with-field': wrapComponent(Autocomplete, Field.Default),
      'checkbox': Checkbox.Default,
      'checkbox-button': wrapComponent(Checkbox.CheckboxButton, Field.MultiField),
      'datepicker': Datepicker,
      'datepicker-with-field': wrapComponent(Datepicker, Field.Default),
      'input': Input,
      'input-with-field': wrapComponent(Input, Field.Default),
      'radio': Radio.Default,
      'radio-button': wrapComponent(Radio.RadioButton, Field.MultiField),
      'select': Select,
      'select-with-field': wrapComponent(Select, Field.Default),
      'switch': Switch,
      'taginput': Taginput,
      'taginput-with-field': wrapComponent(Taginput, Field.Default),
      'timepicker': Timepicker,
      'timepicker-with-field': wrapComponent(Timepicker, Field.Default),
      'upload': Upload.Default,
      'upload-drag-drop': Upload.DragDrop
    })
  }
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(VueFormlyBuefy)
}

export default VueFormlyBuefy
<commit_msg>Update supported Formly types<commit_after>import { addTypes, wrapComponent } from './utils'

import Autocomplete from './components/form/autocomplete'
import Datepicker from './components/form/datepicker'
import Input from './components/form/input'
import Checkbox from './components/form/checkbox'
import Radio from './components/form/radio'
import Select from './components/form/select'
import Switch from './components/form/switch'
import Taginput from './components/form/taginput'
import Timepicker from './components/form/timepicker'
import Upload from './components/form/upload'

import MultiBlock from './components/wrappers/block'
import Field from './components/wrappers/field'

const VueFormlyBuefy = {
  install (Vue, options) {
    addTypes(Vue.$formly, {
      'autocomplete': Autocomplete,
      'autocomplete-with-field': wrapComponent(Autocomplete, Field.Default),
      'checkbox': Checkbox.Default,
      'checkbox-with-block': wrapComponent(Checkbox.Default, MultiBlock),
      'checkbox-with-field': wrapComponent(Checkbox.Default, Field.MultiField),
      'checkbox-button': wrapComponent(Checkbox.CheckboxButton, Field.MultiField),
      'datepicker': Datepicker,
      'datepicker-with-field': wrapComponent(Datepicker, Field.Default),
      'input': Input,
      'input-with-field': wrapComponent(Input, Field.Default),
      'radio': Radio.Default,
      'radio-with-block': wrapComponent(Radio.Default, MultiBlock),
      'radio-with-field': wrapComponent(Radio.Default, Field.MultiField),
      'radio-button': wrapComponent(Radio.RadioButton, Field.MultiField),
      'select': Select,
      'select-with-field': wrapComponent(Select, Field.Default),
      'switch': Switch,
      'taginput': Taginput,
      'taginput-with-field': wrapComponent(Taginput, Field.Default),
      'timepicker': Timepicker,
      'timepicker-with-field': wrapComponent(Timepicker, Field.Default),
      'upload': Upload.Default,
      'upload-drag-drop': Upload.DragDrop
    })
  }
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(VueFormlyBuefy)
}

export default VueFormlyBuefy
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Square extends React.Component {
    render() {
        return (
            <button className="square">
                {/* TODO */}
            </button>
        );
    }
}

class Board extends React.Component {

    renderSquare(i) {
        return <Square/>;
    }

    render() {
        const status = 'Next player: X';

        return (

{status}

                    {this.renderSquare(0)}
                    {this.renderSquare(1)}
                    {this.renderSquare(2)}

                    {this.renderSquare(3)}
                    {this.renderSquare(4)}
                    {this.renderSquare(5)}

                    {this.renderSquare(6)}
                    {this.renderSquare(7)}
                    {this.renderSquare(8)}

        );
    }
}

class Game extends React.Component {
    render() {
        return (

                    <Board/>

{/* status */}

{/* TODO */}

        );
    }
}

// ========================================

ReactDOM.render(
    <Game/>,
    document.getElementById('root')
);
<commit_msg>When click a square display an X<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Square extends React.Component {

    constructor() {
        super();
        this.state = {
            value: null,
        };
    }

    render() {
        return (
            <button className="square" onClick={() => this.setState({value: 'X'})}>
                {this.state.value}
            </button>
        );
    }
}

class Board extends React.Component {

    renderSquare(i) {
        return <Square value={i}/>;
    }

    render() {
        const status = 'Next player: X';

        return (

{status}

                    {this.renderSquare(0)}
                    {this.renderSquare(1)}
                    {this.renderSquare(2)}

                    {this.renderSquare(3)}
                    {this.renderSquare(4)}
                    {this.renderSquare(5)}

                    {this.renderSquare(6)}
                    {this.renderSquare(7)}
                    {this.renderSquare(8)}

        );
    }
}

class Game extends React.Component {
    render() {
        return (

                    <Board/>

{/* status */}

{/* TODO */}

        );
    }
}

// ========================================

ReactDOM.render(
    <Game/>,
    document.getElementById('root')
);
<|endoftext|>


<commit_before>var Upvote = (function (window, document) {

	that = this;

	// endEvent = hasTouch ? 'touchend' : 'mouseup',

	Upvote = function (opts) {

		that = this;

		this.current_category = 'us';

		// ---------------------------------------------------------
		// Muench launch
		// ---------------------------------------------------------

		// Options from user
		for (i in opts) this.options[i] = opts[i];

		// ---------------------------------------------------------
		// Skimmin launch
		// ---------------------------------------------------------

        	$('.upvote-container').on('click', this.fn_tap_upvote.bind(this));
        	$('.category-container').on('click', this.fn_change_category.bind(this));

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		this.fn_hide_rendering_icons();
		this.fn_loading();
       		this.fn_reveal_content();

    	};

	Upvote.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	// primarily used to hide slow rendering
        	fn_loading: function() {

            	that = this;

            	$('#L').fadeIn(0);
            	$('#L').addClass('animated zoomIn');

            	setTimeout(function() {
            		$('#O').fadeIn(0);
            		$('#O').addClass('animated zoomIn');
            	}, 75);

            	setTimeout(function() {
            		$('#A').fadeIn(0);
            		$('#A').addClass('animated zoomIn');
            	}, 150);

            	setTimeout(function() {
            		$('#D').fadeIn(0);
            		$('#D').addClass('animated zoomIn');
            	}, 225);

            	setTimeout(function() {
            		$('#I').fadeIn(0);
            		$('#I').addClass('animated zoomIn');
            	}, 300);

            	setTimeout(function() {
            		$('#N').fadeIn(0);
            		$('#N').addClass('animated zoomIn');
            	}, 375);

            	setTimeout(function() {
            		$('#G').fadeIn(0);
            		$('#G').addClass('animated zoomIn');
            	}, 450);

            	/*setTimeout(function() {
            		$('#loading-container').addClass('animated pulse');
            	}, 1500);*/

            	/*setTimeout(function() {
            		$('#L').removeClass('animated zoomIn');
            		$('#O').removeClass('animated zoomIn');
            		$('#A').removeClass('animated zoomIn');
            		$('#D').removeClass('animated zoomIn');
            		$('#I').removeClass('animated zoomIn');
            		$('#N').removeClass('animated zoomIn');
            		$('#G').removeClass('animated zoomIn');
            	}, 1500);*/

            	int_loading_count = 0;
            	arr_colors = Array('rgba(52, 152, 219, 1)', 'rgba(255, 140, 0, 1)', 'rgba(231, 76, 60, 1)', 'rgba(0, 128, 0, .9)', 'rgba(0, 154, 136, .9)', 'rgba(164, 121, 228, 1)');

            	// bool_kill_next_loop = false;

        		// $('#loading-circle').addClass('animated pulse');

        	pulsing_circle_interval = setInterval(function() {

        			/*$('#L').fadeOut(300);
        			$('#O').fadeOut(300);
        			$('#A').fadeOut(300);
        			$('#D').fadeOut(300);
        			$('#I').fadeOut(300);
        			$('#N').fadeOut(300);
        			$('#G').fadeOut(300);*/

        			if (int_loading_count == 0 || int_loading_count == 2 || int_loading_count == 4 || int_loading_count == 6) {

        				$('#L').fadeIn(0);
            				$('#L').addClass('animated zoomIn');

            				setTimeout(function() {
            					$('#O').fadeIn(0);
            					$('#O').addClass('animated zoomIn');
            				}, 75);

            				setTimeout(function() {
            					$('#A').fadeIn(0);
            					$('#A').addClass('animated zoomIn');
            				}, 150);

            				setTimeout(function() {
            					$('#D').fadeIn(0);
            					$('#D').addClass('animated zoomIn');
            				}, 225);

            				setTimeout(function() {
            					$('#I').fadeIn(0);
            					$('#I').addClass('animated zoomIn');
            				}, 300);

            				setTimeout(function() {
            					$('#N').fadeIn(0);
            					$('#N').addClass('animated zoomIn');
            				}, 375);

            				setTimeout(function() {
            					$('#G').fadeIn(0);
            					$('#G').addClass('animated zoomIn');
            				}, 450);

        				setTimeout(function() {
        					$('#L').removeClass('animated zoomIn');
        					$('#O').removeClass('animated zoomIn');
        					$('#A').removeClass('animated zoomIn');
        					$('#D').removeClass('animated zoomIn');
        					$('#I').removeClass('animated zoomIn');
        					$('#N').removeClass('animated zoomIn');
        					$('#G').removeClass('animated zoomIn');
        				}, 1000);

        				setTimeout(function(){
        					$('#L').addClass('animated zoomOut');
        					$('#O').addClass('animated zoomOut');
        					$('#A').addClass('animated zoomOut');
        					$('#D').addClass('animated zoomOut');
        					$('#I').addClass('animated zoomOut');
        					$('#N').addClass('animated zoomOut');
        					$('#G').addClass('animated zoomOut');
        				}, 1700);

        			/*if (int_loading_count == 0 || int_loading_count == 2 || int_loading_count == 4 || int_loading_count == 6 || int_loading_count == 8) {
        				$('#L').css('opacity', '0');
        				$('#O').css('opacity', '0');
        				$('#A').css('opacity', '0');
        				$('#D').css('opacity', '0');
        				$('#I').css('opacity', '0');
        				$('#N').css('opacity', '0');
        				$('#G').css('opacity', '0');
        			}
        			else {
        				$('#L').css('opacity', '1');
        				$('#O').css('opacity', '1');
        				$('#A').css('opacity', '1');
        				$('#D').css('opacity', '1');
        				$('#I').css('opacity', '1');
        				$('#N').css('opacity', '1');
        				$('#G').css('opacity', '1');
        			}*/

        			// $('#L').addClass('zoomOut');
        			/*$('#L').css('opacity', '.7');

        			setTimeout(function() {
        				// $('#O').addClass('zoomOut');
        				$('#L').css('opacity', '1');
        				$('#O').css('opacity', '.7');
        			}, 75);

        			setTimeout(function() {
        				$('#O').css('opacity', '1');
        				$('#A').css('opacity', '.7');
        			}, 150);

        			setTimeout(function() {
        				$('#A').css('opacity', '1');
        				$('#D').css('opacity', '.7');
        			}, 225);

        			setTimeout(function() {
        				$('#D').css('opacity', '1');
        				$('#I').css('opacity', '.7');
        			}, 300);

        			setTimeout(function() {
        				$('#I').css('opacity', '1');
        				$('#N').css('opacity', '.7');
        			}, 375);

        			setTimeout(function() {
        				$('#N').css('opacity', '1');
        				$('#G').css('opacity', '.7');
        			}, 450);*/

        			// $('#loading-circle').css('background-color', arr_colors[int_loading_count]);
        			int_loading_count += 1;
        			if (int_loading_count == 8) {
        				clearInterval(pulsing_circle_interval);
        				setTimeout(function() {
        					$('#loading-container').addClass('animated slideOutUp');
        					$('#loading-container').fadeOut(300);
        				}, 500);
        				setTimeout(function() {
        					$('#content').fadeIn(300);
        					$('#content').addClass('animated slideInUp');
        				}, 750);
        			}

        			/*setTimeout(function() {
        				$('#loading-circle').css('opacity', '1');
        			}, 500);*/

        		}, 1800);

        	},

        	fn_reveal_content: function() {

        		/*setTimeout(function() {
        			$('#loading-circle').addClass('animated zoomOut');
        			$('#content').addClass('animated slideInUp');
        		}, 300);*/

        	},

        	fn_hide_rendering_icons: function() {

        		setTimeout(function() {
        			$('.rendering-container').addClass('display-none');
        		}, 3000);

        	},

        	fn_change_category: function(e) {

        		if (this.current_category == 'world') {
        			$('#category-container').removeClass('world')
        			$('#category-container').addClass('us');
        			$('#category-text').html('us');
        			this.current_category = 'us';
        		}

        		else if (this.current_category == 'us') {
        			$('#category-container').removeClass('us')
        			$('#category-container').addClass('sports');
        			$('#category-text').html('sports');
        			this.current_category = 'sports';
        		}

        		else if (this.current_category == 'sports') {
        			$('#category-container').removeClass('sports')
        			$('#category-container').addClass('business');
        			$('#category-text').html('business');
        			this.current_category = 'business';
        		}

        		else if (this.current_category == 'business') {
        			$('#category-container').removeClass('business')
        			$('#category-container').addClass('technology');
        			$('#category-text').html('technology');
        			this.current_category = 'technology';
        		}

        		else if (this.current_category == 'technology') {
        			$('#category-container').removeClass('technology')
        			$('#category-container').addClass('entertainment');
        			$('#category-text').html('entertainment');
        			this.current_category = 'entertainment';
        		}

        		else {
        			$('#category-container').removeClass('entertainment')
        			$('#category-container').addClass('world');
        			$('#category-text').html('world');
        			this.current_category = 'world';
        		}

        		if ($('.upvote-container').hasClass('upvoted') == true) {
        			$('.upvote-container').removeClass('us world sports business technology entertainment');
        			$('.upvote-text').removeClass('us world sports business technology entertainment');
        			$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			$('.upvote-container').addClass(this.current_category);
        			$('.upvote-text').addClass(this.current_category);
        			$('.upvote-icon').addClass(this.current_category);
        		}

        	},

		fn_tap_upvote: function() {

			if ($('.upvote-container').hasClass('upvoted') == true) {

				$('.upvote-container').removeClass('upvoted');

				setTimeout(function() {
        				$('.upvote-container').removeClass('tapped us world sports business technology entertainment');
        				$('.upvote-text').removeClass('us world sports business technology entertainment');
        				$('.upvote-text').html(30);
        				$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			}, 300);
        		}

			else {

				$('.upvote-container').addClass('upvoted');
    				setTimeout(function() {
        				$('.upvote-container').addClass('tapped ' + that.current_category);
        				$('.upvote-text').addClass(that.current_category);
        				$('.upvote-text').html(31);
        				$('.upvote-icon').addClass(that.current_category);
    				}, 300);
			}

		},

	};

	return Upvote;

})(window, document);
<commit_msg>Update upvote.js<commit_after>var Upvote = (function (window, document) {

	that = this;

	// endEvent = hasTouch ? 'touchend' : 'mouseup',

	Upvote = function (opts) {

		that = this;

		this.current_category = 'us';

		// ---------------------------------------------------------
		// Muench launch
		// ---------------------------------------------------------

		// Options from user
		for (i in opts) this.options[i] = opts[i];

		// ---------------------------------------------------------
		// Skimmin launch
		// ---------------------------------------------------------

        	$('.upvote-container').on('click', this.fn_tap_upvote.bind(this));
        	$('.category-container').on('click', this.fn_change_category.bind(this));

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		this.fn_hide_rendering_icons();
		this.fn_loading();
       		this.fn_reveal_content();

    	};

	Upvote.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	// primarily used to hide slow rendering
        	fn_loading: function() {

            	that = this;

            	$('#L').fadeIn(0);
            	$('#L').addClass('animated zoomIn');

            	setTimeout(function() {
            		$('#O').fadeIn(0);
            		$('#O').addClass('animated zoomIn');
            	}, 75);

            	setTimeout(function() {
            		$('#A').fadeIn(0);
            		$('#A').addClass('animated zoomIn');
            	}, 150);

            	setTimeout(function() {
            		$('#D').fadeIn(0);
            		$('#D').addClass('animated zoomIn');
            	}, 225);

            	setTimeout(function() {
            		$('#I').fadeIn(0);
            		$('#I').addClass('animated zoomIn');
            	}, 300);

            	setTimeout(function() {
            		$('#N').fadeIn(0);
            		$('#N').addClass('animated zoomIn');
            	}, 375);

            	setTimeout(function() {
            		$('#G').fadeIn(0);
            		$('#G').addClass('animated zoomIn');
            	}, 450);

            	/*setTimeout(function() {
            		$('#loading-container').addClass('animated pulse');
            	}, 1500);*/

            	/*setTimeout(function() {
            		$('#L').removeClass('animated zoomIn');
            		$('#O').removeClass('animated zoomIn');
            		$('#A').removeClass('animated zoomIn');
            		$('#D').removeClass('animated zoomIn');
            		$('#I').removeClass('animated zoomIn');
            		$('#N').removeClass('animated zoomIn');
            		$('#G').removeClass('animated zoomIn');
            	}, 1500);*/

            	int_loading_count = 0;
            	arr_colors = Array('rgba(52, 152, 219, 1)', 'rgba(255, 140, 0, 1)', 'rgba(231, 76, 60, 1)', 'rgba(0, 128, 0, .9)', 'rgba(0, 154, 136, .9)', 'rgba(164, 121, 228, 1)');

            	// bool_kill_next_loop = false;

        		// $('#loading-circle').addClass('animated pulse');

        	pulsing_circle_interval = setInterval(function() {

        			/*$('#L').fadeOut(300);
        			$('#O').fadeOut(300);
        			$('#A').fadeOut(300);
        			$('#D').fadeOut(300);
        			$('#I').fadeOut(300);
        			$('#N').fadeOut(300);
        			$('#G').fadeOut(300);*/

        			if (int_loading_count == 0 || int_loading_count == 1 || int_loading_count == 2 || int_loading_count == 3) {

        				$('#L').fadeIn(0);
            				$('#L').addClass('animated zoomIn');

            				setTimeout(function() {
            					$('#O').fadeIn(0);
            					$('#O').addClass('animated zoomIn');
            				}, 75);

            				setTimeout(function() {
            					$('#A').fadeIn(0);
            					$('#A').addClass('animated zoomIn');
            				}, 150);

            				setTimeout(function() {
            					$('#D').fadeIn(0);
            					$('#D').addClass('animated zoomIn');
            				}, 225);

            				setTimeout(function() {
            					$('#I').fadeIn(0);
            					$('#I').addClass('animated zoomIn');
            				}, 300);

            				setTimeout(function() {
            					$('#N').fadeIn(0);
            					$('#N').addClass('animated zoomIn');
            				}, 375);

            				setTimeout(function() {
            					$('#G').fadeIn(0);
            					$('#G').addClass('animated zoomIn');
            				}, 450);

        				setTimeout(function() {
        					$('#L').removeClass('animated zoomIn');
        					$('#O').removeClass('animated zoomIn');
        					$('#A').removeClass('animated zoomIn');
        					$('#D').removeClass('animated zoomIn');
        					$('#I').removeClass('animated zoomIn');
        					$('#N').removeClass('animated zoomIn');
        					$('#G').removeClass('animated zoomIn');
        				}, 1000);

        				setTimeout(function(){
        					$('#L').addClass('animated zoomOut');
        					$('#O').addClass('animated zoomOut');
        					$('#A').addClass('animated zoomOut');
        					$('#D').addClass('animated zoomOut');
        					$('#I').addClass('animated zoomOut');
        					$('#N').addClass('animated zoomOut');
        					$('#G').addClass('animated zoomOut');
        				}, 1700);

        			/*if (int_loading_count == 0 || int_loading_count == 2 || int_loading_count == 4 || int_loading_count == 6 || int_loading_count == 8) {
        				$('#L').css('opacity', '0');
        				$('#O').css('opacity', '0');
        				$('#A').css('opacity', '0');
        				$('#D').css('opacity', '0');
        				$('#I').css('opacity', '0');
        				$('#N').css('opacity', '0');
        				$('#G').css('opacity', '0');
        			}
        			else {
        				$('#L').css('opacity', '1');
        				$('#O').css('opacity', '1');
        				$('#A').css('opacity', '1');
        				$('#D').css('opacity', '1');
        				$('#I').css('opacity', '1');
        				$('#N').css('opacity', '1');
        				$('#G').css('opacity', '1');
        			}*/

        			// $('#L').addClass('zoomOut');
        			/*$('#L').css('opacity', '.7');

        			setTimeout(function() {
        				// $('#O').addClass('zoomOut');
        				$('#L').css('opacity', '1');
        				$('#O').css('opacity', '.7');
        			}, 75);

        			setTimeout(function() {
        				$('#O').css('opacity', '1');
        				$('#A').css('opacity', '.7');
        			}, 150);

        			setTimeout(function() {
        				$('#A').css('opacity', '1');
        				$('#D').css('opacity', '.7');
        			}, 225);

        			setTimeout(function() {
        				$('#D').css('opacity', '1');
        				$('#I').css('opacity', '.7');
        			}, 300);

        			setTimeout(function() {
        				$('#I').css('opacity', '1');
        				$('#N').css('opacity', '.7');
        			}, 375);

        			setTimeout(function() {
        				$('#N').css('opacity', '1');
        				$('#G').css('opacity', '.7');
        			}, 450);*/

        			// $('#loading-circle').css('background-color', arr_colors[int_loading_count]);
        			int_loading_count += 1;
        			if (int_loading_count == 8) {
        				clearInterval(pulsing_circle_interval);
        				setTimeout(function() {
        					$('#loading-container').addClass('animated slideOutUp');
        					$('#loading-container').fadeOut(300);
        				}, 500);
        				setTimeout(function() {
        					$('#content').fadeIn(300);
        					$('#content').addClass('animated slideInUp');
        				}, 750);
        			}

        			/*setTimeout(function() {
        				$('#loading-circle').css('opacity', '1');
        			}, 500);*/

        		}, 1800);

        	},

        	fn_reveal_content: function() {

        		/*setTimeout(function() {
        			$('#loading-circle').addClass('animated zoomOut');
        			$('#content').addClass('animated slideInUp');
        		}, 300);*/

        	},

        	fn_hide_rendering_icons: function() {

        		setTimeout(function() {
        			$('.rendering-container').addClass('display-none');
        		}, 3000);

        	},

        	fn_change_category: function(e) {

        		if (this.current_category == 'world') {
        			$('#category-container').removeClass('world')
        			$('#category-container').addClass('us');
        			$('#category-text').html('us');
        			this.current_category = 'us';
        		}

        		else if (this.current_category == 'us') {
        			$('#category-container').removeClass('us')
        			$('#category-container').addClass('sports');
        			$('#category-text').html('sports');
        			this.current_category = 'sports';
        		}

        		else if (this.current_category == 'sports') {
        			$('#category-container').removeClass('sports')
        			$('#category-container').addClass('business');
        			$('#category-text').html('business');
        			this.current_category = 'business';
        		}

        		else if (this.current_category == 'business') {
        			$('#category-container').removeClass('business')
        			$('#category-container').addClass('technology');
        			$('#category-text').html('technology');
        			this.current_category = 'technology';
        		}

        		else if (this.current_category == 'technology') {
        			$('#category-container').removeClass('technology')
        			$('#category-container').addClass('entertainment');
        			$('#category-text').html('entertainment');
        			this.current_category = 'entertainment';
        		}

        		else {
        			$('#category-container').removeClass('entertainment')
        			$('#category-container').addClass('world');
        			$('#category-text').html('world');
        			this.current_category = 'world';
        		}

        		if ($('.upvote-container').hasClass('upvoted') == true) {
        			$('.upvote-container').removeClass('us world sports business technology entertainment');
        			$('.upvote-text').removeClass('us world sports business technology entertainment');
        			$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			$('.upvote-container').addClass(this.current_category);
        			$('.upvote-text').addClass(this.current_category);
        			$('.upvote-icon').addClass(this.current_category);
        		}

        	},

		fn_tap_upvote: function() {

			if ($('.upvote-container').hasClass('upvoted') == true) {

				$('.upvote-container').removeClass('upvoted');

				setTimeout(function() {
        				$('.upvote-container').removeClass('tapped us world sports business technology entertainment');
        				$('.upvote-text').removeClass('us world sports business technology entertainment');
        				$('.upvote-text').html(30);
        				$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			}, 300);
        		}

			else {

				$('.upvote-container').addClass('upvoted');
    				setTimeout(function() {
        				$('.upvote-container').addClass('tapped ' + that.current_category);
        				$('.upvote-text').addClass(that.current_category);
        				$('.upvote-text').html(31);
        				$('.upvote-icon').addClass(that.current_category);
    				}, 300);
			}

		},

	};

	return Upvote;

})(window, document);
<|endoftext|>


<commit_before>import program from 'commander'
import pkg from '../package.json'
import aliasEnv from '../script/util/alias-env'
import pkgUpdate from '../script/util/pkg-update'
import taskInit from '../script/task/init'
import taskWebpack from '../script/task/webpack'
import taskCopy from '../script/task/copy'
import taskPostcss from '../script/task/postcss'
import taskGeneratePages from '../script/task/generate-pages'
import taskServeClient from '../script/task/serve-client'
import watchTask from '../script/task/watch'
import taskClean from '../script/task/clean'
import taskUpload from '../script/task/upload'
import taskPack from '../script/task/pack'

pkgUpdate()

function keyMapTask(key) {
  switch (key) {
    case 'init':
      return taskInitcase
    case 'webpack':
      return taskWebpack
    case 'copy':
      return taskCopy
    case 'postcss':
      return taskPostcss
    case 'generate-pages':
      return taskGeneratePages
    case 'serve-client':
      return taskServeClient
    case 'clean':
      return taskClean
    case 'upload':
      return taskUpload
    case 'pack':
      return taskPack
    default:
  }
}

function runTasks(list) {
  let idx = 0
  let exec = () => {
    return keyMapTask(list[idx])()
      .then(() => {
        idx += 1
        if (idx < list.length) {
          exec()
        }
      })
      .catch((err) => {
        throw new Error(err)
      })
  }
  exec()
}

program.version(pkg.version)

program
  .command('init')
  .action(() => {
    taskInit()
  })

program
  .command('build')
  .description('produce dist files')
  .option('--watch', 'watch fs tree, work automaticly')
  .option('--serve', 'serve static files')
  .action((options) => {
    process.env.NODE_ENV = aliasEnv(program['node_env'])
    if (options.watch) {
      watchTask()
    }
    var tasks = ['clean', 'copy', 'webpack', 'postcss', 'generate-pages']
    if (options.serve) {
      tasks.push('serve-client')
    }
    runTasks(tasks)
  })

program
  .command('upload')
  .description('upload dist files to remote server')
  .action(() => {
    taskUpload()
  })

program
  .command('clean')
  .description('remove all tmp folders')
  .action(() => {
    taskClean()
  })

program
  .command('pack')
  .description('pack dist files')
  .action(() => {
    taskPack()
  })

program
  .option('-t, --tasks <items>', 'list tasks to exec', (val) => {
    return val.split(',')
  })
  .option('-e, --node_env [env]', 'define NODE_ENV, a string should be "development", "dev", "experiment", "exp", "production" or "prod"')

program.parse(process.argv)

if (program.tasks) {
  process.env.NODE_ENV = aliasEnv(program['node_env'])
  runTasks(program.tasks)
}
<commit_msg>fix bin wcx<commit_after>#!/usr/bin/env node

import program from 'commander'
import pkg from '../package.json'
import aliasEnv from '../script/util/alias-env'
import pkgUpdate from '../script/util/pkg-update'
import taskInit from '../script/task/init'
import taskWebpack from '../script/task/webpack'
import taskCopy from '../script/task/copy'
import taskPostcss from '../script/task/postcss'
import taskGeneratePages from '../script/task/generate-pages'
import taskServeClient from '../script/task/serve-client'
import watchTask from '../script/task/watch'
import taskClean from '../script/task/clean'
import taskUpload from '../script/task/upload'
import taskPack from '../script/task/pack'

pkgUpdate()

function keyMapTask(key) {
  switch (key) {
    case 'init':
      return taskInitcase
    case 'webpack':
      return taskWebpack
    case 'copy':
      return taskCopy
    case 'postcss':
      return taskPostcss
    case 'generate-pages':
      return taskGeneratePages
    case 'serve-client':
      return taskServeClient
    case 'clean':
      return taskClean
    case 'upload':
      return taskUpload
    case 'pack':
      return taskPack
    default:
  }
}

function runTasks(list) {
  let idx = 0
  let exec = () => {
    return keyMapTask(list[idx])()
      .then(() => {
        idx += 1
        if (idx < list.length) {
          exec()
        }
      })
      .catch((err) => {
        throw new Error(err)
      })
  }
  exec()
}

program.version(pkg.version)

program
  .command('init')
  .action(() => {
    taskInit()
  })

program
  .command('build')
  .description('produce dist files')
  .option('--watch', 'watch fs tree, work automaticly')
  .option('--serve', 'serve static files')
  .action((options) => {
    process.env.NODE_ENV = aliasEnv(program['node_env'])
    if (options.watch) {
      watchTask()
    }
    var tasks = ['clean', 'copy', 'webpack', 'postcss', 'generate-pages']
    if (options.serve) {
      tasks.push('serve-client')
    }
    runTasks(tasks)
  })

program
  .command('upload')
  .description('upload dist files to remote server')
  .action(() => {
    taskUpload()
  })

program
  .command('clean')
  .description('remove all tmp folders')
  .action(() => {
    taskClean()
  })

program
  .command('pack')
  .description('pack dist files')
  .action(() => {
    taskPack()
  })

program
  .option('-t, --tasks <items>', 'tasks\' list to exec', (val) => {
    return val.split(',')
  })
  .option('-e, --node_env [env]', 'define NODE_ENV, a string should be "development", "dev", "experiment", "exp", "production" or "prod"')

program.parse(process.argv)

if (program.tasks) {
  process.env.NODE_ENV = aliasEnv(program['node_env'])
  runTasks(program.tasks)
}
<|endoftext|>


<commit_before>(function () {
    "use strict";

    angular.module("angularFretboard", [])
        .directive("fretboard", fretboard)
        .directive("tuning", ["twoWayDataBindingHelper", tuning])
        .directive("numFrets", ["twoWayDataBindingHelper", numFrets])
        .directive("isChordMode", ["twoWayDataBindingHelper", isChordMode])
        .directive("noteClickingDisabled", ["twoWayDataBindingHelper", noteClickingDisabled])
        .directive("noteMode", ["twoWayDataBindingHelper", noteMode])
        .directive("intervalSettings", ["twoWayDataBindingHelper", intervalSettings])
        .directive("allNoteLetters", allNoteLetters)
        .directive("animationSpeed", animationSpeed)
        .directive("noteCircleList", noteCircleList)
        .directive("clickedNotes", clickedNotes)
        .factory("twoWayDataBindingHelper", twoWayDataBindingHelper);

    function twoWayDataBindingHelper() {
        function bind(ngModelCtrl, viewValueFn, fretboardCtrl, renderFn, scope) {
            var isFirst = true;

            ngModelCtrl.$render = render;

            function render() {
                if (isFirst) {
                    if (isUndefinedOrNull(ngModelCtrl.$viewValue)) {
                        scope.$evalAsync(function () {
                            ngModelCtrl.$setViewValue(viewValueFn());
                        });
                    }
                    isFirst = false;
                } else {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = true;
                    renderFn(ngModelCtrl.$viewValue);
                }
            };
        }

        return {
            bind: bind
        };
    }

    function fretboard() {
        return {
            restrict: "AE",
            scope: {
                config: "=fretboardConfig"
            },
            controller: ["$scope", "$element", fretboardController],
            // The inner directives each have their own ngModel which handle two-way data-binding for a single config property.
            template:
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            ""
        }

        function fretboardController($scope, $element) {
            var ctrl = this;
            ctrl.clickedNotesModelNeedsUpdate = false;

            $scope.$on("$destroy", function () {
                destroy(ctrl);
            });

            $scope.$watch(function () {
                return $scope.config;
            }, function (newVal, oldVal) {
                if (newVal) {
                    initialize($scope, $element, ctrl);
                } else {
                    destroy(ctrl);
                }
            });

            function initialize() {
                // When a user clicks a note, we need to ensure that the clicked notes on the parent
                // scope are updated before the clicked note callbacks are invoked. So we delete the
                // clicked note callbacks from the config here so the plugin cannot invoke them. We
                // hand the callbacks to the clickedNotes directive, which will first update
                // the clicked notes on the parent scope and then invoke the callbacks.
                ctrl.onClickedNotesChange = $scope.config.onClickedNotesChange;

                var configCopy = angular.copy($scope.config);
                delete configCopy.onClickedNotesChange;
                $element.fretboard(configCopy);

                ctrl.jQueryFretboardApi = $element.data("api");
            }

            function destroy() {
                if (ctrl.jQueryFretboardApi) {
                    ctrl.jQueryFretboardApi.destroy();
                    ctrl.jQueryFretboardApi = null;
                }
            }
        }
    }

    function tuning(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getTuning,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setTuning,
                    scope
                );
            }
        }
    }

    function numFrets(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getNumFrets,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setNumFrets,
                    scope
                );
            }
        }
    }

    function isChordMode(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getChordMode,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setChordMode,
                    scope
                );
            }
        }
    }

    function noteClickingDisabled(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getNoteClickingDisabled,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setNoteClickingDisabled,
                    scope
                );
            }
        }
    }

    function noteMode(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getNoteMode,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setNoteMode,
                    scope
                );
            }
        }
    }

    function intervalSettings(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getIntervalSettings,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setIntervalSettings,
                    scope
                );
            }
        }
    }

    function animationSpeed() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                scope.$evalAsync(function () {
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getAnimationSpeed());
                });
            }
        }
    }

    function allNoteLetters() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                scope.$evalAsync(function () {
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getAllNoteLetters());
                });
            }
        }
    }

    function noteCircleList() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                scope.$evalAsync(function () {
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getNoteCircles());
                });
            }
        }
    }

    function clickedNotes() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: clickedNotesLinkFn
        }

        function clickedNotesLinkFn(scope, element, attrs, ctrls) {
            var ngModelCtrl = ctrls[0];
            var fretboardCtrl = ctrls[1];

            fretboardCtrl.jQueryFretboardApi.addNotesClickedListener(function () {
                scope.$evalAsync(function () {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = true;
                });
            });

            ngModelCtrl.$render = function () {
                var clickedNotes = ngModelCtrl.$viewValue || [];

                fretboardCtrl.jQueryFretboardApi.clearClickedNotes();
                fretboardCtrl.jQueryFretboardApi.setClickedNotes(clickedNotes);

                scope.$evalAsync(function () {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = true;
                });
            };

            scope.$watch(function () {
                return fretboardCtrl.clickedNotesModelNeedsUpdate;
            }, function (newVal, oldVal) {
                if (!newVal) return;

                scope.$evalAsync(function () {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = false;
                    // Set the callbacks in the correct order so the parent scope is always up to date.
                    // First the new clicked notes get pushed up.
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getClickedNotes());
                    // Then we invoke the callbacks.
                    invokeFns(fretboardCtrl.onClickedNotesChange);
                });
            });
        }

        function invokeFns(fns) {
            if (!fns) return;

            for (var i = 0; i < fns.length; i++) {
                if (!angular.isFunction(fns[i])) continue;

                fns[i]();
            }
        }
    }

    function isUndefinedOrNull(val) {
        return angular.isUndefined(val) || val === null;
    }
})();<commit_msg>Bug fix: note-clicking-disabled was misspelled<commit_after>(function () {
    "use strict";

    angular.module("angularFretboard", [])
        .directive("fretboard", fretboard)
        .directive("tuning", ["twoWayDataBindingHelper", tuning])
        .directive("numFrets", ["twoWayDataBindingHelper", numFrets])
        .directive("isChordMode", ["twoWayDataBindingHelper", isChordMode])
        .directive("noteClickingDisabled", ["twoWayDataBindingHelper", noteClickingDisabled])
        .directive("noteMode", ["twoWayDataBindingHelper", noteMode])
        .directive("intervalSettings", ["twoWayDataBindingHelper", intervalSettings])
        .directive("allNoteLetters", allNoteLetters)
        .directive("animationSpeed", animationSpeed)
        .directive("noteCircleList", noteCircleList)
        .directive("clickedNotes", clickedNotes)
        .factory("twoWayDataBindingHelper", twoWayDataBindingHelper);

    function twoWayDataBindingHelper() {
        function bind(ngModelCtrl, viewValueFn, fretboardCtrl, renderFn, scope) {
            var isFirst = true;

            ngModelCtrl.$render = render;

            function render() {
                if (isFirst) {
                    if (isUndefinedOrNull(ngModelCtrl.$viewValue)) {
                        scope.$evalAsync(function () {
                            ngModelCtrl.$setViewValue(viewValueFn());
                        });
                    }
                    isFirst = false;
                } else {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = true;
                    renderFn(ngModelCtrl.$viewValue);
                }
            };
        }

        return {
            bind: bind
        };
    }

    function fretboard() {
        return {
            restrict: "AE",
            scope: {
                config: "=fretboardConfig"
            },
            controller: ["$scope", "$element", fretboardController],
            // The inner directives each have their own ngModel which handle two-way data-binding for a single config property.
            template:
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            "" +
            ""
        }

        function fretboardController($scope, $element) {
            var ctrl = this;
            ctrl.clickedNotesModelNeedsUpdate = false;

            $scope.$on("$destroy", function () {
                destroy(ctrl);
            });

            $scope.$watch(function () {
                return $scope.config;
            }, function (newVal, oldVal) {
                if (newVal) {
                    initialize($scope, $element, ctrl);
                } else {
                    destroy(ctrl);
                }
            });

            function initialize() {
                // When a user clicks a note, we need to ensure that the clicked notes on the parent
                // scope are updated before the clicked note callbacks are invoked. So we delete the
                // clicked note callbacks from the config here so the plugin cannot invoke them. We
                // hand the callbacks to the clickedNotes directive, which will first update
                // the clicked notes on the parent scope and then invoke the callbacks.
                ctrl.onClickedNotesChange = $scope.config.onClickedNotesChange;

                var configCopy = angular.copy($scope.config);
                delete configCopy.onClickedNotesChange;
                $element.fretboard(configCopy);

                ctrl.jQueryFretboardApi = $element.data("api");
            }

            function destroy() {
                if (ctrl.jQueryFretboardApi) {
                    ctrl.jQueryFretboardApi.destroy();
                    ctrl.jQueryFretboardApi = null;
                }
            }
        }
    }

    function tuning(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getTuning,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setTuning,
                    scope
                );
            }
        }
    }

    function numFrets(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getNumFrets,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setNumFrets,
                    scope
                );
            }
        }
    }

    function isChordMode(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getChordMode,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setChordMode,
                    scope
                );
            }
        }
    }

    function noteClickingDisabled(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getNoteClickingDisabled,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setNoteClickingDisabled,
                    scope
                );
            }
        }
    }

    function noteMode(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getNoteMode,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setNoteMode,
                    scope
                );
            }
        }
    }

    function intervalSettings(twoWayDataBindingHelper) {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                twoWayDataBindingHelper.bind(
                    ngModelCtrl,
                    fretboardCtrl.jQueryFretboardApi.getIntervalSettings,
                    fretboardCtrl,
                    fretboardCtrl.jQueryFretboardApi.setIntervalSettings,
                    scope
                );
            }
        }
    }

    function animationSpeed() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                scope.$evalAsync(function () {
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getAnimationSpeed());
                });
            }
        }
    }

    function allNoteLetters() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                scope.$evalAsync(function () {
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getAllNoteLetters());
                });
            }
        }
    }

    function noteCircleList() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: function (scope, element, attrs, ctrls) {
                var ngModelCtrl = ctrls[0];
                var fretboardCtrl = ctrls[1];

                scope.$evalAsync(function () {
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getNoteCircles());
                });
            }
        }
    }

    function clickedNotes() {
        return {
            restrict: "AE",
            require: ["ngModel", "^fretboard"],
            link: clickedNotesLinkFn
        }

        function clickedNotesLinkFn(scope, element, attrs, ctrls) {
            var ngModelCtrl = ctrls[0];
            var fretboardCtrl = ctrls[1];

            fretboardCtrl.jQueryFretboardApi.addNotesClickedListener(function () {
                scope.$evalAsync(function () {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = true;
                });
            });

            ngModelCtrl.$render = function () {
                var clickedNotes = ngModelCtrl.$viewValue || [];

                fretboardCtrl.jQueryFretboardApi.clearClickedNotes();
                fretboardCtrl.jQueryFretboardApi.setClickedNotes(clickedNotes);

                scope.$evalAsync(function () {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = true;
                });
            };

            scope.$watch(function () {
                return fretboardCtrl.clickedNotesModelNeedsUpdate;
            }, function (newVal, oldVal) {
                if (!newVal) return;

                scope.$evalAsync(function () {
                    fretboardCtrl.clickedNotesModelNeedsUpdate = false;
                    // Set the callbacks in the correct order so the parent scope is always up to date.
                    // First the new clicked notes get pushed up.
                    ngModelCtrl.$setViewValue(fretboardCtrl.jQueryFretboardApi.getClickedNotes());
                    // Then we invoke the callbacks.
                    invokeFns(fretboardCtrl.onClickedNotesChange);
                });
            });
        }

        function invokeFns(fns) {
            if (!fns) return;

            for (var i = 0; i < fns.length; i++) {
                if (!angular.isFunction(fns[i])) continue;

                fns[i]();
            }
        }
    }

    function isUndefinedOrNull(val) {
        return angular.isUndefined(val) || val === null;
    }
})();<|endoftext|>


<commit_before>const http = require('http');
const httpProxy = require('http-proxy');
const config = require('./config');
const host = 'http://localhost';

const proxy = httpProxy.createProxyServer({});

const server = http.createServer((req, res) => {
	const forwarded = req.headers['X-Forwarded-Proto'];

	if (typeof forwarded !== 'undefined' && forwarded !== null && forwarded === 'http' && config.https) {
		res.writeHead(301, {
			'Location': 'https://' + req.host + req.originalUrl
		});
		res.end();
		return;
	}

	const domain = req.headers.host.replace(/\.?misskey\.xyz$/, '');
	switch (domain) {
		case '':
		case 'about':
		case 'signin':
		case 'signout':
		case 'signup':
		case 'status':
		case 'talk':
			proxy.web(req, res, { target: `${host}:${config.ports.web}` });
			break;
		case 'api':
			proxy.web(req, res, { target: `${host}:${config.ports.core}` });
			break;
		case 'file':
			proxy.web(req, res, { target: `${host}:${config.ports.file}` });
			break;
		default:
			console.log(`Unknown domain: ${domain}`);
			break;
	}
});

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head, { target: 'ws://localhost:8001' });
});

server.listen(conf.port);
<commit_msg>Improve readability<commit_after>const http = require('http');
const httpProxy = require('http-proxy');
const config = require('./config');
const host = 'http://localhost';

const proxy = httpProxy.createProxyServer({});

const server = http.createServer((req, res) => {
	const forwarded = req.headers['X-Forwarded-Proto'];

	if (forwarded && forwarded === 'http' && config.https) {
		res.writeHead(301, {
			'Location': 'https://' + req.host + req.originalUrl
		});
		res.end();
		return;
	}

	const domain = req.headers.host.replace(/\.?misskey\.xyz$/, '');
	switch (domain) {
		case '':
		case 'about':
		case 'signin':
		case 'signout':
		case 'signup':
		case 'status':
		case 'talk':
			proxy.web(req, res, { target: `${host}:${config.ports.web}` });
			break;
		case 'api':
			proxy.web(req, res, { target: `${host}:${config.ports.core}` });
			break;
		case 'file':
			proxy.web(req, res, { target: `${host}:${config.ports.file}` });
			break;
		default:
			console.log(`Unknown domain: ${domain}`);
			break;
	}
});

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head, { target: 'ws://localhost:8001' });
});

server.listen(conf.port);
<|endoftext|>


<commit_before>/**
* @author Daniel Desira
* @version 0.5
*/

(function () {

'use strict';

var TRANSITION_CLASS = 'view';

var photoIndex, delay, photos, touchStartX,

  Switcher = (function () {
    var interval,
      Switcher = {};

    Switcher.next = function () {
      flipPhoto(function ( index ) {
        return (++index) % photos.length;
      });
    };

    Switcher.prev = function () {
      flipPhoto(function ( index ) {
        return (--index) === -1 ? photos.length - 1 : index;
      });
    };

    Switcher.goto = function ( index ) {
      selectImage( photos[index] );
      photoIndex = index;
      setTimeout( changePhoto, delay );
    };

    Switcher.slideshow = function () {
      interval = setInterval( Switcher.next, delay * 4 );
    };

    Switcher.stopSlideshow = function () {
      clearInterval( interval );
    };

    function changePhoto() {
      ag.dom.image.classList.remove( TRANSITION_CLASS );
      setTimeout(function() {
        ag.dom.image.src = photos[photoIndex].bigsrc ? photos[photoIndex].bigsrc : photos[photoIndex].src;
        ag.dom.image.onload = function () {
          ag.dom.image.classList.add( TRANSITION_CLASS );
          if (ag.dom.description) {
            ag.dom.description.textContent = photos[ photoSwitcher.getPhotoIndex() ].alt;
          }
        };

        //Work-around: WebKit and Blink do not display <img> alt text.
        ag.dom.image.onerror = function () {
          ag.dom.description.textContent = (/WebKit/.test( navigator.userAgent ) ?
                ag.dom.description.textContent : '') + ' Unable to fetch image!';
        };
      }, delay );
    }

    function flipPhoto( callback ) {
      var index = photoIndex;
      index = callback( index );
      selectImage( photos[index] );
      photoIndex = index;
      changePhoto();
    }

    return Switcher;
  })(),

  ag = {
    Switcher: Switcher,
    photos: [],
    dom: {
      prev: null,
      next: null,
      slideshowStart: null,
      slideshowEnd: null,
      image: null,
      description: null,
      images: null,
      galleryActivated: true
    }
  };

function _activateGallery( gallery ) {
  document.documentElement.addEventListener( 'click', function ( event ) {
    ag.dom.galleryActivated = (event.target === gallery);
  });
}

function handleKeyDown( event ) {
  if (ag.dom.galleryActivated) {
    if (event.keyCode === 37) {
      Switcher.prev();
    } else if (event.keyCode === 39) {
      Switcher.next();
    }
  }
}

function handleTouchStart( event ) {
  touchStartX = event.touches[0].pageX;
}

function handleTouchEnd( event ) {
  if (event.touches[0].pageX > touchStartX) {
    Switcher.prev();
  } else if (event.touches[0].pageX < touchStartX) {
    Switcher.next();
  }
  event.preventDefault();
}

function registerButtonClick( action, selector ) {
  var element = (selector ? $( selector ) : document.createElement( 'a' ));
  element.addEventListener( 'click', Switcher[action] );
  return element;
}

function $( selector ) {
  return document.querySelector( selector );
}

function selectImage( image ) {
  var SELECTION_CLASS = 'selected'
  if (image.classList) {
    image.classList.add( SELECTION_CLASS );
    image !== photos[photoIndex] ? photos[photoIndex].classList.remove( SELECTION_CLASS ) : undefined;
  }
}

window.AG = {};

AG.init = function ( options ) {
  ag.dom.image = $( options.$image );
  if (options.$$images) {
    ag.dom.images = photos = document.querySelectorAll( options.$$images );
    for (photoIndex = 0; photoIndex < photos.length; photoIndex++) {
      (function (i) {
        photos[photoIndex].addEventListener( 'click', function () {
          Switcher.goto( i );
        });
      })( photoIndex );
    }
    photoIndex = 0;
  } else {
    ag.photos = photos = options.photos;
  }

  selectImage( photos[0] );
  ag.dom.image.src = photos[0].src;
  ag.dom.image.classList.add( TRANSITION_CLASS );

  if (options.$description) {
    ag.dom.description = $( options.$description );
  }

  delay = (function () {
    var transitionDuration = getComputedStyle( ag.dom.image ).transitionDuration;
    return parseFloat( transitionDuration.substring( 0, transitionDuration.length - 1 ) ) * 1000;
  })();

  ag.dom.image.addEventListener( 'click', Switcher.next );
  document.addEventListener( 'keydown', handleKeyDown );
  ag.dom.image.addEventListener( 'touchstart', handleTouchStart );
  ag.dom.image.addEventListener( 'touchend', handleTouchEnd );
  ag.dom.prev = registerButtonClick( 'prev', options.$prev );
  ag.dom.next = registerButtonClick( 'next', options.$next );
  ag.dom.slideshowStart = registerButtonClick( 'slideshow', options.$slideshow );
  ag.dom.slideshowEnd = registerButtonClick( 'stopslideshow', options.$stopSlideshow );

  if (options.$gallery) {
    _activateGallery( $( options.$gallery ) );
    ag.dom.galleryActivated = false;
  }

  if (options.quickSetup) {
    Switcher.slideshow();
    ag.dom.prev = registerButtonClick( 'prev' );
    ag.dom.next = registerButtonClick( 'next' );
    ag.dom.slideshowStart = registerButtonClick( 'slideshow' );
    ag.dom.slideshowEnd = registerButtonClick( 'stopslideshow' );
  }

  return AG;
};

AG.extend = function ( callback, methodName ) {
  methodName ? (AG[methodName] = function () {
    callback( ag );
  }) : callback( ag );

  return AG;
};

})();
<commit_msg>Better event registration<commit_after>/**
* @author Daniel Desira
* @version 0.5
*/

(function () {

'use strict';

var TRANSITION_CLASS = 'view';

var photoIndex, delay, photos, touchStartX,

  Switcher = (function () {
    var interval,
      Switcher = {};

    Switcher.next = function () {
      flipPhoto(function ( index ) {
        return (++index) % photos.length;
      });
    };

    Switcher.prev = function () {
      flipPhoto(function ( index ) {
        return (--index) === -1 ? photos.length - 1 : index;
      });
    };

    Switcher.goto = function ( index ) {
      selectImage( photos[index] );
      photoIndex = index;
      setTimeout( changePhoto, delay );
    };

    Switcher.slideshow = function () {
      interval = setInterval( Switcher.next, delay * 4 );
    };

    Switcher.stopSlideshow = function () {
      clearInterval( interval );
    };

    function changePhoto() {
      ag.dom.image.classList.remove( TRANSITION_CLASS );
      setTimeout(function() {
        ag.dom.image.src = photos[photoIndex].bigsrc ? photos[photoIndex].bigsrc : photos[photoIndex].src;
        ag.dom.image.onload = function () {
          ag.dom.image.classList.add( TRANSITION_CLASS );
          if (ag.dom.description) {
            ag.dom.description.textContent = photos[ photoSwitcher.getPhotoIndex() ].alt;
          }
        };

        //Work-around: WebKit and Blink do not display <img> alt text.
        ag.dom.image.onerror = function () {
          ag.dom.description.textContent = (/WebKit/.test( navigator.userAgent ) ?
                ag.dom.description.textContent : '') + ' Unable to fetch image!';
        };
      }, delay );
    }

    function flipPhoto( callback ) {
      var index = photoIndex;
      index = callback( index );
      selectImage( photos[index] );
      photoIndex = index;
      changePhoto();
    }

    return Switcher;
  })(),

  ag = {
    Switcher: Switcher,
    photos: [],
    dom: {
      prev: null,
      next: null,
      slideshowStart: null,
      slideshowEnd: null,
      image: null,
      description: null,
      images: null,
      gallery: null,
      galleryActivated: true
    }
  };

function _activateGallery() {
  document.documentElement.addEventListener( 'click', function ( event ) {
    ag.dom.galleryActivated = (event.target === ag.dom.gallery);
  });
}

function handleKeyDown( event ) {
  if (ag.dom.galleryActivated) {
    if (event.keyCode === 37) {
      Switcher.prev();
    } else if (event.keyCode === 39) {
      Switcher.next();
    }
  }
}

function handleTouchStart( event ) {
  touchStartX = event.touches[0].pageX;
}

function handleTouchEnd( event ) {
  if (event.touches[0].pageX > touchStartX) {
    Switcher.prev();
  } else if (event.touches[0].pageX < touchStartX) {
    Switcher.next();
  }
  event.preventDefault();
}

function registerButtonClick( action, selector ) {
  var element = (selector ?
    $( selector ) :
    (ag.dom.gallery ? gallery.appendChild( document.createElement( 'a' ) ) : null));
  element.addEventListener( 'click', Switcher[action] );
  return element;
}

function $( selector ) {
  return document.querySelector( selector );
}

function selectImage( image ) {
  var SELECTION_CLASS = 'selected'
  if (image.classList) {
    image.classList.add( SELECTION_CLASS );
    image !== photos[photoIndex] ? photos[photoIndex].classList.remove( SELECTION_CLASS ) : undefined;
  }
}

window.AG = {};

AG.init = function ( options ) {
  options.autoSlideshow ? Switcher.slideshow() : undefined;

  if (options.$gallery) {
    ag.dom.gallery = $( options.$gallery );
    _activateGallery(;
    ag.dom.galleryActivated = false;
  }

  ag.dom.prev = registerButtonClick( 'prev', options.$prev );
  ag.dom.next = registerButtonClick( 'next', options.$next );
  ag.dom.slideshowStart = registerButtonClick( 'slideshow', options.$slideshow );
  ag.dom.slideshowEnd = registerButtonClick( 'stopslideshow', options.$stopSlideshow );

  ag.dom.image = $( options.$image );
  ag.dom.image.addEventListener( 'click', Switcher.next );
  document.addEventListener( 'keydown', handleKeyDown );
  ag.dom.image.addEventListener( 'touchstart', handleTouchStart );
  ag.dom.image.addEventListener( 'touchend', handleTouchEnd );

  if (options.$$images) {
    ag.dom.images = photos = document.querySelectorAll( options.$$images );
    for (photoIndex = 0; photoIndex < photos.length; photoIndex++) {
      (function (i) {
        photos[photoIndex].addEventListener( 'click', function () {
          Switcher.goto( i );
        });
      })( photoIndex );
    }
    photoIndex = 0;
  } else {
    ag.photos = photos = options.photos;

  }

  selectImage( photos[0] );
  ag.dom.image.src = photos[0].src;
  ag.dom.image.classList.add( TRANSITION_CLASS );

  if (options.$description) {
    ag.dom.description = $( options.$description );
  }

  delay = (function () {
    var transitionDuration = getComputedStyle( ag.dom.image ).transitionDuration;
    return parseFloat( transitionDuration.substring( 0, transitionDuration.length - 1 ) ) * 1000;
  })();

  return AG;
};

AG.extend = function ( callback, methodName ) {
  methodName ? (AG[methodName] = function () {
    callback( ag );
  }) : callback( ag );

  return AG;
};

})();
<|endoftext|>