<commit_before>/**
 * Created by Chen on 2016-12-11.
 */

'use strict';

let AWS = require("aws-sdk");
const config = require('../config');
// AWS.config.update({
//   region: "us-west-2",
//   endpoint: "http://localhost:8000"
// });

let request = require('request');
let docClient = new AWS.DynamoDB.DocumentClient();

/**
 * Get all users' ids from Table UserIds
 * @param {string} userId
 * @returns {Promise}
 */
const getAllUserIds = (userId) => {
  return new Promise((resolve, reject) => {
    let params = {
      TableName: "UserIds",
      Key: {
        id: "allIds"
      },
    };
    // docClient.get()
    docClient.get(params, (err, data) => {
      if (err) {
        console.error("Unable to get userIds. Error JSON:", JSON.stringify(err), err.stack);
        return reject(err);
      } else {
        // console.log("Get user ids successfully", data);
        let userIds = data.Item.usersIds.values,
            candidateIds = userIds.filter(id => id !== userId);
        // console.log("candidateIds", candidateIds);
        console.log("Get all users ID successfully.");
        // console.log("userId", userId);
        // console.log("candidateIds", candidateIds);
        resolve(candidateIds);
      }
    });
  });
};

const randPickFollowers = (validCandis, followNumber) => {
  followNumber = Math.min(followNumber, validCandis.length);
  // console.log("userId", userId);
  // console.log("candidateIds", candidateIds);
  for (let i = 0; i < followNumber; i++) {
    // hardcoded value
    let index = Math.floor(Math.random() * validCandis.length);

    //Swap the two elements
    let temp = validCandis[i];
    validCandis[i] = validCandis[index];
    validCandis[index] = temp;
  }
  let pickedUsers = validCandis.slice(0, followNumber);
  console.log("Picked users successfully"/*, JSON.stringify(pickedUsers)*/);
  return pickedUsers;
};

const getPickedUsers = (pickedIds) => {
  let promises = pickedIds.map(id => {
    return new Promise((resolve, reject) => {
      let params = {
        TableName: "Users",
        Key: {
          id: id
        },
        ProjectionExpression: "id, login, avatar_url, followNumber, html_url, #name, #token",
        ExpressionAttributeNames: {
          "#name": "name",
          "#token": "token"
        },
      };
      docClient.get(params, (err, data) => {
        if (err) {
          console.error("Unable to get item. Error JSON:", JSON.stringify(err), err.stack);
          return reject(err);
        }
        let item = data.Item;
        // console.log("GetItem succeeded:", JSON.stringify(item));
        resolve(item);
      });
    });
  });

  return Promise.all(promises)
      .then((users) => {
        console.log("Fetched all users successfully");
        // console.log("users", users);
        return users;
      });
};

const followAndStore = (users, user) => {
  // console.log("fetched users", users);
  // console.log("original user", user);
  //promise -> send PUT request to follow -> add in "Friends" Table
  let promises = [];

  const followUser = (token, username) => {
    return new Promise((resolve, reject) => {
      let options = {
        url: "https://api.github.com/user/following/" + username + "?access_token=" + token,
        method: "put",
        headers: {
          'User-Agent': "GitMax"
        }
      };

      request(options, (error, response, body) => {
        if (error) {
          console.error("error following user " + username, error, error.stack);
          return reject(error);
        }
        // console.log("Successfully added")
        resolve();
      });
    })
  };

  const storeFriendship = (user1, user2) => {
    return new Promise((resolve, reject) => {
      let item = {
        "userId": user1.id,
        "username": user1.name,
        "userLogin": user1.login,
        "userUrl": user1.html_url,
        "userAvatarUrl": user1.avatar_url,
        "friendId": user2.id,
        "friendName": user2.name,
        "friendLogin": user2.login,
        "friendUrl": user2.html_url,
        "friendAvatarUrl": user2.avatar_url,
      };
      let params = {
        TableName: "Friends",
        Item: item,
      };
      docClient.put(params, (err, data) => {
        if (err) {
          console.error("Unable to add friendship to friends Table. ", JSON.stringify(err),
              err.stack);
          return reject(err);
        } else {
          // console.log("Friendship added successfully");
          resolve(item);
        }
      });
    });
  };

  users.forEach(userX => {
    // console.log("userX", userX);
    // console.log("user", user);
    promises.push(
        followUser(userX.token, user.login)
            .then(() => storeFriendship(userX, user))
            .then(() => userX)
    );
    promises.push(
        followUser(user.token, userX.login)
            .then(() => storeFriendship(user, userX))
            .then(() => null) //users only need to be added once
    );
  });

  function getNeededProps(friend) {
    return {
      id: friend.id,
      url: friend.url,
      avatar_url: friend.avatar_url,
      login: friend.login,
      name: friend.name,
      created_at: friend.created_at,
    }
  }

  return Promise.all(promises)
      .then((result) => {
        console.log("storeFriendship finished"/*, result*/);
        let addedFriends = [];
        result.forEach(friend => friend && addedFriends.push(getNeededProps(friend)));
        return (addedFriends);
      });
};

const getFriends = (userId) => {
  console.log("getFriends start with id", userId);
  const params = {
    TableName: "Friends",
    KeyConditionExpression: "#userId = :id",
    ExpressionAttributeNames: {
      "#userId": "userId"
    },
    ExpressionAttributeValues: {
      ":id": userId
    }
  };
  return new Promise((resolve, reject) => {
    docClient.query(params, (err, data) => {
      if (err) {
        console.error("Unable to get friends. Error JSON:", JSON.stringify(err), err.stack);
        return reject(err);
      } else {
        console.log("Query succeeded."/*, JSON.stringify(data)*/);
        let friends = data.Items;
        resolve(friends);
      }
    });
  });
};

const getCandisByScan = (user) => {
  const params = { // 找到与用户互相欣赏的人，作为好友candidate
    TableName: "Users",
    ProjectionExpression: "#id, #url, created_at, avatar_url, followers, following, login, #name," +
    " #token, addFollowersMax, crit_FollowersCount, crit_StargazersCount, totalStars",
    FilterExpression: "totalStars >= :user_star_crit AND followers >= :user_follower_crit AND" +
    " crit_StargazersCount <= :user_star AND crit_FollowersCount <= :user_follower",
    ExpressionAttributeNames: {
      "#id": "id",
      "#url": "url",
      "#name": "name",
      "#token": "token",
    },
    ExpressionAttributeValues: {
      ":user_star_crit": user.crit_StargazersCount,
      ":user_follower_crit": user.crit_FollowersCount,
      ":user_star": user.totalStars,
      ":user_follower": user.followers,
    }
  };

  return new Promise((resolve, reject) => {
    docClient.scan(params, (err, data) => {
      if (err) {
        console.error("Unable to get item. Error JSON:", JSON.stringify(err), err.stack);
        return reject(err);
      } else {
        console.log("Scan succeeded."/*, JSON.stringify(data)*/);//Todo, comment data
        let candidates = data.Items;
        resolve(candidates);
      }
    });
  });
};

const removeAddedCandis = (candidates, friends, userId) => {
  let set = new Set();
  friends.forEach(obj => set.add(obj.friendId));// Add all friends' Ids in a set
  set.add(userId); // Remove the user from valid candidates

  let validCandis = [];
  candidates.forEach((candidate) => {
    if (!set.has(candidate.id)) validCandis.push(candidate);
  });
  return validCandis;
};

const removeFullFriendsCandidates = (candidates) => {
  let validCandis = [];
  candidates.forEach(candi => {
    if (candi.addFollowersMax > candi.followers) validCandis.push(candi);
  });
  return validCandis;
};

const configUpdate = (user, stage) => {
  // const stage = event.requestContext.stage;
  // const stage = config.getStage();
  user.followedFriendsAt = new Date().getTime();
  const url = config.lambda[stage].configUpdateEndpoint;

  let options = {
    url: url,
    method: "POST",
    body: JSON.stringify({user: user}),
  };

  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) {
        return reject(error);
      }
      let newUser = JSON.parse(body).user;
      // console.log("response", response);
      // console.log("data", data);
      // console.log("Update followedAt, user:", newUser);
      //DynamoDB不能包含任何empty attributes
      resolve(newUser);
    });
  });
};

module.exports = (event, context, callback) => {
  // console.log("DynamoDB triggered lambda successfully");
  // console.log("event", JSON.stringify(event));
  // console.log("context", context);

  let data = JSON.parse(event.body);
  console.log("input data", JSON.stringify(data));
  if (!data.user) {
    callback(new Error("Data format error: not found `user`."));
    return;
  }

  let user = data.user;
  let friends;
  let newFriendsList;
  getFriends(user.id)//获得所有好友的ids
      .then(friendsList => friends = friendsList)
      .then(
          () => getCandisByScan(user))//scan+filterExpression获得所有符合filter的用户，只传递回，login, id, 4个crits
      .then((candidates) => removeAddedCandis(candidates, friends, user.id)) //去除已经是好友的人
      .then((candidates) => removeFullFriendsCandidates(candidates)) //去除超过上限的人
      .then(
          (validCandis) => randPickFollowers(validCandis, user.addFollowersNow))//从validCandis中调出xx个
      .then((foUsers) => followAndStore(foUsers, user)) //开始用户互相follow
      .then((newFriends) => newFriendsList = newFriends)
      .then(() => configUpdate(user, event.requestContext.stage))
      .then((newUser) => {
        // console.log("newFriends", newFriends);
        let response = {
          statusCode: 200,
          headers: {"Access-Control-Allow-Origin": "*"},
        };
        console.log("Follow user task is accomplished");
        response.body = JSON.stringify({newFriends: newFriendsList, user: newUser});
        callback(null, response);
      })//follow task is accomplished;
      .catch((err) => {
        console.error("err", err, err.stack);
        callback(new Error("Error found:", err));
      });
};
<commit_msg>Implementing getFollowers in lambda<commit_after>/**
 * Created by Chen on 2016-12-11.
 */

