Angular ngFor select options with object value as default shown Ask Question

Let’s say I have an object one of statusOptions=[‘Approved’, ‘Waiting’, ‘Rejected’]

In the markup we have:

<div *ngFor="let myObject of objects">
    <select (change)="updateStatus($event.target.value)">
       <option selected>{{myObject.status}}</option>
       <option *ngFor="let status of statusOptions">{{status}}</option>
    </select>
<div>

How would I show the object’s current status as the default selected value? As of right now it will duplicate and the dropdown will show ['Approved', 'Waiting', 'Rejected', 'Approved'] if the object’s current status is 'Approved'

I do not need two way binding as I just grab the value on change and update my database.

Cloning a rigged mesh and dealing with skinned materials Ask Question

I have a scene with multiple rigged meshes uploaded from a .json file. To create independent meshes I use .copy(). I want all these meshes to have different materials, every material must have different color.

Loader:

jsonLoader.load("models/player.json", function (geometry, materials) {
    materials.forEach(function (material) {
        material.skinning = true;
        material.side = THREE.FrontSide;
    });
    meshes.player = new THREE.SkinnedMesh(geometry, materials);
    meshes.player.castShadow = true;
    meshes.player.receiveShadow = true;
    meshes.player.scale.set(0.5,0.5,0.5);
});

Than clone it:

mesh = meshes.player.clone();
mesh.material[0] = meshes.player.material[0].clone();
mesh.material[0].color.setHex( randomColor );

But it works very weird: if I add to the scene one mesh with random color and than add second mesh with the other color, the first mesh changes it’s color to the color of the second mesh.

All my materials use skinning, every mesh must have it’s own skeleton. I found this page on GitHub, maybe I have the same issue. But I still don’t realise how skeleton affects material.

req.user is unidentified in session (Node, express, session, passport) Ask Question

For some reason req.user is undefined, and after 4+ hours of trying to figure out why, I’m asking here. I even copy-pasted the server/index.js file of a friend’s server, changed the auth strategy so it worked for mine, and I get the same issue.

Everything else is working. It redirects to auth0, comes back to the correct place, either creates a new user in the DB or finds the user. In passport.serializeUser it has all the data I passed along. But when I hit the ‘/auth/me’ endpoint, req.user is undefined.

server/index.js

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const session = require("express-session");
const passport = require('passport');
const Auth0Strategy = require('passport-auth0');
const massive = require('massive');
const axios = require('axios');
const process = require("process");
const moment = require('moment');

const app = express();

//app.use(express.static(__dirname + './../build'));
app.use(bodyParser.json());
app.use(cors());

app.use(session({
    secret: process.env.SECRET, 
    cookie: { maxAge: 60000 },
    resave: false,
    saveUninitialized: true
   }));
app.use(passport.initialize());
app.use(passport.session()); 

// Use the session middleware
massive(process.env.CONNECTION_STRING)
.then( (db) => {
    console.log('Connected to Heroku')
    app.set('db', db);
}).catch(err=>console.log(err))
 


passport.use(new Auth0Strategy({
    domain: process.env.AUTH_DOMAIN,
    clientID: process.env.AUTH_CLIENT_ID,
    clientSecret: process.env.AUTH_CLIENT_SECRET,
    callbackURL: process.env.AUTH_CALLBACK
}, (accessToken, refreshToken, extraParams, profile, done) => {
    const db = app.get("db");
    const userData = profile._json;

    db.find_user([userData.identities[0].user_id]).then(user => {
    if (user[0]) {
        return done(null, user[0]);
    } else {
        db.create_user([
            userData.given_name,
            userData.family_name,
            userData.email,
            userData.identities[0].user_id
        ])
        .then(user => {
            return done(null, user);
        });
    }
    });
}))

passport.serializeUser( (user, done) => {
    //console.log('serializeuser', user)
    done(null, user);
}) 

passport.deserializeUser( (id, done) => {
    app.get("db").find_session_user([id])
        .then(user => {
        console.log(user);
        done(null, user[0]);
        });
})

app.get('/auth', passport.authenticate('auth0'));
app.get('/auth/callback', passport.authenticate('auth0', {
    successRedirect: process.env.SUCCESS_REDIRECT
}))

app.get('/auth/me', (req, res) => {
    console.log('auth/me endpoint hit')
    console.log(req.user)
    if(!req.user){
        return res.status(401).send('No user logged in.');
    }
    return res.status(200).send(req.user);
})