'use strict';

let AWS = require("aws-sdk");
const config = require('../config');
// AWS.config.update({
//   region: "us-west-2",
//   endpoint: "http://localhost:8000"
// });

let request = require('request');
let docClient = new AWS.DynamoDB.DocumentClient();

/**
 * Get all users' ids from Table UserIds
 * @param {string} userId
 * @returns {Promise}
 */
const getAllUserIds = (userId) => {
  return new Promise((resolve, reject) => {
    let params = {
      TableName: "UserIds",
      Key: {
        id: "allIds"
      },
    };
    // docClient.get()
    docClient.get(params, (err, data) => {
      if (err) {
        console.error("Unable to get userIds. Error JSON:", JSON.stringify(err), err.stack);
        return reject(err);
      } else {
        // console.log("Get user ids successfully", data);
        let userIds = data.Item.usersIds.values,
            candidateIds = userIds.filter(id => id !== userId);
        // console.log("candidateIds", candidateIds);
        console.log("Get all users ID successfully.");
        // console.log("userId", userId);
        // console.log("candidateIds", candidateIds);
        resolve(candidateIds);
      }
    });
  });
};

const randPickFollowers = (validCandis, followNumber) => {
  followNumber = Math.min(followNumber, validCandis.length);
  // console.log("userId", userId);
  // console.log("candidateIds", candidateIds);
  for (let i = 0; i < followNumber; i++) {
    // hardcoded value
    let index = Math.floor(Math.random() * validCandis.length);

    //Swap the two elements
    let temp = validCandis[i];
    validCandis[i] = validCandis[index];
    validCandis[index] = temp;
  }
  let pickedUsers = validCandis.slice(0, followNumber);
  console.log("Picked users successfully"/*, JSON.stringify(pickedUsers)*/);
  return pickedUsers;
};

const getPickedUsers = (pickedIds) => {
  let promises = pickedIds.map(id => {
    return new Promise((resolve, reject) => {
      let params = {
        TableName: "Users",
        Key: {
          id: id
        },
        ProjectionExpression: "id, login, avatar_url, followNumber, html_url, #name, #token",
        ExpressionAttributeNames: {
          "#name": "name",
          "#token": "token"
        },
      };
      docClient.get(params, (err, data) => {
        if (err) {
          console.error("Unable to get item. Error JSON:", JSON.stringify(err), err.stack);
          return reject(err);
        }
        let item = data.Item;
        // console.log("GetItem succeeded:", JSON.stringify(item));
        resolve(item);
      });
    });
  });

  return Promise.all(promises)
      .then((users) => {
        console.log("Fetched all users successfully");
        // console.log("users", users);
        return users;
      });
};

const followAndStore = (users, user) => {
  // console.log("fetched users", users);
  // console.log("original user", user);
  //promise -> send PUT request to follow -> add in "Friends" Table
  let promises = [];

  const followUser = (token, username) => {
    return new Promise((resolve, reject) => {
      let options = {
        url: "https://api.github.com/user/following/" + username + "?access_token=" + token,
        method: "put",
        headers: {
          'User-Agent': "GitMax"
        }
      };

      request(options, (error, response, body) => {
        if (error) {
          console.error("error following user " + username, error, error.stack);
          return reject(error);
        }
        // console.log("Successfully added")
        resolve();
      });
    })
  };

  const storeFriendship = (user1, user2) => {
    return new Promise((resolve, reject) => {
      let item = {
        "userId": user1.id,
        "username": user1.name,
        "userLogin": user1.login,
        "userUrl": user1.html_url,
        "userAvatarUrl": user1.avatar_url,
        "friendId": user2.id,
        "friendName": user2.name,
        "friendLogin": user2.login,
        "friendUrl": user2.html_url,
        "friendAvatarUrl": user2.avatar_url,
      };
      let params = {
        TableName: "Friends",
        Item: item,
      };
      docClient.put(params, (err, data) => {
        if (err) {
          console.error("Unable to add friendship to friends Table. ", JSON.stringify(err),
              err.stack);
          return reject(err);
        } else {
          // console.log("Friendship added successfully");
          resolve(item);
        }
      });
    });
  };

  users.forEach(userX => {
    // console.log("userX", userX);
    // console.log("user", user);
    promises.push(
        followUser(userX.token, user.login)
            .then(() => storeFriendship(userX, user))
            .then(() => userX)
    );
    promises.push(
        followUser(user.token, userX.login)
            .then(() => storeFriendship(user, userX))
            .then(() => null) //users only need to be added once
    );
  });

  function getNeededProps(friend) {
    return {
      id: friend.id,
      url: friend.url,
      avatar_url: friend.avatar_url,
      login: friend.login,
      name: friend.name,
      created_at: friend.created_at,
    }
  }

  return Promise.all(promises)
      .then((result) => {
        console.log("storeFriendship finished"/*, result*/);
        let addedFriends = [];
        result.forEach(friend => friend && addedFriends.push(getNeededProps(friend)));
        return (addedFriends);
      });
};

const getFriends = (userId) => {
  console.log("getFriends start with id", userId);
  const params = {
    TableName: "Friends",
    KeyConditionExpression: "#userId = :id",
    ExpressionAttributeNames: {
      "#userId": "userId"
    },
    ExpressionAttributeValues: {
      ":id": userId
    }
  };
  return new Promise((resolve, reject) => {
    docClient.query(params, (err, data) => {
      if (err) {
        console.error("Unable to get friends. Error JSON:", JSON.stringify(err), err.stack);
        return reject(err);
      } else {
        console.log("Query succeeded."/*, JSON.stringify(data)*/);
        let friends = data.Items;
        resolve(friends);
      }
    });
  });
};

const getCandisByScan = (user) => {
  const params = { // 找到与用户互相欣赏的人，作为好友candidate
    TableName: "Users",
    ProjectionExpression: "#id, #url, created_at, avatar_url, followers, following, login, #name," +
    " #token, addFollowersMax, crit_FollowersCount, crit_StargazersCount, totalStars",
    FilterExpression: "totalStars >= :user_star_crit AND followers >= :user_follower_crit AND" +
    " crit_StargazersCount <= :user_star AND crit_FollowersCount <= :user_follower",
    ExpressionAttributeNames: {
      "#id": "id",
      "#url": "url",
      "#name": "name",
      "#token": "token",
    },
    ExpressionAttributeValues: {
      ":user_star_crit": user.crit_StargazersCount,
      ":user_follower_crit": user.crit_FollowersCount,
      ":user_star": user.totalStars,
      ":user_follower": user.followers,
    }
  };

  return new Promise((resolve, reject) => {
    docClient.scan(params, (err, data) => {
      if (err) {
        console.error("Unable to get item. Error JSON:", JSON.stringify(err), err.stack);
        return reject(err);
      } else {
        console.log("Scan succeeded."/*, JSON.stringify(data)*/);//Todo, comment data
        let candidates = data.Items;
        resolve(candidates);
      }
    });
  });
};

const removeAddedCandis = (candidates, friends, userId) => {
  let set = new Set();
  friends.forEach(obj => set.add(obj.friendId));// Add all friends' Ids in a set
  set.add(userId); // Remove the user from valid candidates

  let validCandis = [];
  candidates.forEach((candidate) => {
    if (!set.has(candidate.id)) validCandis.push(candidate);
  });
  return validCandis;
};

const removeFullFriendsCandidates = (candidates) => {
  let validCandis = [];
  candidates.forEach(candi => {
    if (candi.addFollowersMax > candi.followers) validCandis.push(candi);
  });
  return validCandis;
};

const configUpdate = (user, stage) => {
  // const stage = event.requestContext.stage;
  // const stage = config.getStage();
  user.followedFriendsAt = new Date().getTime();
  const url = config.lambda[stage].configUpdateEndpoint;

  let options = {
    url: url,
    method: "POST",
    body: JSON.stringify({user: user}),
  };

  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) {
        return reject(error);
      }
      let newUser = JSON.parse(body).user;
      // console.log("response", response);
      // console.log("data", data);
      // console.log("Update followedAt, user:", newUser);
      //DynamoDB不能包含任何empty attributes
      resolve(newUser);
    });
  });
};

const handleFollow = (event, context, callback) => {
  // console.log("DynamoDB triggered lambda successfully");
  // console.log("event", JSON.stringify(event));
  // console.log("context", context);

  let data = JSON.parse(event.body);
  console.log("input data", JSON.stringify(data));
  if (!data.user) {
    callback(new Error("Data format error: not found `user`."));
    return;
  }

  let user = data.user;
  let friends;
  let newFriendsList;
  getFriends(user.id)//获得所有好友的ids
      .then(friendsList => friends = friendsList)
      .then(
          () => getCandisByScan(user))//scan+filterExpression获得所有符合filter的用户，只传递回，login, id, 4个crits
      .then((candidates) => removeAddedCandis(candidates, friends, user.id)) //去除已经是好友的人
      .then((candidates) => removeFullFriendsCandidates(candidates)) //去除超过上限的人
      .then(
          (validCandis) => randPickFollowers(validCandis, user.addFollowersNow))//从validCandis中调出xx个
      .then((foUsers) => followAndStore(foUsers, user)) //开始用户互相follow
      .then((newFriends) => newFriendsList = newFriends)
      .then(() => configUpdate(user, event.requestContext.stage))
      .then((newUser) => {
        // console.log("newFriends", newFriends);
        let response = {
          statusCode: 200,
          headers: {"Access-Control-Allow-Origin": "*"},
        };
        console.log("Follow user task is accomplished");
        response.body = JSON.stringify({newFriends: newFriendsList, user: newUser});
        callback(null, response);
      })//follow task is accomplished;
      .catch((err) => {
        console.error("err", err, err.stack);
        callback(new Error("Error found:", err));
      });
};

const handleGetFollowers = (event, context, callback) => {
  let data = JSON.parse(event.body);
  console.log("input data", JSON.stringify(data));
  if (!data.user) {
    callback(new Error("Data format error: not found `user`."));
    return;
  }

  let user = data.user;

  getFriends(user.id)//获得所有好友的ids
      .then(friendsList => {
        // console.log("friendsList", JSON.stringify(friendsList));
        let response = {
          statusCode: 200,
          headers: {"Access-Control-Allow-Origin": "*"},
          body: JSON.stringify(friendsList),
        };
        console.log("Get followers successfully");
        callback(null, response);
      })
      .catch((err) => {
        console.error("err", err, err.stack);
        callback(new Error("Error found:", err));
      });
};

const main = (event, context, callback) => {
  switch (event.path) {
    case "/user/getFollowers":
      handleGetFollowers(event, context, callback);
      break;
    case "user/follow":
      handleFollow(event, context, callback);
      break;
  }
};

module.exports = main;
<|endoftext|>


<commit_before>function Wavebox(name, topleft, specArgs) {
    if (arguments.length) {
        this.getready(name, topleft, specArgs);
    }
}

//inherit from the Element prototype
Wavebox.prototype = new Element();
//put the correct constructor reference back (not essential)
Wavebox.prototype.constructor = Wavebox;

Wavebox.prototype.getready = function (name, topleft, specArgs) {
    //Reference the getready method from the parent class
    this.tempReady = Element.prototype.getready;
    //and run it as if it were part of this object
    this.tempReady(name, topleft);

    this.values = {"waveboxposition" : 0,
                   "startsample" : 0,
                   "endsample" : NaN,
                   "waveboxsignal" : undefined
               };

    //By default, a Wavebox always draws itself when a value is set.
    this.drawItself = true;

    this.width = specArgs.wh[0];
    this.height = specArgs.wh[1];

    this.completed = false;

    // As soon as we can, we want to save our background.
    this.backgroundSavePending = true;

};

// This methods returns true if the point given belongs to this element.
Wavebox.prototype.isInROI = function (x, y) {
    if ((x > this.xOrigin) && (y > this.yOrigin)) {
        if ((x < (this.xOrigin + this.width)) && (y < (this.yOrigin + this.height))) {
            //console.log(this.name, "point ", x, y, " is in ROI ", this.xOrigin, this.yOrigin, this.xOrigin + this.width, this.yOrigin + this.height);
            return true;
        }
        //console.log(this.name, " ROI Handler: ", x, y, " is NOT in ROI ", this.xOrigin, this.yOrigin, this.xOrigin + this.width, this.yOrigin + this.height);
    }
    return false;
};

Wavebox.prototype.onROI = function (start_x, start_y, curr_x, curr_y) {
    var ret = {"slot" : "waveboxposition", "value" : this.values.waveboxposition};
    return ret;
};

//This has to go, it makes no sense at all.
Wavebox.prototype.getDefaultValue = function () {
    return this.values.waveboxposition;
};

Wavebox.prototype.setValue = function (slot, value) {

    // Won't call the parent: this element has a custom way to set values.

    if (this.values[slot] === value) {
        //Nothing changed, don't redraw.
        return;
    }

    // Check some boundaries.

    if ((slot === "startsample") || (slot === "endsample")) {
        if (value < 0) {
            throw new Error("Error: Trying to set ", slot, " less than 0: ", value);
        }
        if (this.values["waveboxsignal"] !== undefined) {
            if (value > this.values["waveboxsignal"].length) {
                throw new Error("Error: Trying to set ", slot, " bigger than signal length: ", value, " > ", this.values["waveboxsignal"].length);
            }
        }
    }

    if (slot === "startsample") {
        if (value > this.values["endsample"]) {
                throw new Error("Error: Trying to set startsample > endsample: ", value, " > ", this.values["endsample"]);
            }
    }

    if (slot === "endsample") {
        if (value < this.values["startample"]) {
                throw new Error("Error: Trying to set endsample < startsample: ", value, " < ", this.values["startsample"]);
            }
    }

    this.values[slot] = value;
    console.log ("set value for slot ", slot);

    // When we change the signal, we know we must reset the whole thing.
    if (slot === "waveboxsignal") {
        //Take the whole waveform
        console.log ("inside!");
        this.values["endsample"] = this.values["waveboxsignal"].length;
        this.values["startsample"] = 0;
    }

    if (this.drawItself === true) {
        this.refresh();
    }
};

Wavebox.prototype.refresh = function () {
    if (this.drawClass === undefined) {
        throw new Error("Error: drawClass is undefined!");
    }
    else {

        // Is there a save background pending?
        if (this.backgroundSavePending === true) {
                        console.log ("Saving background inside Wavebox.js");
            this.drawClass.saveBackground (this.xOrigin, this.yOrigin, this.width, this.height);
            this.backgroundSavePending = false;
        }

        else {
            // We want drawClass to refresh the saved background.
            this.drawClass.restoreBackground();
        }

        var oldpoint = 0;

        this.drawClass.beginDraw();
        for (var i = 0; i < this.width; i += 1) {
            var point = this.calculateSampleCoord(i);
            if (point !== oldpoint) {
                //console.log ("Drawing a point, x is ", point.x, " y is ", point.y);
                this.drawClass.draw (point.x, point.y);
            }
            oldpoint = point;
        }
        this.drawClass.endDraw();

    }
};

//Non-interface functions

Wavebox.prototype.sampleindexToY = function (samplenum) {
    //Check boundaries
    if ((samplenum >= this.values.endsample) || (this.values.waveboxsignal[samplenum] === undefined) || (this.values.waveboxsignal[samplenum] === NaN)) {
        throw new Error("Error: problem with sample index: ", samplenum, " or sample value: ", this.values.waveboxsignal[samplenum]);
    }

    //We got a sample number, and we want to know where it should be drawn.
    //Sample values go from -1 to 1.
    //NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
    var range01 = (this.values.waveboxsignal[samplenum] + 1) / 2;
    //console.log ("signal that was ", this.values.waveboxsignal[samplenum], " is now transformed in ", range01);
    var temp = ((1 - range01) *  this.height);
    //console.log ("Adding to origin ", temp);
    var y = this.yOrigin + temp;
    return parseInt (y, 10);

}

Wavebox.prototype.sampleXToIndex = function (xcoord) {

    var factor = ((this.values.endsample - this.values.startsample) / this.width);
    var x = xcoord * factor;
    var ret = parseInt (x, 10);
    //if (( x % 100) == 0 ) {
        //console.log ("xcoord is ", xcoord , " of ", this.width , " factor is ", factor, " and corresponding sample number is ", ret , " finishing at ", this.values.endsample);
    //}
    return ret;

}

Wavebox.prototype.calculateSampleCoord = function (xcoord) {
    // this returns the absolute x,y coordinates from the sample in x position, relative to the x-origin of the box
    var ret = {};
    ret.x = xcoord + this.xOrigin;
    ret.y = this.sampleindexToY(this.sampleXToIndex(xcoord));
    return ret;
}<commit_msg>Deleted from wavebox the now useless onROI and the deprecated getDefaultValue.<commit_after>function Wavebox(name, topleft, specArgs) {
    if (arguments.length) {
        this.getready(name, topleft, specArgs);
    }
}

//inherit from the Element prototype
Wavebox.prototype = new Element();
//put the correct constructor reference back (not essential)
Wavebox.prototype.constructor = Wavebox;

Wavebox.prototype.getready = function (name, topleft, specArgs) {
    //Reference the getready method from the parent class
    this.tempReady = Element.prototype.getready;
    //and run it as if it were part of this object
    this.tempReady(name, topleft);

    this.values = {"waveboxposition" : 0,
                   "startsample" : 0,
                   "endsample" : NaN,
                   "waveboxsignal" : undefined
               };

    //By default, a Wavebox always draws itself when a value is set.
    this.drawItself = true;

    this.width = specArgs.wh[0];
    this.height = specArgs.wh[1];

    this.completed = false;

    // As soon as we can, we want to save our background.
    this.backgroundSavePending = true;

};