app.listen(process.env.PORT, () => console.log(`Listening on port: ${process.env.PORT}`));

d3 v4 line chart transition not working Ask Question

I would like my line to draw like this example:

https://bl.ocks.org/shimizu/f7ef798894427a99efe5e173e003260d

The code below does not make any transitions, the chart just appears.

I’m aware of browser caching and that is not the issue. I’ve also tried changing the duration and that doesn’t help either. I feel like I’m probably not being explicit about how I want d3 to transition, but I’m unsure how to give d3 what it wants. Your help is greatly appreciated.

EDIT: x-axis domain: [0, 1]. y-axis domain: [-18600, -3300].

// Here's just a few rows of the data
data = [{"threshold": 0.0, "loss": -18600},
        {"threshold": 0.008571428571428572, "loss": -18600},
        {"threshold": 0.017142857142857144, "loss": -18600}]

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 20},
    width = +svg.attr("width") - 400 - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;


var x = d3.scaleLinear()
    .range([0, width]);

var y = d3.scaleLinear()
    .range([0, height]);

var line = d3.line()
    .x(d => x(d.threshold))
    .y(d => y(d.loss));

var g = svg.append("g")
    .attr("transform", "translate(" + (margin.left + 50) + "," + margin.top + ")");

d3.json("static/data/thresh_losses.json", function(thisData) {
 draw(thisData);
});

let draw = function(data) {
    $("svg").empty()
    var x = d3.scaleLinear()
        .range([0, width]);

    var y = d3.scaleLinear()
        .range([0, height]);

    var line = d3.line()
        .x(d => x(d.threshold))
        .y(d => y(d.loss));

    var g = svg.append("g")
        .attr("transform", "translate(" + (margin.left + 50) + "," + margin.top + ")");

    d3.selectAll("g").transition().duration(3000).ease(d3.easeLinear);

    x.domain([0, d3.max(data, d => d.threshold)]);
    y.domain([d3.max(data, d => d.loss), d3.min(data, d => d.loss)]);

    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))
        .append("text")
        .attr("class", "axis-title")
        .attr("y", 18)
        .attr("dy", "1em")
        .attr("x", (height/2) - 40)
        .attr("dx", "1em")
        .style("text-anchor", "start")
        .attr("fill", "#5D6971")
        .text("Threshold");

    g.append("g")
        .attr("class", "axis axis--y")
        .call(d3.axisLeft(y))
        .append("text")
       .attr("class", "axis-title")
       .attr("transform", "rotate(-90)")
       .attr("y", -40)
       .attr("dy", ".71em")
       .attr("x", -height/2 + 40)
       .attr("dx", ".71em")
       .style("text-anchor", "end")
       .attr("fill", "#5D6971")
       .text("Profit ($)");

    var line_stuff = g.selectAll(".line")
        .data([data]);

    line_stuff.enter().append("path").classed("line", true)
           .merge(line_stuff);

    g.selectAll(".line")
      .transition()
      .duration(10000)
      .ease(d3.easeLinear)
      .attr("d", line);
};

Is there any way to run old versions of JavaScript? [closed] Ask Question

I’m trying to use new browsers and old browsers on a website I’m working on (no, it isn’t online, and even if it was I wouldn’t post it here because that is pretty much advertising!)

While it works fine, I want it to use ECMAScript 3 for functions like goto and such and I dislike using the newer keywords. Does anyone know of a way to use older ECMAScript/JavaScript versions?

how to create mutiple rectangle on gmaps? Ask Question

I want to create multiple rectangle on gmaps but I don’t know where must I put the code.

This is my sample code

 function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 5,
      center: {lat: 37.0924, lng: -119.4179324},
      mapTypeId: 'terrain'
    });

	var contentString = '<div id="content">'+
        '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large 
        '</div>';
		
	  var infowindow = new google.maps.InfoWindow({
      content: contentString
    });

    var rectangle = new google.maps.Rectangle({
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      bounds: 
      new google.maps.LatLngBounds
  <?php 
	  $con = mysqli_connect("localhost","root","","test");
	  
	  $query=mysqli_query($con,"SELECT * FROM map");
	  $cc=mysqli_fetch_array($query);
	  ?>
      (
        new google.maps.LatLng (<?php echo $cc['nelat']; ?>, <?php echo $cc['nelng']; ?>),
		new google.maps.LatLng (<?php echo $cc['swlat']; ?>, <?php echo $cc['swlng']; ?>),
        ),

      
    });
	  rectangle.addListener('click', function() {
      infowindow.open(map, rectangle);
    });
  }
    #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Rectangles</title>
   
  </head>
  <body>
    <div id="map"></div>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAogXD-AHrsmnWinZIyhRORJ84bgLwDPpg&callback=initMap">
  </script>