// This methods returns true if the point given belongs to this element.
Wavebox.prototype.isInROI = function (x, y) {
    if ((x > this.xOrigin) && (y > this.yOrigin)) {
        if ((x < (this.xOrigin + this.width)) && (y < (this.yOrigin + this.height))) {
            //console.log(this.name, "point ", x, y, " is in ROI ", this.xOrigin, this.yOrigin, this.xOrigin + this.width, this.yOrigin + this.height);
            return true;
        }
        //console.log(this.name, " ROI Handler: ", x, y, " is NOT in ROI ", this.xOrigin, this.yOrigin, this.xOrigin + this.width, this.yOrigin + this.height);
    }
    return false;
};

Wavebox.prototype.setValue = function (slot, value) {

    // Won't call the parent: this element has a custom way to set values.

    if (this.values[slot] === value) {
        //Nothing changed, don't redraw.
        return;
    }

    // Check some boundaries.

    if ((slot === "startsample") || (slot === "endsample")) {
        if (value < 0) {
            throw new Error("Error: Trying to set ", slot, " less than 0: ", value);
        }
        if (this.values["waveboxsignal"] !== undefined) {
            if (value > this.values["waveboxsignal"].length) {
                throw new Error("Error: Trying to set ", slot, " bigger than signal length: ", value, " > ", this.values["waveboxsignal"].length);
            }
        }
    }

    if (slot === "startsample") {
        if (value > this.values["endsample"]) {
                throw new Error("Error: Trying to set startsample > endsample: ", value, " > ", this.values["endsample"]);
            }
    }

    if (slot === "endsample") {
        if (value < this.values["startample"]) {
                throw new Error("Error: Trying to set endsample < startsample: ", value, " < ", this.values["startsample"]);
            }
    }

    this.values[slot] = value;
    console.log ("set value for slot ", slot);

    // When we change the signal, we know we must reset the whole thing.
    if (slot === "waveboxsignal") {
        //Take the whole waveform
        console.log ("inside!");
        this.values["endsample"] = this.values["waveboxsignal"].length;
        this.values["startsample"] = 0;
    }

    if (this.drawItself === true) {
        this.refresh();
    }
};

Wavebox.prototype.refresh = function () {
    if (this.drawClass === undefined) {
        throw new Error("Error: drawClass is undefined!");
    }
    else {

        // Is there a save background pending?
        if (this.backgroundSavePending === true) {
                        console.log ("Saving background inside Wavebox.js");
            this.drawClass.saveBackground (this.xOrigin, this.yOrigin, this.width, this.height);
            this.backgroundSavePending = false;
        }

        else {
            // We want drawClass to refresh the saved background.
            this.drawClass.restoreBackground();
        }

        var oldpoint = 0;

        this.drawClass.beginDraw();
        for (var i = 0; i < this.width; i += 1) {
            var point = this.calculateSampleCoord(i);
            if (point !== oldpoint) {
                //console.log ("Drawing a point, x is ", point.x, " y is ", point.y);
                this.drawClass.draw (point.x, point.y);
            }
            oldpoint = point;
        }
        this.drawClass.endDraw();

    }
};

//Non-interface functions

Wavebox.prototype.sampleindexToY = function (samplenum) {
    //Check boundaries
    if ((samplenum >= this.values.endsample) || (this.values.waveboxsignal[samplenum] === undefined) || (this.values.waveboxsignal[samplenum] === NaN)) {
        throw new Error("Error: problem with sample index: ", samplenum, " or sample value: ", this.values.waveboxsignal[samplenum]);
    }

    //We got a sample number, and we want to know where it should be drawn.
    //Sample values go from -1 to 1.
    //NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
    var range01 = (this.values.waveboxsignal[samplenum] + 1) / 2;
    //console.log ("signal that was ", this.values.waveboxsignal[samplenum], " is now transformed in ", range01);
    var temp = ((1 - range01) *  this.height);
    //console.log ("Adding to origin ", temp);
    var y = this.yOrigin + temp;
    return parseInt (y, 10);

}

Wavebox.prototype.sampleXToIndex = function (xcoord) {

    var factor = ((this.values.endsample - this.values.startsample) / this.width);
    var x = xcoord * factor;
    var ret = parseInt (x, 10);
    //if (( x % 100) == 0 ) {
        //console.log ("xcoord is ", xcoord , " of ", this.width , " factor is ", factor, " and corresponding sample number is ", ret , " finishing at ", this.values.endsample);
    //}
    return ret;

}

Wavebox.prototype.calculateSampleCoord = function (xcoord) {
    // this returns the absolute x,y coordinates from the sample in x position, relative to the x-origin of the box
    var ret = {};
    ret.x = xcoord + this.xOrigin;
    ret.y = this.sampleindexToY(this.sampleXToIndex(xcoord));
    return ret;
}<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright 2017 kuniaki.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var webpack = require('webpack');
const outputPath = __dirname + "/../../public_html/application";

module.exports = {
    mode: "development",
    cache: true,
    entry:
    {
        // Register meter application and set entry point typescript file.
        "AnalogMeterCluster-Defi-SSM": './AnalogMeterCluster/AnalogMeterCluster-Defi-SSM.ts',
        "AnalogMeterCluster-SSM": './AnalogMeterCluster/AnalogMeterCluster-SSM.ts',
        "AnalogMeterCluster-ELM327": './AnalogMeterCluster/AnalogMeterCluster-ELM327.ts',
        "AnalogMeterCluster-AssettoCorsaSHM": './AnalogMeterCluster/AnalogMeterCluster-AssettoCorsaSHM.ts',
        "DigitalMFD-Defi-SSM": './DigitalMFD/DigitalMFD-Defi-SSM.ts',
        "DigitalMFD-SSM": './DigitalMFD/DigitalMFD-SSM.ts',
        "CompactMFD-ELM327": './CompactMFD/CompactMFD-ELM327.ts',
        "CompactMFD-Arduino": './CompactMFD/CompactMFD-Arduino.ts',
        "CompactMFD-SSM": './CompactMFD/CompactMFD-SSM.ts',
        "CompactMFD-AssettoCorsaSHM": './CompactMFD/CompactMFD-AssettoCorsaSHM.ts',
        "AnalogTripleMeter-SSM": './AnalogTripleMeter/AnalogTripleMeter-SSM.ts',
        "AnalogTripleMeter-ELM327": './AnalogTripleMeter/AnalogTripleMeter-ELM327.ts',
        "AnalogTripleMeter-Defi": './AnalogTripleMeter/AnalogTripleMeter-Defi.ts',
        "AnalogTripleMeter-Arduino": './AnalogTripleMeter/AnalogTripleMeter-Arduino.ts',
        "LEDRevMeter-SSM": './LEDRevMeter/LEDRevMeter-SSM.ts',
        "LEDRevMeter-ELM327": './LEDRevMeter/LEDRevMeter-ELM327.ts',
        "LEDRevMeter-Defi-SSM": './LEDRevMeter/LEDRevMeter-Defi-SSM.ts'
    },
    devtool: "#inline-source-map",
    output:
    {
        path: outputPath,
        filename: "./js/[name].js"
    },
    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension.
        extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        })
    ],
    devServer: {
        contentBase: outputPath
    },
    module: {
        rules: [
            { test: /\.tsx?$/, loader: 'ts-loader' },
            { test: /\.png$/, loader: "file-loader?name=img/[name].[ext]" },
            { test: /\.fnt$/, loader: "file-loader?name=img/[name].[ext]" }, // Bitmap font setting files
            { type: "javascript/auto", test: /\.json$/, loader: "file-loader?name=img/[name].[ext]" },
            { test: /\.html$/, loader: "file-loader?name=[name].[ext]" },
            { test: /bootstrap.slate.min.css/, loader: "style-loader!css-loader" },// for bootstrap
            { test: /\.css$/, exclude: /bootstrap.slate.min.css/, loader: 'file-loader?name=[name].[ext]' },
            { test: /\.svg$/, loader: 'url-loader?mimetype=image/svg+xml' },
            { test: /\.woff$/, loader: 'url-loader?mimetype=application/font-woff' },
            { test: /\.woff2$/, loader: 'url-loader?mimetype=application/font-woff' },
            { test: /\.eot$/, loader: 'url-loader?mimetype=application/font-woff' },
            { test: /\.(ttf|otf)$/, loader: "file-loader?name=fonts/[name].[ext]" },
            {
                test: /\.(scss)$/,
                use: [{
                    loader: 'style-loader' // inject CSS to page
                }, {
                    loader: 'css-loader' // translates CSS into CommonJS modules
                }, {
                    loader: 'postcss-loader', // Run post css actions
                    options: {
                        plugins: function () { // post css plugins, can be exported to postcss.config.js
                            return [
                                require('precss'),
                                require('autoprefixer')
                            ];
                        }
                    }
                }, {
                    loader: 'sass-loader' // compiles SASS to CSS
                }]
            }
        ]
    }
};
<commit_msg>Fix webpack.config.js of application.<commit_after>/*
 * The MIT License
 *
 * Copyright 2017 kuniaki.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var webpack = require('webpack');
const outputPath = __dirname + "/../../public_html/application";

module.exports = {
    mode: "development",
    cache: true,
    entry:
    {
        // Register meter application and set entry point typescript file.
        "AnalogMeterCluster-Defi-SSM": './AnalogMeterCluster/AnalogMeterCluster-Defi-SSM.ts',
        "AnalogMeterCluster-SSM": './AnalogMeterCluster/AnalogMeterCluster-SSM.ts',
        "AnalogMeterCluster-ELM327": './AnalogMeterCluster/AnalogMeterCluster-ELM327.ts',
        "AnalogMeterCluster-AssettoCorsaSHM": './AnalogMeterCluster/AnalogMeterCluster-AssettoCorsaSHM.ts',
        "DigitalMFD-Defi-SSM": './DigitalMFD/DigitalMFD-Defi-SSM.ts',
        "DigitalMFD-SSM": './DigitalMFD/DigitalMFD-SSM.ts',
        "CompactMFD-ELM327": './CompactMFD/CompactMFD-ELM327.ts',
        "CompactMFD-Arduino": './CompactMFD/CompactMFD-Arduino.ts',
        "CompactMFD-SSM": './CompactMFD/CompactMFD-SSM.ts',
        "CompactMFD-AssettoCorsaSHM": './CompactMFD/CompactMFD-AssettoCorsaSHM.ts',
        "AnalogTripleMeter-SSM": './AnalogTripleMeter/AnalogTripleMeter-SSM.ts',
        "AnalogTripleMeter-ELM327": './AnalogTripleMeter/AnalogTripleMeter-ELM327.ts',
        "AnalogTripleMeter-Defi": './AnalogTripleMeter/AnalogTripleMeter-Defi.ts',
        "AnalogTripleMeter-Arduino": './AnalogTripleMeter/AnalogTripleMeter-Arduino.ts',
        "LEDRevMeter-SSM": './LEDRevMeter/LEDRevMeter-SSM.ts',
        "LEDRevMeter-ELM327": './LEDRevMeter/LEDRevMeter-ELM327.ts',
        "LEDRevMeter-Defi-SSM": './LEDRevMeter/LEDRevMeter-Defi-SSM.ts'
    },
    devtool: "source-map",
    output:
    {
        path: outputPath,
        filename: "./js/[name].js"
    },
    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension.
        extensions: ['.ts', '.tsx', '.js']
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        })
    ],
    devServer: {
        contentBase: outputPath
    },
    module: {
        rules: [
            { test: /\.tsx?$/, use: 'ts-loader' },
            { test: /\.png$/, use: "file-loader?name=img/[name].[ext]" },
            { test: /\.fnt$/, use: "file-loader?name=img/[name].[ext]" }, // Bitmap font setting files
            { type: "javascript/auto", test: /\.json$/, use: "file-loader?name=img/[name].[ext]" },
            { test: /\.html$/, use: "file-loader?name=[name].[ext]" },
            { test: /bootstrap.slate.min.css/, use: "style-loader!css-loader" },// for bootstrap
            { test: /\.css$/, exclude: /bootstrap.slate.min.css/, use: 'file-loader?name=[name].[ext]' },
            { test: /\.svg$/, use: 'url-loader?mimetype=image/svg+xml' },
            { test: /\.woff$/, use: 'url-loader?mimetype=application/font-woff' },
            { test: /\.woff2$/, use: 'url-loader?mimetype=application/font-woff' },
            { test: /\.eot$/, use: 'url-loader?mimetype=application/font-woff' },
            { test: /\.(ttf|otf)$/, use: "file-loader?name=fonts/[name].[ext]" },
            {
                test: /\.(scss)$/,
                use: [{
                    loader: 'style-loader' // inject CSS to page
                }, {
                    loader: 'css-loader' // translates CSS into CommonJS modules
                }, {
                    loader: 'postcss-loader', // Run post css actions
                    options: {
                        plugins: function () { // post css plugins, can be exported to postcss.config.js
                            return [
                                require('precss'),
                                require('autoprefixer')
                            ];
                        }
                    }
                }, {
                    loader: 'sass-loader' // compiles SASS to CSS
                }]
            }
        ]
    }
};
<|endoftext|>


<commit_before>goog.provide('app.layerinfoDirective');

goog.require('app');
goog.require('app.ShowLayerinfo');

/**
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.layerinfoDirective = function(appLayerinfoTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'layer': '=appLayerinfoLayer'
    },
    controller: 'AppLayerinfoController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appLayerinfoTemplateUrl
  };
};

app.module.directive('appLayerinfo', app.layerinfoDirective);

/**
 * @constructor
 * @param {app.ShowLayerinfo} appShowLayerinfo app.ShowLayerinfo service.
 * @ngInject
 * @export
 */
app.LayerinfoController = function(appShowLayerinfo) {
  /**
   * @private
   */
  this.showLayerInfo_ = appShowLayerinfo;
};

/**
 * @export
 */
app.LayerinfoController.prototype.getInfo = function() {
  this.showLayerInfo_(this['layer']);
};

app.module.controller('AppLayerinfoController', app.LayerinfoController);
<commit_msg>Fix lint error for layerinfodirective.js<commit_after>goog.provide('app.layerinfoDirective');

goog.require('app');
goog.require('app.ShowLayerinfo');

/**
 * @param {string} appLayerinfoTemplateUrl URL to directive template.
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.layerinfoDirective = function(appLayerinfoTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'layer': '=appLayerinfoLayer'
    },
    controller: 'AppLayerinfoController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appLayerinfoTemplateUrl
  };
};

app.module.directive('appLayerinfo', app.layerinfoDirective);

/**
 * @constructor
 * @param {app.ShowLayerinfo} appShowLayerinfo app.ShowLayerinfo service.
 * @ngInject
 * @export
 */
app.LayerinfoController = function(appShowLayerinfo) {
  /**
   * @private
   */
  this.showLayerInfo_ = appShowLayerinfo;
};

/**
 * @export
 */
app.LayerinfoController.prototype.getInfo = function() {
  this.showLayerInfo_(this['layer']);
};

app.module.controller('AppLayerinfoController', app.LayerinfoController);
<|endoftext|>


<commit_before>module.exports = {
	cliPath: __dirname + '/../test.py'
};
<commit_msg>dynamic change python script location test<commit_after>
var path = process.platform == "linux" ? __dirname +'/../scale.py' : __dirname+'/../test.py';
module.exports = {
	cliPath: path
};<|endoftext|>