</body>
</html>

Angularjs change url parm and refresh onClick Ask Question

I’m displaying a chart with default values when the page is loaded. I’d like to add angularjs clickable links to change the period (month, week, day) displayed on the chart.

I’m currently doing a regular page reload with <a href="{{ URL::to('t') }}?c={{ $currency }}&p=1m">1m</a> but how would it be possible to change the url parm and refreshing the chart without having to reload the page?

html

<div ng-app="app">
<div ng-controller="tickerchartsCtrl">
    <canvas class="chart chart-line" chart-data="data" chart-labels="labels" chart-options="options"></canvas>

     <a href="{{ URL::to('t') }}?c={{ $currency }}&p=1m">1m</a> --> Change to angularJs onClick instead of page reload
     <a href="{{ URL::to('t') }}?c={{ $currency }}&p=1w">1w</a> --> Change to angularJs onClick instead of page reload
     <a href="{{ URL::to('t') }}?c={{ $currency }}&p=1d">1d</a> --> Change to angularJs onClick instead of page reload

     <input type="hidden" ng-model="currency" name="period" value="{{ $currency }}">
     <input type="hidden" ng-model="period" name="period" value="{{ $period }}">

</div>
</div>

js

var app = angular.module('tickercharts',['chart.js']);
app.controller('tickerchartsCtrl', ['$scope', '$http', '$location', function($scope, $http, $location){

    $scope.currency      = angular.element(document.getElementsByName('currency')).val();
    $scope.period        = angular.element(document.getElementsByName('period')).val();

    var urlapigettickers = $location.protocol() + "://" + $location.host() + "/api/gettickers?c=" + $scope.currency + "&p=" + $scope.period ;        

    $http.get(urlapigettickers).success(function(data, status, headers, config) {
        $scope.gettickeritems = data.gettickers;

     //console.log(data);
    }).error(function(data, status, headers, config) {
        console.log("No data found..");
  });

}]);

How to call function in certain time interval Ask Question

I need to run a certain API function, in a certain time period once the access token is granted, and check the status and inform the user if there any changes.

So far i did it by clicking a button on popup window of the firefox addon and calling the functions background js files, so i can receive the info from the API and notify the user. But i need to automate this process in background js files.

Are there any firefox inbuild JS API or any other way to achieve this auto API request calling from addon background files?

I am not Getting Any Errors but When i am trying to click on Form my form Type Mouse does not appear Ask Question

My form is Getting no Errors on Chrome Developers Error code but i am not getting and Text field or anything in my forms it is a very easy task but it had become a headache for me i will be very Helpfull if you help me with this

 <section class="reservation">
        <img class="img-responsive section-icon hidden-sm hidden-xs" src="{{ asset('frontend/images/icons/reserve_color.png') }}">
        <div class="wrapper">
            <div class="container-fluid">
                <div class=" section-content">
                    <div class="row">
                        <div class="col-md-5 col-sm-6">
                            <form class="reservation-form" method="post" action="{{ route('resrvation.reserve') }}">
                                      {{ csrf_field() }}

                                <div class="row">
                                    <div class="col-md-6 col-sm-6">

                                    <div class="form-group">
                                        <input type="text" class="form-control reserve-form empty iconified" name="name" id="name"
                                               placeholder="    Name">
                                    </div>
                                    <div class="form-group">
                                        <input type="email" name="email" class="form-control reserve-form empty iconified" id="email"  placeholder="    e-mail">
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6">
                                    <div class="form-group">
                                        <input type="tel" class="form-control reserve-form empty iconified" name="phone" id="phone"  placeholder="    Phone">
                                    </div>
                                    <div class="form-group">
                                        <input type="text" class="form-control reserve-form empty iconified" name="dateandtime" id="datetimepicker1" placeholder="  Time">
                                    </div>
                                </div>
                                <div class="col-md-12 col-sm-12">
                                    <textarea type="text" name="message" class="form-control reserve-form empty iconified" id="message" rows="3"  placeholder="    We're listening"></textarea>
                                </div>
                                <div class="col-md-12 col-sm-12">
                                    <button type="submit" id="submit" name="submit" class="btn btn-reservation">
                                        <span><i class="fa fa-check-circle-o"></i></span>
                                        Make a reservation
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>