<commit_before>export default ({
    input: {
        control: {
            backgroundColor: '#fff',
            fontWeight: 'normal',
        },

        input: {
            margin: 0,
        },

        '&multiLine': {
            control: {
                border: '1px solid silver',
            },

            highlighter: {
                padding: 9,
            },

            input: {
                padding: 9,
                minHeight: 63,
                outline: 0,
                border: 0,
            },
        },

        suggestions: {
            list: {
                backgroundColor: 'white',
                border: '1px solid rgba(0,0,0,0.15)',
            },

            item: {
                padding: '5px 15px',
                borderBottom: '1px solid rgba(0,0,0,0.15)',

                '&focused': {
                    backgroundColor: '#5ea9c8',
                },
            },
        },
    },

    mention: {
        backgroundColor: '#cee4e5',
    }
});
<commit_msg>Limit input height to prevent overlapping the buttons<commit_after>export default ({
    input: {
        control: {
            backgroundColor: '#fff',
            fontWeight: 'normal',
        },

        input: {
            margin: 0,
        },

        '&multiLine': {
            control: {
                border: '1px solid silver',
            },

            highlighter: {
                padding: 9,
                overflowY: 'hidden',
            },

            input: {
                padding: 9,
                minHeight: 63,
                maxHeight: 200,
                overflowY: 'scroll',
                outline: 0,
                border: 0,
            },
        },

        suggestions: {
            list: {
                backgroundColor: 'white',
                border: '1px solid rgba(0,0,0,0.15)',
            },

            item: {
                padding: '5px 15px',
                borderBottom: '1px solid rgba(0,0,0,0.15)',

                '&focused': {
                    backgroundColor: '#5ea9c8',
                },
            },
        },
    },

    mention: {
        backgroundColor: '#cee4e5',
    }
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var citizen = require('citizen');
var config = require('config');
var request = require('request');
var SideComments = require('side-comments');
var template = require('./template');
var StatefulView = require('stateful-view');

/**
 * Expose `ProposalClauses`
 */

module.exports = ProposalClauses;

function ProposalClauses(law) {
  StatefulView.call(this, template, { clauses: law.clauses });

  this.law = law;
  this.context = 'clause';
  this.loadComments();
}

StatefulView(ProposalClauses);

ProposalClauses.prototype.loadComments = function() {
  this
    .load()
    .ready(this.sideComments.bind(this));
};

ProposalClauses.prototype.load = function(clauseId) {
  var self = this;

  request
    .get('/api/law/:id/clause-comments'.replace(':id', this.law.id))
    .end(function (err, res) {
      if (res.status !== 200) ; //log error

      self.comments = res.body;
      self.state('loaded');
    });

  return this;
};

ProposalClauses.prototype.sideComments = function () {
  var self = this;
  citizen.ready(function () {
    var userComment = citizen ? { id: citizen.id, avatarUrl: citizen.gravatar, name: citizen.firstName} : null;
    var sections = [];
    self.law.clauses.forEach(function (clause) {
      var section = {};
      section.sectionId = clause.id;

      function filterBySection(comment) {
        return comment.reference == clause.id;
      }

      section.comments = self.comments.filter(filterBySection).map(self.formatComment);
      sections.push(section);
    });
    var sideComments = self.sideComments = new SideComments('.proposal.commentable-container', userComment, sections, { locale: config['locale'], voting: true });
    sideComments.on('commentPosted', self.onClauseCommentPosted.bind(self));
    // sideComments.on('commentUpvoted', function (comment) {
    //   console.log(comment);
    // });
  });
}

ProposalClauses.prototype.formatComment = function (comment) {
  comment.authorAvatarUrl = comment.author.gravatar;
  comment.authorName = comment.author.fullName;
  comment.authorId = comment.author.id;
  comment.comment = comment.text;
  comment.sectionId = comment.reference;
  return comment;
}

ProposalClauses.prototype.onClauseCommentPosted = function(comment) {
  var self = this;
  var clauseComment = {};
  clauseComment.reference = comment.sectionId;
  clauseComment.context = this.context;
  clauseComment.text = comment.comment;
  request
  .post(
    '/api/:context/:reference/comment'
    .replace(':context', 'law')
    .replace(':reference', comment.sectionId))
  .send({ comment: clauseComment })
  .end(function(err, res) {
    if (err) return log('')
    var comment = self.formatComment(res.body);
    self.sideComments.insertComment(comment);
  });
};<commit_msg>[proposal-clauses] - Add delete comment handler #390<commit_after>/**
 * Module dependencies.
 */

var citizen = require('citizen');
var config = require('config');
var request = require('request');
var SideComments = require('side-comments');
var template = require('./template');
var StatefulView = require('stateful-view');

/**
 * Expose `ProposalClauses`
 */

module.exports = ProposalClauses;

function ProposalClauses(law) {
  StatefulView.call(this, template, { clauses: law.clauses });

  this.law = law;
  this.context = 'clause';
  this.loadComments();
}

StatefulView(ProposalClauses);

ProposalClauses.prototype.loadComments = function() {
  this
    .load()
    .ready(this.sideComments.bind(this));
};

ProposalClauses.prototype.load = function(clauseId) {
  var self = this;

  request
    .get('/api/law/:id/clause-comments'.replace(':id', this.law.id))
    .end(function (err, res) {
      if (res.status !== 200) ; //log error

      self.comments = res.body;
      self.state('loaded');
    });

  return this;
};

ProposalClauses.prototype.sideComments = function () {
  var self = this;
  citizen.ready(function () {
    var userComment = citizen ? { id: citizen.id, avatarUrl: citizen.gravatar, name: citizen.firstName} : null;
    var sections = [];
    self.law.clauses.forEach(function (clause) {
      var section = {};
      section.sectionId = clause.id;

      function filterBySection(comment) {
        return comment.reference == clause.id;
      }

      section.comments = self.comments.filter(filterBySection).map(self.formatComment);
      sections.push(section);
    });
    var sideComments = self.sideComments = new SideComments('.proposal.commentable-container', userComment, sections, { locale: config['locale'], voting: true });
    sideComments.on('commentPosted', self.onClauseCommentPosted.bind(self));
    sideComments.on('commentDeleted', self.onClauseCommentDeleted.bind(self));
  });
}

ProposalClauses.prototype.formatComment = function (comment) {
  comment.authorAvatarUrl = comment.author.gravatar;
  comment.authorName = comment.author.fullName;
  comment.authorId = comment.author.id;
  comment.comment = comment.text;
  comment.sectionId = comment.reference;
  return comment;
}

ProposalClauses.prototype.onClauseCommentPosted = function(comment) {
  var self = this;
  var clauseComment = {};
  clauseComment.reference = comment.sectionId;
  clauseComment.context = this.context;
  clauseComment.text = comment.comment;
  request
  .post(
    '/api/:context/:reference/comment'
    .replace(':context', 'law')
    .replace(':reference', comment.sectionId))
  .send({ comment: clauseComment })
  .end(function(err, res) {
    if (err) return log('')
    var comment = self.formatComment(res.body);
    self.sideComments.insertComment(comment);
  });
};

ProposalClauses.prototype.onClauseCommentDeleted = function(comment) {
  var self = this;
  request
    .del('/api/comment/:id'
      .replace(':id', comment.id))
    .end(function(err, res) {
      if (err) return log('Fetch error: %s', err);
      if (!res.ok) err = res.error, log('Fetch error: %s', err);
      if (res.body && res.body.error) err = res.body.error, log('Fetch response error: %s', err);

      self.sideComments.removeComment(comment.sectionId, comment.id);
    });
};<|endoftext|>


<commit_before>class PlateViewer {
  constructor(p_xSizeAndPos){
    this.sizeAndPosition = p_xSizeAndPos;
  }

  get x(){ return this.sizeAndPosition.x; }
  get y(){ return this.sizeAndPosition.y; }
  get width(){ return this.sizeAndPosition.width; }
  get height(){ return this.sizeAndPosition.height; }
  get aspectRatio(){ return this._aspectRatioOf(this.sizeAndPosition); }

  viewPlate(plate){
    this.shapeGroup = new paper.Group();
    this.plate = plate;
    this.viewParts(plate.parts);
    this.shapeGroup.fitBounds(this.sizeAndPosition);
  }

  viewParts(parts){
    parts.forEach(p => this.viewPart(p));
  }

  viewPart(part){
    let shape = this.buildShape(part);
    shape.fillColor = this.colorFrom(part.color);
    this.shapeGroup.addChild(shape);
  }

  buildShape(shapeData){
    switch (shapeData.shape){
      case "rect": return this.viewRect(shapeData);
      default: console.log(`Unrecognized shape: ${shapeData.shape}`);
    }
  }

  viewRect(shape){
    let rect = this.rectForShape(shape);
    let newRect = new paper.Shape.Rectangle(rect);
    return newRect;
  }

  rectForShape(shape){
    let point = this.pointForShape(shape.pos);
    let size = this.sizeForShape(shape.size);
    return new paper.Rectangle(point, size);
  }

  pointForShape(pos_csv){
    var pos = this.parseNumbersFromCsv(pos_csv);
    return new paper.Point( pos[0], pos[1] );
  }

  sizeForShape(size_csv){
    var size = this.parseNumbersFromCsv(size_csv);
    return new paper.Size( size[0], size[1] );
  }

  colorFrom(colorStr){
    var colorParts = this.parseNumbersFromCsv(colorStr);
    colorParts = colorParts.map(p => p / 255.0);
    return new paper.Color(colorParts[0], colorParts[1], colorParts[2]);
  }

  parseNumbersFromCsv(str){
    return str.split(',').map(p => Number(p));
  }
}<commit_msg>paperjs/int-of-color - Fix bug related to rendering unknown shapes<commit_after>class PlateViewer {
  constructor(p_xSizeAndPos){
    this.sizeAndPosition = p_xSizeAndPos;
  }

  get x(){ return this.sizeAndPosition.x; }
  get y(){ return this.sizeAndPosition.y; }
  get width(){ return this.sizeAndPosition.width; }
  get height(){ return this.sizeAndPosition.height; }
  get aspectRatio(){ return this._aspectRatioOf(this.sizeAndPosition); }

  viewPlate(plate){
    this.shapeGroup = new paper.Group();
    this.plate = plate;
    this.viewParts(plate.parts);
    this.shapeGroup.fitBounds(this.sizeAndPosition);
  }

  viewParts(parts){
    parts.forEach(p => this.viewPart(p));
  }

  viewPart(part){
    let shape = this.buildShape(part);
    if (shape) {
      shape.fillColor = this.colorFrom(part.color);
      this.shapeGroup.addChild(shape);
    }
  }

  buildShape(shapeData){
    switch (shapeData.shape){
      case "rect": return this.viewRect(shapeData);
      default: console.log(`Unrecognized shape: ${shapeData.shape}`);
    }
  }

  viewRect(shape){
    let rect = this.rectForShape(shape);
    let newRect = new paper.Shape.Rectangle(rect);
    return newRect;
  }

  rectForShape(shape){
    let point = this.pointForShape(shape.pos);
    let size = this.sizeForShape(shape.size);
    return new paper.Rectangle(point, size);
  }

  pointForShape(pos_csv){
    var pos = this.parseNumbersFromCsv(pos_csv);
    return new paper.Point( pos[0], pos[1] );
  }

  sizeForShape(size_csv){
    var size = this.parseNumbersFromCsv(size_csv);
    return new paper.Size( size[0], size[1] );
  }

  colorFrom(colorStr){
    var colorParts = this.parseNumbersFromCsv(colorStr);
    colorParts = colorParts.map(p => p / 255.0);
    return new paper.Color(colorParts[0], colorParts[1], colorParts[2]);
  }

  parseNumbersFromCsv(str){
    return str.split(',').map(p => Number(p));
  }
}<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable consistent-return */
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const writeFiles = require('./files').writeFiles;
const constants = require('../generator-constants');

let useBlueprints;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = this.options.configOptions || {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false,
        });

        useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('e2e', { 'client-hook': !this.skipClient });
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            setupConstants() {
                // Make constants available in templates
                this.MAIN_DIR = constants.MAIN_DIR;
                this.TEST_DIR = constants.TEST_DIR;
                this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
                this.ANGULAR = constants.SUPPORTED_CLIENT_FRAMEWORKS.ANGULAR;
                this.CLIENT_DIST_DIR = this.getResourceBuildDirectoryForBuildTool(this.configOptions.buildTool) + constants.CLIENT_DIST_DIR;
            },
        };
    }

    get initializing() {
        if (useBlueprints) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return {
            loadSharedConfig() {
                this.loadAppConfig();
                this.loadClientConfig();
                this.loadServerConfig();
                this.loadTranslationConfig();
            },
            setupConstants() {
                this.BUILD_DIR = this.getBuildDirectoryForBuildTool(this.buildTool);
            },
        };
    }

    get default() {
        if (useBlueprints) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return writeFiles();
    }

    get writing() {
        if (useBlueprints) return;
        return this._writing();
    }
};
<commit_msg>Move CLIENT_DIST_DIR to default priority<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable consistent-return */
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const writeFiles = require('./files').writeFiles;
const constants = require('../generator-constants');

let useBlueprints;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = this.options.configOptions || {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false,
        });

        useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('e2e', { 'client-hook': !this.skipClient });
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            setupConstants() {
                // Make constants available in templates
                this.MAIN_DIR = constants.MAIN_DIR;
                this.TEST_DIR = constants.TEST_DIR;
                this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
                this.ANGULAR = constants.SUPPORTED_CLIENT_FRAMEWORKS.ANGULAR;
            },
        };
    }

    get initializing() {
        if (useBlueprints) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return {
            loadSharedConfig() {
                this.loadAppConfig();
                this.loadClientConfig();
                this.loadServerConfig();
                this.loadTranslationConfig();
            },
            setupConstants() {
                this.BUILD_DIR = this.getBuildDirectoryForBuildTool(this.buildTool);
                this.CLIENT_DIST_DIR = this.getResourceBuildDirectoryForBuildTool(this.buildTool) + constants.CLIENT_DIST_DIR;
            },
        };
    }

    get default() {
        if (useBlueprints) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return writeFiles();
    }

    get writing() {
        if (useBlueprints) return;
        return this._writing();
    }
};
<|endoftext|>


<commit_before>import { resolve } from 'path';
import { optimize } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';

module.exports = env => {
  const styleLoader = [
    'style-loader',
    { loader: 'css-loader', options: { importLoaders: 1 } },
    'postcss-loader',
    'sass-loader',
  ];

  const plugins = [
    new HtmlWebpackPlugin({ template: 'index.html', hash: true }),
  ];

  const productionPlugins = [
    new optimize.UglifyJsPlugin({
      output: { comments: false },
      sourceMap: true,
    }),
  ];

  return {
    entry: './index.js',
    output: {
      filename: 'bundle.js',
      path: resolve(__dirname, 'build'),
      pathinfo: !env.prod,
    },
    context: resolve(__dirname, 'src'),
    devtool: env.prod ? 'source-map' : 'cheap-source-map',
    bail: env.prod,
    module: {
      rules: [
        { test: /\.jsx?$/, use: 'babel-loader', exclude: /^(?!.*src)/ },
        { test: /\.scss$/, use: styleLoader },
        { test: /\.svg$/, use: 'svg-sprite-loader' },
      ],
    },
    plugins: plugins.concat(env.prod ? productionPlugins : []),
  };
}
<commit_msg>use production inferno when building<commit_after>import { resolve } from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';

module.exports = env => {
  const styleLoader = [
    'style-loader',
    { loader: 'css-loader', options: { importLoaders: 1 } },
    'postcss-loader',
    'sass-loader',
  ];

  const plugins = [
    new HtmlWebpackPlugin({ template: 'index.html', hash: true }),
  ];

  const productionPlugins = [
    new webpack.optimize.UglifyJsPlugin({
      output: { comments: false },
      sourceMap: true,
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: '"production"' }
    }),
  ];

  return {
    entry: './index.js',
    output: {
      filename: 'bundle.js',
      path: resolve(__dirname, 'build'),
      pathinfo: !env.prod,
    },
    context: resolve(__dirname, 'src'),
    devtool: env.prod ? 'source-map' : 'cheap-source-map',
    bail: env.prod,
    module: {
      rules: [
        { test: /\.jsx?$/, use: 'babel-loader', exclude: /^(?!.*src)/ },
        { test: /\.scss$/, use: styleLoader },
        { test: /\.svg$/, use: 'svg-sprite-loader' },
      ],
    },
    plugins: plugins.concat(env.prod ? productionPlugins : []),
  };
}
<|endoftext|>


<commit_before>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off", no-negated-condition: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, Service, Characteristic} = iface;

    return function createService_CarbonDioxideSensor(acc, settings, subtype) {
        acc.addService(Service.CarbonDioxideSensor, settings.name, subtype)
            .getCharacteristic(Characteristic.CarbonDioxideDetected)
            .on('get', callback => {
                log.debug('< hap get', settings.name, 'CarbonDioxideDetected');
                const contact = mqttStatus[settings.topic.statusCarbonDioxideDetected] === settings.payload.onCarbonDioxideDetected ?
                    Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL :
                    Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL;

                log.debug('> hap re_get', settings.name, 'CarbonDioxideDetected', contact);
                callback(null, contact);
            });

        mqttSub(settings.topic.statusCarbonDioxideDetected, val => {
            const contact = val === settings.payload.onCarbonDioxideDetected ?
                Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL :
                Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL;
            log.debug('> hap update', settings.name, 'CarbonDioxideDetected', contact);
            acc.getService(subtype)
                .updateCharacteristic(Characteristic.CarbonDioxideDetected, contact);
        });

        /* istanbul ignore else */
        if (settings.topic.statusLowBattery) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusLowBattery)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusLowBattery');
                    const bat = mqttStatus[settings.topic.statusLowBattery] !== settings.payload.onLowBattery ?
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                    log.debug('> hap re_get', settings.name, 'StatusLowBattery', bat);
                    callback(null, bat);
                });

            mqttSub(settings.topic.statusLowBattery, val => {
                const bat = val !== settings.payload.onLowBattery ?
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                log.debug('> hap update', settings.name, 'StatusLowBattery', bat);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusLowBattery, bat);
            });
        }

        /* istanbul ignore else */
        /* Optional: Status Active */
        if (settings.topic.statusActive) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusActive)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusActive');
                    const act = mqttStatus[settings.topic.statusActive] === settings.payload.onActive;
                    log.debug('> hap re_get', settings.name, 'StatusActive', act);
                    callback(null, act);
                });

            mqttSub(settings.topic.statusActive, val => {
                const act = val === settings.payload.onActive;
                log.debug('> hap update', settings.name, 'StatusActive', act);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusActive, act);
            });
        }

        /* istanbul ignore else */
        /* Optional: Status Fault */
        if (settings.topic.statusFault) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusFault)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusFault');
                    const fault = mqttStatus[settings.topic.statusFault] !== settings.payload.onFault ?
                        Characteristic.StatusFault.NO_FAULT :
                        Characteristic.StatusFault.GENERAL_FAULT;
                    log.debug('> hap re_get', settings.name, 'StatusFault', fault);
                    callback(null, fault);
                });

            mqttSub(settings.topic.statusFault, val => {
                const fault = val !== settings.payload.onFault ?
                    Characteristic.StatusFault.NO_FAULT :
                    Characteristic.StatusFault.GENERAL_FAULT;
                log.debug('> hap update', settings.name, 'StatusFault', fault);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusFault, fault);
            });
        }

        /* istanbul ignore else */
        /* Optional: Status Tampered */
        if (settings.topic.statusTampered) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusTampered)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusTampered');
                    const tampered = mqttStatus[settings.topic.statusTampered] !== settings.payload.onTampered ?
                        Characteristic.StatusTampered.NOT_TAMPERED :
                        Characteristic.StatusTampered.TAMPERED;
                    log.debug('> hap re_get', settings.name, 'StatusTampered', tampered);
                    callback(null, tampered);
                });

            mqttSub(settings.topic.statusTampered, val => {
                const tampered = val !== settings.payload.onTampered ?
                    Characteristic.StatusTampered.NOT_TAMPERED :
                    Characteristic.StatusTampered.TAMPERED;
                log.debug('> hap update', settings.name, 'StatusTampered', tampered);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusTampered, tampered);
            });
        }
    };
};

<commit_msg>Update CarbonDioxideSensor.js<commit_after>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off", no-negated-condition: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, Service, Characteristic} = iface;

    return function createService_CarbonDioxideSensor(acc, settings, subtype) {
        acc.addService(Service.CarbonDioxideSensor, settings.name, subtype)
            .getCharacteristic(Characteristic.CarbonDioxideDetected)
            .on('get', callback => {
                log.debug('< hap get', settings.name, 'CarbonDioxideDetected');
                const contact = mqttStatus[settings.topic.statusCarbonDioxideDetected] === settings.payload.onCarbonDioxideDetected ?
                    Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL :
                    Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL;

                log.debug('> hap re_get', settings.name, 'CarbonDioxideDetected', contact);
                callback(null, contact);
            });

        mqttSub(settings.topic.statusCarbonDioxideDetected, val => {
            const contact = val === settings.payload.onCarbonDioxideDetected ?
                Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL :
                Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL;
            log.debug('> hap update', settings.name, 'CarbonDioxideDetected', contact);
            acc.getService(subtype)
                .updateCharacteristic(Characteristic.CarbonDioxideDetected, contact);
        });

        /* istanbul ignore else */
        if (settings.topic.statusLowBattery) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusLowBattery)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusLowBattery');
                    const bat = mqttStatus[settings.topic.statusLowBattery] !== settings.payload.onLowBattery ?
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                        Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                    log.debug('> hap re_get', settings.name, 'StatusLowBattery', bat);
                    callback(null, bat);
                });

            mqttSub(settings.topic.statusLowBattery, val => {
                const bat = val !== settings.payload.onLowBattery ?
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL :
                    Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
                log.debug('> hap update', settings.name, 'StatusLowBattery', bat);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusLowBattery, bat);
            });
        }

        /* istanbul ignore else */
        /* Optional: Status Active */
        if (settings.topic.statusActive) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusActive)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusActive');
                    const act = mqttStatus[settings.topic.statusActive] === settings.payload.onActive;
                    log.debug('> hap re_get', settings.name, 'StatusActive', act);
                    callback(null, act);
                });

            mqttSub(settings.topic.statusActive, val => {
                const act = val === settings.payload.onActive;
                log.debug('> hap update', settings.name, 'StatusActive', act);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusActive, act);
            });
        }

        /* istanbul ignore else */
        /* Optional: Status Fault */
        if (settings.topic.statusFault) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusFault)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusFault');
                    const fault = mqttStatus[settings.topic.statusFault] !== settings.payload.onFault ?
                        Characteristic.StatusFault.NO_FAULT :
                        Characteristic.StatusFault.GENERAL_FAULT;
                    log.debug('> hap re_get', settings.name, 'StatusFault', fault);
                    callback(null, fault);
                });

            mqttSub(settings.topic.statusFault, val => {
                const fault = val !== settings.payload.onFault ?
                    Characteristic.StatusFault.NO_FAULT :
                    Characteristic.StatusFault.GENERAL_FAULT;
                log.debug('> hap update', settings.name, 'StatusFault', fault);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusFault, fault);
            });
        }

        /* istanbul ignore else */
        /* Optional: Status Tampered */
        if (settings.topic.statusTampered) {
            acc.getService(subtype)
                .getCharacteristic(Characteristic.StatusTampered)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'StatusTampered');
                    const tampered = mqttStatus[settings.topic.statusTampered] !== settings.payload.onTampered ?
                        Characteristic.StatusTampered.NOT_TAMPERED :
                        Characteristic.StatusTampered.TAMPERED;
                    log.debug('> hap re_get', settings.name, 'StatusTampered', tampered);
                    callback(null, tampered);
                });

            mqttSub(settings.topic.statusTampered, val => {
                const tampered = val !== settings.payload.onTampered ?
                    Characteristic.StatusTampered.NOT_TAMPERED :
                    Characteristic.StatusTampered.TAMPERED;
                log.debug('> hap update', settings.name, 'StatusTampered', tampered);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.StatusTampered, tampered);
            });
        }

        if (settings.topic.statusCarbonDioxideLevel) {
             mqttSub(settings.topic.statusCarbonDioxideLevel, val => {
                log.debug('> hap update', settings.name, 'CarbonDioxideLevel', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.CarbonDioxideLevel, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.CarbonDioxideLevel)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'CarbonDioxideLevel');
                    log.debug('> hap re_get', settings.name, 'CarbonDioxideLevel', mqttStatus[settings.topic.statusCarbonDioxideLevel]);
                    callback(null, mqttStatus[settings.topic.statusCarbonDioxideLevel]);
                });
      	}

        if (settings.topic.statusCarbonDioxidePeakLevel) {
              mqttSub(settings.topic.statusCarbonDioxidePeakLevel, val => {
                log.debug('> hap update', settings.name, 'CarbonDioxidePeakLevel', val);
                acc.getService(subtype)
                    .updateCharacteristic(Characteristic.CarbonDioxidePeakLevel, val);
            });
            acc.getService(subtype)
                .getCharacteristic(Characteristic.CarbonDioxidePeakLevel)
                .on('get', callback => {
                    log.debug('< hap get', settings.name, 'CarbonDioxidePeakLevel');
                    log.debug('> hap re_get', settings.name, 'CarbonDioxidePeakLevel', mqttStatus[settings.topic.statusCarbonDioxidePeakLevel]);
                    callback(null, mqttStatus[settings.topic.statusCarbonDioxidePeakLevel]);
                });

      	}

    };
};

<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.tags.multiselect");
pimcore.object.tags.multiselect = Class.create(pimcore.object.tags.abstract, {

    type: "multiselect",

    initialize: function (data, fieldConfig) {
        this.data = data;
        this.fieldConfig = fieldConfig;

    },

    getGridColumnConfig: function(field) {
        return {header: ts(field.label), width: 150, sortable: false, dataIndex: field.key,
            renderer: function (key, value, metaData, record) {
                if(record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
                    metaData.css += " grid_value_inherited";
                }

                if (value && value.length > 0) {
                    return value.join(",");
                }
            }.bind(this, field.key)};
    },

    getGridColumnFilter: function(field) {
        var selectFilterFields = [];

        var store = new Ext.data.JsonStore({
            autoDestroy: true,
            root: 'options',
            fields: ['key',"value"],
            data: field.layout
        });

        store.each(function (rec) {
            selectFilterFields.push(rec.data.value);
        });

        return {type: 'list', dataIndex: field.key, options: selectFilterFields};
    },

    getLayoutEdit: function () {

        // generate store
        var storeData = [];
        var validValues = [];

        var restrictTo = null;
        if (this.fieldConfig.restrictTo) {
            restrictTo = this.fieldConfig.restrictTo.split(",");
        }

        for (var i = 0; i < this.fieldConfig.options.length; i++) {
            var value = this.fieldConfig.options[i].value;
            if (restrictTo) {
                if (!in_array(value, restrictTo)) {
                    continue;
                }
            }

            storeData.push([value, this.fieldConfig.options[i].key]);
            validValues.push(value);
        }

        var store = Ext.create('Ext.data.ArrayStore', {
            fields: ['id', 'text'],
            data: storeData
        });

        var options = {
            name: this.fieldConfig.name,
            triggerAction: "all",
            editable: false,
            fieldLabel: this.fieldConfig.title,
            store: store,
            itemCls: "object_field"
        };

        if (this.fieldConfig.width) {
            options.width = this.fieldConfig.width;
        } else {
            options.width = 100;
        }
        if (this.fieldConfig.height) {
            options.height = this.fieldConfig.height;
        }

        if (typeof this.data == "string" || typeof this.data == "number") {
            options.value = this.data;
        }

        this.component = new Ext.ux.form.MultiSelect(options);

        return this.component;
    },

    getLayoutShow: function () {

        this.component = this.getLayoutEdit();

        this.component.on("afterrender", function () {
            this.component.disable();
        }.bind(this));

        return this.component;
    },

    getValue: function () {
        if(this.isRendered()) {
            return this.component.getValue();
        }
    },

    getName: function () {
        return this.fieldConfig.name;
    }
});<commit_msg>multiselect: fixed default height<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.tags.multiselect");
pimcore.object.tags.multiselect = Class.create(pimcore.object.tags.abstract, {

    type: "multiselect",

    initialize: function (data, fieldConfig) {
        this.data = data;
        this.fieldConfig = fieldConfig;

    },

    getGridColumnConfig: function(field) {
        return {header: ts(field.label), width: 150, sortable: false, dataIndex: field.key,
            renderer: function (key, value, metaData, record) {
                if(record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
                    metaData.css += " grid_value_inherited";
                }

                if (value && value.length > 0) {
                    return value.join(",");
                }
            }.bind(this, field.key)};
    },

    getGridColumnFilter: function(field) {
        var selectFilterFields = [];

        var store = new Ext.data.JsonStore({
            autoDestroy: true,
            root: 'options',
            fields: ['key',"value"],
            data: field.layout
        });

        store.each(function (rec) {
            selectFilterFields.push(rec.data.value);
        });

        return {type: 'list', dataIndex: field.key, options: selectFilterFields};
    },

    getLayoutEdit: function () {

        // generate store
        var storeData = [];
        var validValues = [];

        var restrictTo = null;
        if (this.fieldConfig.restrictTo) {
            restrictTo = this.fieldConfig.restrictTo.split(",");
        }

        for (var i = 0; i < this.fieldConfig.options.length; i++) {
            var value = this.fieldConfig.options[i].value;
            if (restrictTo) {
                if (!in_array(value, restrictTo)) {
                    continue;
                }
            }

            storeData.push([value, this.fieldConfig.options[i].key]);
            validValues.push(value);
        }

        var store = Ext.create('Ext.data.ArrayStore', {
            fields: ['id', 'text'],
            data: storeData
        });

        var options = {
            name: this.fieldConfig.name,
            triggerAction: "all",
            editable: false,
            fieldLabel: this.fieldConfig.title,
            store: store,
            itemCls: "object_field",
            height: 100
        };

        if (this.fieldConfig.width) {
            options.width = this.fieldConfig.width;
        } else {
            options.width = 100;
        }
        if (this.fieldConfig.height) {
            options.height = this.fieldConfig.height;
        }

        if (typeof this.data == "string" || typeof this.data == "number") {
            options.value = this.data;
        }

        this.component = new Ext.ux.form.MultiSelect(options);

        return this.component;
    },

    getLayoutShow: function () {

        this.component = this.getLayoutEdit();

        this.component.on("afterrender", function () {
            this.component.disable();
        }.bind(this));

        return this.component;
    },

    getValue: function () {
        if(this.isRendered()) {
            return this.component.getValue();
        }
    },

    getName: function () {
        return this.fieldConfig.name;
    }
});<|endoftext|>