问:
MongoError: E11000 duplicate key error
i'm making a simple blog app using nodejs + express, i can add first post without a problem but when i try to add second post i got his error { MongoError: E11000 duplicate key error collection: restful_blog_app_v2.blogs index: username_1 dup key: { : null }

this is my schema

```<code>var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

BlogSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Blog", BlogSchema);
</code>```

this is the user schema

```<code>var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);
</code>```

this is the create new post route

```<code>app.post("/blogs", isLoggedIn, function (req, res) {
    req.body.blog.body = req.sanitize(req.body.blog.body);
    var title = req.body.blog.title;
    var image = req.body.blog.image
    var body = req.body.blog.body;
    var created  = req.body.blog.created;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var newPost = {
        title: title,
        image: image,
        body: body,
        created: created,
        author: author
    }
    Blog.create(newPost, function (err, newBlog) {
        if (err) {
            console.log(err);
            res.render("new");
        } else {
            console.log(newBlog);
            res.redirect("/blogs");
        }
    });

});
</code>```

I've tried to dropped the entire database using db.dropDatabase() from the mongo console but the problem still persist, not sure what to do now

答:
This is caused by passport-local-mongoose, which, according to its fine manual, makes username a unique field by default.

You have added this plugin to BlogSchema, which seems like you initially had the user data in that schema but moved it to a separate schema (UserSchema) and forgot to remove it from the former.

Start by not using it for BlogSchema, and you also need to drop the unique index on username on the blogs collection.

Title: MongoError: E11000 duplicate key error

Body:
i'm making a simple blog app using nodejs + express, i can add first post without a problem but when i try to add second post i got his error { MongoError: E11000 duplicate key error collection: restful_blog_app_v2.blogs index: username_1 dup key: { : null }

this is my schema

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

BlogSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Blog", BlogSchema);

this is the user schema

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

this is the create new post route

app.post("/blogs", isLoggedIn, function (req, res) {
    req.body.blog.body = req.sanitize(req.body.blog.body);
    var title = req.body.blog.title;
    var image = req.body.blog.image
    var body = req.body.blog.body;
    var created  = req.body.blog.created;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var newPost = {
        title: title,
        image: image,
        body: body,
        created: created,
        author: author
    }
    Blog.create(newPost, function (err, newBlog) {
        if (err) {
            console.log(err);
            res.render("new");
        } else {
            console.log(newBlog);
            res.redirect("/blogs");
        }
    });

});

I've tried to dropped the entire database using db.dropDatabase() from the mongo console but the problem still persist, not sure what to do now


来源: stackexchange

问:
HTML, Create line numbers for large lines
I have the following code that create automatic line numbers, for each div with the class "lineNum". I want to create line numbers also to the break lines (in the code snippet, the lines between line number 1 and 2).
Thanks!

.container {direction:rtl; counter-reset: line;}
.container .lineNum {display: flex;line-height: 1.5rem;}
.lineNum>center, .lineNum>right, .lineNum>left, .lineNum>span
{width: 100%;}

.container .lineNum:before
{
  width: 2%;font-weight: bold;
  counter-increment: line;content:counter(line);
  display: inline-block;
  background-color: lightgray;
  margin-left: 10px;
  padding-right: .5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="lineNum"><span>במהלך תקופה זו, גדלנו מקבוצה קטנה של עורכים לקהילה מגוונת של עורכים, מפתחים, קוראים, תורמים ושותפים. איפה נהיה בעוד 15 שנה? איזה תפקיד נמלא בעולם? מי עוד יצטרף לתנועה? מה אופי העבודה הניצבת לפנינו? שאלות אלו ייענו על ידי תנועת ויקימדיה כולה במהלך השבועות הקרובים, במסגרת התהליך האסטרטגי לשנת 2017, המתנהל בימים אלו.</span></div>
<div class="lineNum"><span>תצלום לוויין של ארץ ישראל, משנת 2003, הכולל את מדינת ישראל, שטחי הרשות הפלסטינית, וחלקים מירדן, לבנון, סוריה ומצרים</span></div></div></code>```

edit:
the follow result is expected

答:
If you want a break inbetween each .lineNum class, simply add a margin-top: 10px; I have added a snippet below to show you.

.container {direction:rtl; counter-reset: line;}
.container .lineNum {display: flex;line-height: 1.5rem;}
.lineNum>center, .lineNum>right, .lineNum>left, .lineNum>span
{width: 100%;}

.lineNum {margin-top: 10px;}

.container .lineNum:before
{
  width: 2%;font-weight: bold;
  counter-increment: line;content:counter(line);
  display: inline-block;
  background-color: lightgray;
  margin-left: 10px;
  padding-right: .5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="lineNum"><span>במהלך תקופה זו, גדלנו מקבוצה קטנה של עורכים לקהילה מגוונת של עורכים, מפתחים, קוראים, תורמים ושותפים. איפה נהיה בעוד 15 שנה? איזה תפקיד נמלא בעולם? מי עוד יצטרף לתנועה? מה אופי העבודה הניצבת לפנינו? שאלות אלו ייענו על ידי תנועת ויקימדיה כולה במהלך השבועות הקרובים, במסגרת התהליך האסטרטגי לשנת 2017, המתנהל בימים אלו.</span></div>
<div class="lineNum"><span>תצלום לוויין של ארץ ישראל, משנת 2003, הכולל את מדינת ישראל, שטחי הרשות הפלסטינית, וחלקים מירדן, לבנון, סוריה ומצרים</span></div></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code that create automatic line numbers, for each div with the class "lineNum". I want to create line numbers also to the break lines (in the code snippet, the lines between line number 1 and 2).
Thanks!

.container {direction:rtl; counter-reset: line;}
.container .lineNum {display: flex;line-height: 1.5rem;}
.lineNum>center, .lineNum>right, .lineNum>left, .lineNum>span
{width: 100%;}

.container .lineNum:before
{
  width: 2%;font-weight: bold;
  counter-increment: line;content:counter(line);
  display: inline-block;
  background-color: lightgray;
  margin-left: 10px;
  padding-right: .5em;
}

במהלך תקופה זו, גדלנו מקבוצה קטנה של עורכים לקהילה מגוונת של עורכים, מפתחים, קוראים, תורמים ושותפים. איפה נהיה בעוד 15 שנה? איזה תפקיד נמלא בעולם? מי עוד יצטרף לתנועה? מה אופי העבודה הניצבת לפנינו? שאלות אלו ייענו על ידי תנועת ויקימדיה כולה במהלך השבועות הקרובים, במסגרת התהליך האסטרטגי לשנת 2017, המתנהל בימים אלו.

תצלום לוויין של ארץ ישראל, משנת 2003, הכולל את מדינת ישראל, שטחי הרשות הפלסטינית, וחלקים מירדן, לבנון, סוריה ומצרים

edit:
the follow result is expected

Body:
If you want a break inbetween each .lineNum class, simply add a margin-top: 10px; I have added a snippet below to show you.

.container {direction:rtl; counter-reset: line;}
.container .lineNum {display: flex;line-height: 1.5rem;}
.lineNum>center, .lineNum>right, .lineNum>left, .lineNum>span
{width: 100%;}

.lineNum {margin-top: 10px;}

.container .lineNum:before
{
  width: 2%;font-weight: bold;
  counter-increment: line;content:counter(line);
  display: inline-block;
  background-color: lightgray;
  margin-left: 10px;
  padding-right: .5em;
}

<div class="container">
<div class="lineNum"><span>במהלך תקופה זו, גדלנו מקבוצה קטנה של עורכים לקהילה מגוונת של עורכים, מפתחים, קוראים, תורמים ושותפים. איפה נהיה בעוד 15 שנה? איזה תפקיד נמלא בעולם? מי עוד יצטרף לתנועה? מה אופי העבודה הניצבת לפנינו? שאלות אלו ייענו על ידי תנועת ויקימדיה כולה במהלך השבועות הקרובים, במסגרת התהליך האסטרטגי לשנת 2017, המתנהל בימים אלו.</span></div>
<div class="lineNum"><span>תצלום לוויין של ארץ ישראל, משנת 2003, הכולל את מדינת ישראל, שטחי הרשות הפלסטינית, וחלקים מירדן, לבנון, סוריה ומצרים</span></div></div>


问:
char* = new char And char* = new char[N]
I construct a class named CMyString, here is it:

```<code>class CMyString {
public:
    CMyString();
    CMyString(char* pData);
    CMyString(const CMyString& str);
    ~CMyString(void);

    char* getData();
    void setData(char* pData);

    CMyString& operator=(const CMyString& str);

private:
    char* m_pData;
};

    CMyString::CMyString() {
    m_pData = new char;
}

CMyString::CMyString(char* pData) {
//    m_pData = new char;
    m_pData = pData;
}

CMyString::CMyString(const CMyString& str) {
    // 为指针分配内存
//    m_pData = new char;
    // 拷贝值
    m_pData = str.m_pData;
}

CMyString::~CMyString(void) {
//    delete m_pData;
}

CMyString& CMyString::operator=(const CMyString& str) {
    if (this == &str)
        return *this;

    delete m_pData;
    m_pData = nullptr;
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);

    return *this;
}

char* CMyString::getData() {
    return m_pData;
}

void CMyString::setData(char *pData) {
    m_pData = pData;
}
</code>```

And here is my main.cpp:

```<code>#include <iostream>
#include "CMyString.h"

using std::cout;
using std::endl;

int main() {
    char* pData = "What are you worrying about?";
    std::cout << pData << std::endl;

    cout << strlen(pData) << endl;
    char* test = new char[30];
    cout << sizeof(test) << endl;
    char* test2 = new char;
    test2 = "23";
    cout << test2 << endl;

    strcpy(test, pData);

    cout << endl << test << endl << endl;

    CMyString str(pData);
    std::cout << str.getData() << std::endl;

    CMyString str2, str3;
    str3 = str2 = str;

    std::cout << str3.getData() << endl;

    char* pData2 = "Data has been changed.";
    str3.setData(pData2);

    cout << str.getData() << endl;
    cout << str2.getData() << endl;
    cout << str3.getData() << endl;

    return 0;
}
</code>```

then I'm confused by the

```<code>char* pData = new char;
char* pData2 = new char[30];
</code>```

Am I right in the class implementation?
How can I tell the two different pointers?
Do I write the constructor and de-constructor function and the operator= correctly? if not, how to write them?

答:
```<code>char* pData = new char;  -> Allocates one piece / slot of memory
char* pData2 = new char[30]; -> Allocates 30 continuous pieces / slots of memory
</code>```

First one usesdelete pData, second one delete [] pData

And addition to this, you are using char *pData = "STRING", I wouldn't recommend you using that since you are setting a pointer to that STRING and not copying it to a certain location.

When it comes to the operator= it looks good as I can see if you pass the correct data..

EDIT:
Seen other comments saying for the copy constructor where I didn't throw look at.

Copy Constructor it constructs / makes an instance same as the constructor so if you are dynamically allocating memory in the constructor and in the class then you should do that in the copy constructor too..

```<code>// Ofcourse #include<cstring>
class CMyString {
public:
CMyString();
CMyString(char* pData);
CMyString(const CMyString& str);
~CMyString(void);

char* getData();
void setData(char* pData);

CMyString& operator=(const CMyString& str);

private:
    char* m_pData;
};

    CMyString::CMyString() {
    m_pData = nullptr; // so it doesn't hang
}

CMyString::CMyString(char* pData) {
    m_pData = new char[strlen(pData) + 1]; // allocates slots of memory with length of the string pData
    strcpy(m_pData, pData)
}

CMyString::CMyString(const CMyString& str) {
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);
    // Here you are constructing an instance so you should allocate memory for the dynamic string
}

CMyString::~CMyString(void) {
   delete [] m_pData; // Since we allocated few slots
}

CMyString& CMyString::operator=(const CMyString& str) {
    if (this == &str)
        return *this;

    delete [] m_pData; // Few slots of memory should be released
    // m_pData = nullptr; No need for this since you are allocating after
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);

    return *this;
}

char* CMyString::getData() {
    return m_pData;
}

void CMyString::setData(char *pData) {
     // m_pData = pData; Illegal don't get the address of a string make a copy of it (Don't point to a string you want a copy)
     // If it isn't set. If it is, you will need to delete it
     m_pData = new char[strlen(pData) + 1];
     strcpy(m_pData, pData);
}
</code>```

Possible to have some typos so hit me up if anything needs to be edited or added..

NOTE: test = "String" is illegal always copy the content if it is your intention ( strcpy ). Look at other comments if people leave because I'm limited to the current knowledge (still newbie). However, I will try to help..

Important: When allocating try to understand the concept behind it and what you want to do and what you have done. Don't forget the delete / delete [] :)
Good luck !!

Body:
I construct a class named CMyString, here is it:

class CMyString {
public:
    CMyString();
    CMyString(char* pData);
    CMyString(const CMyString& str);
    ~CMyString(void);

    char* getData();
    void setData(char* pData);

    CMyString& operator=(const CMyString& str);

private:
    char* m_pData;
};

    CMyString::CMyString() {
    m_pData = new char;
}

CMyString::CMyString(char* pData) {
//    m_pData = new char;
    m_pData = pData;
}

CMyString::CMyString(const CMyString& str) {
    // 为指针分配内存
//    m_pData = new char;
    // 拷贝值
    m_pData = str.m_pData;
}

CMyString::~CMyString(void) {
//    delete m_pData;
}

CMyString& CMyString::operator=(const CMyString& str) {
    if (this == &str)
        return *this;

    delete m_pData;
    m_pData = nullptr;
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);

    return *this;
}

char* CMyString::getData() {
    return m_pData;
}

void CMyString::setData(char *pData) {
    m_pData = pData;
}

And here is my main.cpp:

#include <iostream>
#include "CMyString.h"

using std::cout;
using std::endl;

int main() {
    char* pData = "What are you worrying about?";
    std::cout << pData << std::endl;

    cout << strlen(pData) << endl;
    char* test = new char[30];
    cout << sizeof(test) << endl;
    char* test2 = new char;
    test2 = "23";
    cout << test2 << endl;

    strcpy(test, pData);

    cout << endl << test << endl << endl;

    CMyString str(pData);
    std::cout << str.getData() << std::endl;

    CMyString str2, str3;
    str3 = str2 = str;

    std::cout << str3.getData() << endl;

    char* pData2 = "Data has been changed.";
    str3.setData(pData2);

    cout << str.getData() << endl;
    cout << str2.getData() << endl;
    cout << str3.getData() << endl;

    return 0;
}

then I'm confused by the

char* pData = new char;
char* pData2 = new char[30];

Am I right in the class implementation?
How can I tell the two different pointers?
Do I write the constructor and de-constructor function and the operator= correctly? if not, how to write them?

Body:
char* pData = new char;  -> Allocates one piece / slot of memory
char* pData2 = new char[30]; -> Allocates 30 continuous pieces / slots of memory

First one usesdelete pData, second one delete [] pData

And addition to this, you are using char *pData = "STRING", I wouldn't recommend you using that since you are setting a pointer to that STRING and not copying it to a certain location.

When it comes to the operator= it looks good as I can see if you pass the correct data..

EDIT:
Seen other comments saying for the copy constructor where I didn't throw look at.

Copy Constructor it constructs / makes an instance same as the constructor so if you are dynamically allocating memory in the constructor and in the class then you should do that in the copy constructor too..

// Ofcourse #include<cstring>
class CMyString {
public:
CMyString();
CMyString(char* pData);
CMyString(const CMyString& str);
~CMyString(void);

char* getData();
void setData(char* pData);

CMyString& operator=(const CMyString& str);

private:
    char* m_pData;
};

    CMyString::CMyString() {
    m_pData = nullptr; // so it doesn't hang
}

CMyString::CMyString(char* pData) {
    m_pData = new char[strlen(pData) + 1]; // allocates slots of memory with length of the string pData
    strcpy(m_pData, pData)
}

CMyString::CMyString(const CMyString& str) {
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);
    // Here you are constructing an instance so you should allocate memory for the dynamic string
}

CMyString::~CMyString(void) {
   delete [] m_pData; // Since we allocated few slots
}

CMyString& CMyString::operator=(const CMyString& str) {
    if (this == &str)
        return *this;

    delete [] m_pData; // Few slots of memory should be released
    // m_pData = nullptr; No need for this since you are allocating after
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);

    return *this;
}

char* CMyString::getData() {
    return m_pData;
}

void CMyString::setData(char *pData) {
     // m_pData = pData; Illegal don't get the address of a string make a copy of it (Don't point to a string you want a copy)
     // If it isn't set. If it is, you will need to delete it
     m_pData = new char[strlen(pData) + 1];
     strcpy(m_pData, pData);
}

Possible to have some typos so hit me up if anything needs to be edited or added..

NOTE: test = "String" is illegal always copy the content if it is your intention ( strcpy ). Look at other comments if people leave because I'm limited to the current knowledge (still newbie). However, I will try to help..

Important: When allocating try to understand the concept behind it and what you want to do and what you have done. Don't forget the delete / delete [] :)
Good luck !!


问:
why the shape can't be dragged in d3.js
I want to link circles and rects by the shapes' name, it's all right.

I also remove the force layout, cause I want to use the static position.

but the drag function doesn't work, only the link can be dragged, not the Shapes. I dont konw the reason.

does someon help me review the code?

Thanks you very much.

var graph = {
   "nodes":[
      {
         "appId":"AP110358",
         "name":"Customer Account Profile",
         "type":"CIRCLE",
         "x":50,
         "y":50
      },
      {
         "appId":"NB",
         "name":"NB",
         "type":"CIRCLE",
         "x":500,
         "y":500
      },
      {
         "appId":"AP114737",
         "name":"RBG",
         "type":"CIRCLE",
         "x":300,
         "y":600
      },
      {
         "appId":"NULL",
         "name":"Account",
         "type":"RECT",
         "x":400,
         "y":700
      }
    ],
   "links":[
      {
         "source":"Customer Account Profile",
         "target":"NB",
         "value":1,
         "label":null
      },
   {
         "source":"NB",
         "target":"RBG",
         "value":1,
         "label":null
      },
   {
         "source":"RBG",
         "target":"Customer Account Profile",
         "value":1,
         "label":null
      },
   {
         "source":"NB",
         "target":"Customer Account Profile",
         "value":1,
         "label":null
      },
   {
         "source":"Customer Account Profile",
         "target":"Account",
         "value":1,
         "label":null
      },
   {
         "source":"NB",
         "target":"Account",
         "value":1,
         "label":null
      },
   {
         "source":"RBG",
         "target":"Account",
         "value":1,
         "label":null
      }
   ]
};
 var width = window.innerWidth;
 var height = window.innerHeight;
  var center;
if(width > 1200){
 center = [(width-1200) / 2, 0]
}else{
 center = [0, 0]
}

 var edges = [];
 graph.links.forEach(function(e) {
 var sourceNode = graph.nodes.filter(function(n) {
 return n.name === e.source;
 })[0],

 targetNode = graph.nodes.filter(function(n) {
 return n.name === e.target;
 })[0];

 edges.push({
  source: sourceNode,
  target: targetNode,
  value: e.value
  });
 });

 var color = d3.scale.category20();

 var svg = d3.select("body")
 .append("svg")
 .attr("width", "1200")
 .attr("height", "1000")
 .attr("transform", "translate(" + center + ")")
 .append("g");

 var container = svg.append("g");
 var link = container.append("g")
 .attr("class", "links")
 .selectAll(".link")
 .data(edges)
 .enter().append("line")
 .attr("class", "link")
 .attr("x1", function(l) {
     var sourceNode = graph.nodes.filter(function(d) {
       return d == l.source
     })[0];
     d3.select(this).attr("y1", sourceNode.y);
     return sourceNode.x
   })
 .attr("x2", function(l) {
     var targetNode = graph.nodes.filter(function(d) {
       return d == l.target
     })[0];
     d3.select(this).attr("y2", targetNode.y);
     return targetNode.x
 })
 .style("stroke-width", function(d) {
 return d.value;
 });

 link.append("title").text(function(d) {
 return d.value;
 });

 var drag = d3.behavior.drag()
   .on("drag", function(d, i) {
     d.x += d3.event.dx;
     d.y += d3.event.dy;
     d3.select(this).attr("cx", d.x).attr("cy", d.y);
     link.each(function(l) {
       if (l.source == d) {
         d3.select(this).attr("x1", d.x).attr("y1", d.y);
       } else if (l.target == d) {
         d3.select(this).attr("x2", d.x).attr("y2", d.y);
       }
     });
   });
 var node = container.append("g")
 .attr("class", "nodes")
 .selectAll(".node")
 .data(graph.nodes)
 .enter().append("g")
 .attr("class", "node")
 .call(drag);

 var i = 0;
 node.each(function(d) {
 if (d.type == "CIRCLE") {
  d3.select(this).append("circle")
  .attr("r", 50)
  .attr("cx", function(d) {
   return d.x
    })
    .attr("cy", function(d) {
   return d.y
    })
  .style("fill", function(d) { return color(i & 3);});

  d3.select(this).append("text")
  .text(function(d) {
  return d.name;
 })
 .attr("transform", function(d) {
   return "translate(" + d.x + "," + (d.y+5) + ")";
  })
 .style("text-anchor","middle");
 } else {
  d3.select(this).append("rect")
  .attr("height", 40)
  .attr("width", 140)
  .attr("x", -10)
  .attr("y", -(40 / 2))
  .attr("transform", function(d) {
   return "translate(" + d.x + "," + (d.y+5) + ")";
  })
  .style("fill", "green");
  d3.select(this).append("text")
  .text(function(d) {
  return d.name;
  })
  .style("text-anchor","start")
  .attr("transform", function(d) {
   return "translate(" + (d.x - 5) + "," + (d.y+10) + ")";
  });
 }
 i++;
 });

 node.on("click", function(d){
 console.log(d.x + "|--|" + d.y);
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style type="text/css">
 .node {
 stroke: #fff;
 stroke-width: 1.5px;
 cursor: move;
 }
 .node-active {
 stroke: #555;
 stroke-width: 1.5px;
 }
 .link {
 stroke: #555;
 stroke-opacity: .3;
 }
 .link-active {
 stroke-opacity: 1;
 }
 .overlay {
 fill: none;
 pointer-events: all;
 }
 </style></code>```

```

答:
I know the reason
I call the drag method in the node, but the node doesn't append the shape, so the drag doesn't work.

so I change the drag invoke position as snippet

var graph = {
  "nodes": [{
      "appId": "AP110358",
      "name": "Customer Account Profile",
      "type": "CIRCLE",
      "x": 50,
      "y": 50
    },
    {
      "appId": "NB",
      "name": "NB",
      "type": "CIRCLE",
      "x": 500,
      "y": 500
    },
    {
      "appId": "AP114737",
      "name": "RBG",
      "type": "CIRCLE",
      "x": 300,
      "y": 600
    },
    {
      "appId": "NULL",
      "name": "Account",
      "type": "RECT",
      "x": 400,
      "y": 700
    }
  ],
  "links": [{
      "source": "Customer Account Profile",
      "target": "NB",
      "value": 1,
      "label": null
    },
    {
      "source": "NB",
      "target": "RBG",
      "value": 1,
      "label": null
    },
    {
      "source": "RBG",
      "target": "Customer Account Profile",
      "value": 1,
      "label": null
    },
    {
      "source": "NB",
      "target": "Customer Account Profile",
      "value": 1,
      "label": null
    },
    {
      "source": "Customer Account Profile",
      "target": "Account",
      "value": 1,
      "label": null
    },
    {
      "source": "NB",
      "target": "Account",
      "value": 1,
      "label": null
    },
    {
      "source": "RBG",
      "target": "Account",
      "value": 1,
      "label": null
    }
  ]
};
var width = window.innerWidth;
var height = window.innerHeight;
var center;
if (width > 1200) {
  center = [(width - 1200) / 2, 0]
} else {
  center = [0, 0]
}

var edges = [];
graph.links.forEach(function(e) {
  var sourceNode = graph.nodes.filter(function(n) {
      return n.name === e.source;
    })[0],

    targetNode = graph.nodes.filter(function(n) {
      return n.name === e.target;
    })[0];

  edges.push({
    source: sourceNode,
    target: targetNode,
    value: e.value
  });
});

var color = d3.scale.category20();

var svg = d3.select("body")
  .append("svg")
  .attr("width", "1200")
  .attr("height", "1000")
  .attr("transform", "translate(" + center + ")")
  .append("g");

var container = svg.append("g");
var link = container.append("g")
  .attr("class", "links")
  .selectAll(".link")
  .data(edges)
  .enter().append("line")
  .attr("class", "link")
  .attr("x1", function(l) {
    var sourceNode = graph.nodes.filter(function(d) {
      return d == l.source
    })[0];
    d3.select(this).attr("y1", sourceNode.y);
    return sourceNode.x
  })
  .attr("x2", function(l) {
    var targetNode = graph.nodes.filter(function(d) {
      return d == l.target
    })[0];
    d3.select(this).attr("y2", targetNode.y);
    return targetNode.x
  })
  .style("stroke-width", function(d) {
    return d.value;
  });

link.append("title").text(function(d) {
  return d.value;
});

var drag = d3.behavior.drag()
  .on("drag", function(d) {
    d.x += d3.event.dx;
    d.y += d3.event.dy;
    d3.select(this).attr("cx", d.x).attr("cy", d.y);
    link.each(function(l) {
      if (l.source == d) {
        d3.select(this).attr("x1", d.x).attr("y1", d.y);
      } else if (l.target == d) {
        d3.select(this).attr("x2", d.x).attr("y2", d.y);
      }
    });
  });
var node = container.append("g")
  .attr("class", "nodes")
  .selectAll(".node")
  .data(graph.nodes)
  .enter().append("g")
  .attr("class", "node");

var i = 0;
node.each(function(d) {
  if (d.type == "CIRCLE") {
    d3.select(this).append("circle")
      .attr("r", 50)
      .attr("cx", function(d) {
        return d.x
      })
      .attr("cy", function(d) {
        return d.y
      })
      .call(drag)
      .style("fill", function(d) {
        return color(i & 3);
      });

    d3.select(this).append("text")
      .text(function(d) {
        return d.name;
      })
      .attr("transform", function(d) {
        return "translate(" + d.x + "," + (d.y + 5) + ")";
      })
      .style("text-anchor", "middle");
  } else {
    d3.select(this).append("rect")
      .attr("height", 40)
      .attr("width", 140)
      .attr("x", -10)
      .attr("y", -(40 / 2))
      .attr("transform", function(d) {
        return "translate(" + d.x + "," + (d.y + 5) + ")";
      })
      .style("fill", "green");
    d3.select(this).append("text")
      .text(function(d) {
        return d.name;
      })
      .style("text-anchor", "start")
      .attr("transform", function(d) {
        return "translate(" + (d.x - 5) + "," + (d.y + 10) + ")";
      });
  }
  i++;
});

node.on("click", function(d) {
  console.log(d.x + "|--|" + d.y);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style type="text/css">.node {
  stroke: #fff;
  stroke-width: 1.5px;
  cursor: move;
}

.node-active {
  stroke: #555;
  stroke-width: 1.5px;
}

.link {
  stroke: #555;
  stroke-opacity: .3;
}

.link-active {
  stroke-opacity: 1;
}

.overlay {
  fill: none;
  pointer-events: all;
}

</style></code>```

```

Title: why the shape can't be dragged in d3.js

Body:
I know the reason
I call the drag method in the node, but the node doesn't append the shape, so the drag doesn't work.

so I change the drag invoke position as snippet

var graph = {
  "nodes": [{
      "appId": "AP110358",
      "name": "Customer Account Profile",
      "type": "CIRCLE",
      "x": 50,
      "y": 50
    },
    {
      "appId": "NB",
      "name": "NB",
      "type": "CIRCLE",
      "x": 500,
      "y": 500
    },
    {
      "appId": "AP114737",
      "name": "RBG",
      "type": "CIRCLE",
      "x": 300,
      "y": 600
    },
    {
      "appId": "NULL",
      "name": "Account",
      "type": "RECT",
      "x": 400,
      "y": 700
    }
  ],
  "links": [{
      "source": "Customer Account Profile",
      "target": "NB",
      "value": 1,
      "label": null
    },
    {
      "source": "NB",
      "target": "RBG",
      "value": 1,
      "label": null
    },
    {
      "source": "RBG",
      "target": "Customer Account Profile",
      "value": 1,
      "label": null
    },
    {
      "source": "NB",
      "target": "Customer Account Profile",
      "value": 1,
      "label": null
    },
    {
      "source": "Customer Account Profile",
      "target": "Account",
      "value": 1,
      "label": null
    },
    {
      "source": "NB",
      "target": "Account",
      "value": 1,
      "label": null
    },
    {
      "source": "RBG",
      "target": "Account",
      "value": 1,
      "label": null
    }
  ]
};
var width = window.innerWidth;
var height = window.innerHeight;
var center;
if (width > 1200) {
  center = [(width - 1200) / 2, 0]
} else {
  center = [0, 0]
}

var edges = [];
graph.links.forEach(function(e) {
  var sourceNode = graph.nodes.filter(function(n) {
      return n.name === e.source;
    })[0],

    targetNode = graph.nodes.filter(function(n) {
      return n.name === e.target;
    })[0];

  edges.push({
    source: sourceNode,
    target: targetNode,
    value: e.value
  });
});

var color = d3.scale.category20();

var svg = d3.select("body")
  .append("svg")
  .attr("width", "1200")
  .attr("height", "1000")
  .attr("transform", "translate(" + center + ")")
  .append("g");

var container = svg.append("g");
var link = container.append("g")
  .attr("class", "links")
  .selectAll(".link")
  .data(edges)
  .enter().append("line")
  .attr("class", "link")
  .attr("x1", function(l) {
    var sourceNode = graph.nodes.filter(function(d) {
      return d == l.source
    })[0];
    d3.select(this).attr("y1", sourceNode.y);
    return sourceNode.x
  })
  .attr("x2", function(l) {
    var targetNode = graph.nodes.filter(function(d) {
      return d == l.target
    })[0];
    d3.select(this).attr("y2", targetNode.y);
    return targetNode.x
  })
  .style("stroke-width", function(d) {
    return d.value;
  });

link.append("title").text(function(d) {
  return d.value;
});

var drag = d3.behavior.drag()
  .on("drag", function(d) {
    d.x += d3.event.dx;
    d.y += d3.event.dy;
    d3.select(this).attr("cx", d.x).attr("cy", d.y);
    link.each(function(l) {
      if (l.source == d) {
        d3.select(this).attr("x1", d.x).attr("y1", d.y);
      } else if (l.target == d) {
        d3.select(this).attr("x2", d.x).attr("y2", d.y);
      }
    });
  });
var node = container.append("g")
  .attr("class", "nodes")
  .selectAll(".node")
  .data(graph.nodes)
  .enter().append("g")
  .attr("class", "node");

var i = 0;
node.each(function(d) {
  if (d.type == "CIRCLE") {
    d3.select(this).append("circle")
      .attr("r", 50)
      .attr("cx", function(d) {
        return d.x
      })
      .attr("cy", function(d) {
        return d.y
      })
      .call(drag)
      .style("fill", function(d) {
        return color(i & 3);
      });

    d3.select(this).append("text")
      .text(function(d) {
        return d.name;
      })
      .attr("transform", function(d) {
        return "translate(" + d.x + "," + (d.y + 5) + ")";
      })
      .style("text-anchor", "middle");
  } else {
    d3.select(this).append("rect")
      .attr("height", 40)
      .attr("width", 140)
      .attr("x", -10)
      .attr("y", -(40 / 2))
      .attr("transform", function(d) {
        return "translate(" + d.x + "," + (d.y + 5) + ")";
      })
      .style("fill", "green");
    d3.select(this).append("text")
      .text(function(d) {
        return d.name;
      })
      .style("text-anchor", "start")
      .attr("transform", function(d) {
        return "translate(" + (d.x - 5) + "," + (d.y + 10) + ")";
      });
  }
  i++;
});

node.on("click", function(d) {
  console.log(d.x + "|--|" + d.y);
});

<style type="text/css">.node {
  stroke: #fff;
  stroke-width: 1.5px;
  cursor: move;
}

.node-active {
  stroke: #555;
  stroke-width: 1.5px;
}

.link {
  stroke: #555;
  stroke-opacity: .3;
}

.link-active {
  stroke-opacity: 1;
}

.overlay {
  fill: none;
  pointer-events: all;
}

</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js"></script>

<body style="background-color: #42f4e5">
  <!-- <a href="/visualization/main">main</a> -->
</body>


问:
Disable reply or forward in outlook using c#
I'm using c# outlook add-in.
How can I prevent reply or forward if sender address is something?</p>

答:
I was looking for a way to create an email and disallow the reply and reply all function using c# for a visual studio project. I came across your question, but the answer you marked didn't work for me. The following did what I was looking for, I hope it helps someone else looking for something similar:

```<code> Outlook.Application oApp = new Outlook.Application();

 //Create new email
 Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

 //Set recipients here
 Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(myRecipientsVariable);

 //Check to make sure they're all valid recipients in my contact list
 oRecip.Resolve();

 //Stop recipients from being able to reply all
 oMsg.Actions["Reply to All"].Enabled = false;

 //Stop them from being able to reply
 oMsg.Actions["Reply"].Enabled = false;

 //Set the Subject line
 oMsg.Subject = "Test Subject Line";

 //Tidy Up
 oRecip = null;
 oMsg = null;
 oApp = null;
</code>```

Basically the message.Actions[    ].enabled= false; bit. I believe this will work with any outlook 2013 and later.

-Cheers

Body:
I was looking for a way to create an email and disallow the reply and reply all function using c# for a visual studio project. I came across your question, but the answer you marked didn't work for me. The following did what I was looking for, I hope it helps someone else looking for something similar:

 Outlook.Application oApp = new Outlook.Application();

 //Create new email
 Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

 //Set recipients here
 Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(myRecipientsVariable);

 //Check to make sure they're all valid recipients in my contact list
 oRecip.Resolve();

 //Stop recipients from being able to reply all
 oMsg.Actions["Reply to All"].Enabled = false;

 //Stop them from being able to reply
 oMsg.Actions["Reply"].Enabled = false;

 //Set the Subject line
 oMsg.Subject = "Test Subject Line";

 //Tidy Up
 oRecip = null;
 oMsg = null;
 oApp = null;

Basically the message.Actions[    ].enabled= false; bit. I believe this will work with any outlook 2013 and later.

-Cheers


问:
TypeError When Creating Conda Environment
I am attempting to create a conda environment from a yaml file with the following command:

```<code>conda env create -f myenv.yml python=3
</code>```

When my yaml file is written like this:

```<code>name: myenv
channels:
  - conda-forge
dependencies:
  - django=1.10.5
  - pip:
    - gunicorn==19.7.0
    - psycopg2==2.6.2
</code>```

It works fine.

When my yaml file is written like this (without the conda-forge package/channel):

```<code>name: myenv
dependencies:
  - pip:
    - gunicorn==19.7.0
    - psycopg2==2.6.2
</code>```

It generates the following error:

```<code>Traceback (most recent call last):
  File "/home/myuser/anaconda3/lib/python3.6/site-packages/conda/exceptions.py", line 573, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "/home/myuser/anaconda3/lib/python3.6/site-packages/conda_env/cli/main_create.py", line 108, in execute
    installer.install(prefix, pkg_specs, args, env)
  File "/home/myuser/anaconda3/lib/python3.6/site-packages/conda_env/installers/pip.py", line 8, in install
    pip_cmd = pip_args(prefix) + ['install', ] + specs
TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'
</code>```

I need to use the second yaml example without the conda-forge package.

Any advice?

答:
IMO, this looks like a bug in conda. However, you can get around this by adding pip as a dependency. So, make sure the file myenv.yml has the following contents:

```<code>name: myenv
dependencies:
  - pip=9.0.1=py27_1
  - pip:
    - gunicorn==19.7.0
    - psycopg2==2.6.2
</code>```

Body:
I am attempting to create a conda environment from a yaml file with the following command:

conda env create -f myenv.yml python=3

When my yaml file is written like this:

name: myenv
channels:
  - conda-forge
dependencies:
  - django=1.10.5
  - pip:
    - gunicorn==19.7.0
    - psycopg2==2.6.2

It works fine.

When my yaml file is written like this (without the conda-forge package/channel):

name: myenv
dependencies:
  - pip:
    - gunicorn==19.7.0
    - psycopg2==2.6.2

It generates the following error:

Traceback (most recent call last):
  File "/home/myuser/anaconda3/lib/python3.6/site-packages/conda/exceptions.py", line 573, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "/home/myuser/anaconda3/lib/python3.6/site-packages/conda_env/cli/main_create.py", line 108, in execute
    installer.install(prefix, pkg_specs, args, env)
  File "/home/myuser/anaconda3/lib/python3.6/site-packages/conda_env/installers/pip.py", line 8, in install
    pip_cmd = pip_args(prefix) + ['install', ] + specs
TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'

I need to use the second yaml example without the conda-forge package.

Any advice?

Body:
IMO, this looks like a bug in conda. However, you can get around this by adding pip as a dependency. So, make sure the file myenv.yml has the following contents:

name: myenv
dependencies:
  - pip=9.0.1=py27_1
  - pip:
    - gunicorn==19.7.0
    - psycopg2==2.6.2


问:
Formula to distribute values among list
In my application I am using below formula:

```<code>decimal retVal = this.selectedDetailVMItems.
    Sum(prod => prod.Product.NetPrice * prod.Product.ExtendedQty);
</code>```

NetPrice is some thing like for example 457, 33, 40 etc..

Now I have to increase or decrease some value from retVal. When I do this, how do I distribute increased or decreased value in prod => prod.Product.NetPrice?

How do I handle this scenario?

答:
Assuming you want to uniformly distribute a value of

```<code>decimal distributeVal = TotValue / selectedDetailVMItems.Count();
</code>```

then you can use a Linq style Foreach to distribute (with += Operator) the above said value, taking into consideration also the ExtendedQty

```<code>selectedDetailVMItems.ToList().ForEach(prod =>
    prod.Product.NetPrice += distributeVal / prod.Product.ExtendedQty);
</code>```

Title: Formula to distribute values among list

Body:
In my application I am using below formula:

decimal retVal = this.selectedDetailVMItems.
    Sum(prod => prod.Product.NetPrice * prod.Product.ExtendedQty);

NetPrice is some thing like for example 457, 33, 40 etc..

Now I have to increase or decrease some value from retVal. When I do this, how do I distribute increased or decreased value in prod => prod.Product.NetPrice?

How do I handle this scenario?

Body:
Assuming you want to uniformly distribute a value of

decimal distributeVal = TotValue / selectedDetailVMItems.Count();

then you can use a Linq style Foreach to distribute (with += Operator) the above said value, taking into consideration also the ExtendedQty

selectedDetailVMItems.ToList().ForEach(prod =>
    prod.Product.NetPrice += distributeVal / prod.Product.ExtendedQty);


问:
when starting mongod.exe, getting error of missing api-ms-win-crt-runtime-l1-1-0.dll
when starting mongod.exe on windows 7, getting error

"The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing from your computer.
  Try reinstalling the program to fix this problem. ".

After  installing VC ++ .net framework and vc_redist.x64, but still no luck. Any ideas how to solve my problem.

答: First install Window Update KB2999226 or download it from here according to your OS. then install Microsoft Visual C++ 2015 redist (vc_redist.x64 in your case). Restart the pc and run mongodb files(mongod or any).</p>


问:
Open Excel from Java Application
If I am tring to open notepad from Java Application then it will open Notepad.But If I will try to open Excel then it is giving me exception.

```<code>try
    {
        Runtime.getRuntime().exec("excel");
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
</code>```

Following is Exception :

```<code>java.io.IOException: Cannot run program "excel": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at OpenNotepad.main(OpenNotepad.java:18)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 5 more
</code>```

When I do start->Run->Excel then it will open excel.

答:
Runtime.getRuntime().exec("some command"); does the same as "some command" will do in cmd. So the solution for opening Excel you should try this.

```<code>try {
    Runtime.getRuntime().exec("cmd /c start excel.exe");
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Title: Open Excel from Java Application

Body:
If I am tring to open notepad from Java Application then it will open Notepad.But If I will try to open Excel then it is giving me exception.

try
    {
        Runtime.getRuntime().exec("excel");
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }

Following is Exception :

java.io.IOException: Cannot run program "excel": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at OpenNotepad.main(OpenNotepad.java:18)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 5 more

When I do start->Run->Excel then it will open excel.

Body:
Runtime.getRuntime().exec("some command"); does the same as "some command" will do in cmd. So the solution for opening Excel you should try this.

try {
    Runtime.getRuntime().exec("cmd /c start excel.exe");
} catch (IOException e) {
    e.printStackTrace();
}


问:
External JavaScript File
I'm developing a sound library with JavaScript. I created sound.js file and this file included in test.php file. sound.js file contains some function. My sound.js file like this:

```<code>var soundPath   = './sound/';

/*
 * Sounds Path
*/
var phoneNumberSound        = ['0.wav', '1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav'];
// var phoneCallSound          = null;

/*
 * Play Phone Number's Sound
*/
function playPhoneNumberSound (phoneNumber)
{
    phoneNumber = parseInt(phoneNumber);
    if (phoneNumber.length > 1){
        var phoneNumber = phoneNumber.substring(phoneNumber.length - 1);
        new Audio(soundPath + phoneNumberSound[phoneNumber-1]).play();
    } else {
        new Audio(soundPath + phoneNumberSound[phoneNumber-1]).play();
    }
}

/*
 * Coming Phone Incoming Sound
*/
function playPhoneIncomingSound ()
{
    document.writeln('Test this func');
}
</code>```

In test.php, i call above functions. First function is working but the second function or third or others... does not work. Browser error result is like this:

```<code>Uncaught ReferenceError: playPhoneIncomingSound is not defined
</code>```

My test.php file is like this:

```<code><script src="lib/jquery.js"></script>
<script src="lib/sound.js"></script>

<input type="text" id="phoneNumber" />
<button id="playSound">Play Sound</button>

<script type="text/javascript">

    $(document).ready(function ()
    {
        $('#playSound').click(function ()
        {
            playPhoneIncomingSound ();
            // var phoneNumber = $('#phoneNumber').val();
            // playPhoneNumberSound(phoneNumber);
        });
    });
</script>
</code>```

Why? Why this error occur? Where is my mistake?

Thank!

Edit:
This error about Chrome. When i clear browsersing data, this error be lost. In firebox, i didn't take like this error!

答:
Why don't you call playPhoneIncomingSound() using onclick?

var soundPath = './sound/';

/*
 * Sounds Path
 */
var phoneNumberSound = ['0.wav', '1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav'];
// var phoneCallSound          = null;

/*
 * Play Phone Number's Sound
 */
function playPhoneNumberSound(phoneNumber) {
  phoneNumber = parseInt(phoneNumber);
  if (phoneNumber.length > 1) {
    var phoneNumber = phoneNumber.substring(phoneNumber.length - 1);
    new Audio(soundPath + phoneNumberSound[phoneNumber - 1]).play();
  } else {
    new Audio(soundPath + phoneNumberSound[phoneNumber - 1]).play();
  }
}

/*
 * Coming Phone Incoming Sound
 */
function playPhoneIncomingSound() {
  document.writeln('Test this func');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="playSound" onclick="playPhoneIncomingSound()">Play Sound</button></code>```

In your test.php code, the playPhoneIncomingSound (); is trying to find the function in the script tag code but not in sound.js

Title: External JavaScript File

Body:
I'm developing a sound library with JavaScript. I created sound.js file and this file included in test.php file. sound.js file contains some function. My sound.js file like this:

var soundPath   = './sound/';

/*
 * Sounds Path
*/
var phoneNumberSound        = ['0.wav', '1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav'];
// var phoneCallSound          = null;

/*
 * Play Phone Number's Sound
*/
function playPhoneNumberSound (phoneNumber)
{
    phoneNumber = parseInt(phoneNumber);
    if (phoneNumber.length > 1){
        var phoneNumber = phoneNumber.substring(phoneNumber.length - 1);
        new Audio(soundPath + phoneNumberSound[phoneNumber-1]).play();
    } else {
        new Audio(soundPath + phoneNumberSound[phoneNumber-1]).play();
    }
}

/*
 * Coming Phone Incoming Sound
*/
function playPhoneIncomingSound ()
{
    document.writeln('Test this func');
}

In test.php, i call above functions. First function is working but the second function or third or others... does not work. Browser error result is like this:

Uncaught ReferenceError: playPhoneIncomingSound is not defined

My test.php file is like this:

<input type="text" id="phoneNumber" />
<button id="playSound">Play Sound</button>

Why? Why this error occur? Where is my mistake?

Thank!

Edit:
This error about Chrome. When i clear browsersing data, this error be lost. In firebox, i didn't take like this error!

Body:
Why don't you call playPhoneIncomingSound() using onclick?

var soundPath = './sound/';

/*
 * Sounds Path
 */
var phoneNumberSound = ['0.wav', '1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav'];
// var phoneCallSound          = null;

/*
 * Play Phone Number's Sound
 */
function playPhoneNumberSound(phoneNumber) {
  phoneNumber = parseInt(phoneNumber);
  if (phoneNumber.length > 1) {
    var phoneNumber = phoneNumber.substring(phoneNumber.length - 1);
    new Audio(soundPath + phoneNumberSound[phoneNumber - 1]).play();
  } else {
    new Audio(soundPath + phoneNumberSound[phoneNumber - 1]).play();
  }
}

/*
 * Coming Phone Incoming Sound
 */
function playPhoneIncomingSound() {
  document.writeln('Test this func');
}

<button id="playSound" onclick="playPhoneIncomingSound()">Play Sound</button>

In your test.php code, the playPhoneIncomingSound (); is trying to find the function in the script tag code but not in sound.js


问:
There has been an error processing your request, Error log record number
I installed Magento, logged in admin panel. But if I press on any link to open let say CMS pages or users configuration, I get error like this:

There has been an error processing your request
      Exception printing is disabled by default for security reasons.

Error log record number: 673618173351

That error log record number looks like a link, but pressing it nothing happens. I tried to look for some log file in magento files, but didn't find any.

So actually I can only connect to admin panel, but can't do anything here.

What could be wrong? I installed the newest Magento version (magento-1.7.0.2). Default frontend opens and works.

P.S.

.If any additional information is needed, just say it

Update:

So in logs every error is the same (just accessed resource is different).

a:5:{i:0;s:71:"Could not determine temp directory, please specify a cache_dir manually";i:1;s:4546:"#0 /home/geniusinsi/domains/example.com/public_html/lib/Zend/Cache/Backend.php(197): Zend_Cache::throwException('Could not deter...')

As I understand I need to specify cash directory somewhere?

答: Rename pub/local.xml.sample into local.xml . then i will show you exactly error.


问:
How to add text into a .csv data in Swift?
I want to add some text like "Hi;Test;Pen" into my .csv file.

I have used the CSVImporter to insert the text of the .csv into my Xcode project. Here is the code, I have used for it:

```<code>    guard let VokabelPath = Bundle.main.path(forResource: ResourceExample, ofType:"csv") else {
        debugPrint(ResourceExample + " not found")
        return
    }
    let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
    let importedRecords = importer.importRecords { $0 }
    for record in importedRecords {
        self.Vokabeln.insert(record, at: self.Vokabelzähler)
        self.Vokabelzähler += 1
    }
</code>```

But for some reasons I want to

add something to the file

Change something in the file (e.g. in Line 4)

Delete the text in the file (e.g. filetext = ""

I have tried to use this Tutorial and I have made this code:

```<code>let fileName = "Tasks.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Test;Example;Apple;Pen\n"
do {
    try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
    print("Failed to create file")
    print("\(error)")
}

guard let VokabelPath = Bundle.main.path(forResource: "Tasks", ofType:"csv") else {
    debugPrint("Tasks not found")
    return
}
let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
    self.Vokabeln.insert(record, at: self.Vokabelzähler)
    self.Vokabelzähler += 1
    print(record)
}
</code>```

but he prints only "Tasks not found". What is my mistake?

I hope you can help me,

Thank you.

EDIT:

The person who made the first answer has written, I can't save files in the bundle.
He has written to me I should use NSSearchPathForDirectoriesInDomainsso I have updated my code and this works:

```<code>let DownloadPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let VokabelPath = DownloadPath.appendingPathComponent("Tasks.csv")
let InhaltData = Inhalt.data(using: .utf8)
print(VokabelPath)

FileManager.default.createFile(atPath: VokabelPath, contents: InhaltData, attributes: nil)

let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
    self.Vokabeln.insert(record, at: self.Vokabelzähler)
    self.Vokabelzähler += 1
}
</code>```

But I have one further question:
I hav some datas in my Xcode project and I can get them with Bundle.main. But I want to use only one function, so is it possible, to get them with NSSearchPathForDirectoriesInDomainstoo?

答:
In order to change a file, you would need to import the data in, make the necessary changes to the data and then write the data back to the same file, overwriting the previous content. That is how you would make changes generally - you don't make changes directly to the file.

Does that make sense?

If it does, then you could easily modify the tutorial you pointed to (the one for creating and exporting CSV) and write back the data that you read from the original file after you make the modifications.

As for your question about not wanting to use a library, you can always write your own CSV parser. It is not very difficult since all you have to do is read the text from the file a line at a time and then separate out the values by comma. A simple parser is straightforward but allowing for more complicated cases could take a bit more effort. It would all depend on your use-cases and the type of data you'd be handling. The easiest way still would be to use your importing library and then output via custom code.

Regarding your additional questions, if the following code fails:

```<code>guard let VokabelPath = Bundle.main.path(forResource: "Tasks", ofType:"csv") else {
    debugPrint("Tasks not found")
    return
}
</code>```

Then there is either an issue with the file name (or extension) or you have not included the file as part of your Resources. The above code simply gets the path for a given file in your Resources.

The above code is different from what I was talking about with regards to NSSearchPathForDirectoriesInDomains - that was for writing a file from your app. What I meant was that you could not write a file back to your Resources - instead, you would have to write the modified file to your Documents folder. Hope that clarifies things :)

Body:
I want to add some text like "Hi;Test;Pen" into my .csv file.

I have used the CSVImporter to insert the text of the .csv into my Xcode project. Here is the code, I have used for it:

    guard let VokabelPath = Bundle.main.path(forResource: ResourceExample, ofType:"csv") else {
        debugPrint(ResourceExample + " not found")
        return
    }
    let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
    let importedRecords = importer.importRecords { $0 }
    for record in importedRecords {
        self.Vokabeln.insert(record, at: self.Vokabelzähler)
        self.Vokabelzähler += 1
    }

But for some reasons I want to

add something to the file

Change something in the file (e.g. in Line 4)

Delete the text in the file (e.g. filetext = ""

I have tried to use this Tutorial and I have made this code:

let fileName = "Tasks.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Test;Example;Apple;Pen\n"
do {
    try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
    print("Failed to create file")
    print("\(error)")
}

guard let VokabelPath = Bundle.main.path(forResource: "Tasks", ofType:"csv") else {
    debugPrint("Tasks not found")
    return
}
let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
    self.Vokabeln.insert(record, at: self.Vokabelzähler)
    self.Vokabelzähler += 1
    print(record)
}

but he prints only "Tasks not found". What is my mistake?

I hope you can help me,

Thank you.

EDIT:

The person who made the first answer has written, I can't save files in the bundle.
He has written to me I should use NSSearchPathForDirectoriesInDomainsso I have updated my code and this works:

let DownloadPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let VokabelPath = DownloadPath.appendingPathComponent("Tasks.csv")
let InhaltData = Inhalt.data(using: .utf8)
print(VokabelPath)

FileManager.default.createFile(atPath: VokabelPath, contents: InhaltData, attributes: nil)

let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
    self.Vokabeln.insert(record, at: self.Vokabelzähler)
    self.Vokabelzähler += 1
}

But I have one further question:
I hav some datas in my Xcode project and I can get them with Bundle.main. But I want to use only one function, so is it possible, to get them with NSSearchPathForDirectoriesInDomainstoo?

Body:
In order to change a file, you would need to import the data in, make the necessary changes to the data and then write the data back to the same file, overwriting the previous content. That is how you would make changes generally - you don't make changes directly to the file.

Does that make sense?

If it does, then you could easily modify the tutorial you pointed to (the one for creating and exporting CSV) and write back the data that you read from the original file after you make the modifications.

As for your question about not wanting to use a library, you can always write your own CSV parser. It is not very difficult since all you have to do is read the text from the file a line at a time and then separate out the values by comma. A simple parser is straightforward but allowing for more complicated cases could take a bit more effort. It would all depend on your use-cases and the type of data you'd be handling. The easiest way still would be to use your importing library and then output via custom code.

Regarding your additional questions, if the following code fails:

guard let VokabelPath = Bundle.main.path(forResource: "Tasks", ofType:"csv") else {
    debugPrint("Tasks not found")
    return
}

Then there is either an issue with the file name (or extension) or you have not included the file as part of your Resources. The above code simply gets the path for a given file in your Resources.

The above code is different from what I was talking about with regards to NSSearchPathForDirectoriesInDomains - that was for writing a file from your app. What I meant was that you could not write a file back to your Resources - instead, you would have to write the modified file to your Documents folder. Hope that clarifies things :)


问:
Generating a Single Channel Mask
Given a multichannel image (e.g. BGR), what's the most efficient way to generate a (binary) 1C mask for pixel value equality?

cv::compare() works only for single channel input images.

Using op== yields a 3C mask.

I can then reduce that but that seems like a wasteful second pass.

Is there a single pass way of doing this?

答:
For multi-channel Matrices, you need to use cv::inRange(), which takes single channel, 3 channel or 4 channel images as src and takes lower and upper bounds of the colors to be segmented. Since you want to test for equality of a given Color, you need to pass both lower_bound and upper_bound as the same Scalar value.

```<code>cv::Scalar color = cv::Scalar(100, 200, 150);
cv::Mat mask;
cv::inRange(img, color, color, mask);
</code>```

Title: Generating a Single Channel Mask

Body:
For multi-channel Matrices, you need to use cv::inRange(), which takes single channel, 3 channel or 4 channel images as src and takes lower and upper bounds of the colors to be segmented. Since you want to test for equality of a given Color, you need to pass both lower_bound and upper_bound as the same Scalar value.

cv::Scalar color = cv::Scalar(100, 200, 150);
cv::Mat mask;
cv::inRange(img, color, color, mask);


问:
How to retrieve data from a website into an iphone app
I am making an iphone application.

I am a newb.

I want to fetch the data from my website. What should i do to implement this?

What needs to be done?

Help me please

Thanks

Any tutorials would be of great help.

答: Previous answers suggest using NSURLConnection, but I find it to be a bit cumbersome to use on its own. I suggest using something that wraps NSURLConnection (or CFNetwork). Some examples: ASIHTTPRequest (CFNetwork-based), httpriot and Seriously (NSURLConnection/block-based).</p>

ContentLicense: CC BY-SA 2.5


问:
cmd batch file ; assign different parameters from a text file
I have one text file (trimlist.txt) with a variable number of lines, but each line are similar with a variable file path and name and 2 numbers separated by coma:

```<code>E:\test\00037_20161001_100956.mov,3.6369666,1.2345666
</code>```

I need to get 3 different variables from each line: mov, 3.6369666 & 1.2345666 in this example.
I can get the 2 last variables like this

```<code>set prevfile=

for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
    if "!counter!"=="" (set counter=1) else (set /a counter+=1)
) else (
    set counter=
    set "prevfile=%%F"
        )
ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!-trimmed.mov"
</code>```

So with the above text file my final commmand will be

```<code>ffmpeg -ss 3.6369666 -i "E:\test\00037_20161001_100956.mov" -c copy -t 1.2345666 "E:\test\00037_20161001_100956 01 -trimmed.mov"
</code>```

I would like the "mov" of E:\test\00037_20161001_100956 01 -trimmed.movto be a variable taken from the textfile.

Any help will be greatly appreciated.

答:
Try adding

```<code>echo %%~xF
</code>```

into your outer loop.

It's not clear what you actually want to do - with an example of the output elements required, perhaps it would be easier to help.

```<code>set "prevfile="
set "counter="
for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
    if not defined counter set /a counter=10000
    set /a counter+=1
) else (
    set "counter="
    set "prevfile=%%F"
        )
if defined counter (ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF-trimmed%%~xF"
) else (
ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF !counter:~-2! -trimmed%%~xF"
)
</code>```

I believe this should suit.

Note: The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

set var+=1 will happily assign 1 to var if var is undefined.

Since when counter has been defined, you require a space either side of a leading-zero-filled value in the destination-filename, the easiest way would be to initialise counter to a number >100 ending in '00' when you wish to start counting, then select the last two characters of the string.

Body:
I have one text file (trimlist.txt) with a variable number of lines, but each line are similar with a variable file path and name and 2 numbers separated by coma:

E:\test\00037_20161001_100956.mov,3.6369666,1.2345666

I need to get 3 different variables from each line: mov, 3.6369666 & 1.2345666 in this example.
I can get the 2 last variables like this

set prevfile=

for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
    if "!counter!"=="" (set counter=1) else (set /a counter+=1)
) else (
    set counter=
    set "prevfile=%%F"
        )
ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!-trimmed.mov"

So with the above text file my final commmand will be

ffmpeg -ss 3.6369666 -i "E:\test\00037_20161001_100956.mov" -c copy -t 1.2345666 "E:\test\00037_20161001_100956 01 -trimmed.mov"

I would like the "mov" of E:\test\00037_20161001_100956 01 -trimmed.movto be a variable taken from the textfile.

Any help will be greatly appreciated.

Body:
Try adding

echo %%~xF

into your outer loop.

It's not clear what you actually want to do - with an example of the output elements required, perhaps it would be easier to help.

set "prevfile="
set "counter="
for /F "tokens=1,2,3 delims=," %%F in (E:\trimlist.txt) do (
    if "%%F"=="!prevfile!" (
    if not defined counter set /a counter=10000
    set /a counter+=1
) else (
    set "counter="
    set "prevfile=%%F"
        )
if defined counter (ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF-trimmed%%~xF"
) else (
ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF !counter:~-2! -trimmed%%~xF"
)

I believe this should suit.

Note: The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

set var+=1 will happily assign 1 to var if var is undefined.

Since when counter has been defined, you require a space either side of a leading-zero-filled value in the destination-filename, the easiest way would be to initialise counter to a number >100 ending in '00' when you wish to start counting, then select the last two characters of the string.


问:
MEAN stack application - querying by userId
I have built an API to GET and POST values into a database(MongoDB) using NodeJS and Express.

I am able to get only a single comment by the userid
(localhost:3000/comments/userid/3)

But I want to get all comments by a single user

```<code>/* GET /comments/userid/userid */
router.get('/userid/:userid', function(req, res, next) {
  Comments.findOne({userId:req.params.userid}, function (err, post) {
    if (err) return next(err);
    res.json(post);
    })
});
</code>```

Is there any method to do this? Like the findOne method?

答:
just do find with the query

```<code>router.get('/userid/:userid', function(req, res, next) {
  Comments.find({userId:req.params.userid}, function (err, post) {
    if (err) return next(err);
    res.json(post);
    })
});
</code>```

Body:
I have built an API to GET and POST values into a database(MongoDB) using NodeJS and Express.

I am able to get only a single comment by the userid
(localhost:3000/comments/userid/3)

But I want to get all comments by a single user

/* GET /comments/userid/userid */
router.get('/userid/:userid', function(req, res, next) {
  Comments.findOne({userId:req.params.userid}, function (err, post) {
    if (err) return next(err);
    res.json(post);
    })
});

Is there any method to do this? Like the findOne method?

Body:
just do find with the query

router.get('/userid/:userid', function(req, res, next) {
  Comments.find({userId:req.params.userid}, function (err, post) {
    if (err) return next(err);
    res.json(post);
    })
});


问:
ASP.NET MVC Check state for just some properties
I'm new to MVC and I'm facing this problem.

I'm designing a view that allows user to modify their profile and password in 2 different forms.

This is my main action:

```<code>public ActionResult ModifyAccount()
{
    User user = this._userManager.FindById(User.Identity.GetUserId());
    ViewBag.User = user;
    return View(new AccountViewModel
    {
        User = user
    });
}
</code>```

In my ModifyAccount view, i have 2 form:

```<code>@using (Html.BeginForm("ModifyPassword", "Account", FormMethod.Post))
{
    // Change password
}

@using (Html.BeginForm("ModifyProfile", "Account", FormMethod.Post))
{
    // Change profile
}
</code>```

And this is my Model

```<code>public class AccountViewModel
    {
        public User User { get; set; } // For change profile

        // For change password
        [Display(Name = "Mật khẩu cũ")]
        public string OldPassword { get; set; }
        [Display(Name = "Mật khẩu mới")]
        public string NewPassword { get; set; }
        [Display(Name = "Xác nhận mật khẩu mới")]
        [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
        public string NewPasswordConfirm { get; set; }
    }
</code>```

I know that when we use ModelState.IsValid, the whole model will be validated. What I want is if the user submits the ModifyPassword form, only 3 properties OldPassword, NewPassword, NewPasswordConfirm will be validated. Please help, thank you!

答:
Use IValidatableObject for custom multiple value validation</p>

```<code>public class AccountViewModel : IValidatableObject
{
    [Display(Name = "Mật khẩu cũ")]
    public string OldPassword { get; set; }
    [Display(Name = "Mật khẩu mới")]
    public string NewPassword { get; set; }
    [Display(Name = "Xác nhận mật khẩu mới")]
    [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
    public string NewPasswordConfirm { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (// Do something here)
        {
            yield return new ValidationResult("Error Message");
        }
    }
}

public ActionResult ModifyAccount()
{
    if (!ModelState.IsValid)
    {
    }

}
</code>```

Body:
I'm new to MVC and I'm facing this problem.

I'm designing a view that allows user to modify their profile and password in 2 different forms.

This is my main action:

public ActionResult ModifyAccount()
{
    User user = this._userManager.FindById(User.Identity.GetUserId());
    ViewBag.User = user;
    return View(new AccountViewModel
    {
        User = user
    });
}

In my ModifyAccount view, i have 2 form:

@using (Html.BeginForm("ModifyPassword", "Account", FormMethod.Post))
{
    // Change password
}

@using (Html.BeginForm("ModifyProfile", "Account", FormMethod.Post))
{
    // Change profile
}

And this is my Model

public class AccountViewModel
    {
        public User User { get; set; } // For change profile

        // For change password
        [Display(Name = "Mật khẩu cũ")]
        public string OldPassword { get; set; }
        [Display(Name = "Mật khẩu mới")]
        public string NewPassword { get; set; }
        [Display(Name = "Xác nhận mật khẩu mới")]
        [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
        public string NewPasswordConfirm { get; set; }
    }

I know that when we use ModelState.IsValid, the whole model will be validated. What I want is if the user submits the ModifyPassword form, only 3 properties OldPassword, NewPassword, NewPasswordConfirm will be validated. Please help, thank you!

Body:
Use IValidatableObject for custom multiple value validation

public class AccountViewModel : IValidatableObject
{
    [Display(Name = "Mật khẩu cũ")]
    public string OldPassword { get; set; }
    [Display(Name = "Mật khẩu mới")]
    public string NewPassword { get; set; }
    [Display(Name = "Xác nhận mật khẩu mới")]
    [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
    public string NewPasswordConfirm { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (// Do something here)
        {
            yield return new ValidationResult("Error Message");
        }
    }
}

public ActionResult ModifyAccount()
{
    if (!ModelState.IsValid)
    {
    }

}


问:
Correctly convert String array to String and back in java
I have a following code:

```<code>String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));
</code>```

which produces the following string:

```<code>[One,, Two, Three]
</code>```

Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,

How to correctly make this conversion ?

UPDATED

```<code>Arrays.toString(stringArray)
</code>```

is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.

答:
I really don't know what you want to do, but the array separator , is in your string, so the simplest way to avoid this would be to avoid building the string with default array separator! like this:

```<code>String[] stringArray = new String[] { "One,", "Two", "Three" };
    StringBuilder string = new StringBuilder();
    string.append("[");
    for (int i = 0; i < stringArray.length; i++) {
        string.append(stringArray[i] + (i == (stringArray.length - 1) ? "" : "; "));
    }
    string.append("]");
    System.out.println(string);
    System.out.println(string.toString().substring(1, string.length() - 1).split("; "));
</code>```

surely you can do some more stuff do get it work with default array separator, but it depends on what you want to do, I just choose the simplest way.

Body:
I have a following code:

String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));

which produces the following string:

[One,, Two, Three]

Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,

How to correctly make this conversion ?

UPDATED

Arrays.toString(stringArray)

is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.

Body:
I really don't know what you want to do, but the array separator , is in your string, so the simplest way to avoid this would be to avoid building the string with default array separator! like this:

String[] stringArray = new String[] { "One,", "Two", "Three" };
    StringBuilder string = new StringBuilder();
    string.append("[");
    for (int i = 0; i < stringArray.length; i++) {
        string.append(stringArray[i] + (i == (stringArray.length - 1) ? "" : "; "));
    }
    string.append("]");
    System.out.println(string);
    System.out.println(string.toString().substring(1, string.length() - 1).split("; "));

surely you can do some more stuff do get it work with default array separator, but it depends on what you want to do, I just choose the simplest way.


问:
How do I join more than one files, in a Linq (C#) where one of the joins is a left join
My Sql below works great, but now I would like to join another file that has a common key. The file I would like to join has could have one to many records, any suggestions

here is my code:

```<code> var regPoints = (from x in db.CertPoints
                                 join y in db.CommunityPts on x.PointId equals y.PointId into z
                                 from t in
                                     (from r in z
                                      where r.CommunityId == id select r).DefaultIfEmpty()
                                 where x.TypeId == 1
                                 select new Points
                                 {
                                     pointId = x.PointId,
                                     pointsDescription = x.PointDescription,
                                     points = x.Points,
                                     dateApplied = t.DateApplied,
                                     pointsEarned = t.PointsEarned,
                                     pointsPending = t.Pending ? true : false,
                                     pointsApproved = t.Approved ? true : false,
                                     notes = t.Notes

                                 }).AsEnumerable();
</code>```

the new join would be a one to many records, where the key in CommunityPts is Id, and the file I would like to join is a list of file links "CommunityPtsDocs" with a foreign key CommnunityPtId. How do i add it to the above sql statement above?

答:
Sometimes I feel I'm a navigation properties evangelist (fortunately, I'm not the only one).

The answer you accepted is OK, it does the job. But using any ORM like Entity Framework or LINQ-to-SQL you should avoid the join statement as much as possible. It's verbose and error-prone. It causes repetitive code and it's too easy to join the wrong properties erroneously.

You class CertPoint could have a 0..1-n navigation property CommunityPts (a list) and CommunityPt could have a 1-n navigation property CommunityPtsDocs (also a list). If you're using LINQ-to-SQL, chances are that they're already there but you're not aware of them. If you use Entity Framework code-first, you should add them yourself.

Having these navigation properties, your code is going to look like this:

```<code>from cert in CertPoints
from comm in cert.CommunityPts.DefaultIfEmpty()
from doc in comm.CommunityPtsDocs
where comm.CommunityId == id && cert.TypeId == 1
select new Points
{
    pointId = cert.PointId,
    pointsDescription = cert.PointDescription,
    points = cert.Points,
    dateApplied = comm.DateApplied,
    pointsEarned = comm.PointsEarned,
    pointsPending = comm.Pending ? true : false,
    pointsApproved = comm.Approved ? true : false,
    notes = comm.Notes,
    something = doc.Something
})
</code>```

Now the ORM will translate this into SQL with the correct joins and your code looks much cleaner (note that I also prefer more meaningful range variable names).

Body:
My Sql below works great, but now I would like to join another file that has a common key. The file I would like to join has could have one to many records, any suggestions

here is my code:

 var regPoints = (from x in db.CertPoints
                                 join y in db.CommunityPts on x.PointId equals y.PointId into z
                                 from t in
                                     (from r in z
                                      where r.CommunityId == id select r).DefaultIfEmpty()
                                 where x.TypeId == 1
                                 select new Points
                                 {
                                     pointId = x.PointId,
                                     pointsDescription = x.PointDescription,
                                     points = x.Points,
                                     dateApplied = t.DateApplied,
                                     pointsEarned = t.PointsEarned,
                                     pointsPending = t.Pending ? true : false,
                                     pointsApproved = t.Approved ? true : false,
                                     notes = t.Notes

                                 }).AsEnumerable();

the new join would be a one to many records, where the key in CommunityPts is Id, and the file I would like to join is a list of file links "CommunityPtsDocs" with a foreign key CommnunityPtId. How do i add it to the above sql statement above?

Body:
Sometimes I feel I'm a navigation properties evangelist (fortunately, I'm not the only one).

The answer you accepted is OK, it does the job. But using any ORM like Entity Framework or LINQ-to-SQL you should avoid the join statement as much as possible. It's verbose and error-prone. It causes repetitive code and it's too easy to join the wrong properties erroneously.

You class CertPoint could have a 0..1-n navigation property CommunityPts (a list) and CommunityPt could have a 1-n navigation property CommunityPtsDocs (also a list). If you're using LINQ-to-SQL, chances are that they're already there but you're not aware of them. If you use Entity Framework code-first, you should add them yourself.

Having these navigation properties, your code is going to look like this:

from cert in CertPoints
from comm in cert.CommunityPts.DefaultIfEmpty()
from doc in comm.CommunityPtsDocs
where comm.CommunityId == id && cert.TypeId == 1
select new Points
{
    pointId = cert.PointId,
    pointsDescription = cert.PointDescription,
    points = cert.Points,
    dateApplied = comm.DateApplied,
    pointsEarned = comm.PointsEarned,
    pointsPending = comm.Pending ? true : false,
    pointsApproved = comm.Approved ? true : false,
    notes = comm.Notes,
    something = doc.Something
})

Now the ORM will translate this into SQL with the correct joins and your code looks much cleaner (note that I also prefer more meaningful range variable names).


问:
Ruby interacting with Selenium to control Firefox open/save dialog
Capybara.register_driver :session do |app|
        profile = Selenium::WebDriver::Firefox::Profile.new
        Capybara::Selenium::Driver.new app, :profile => profile
      end

What do I add here to get my ruby scripts to tell Selenium (I am running on a MAC OS El Capitan) to interact with the Firefox Open/Save dialog box such that it opens a PDF or DOC file automatically instead of prompting me with the dialog box which requires manual intervention?

答:
You can't interact with the Open/Save dialog box using selenium-webdriver with firefox.  However, you can set preferences in your driver to make the dialog box never appear and a default behavior to just happen.  Something like

```<code>Capybara.register_driver :session do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile['browser.download.dir'] = "~/Downloads"
  # Adjust below to match the type of file reported
  profile['browser.helperApps.neverAsk.saveToDisk'] = "application/pdf, application/octet-stream"
  Capybara::Selenium::Driver.new app, :profile => profile
end
</code>```

should cause it to always download the files without prompting.  You can similarly set the 'browser.helperApps.neverAsk.openFile' profile setting to have specific types of files always be opened.

Body:
You can't interact with the Open/Save dialog box using selenium-webdriver with firefox.  However, you can set preferences in your driver to make the dialog box never appear and a default behavior to just happen.  Something like

Capybara.register_driver :session do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile['browser.download.dir'] = "~/Downloads"
  # Adjust below to match the type of file reported
  profile['browser.helperApps.neverAsk.saveToDisk'] = "application/pdf, application/octet-stream"
  Capybara::Selenium::Driver.new app, :profile => profile
end

should cause it to always download the files without prompting.  You can similarly set the 'browser.helperApps.neverAsk.openFile' profile setting to have specific types of files always be opened.


问:
php or html, css and js
I am programming a school website where I want an easy system for teachers, where they could post news, informations, etc. I also want a timetable there. Which language is best suited for these needs?

Thanks
Adam

答:
For this kind of system, you'd probably use a client-server architecture.

Client is programmed in client languages (like HTML, JS, CSS and many others).

Server is programmed in server languages (like PHP, and many others).

Title: php or html, css and js


问:
Programmatically create PDF photo albums
I have a set of PDF photo album templates (they have blank squares where text and photos should go). My need is to use these templates to generate actual albums.

My plan was to use iText and Java. I would send the app an array of all the image URLs to use. I will know exactly where the images should be placed on the templates and use absolute positioning to place them.

I was just wondering if there was an easier or cleaner way of doing this - even if it means using a different language? After the PDFs are generated they are automatically sent to a printers who require them to be PDFs.

答:
```<code>PdfReader reader = new PdfReader("template.pdf");
PdfStamper stamper = new PdfStamper( reader, new FileOutputStream("output.pdf"));

PdfContentByte content = stamper.getOverContent(1); // first page == 1

Image image = Image.createInstance("someImage.png");
image.setAbsolutePosition( x, y );
image.setAbsoluteHeight( hei );
image.setAbsoluteWidth( wid );

content.addImage(image);

// instead of absolutely positioning the image, you can do:
//content.addImage( image, wid, 0f, 0f, hei, x, y );
// that's a transformation matrix, you can skew, rotate, scale, etc.

stamper.close();
</code>```

If you don't know the exact location, you have a couple options.

1) Replace an existing image.

With this option you can actually have the template overhang the image a bit, use alpha blending, and so on.  Get Fancy.  You could do the same thing with the above code if you used stamper.getUnderContent(1) and built your template with a transparent background.  I just answered a replace an image question that should help on that front.

The new image will inherit all the placeholder image's graphic state.  x,y,wid,hei, optional content groups, transparency, all manner of things.

2) Add an annotation (fields are easy to access) to the template in Acrobat (or with iText I suppose) and use it's RECT to provide x,y,wid,hei for the above code.

```<code>// given the above stamper
AcroFields fields = stamper.getAcroFields();
PdfDictionary replaceAnnot = fields.getFieldItem("ReplaceMe").getMerged(0);

//we can remove the field from the PDF without breaking the info in replaceAnnot.
fields.removeField("ReplaceMe");

// rects are laid out [llx, lly, urx, ury]
PdfArray rect = replaceAnnot.getAsArray(PdfName.RECT);
float x = rect.getAsNumber(0).floatValue();
float y = rect.getAsNumber(1).floatValue();
float width = rect.getAsNumber(2).floatValue() - x;
float height = rect.getAsNumber(3).floatValue() - y;
</code>```

Feed those coordinates to the above image code and you're good to go.

ContentLicense: CC BY-SA 4.0

Body:
PdfReader reader = new PdfReader("template.pdf");
PdfStamper stamper = new PdfStamper( reader, new FileOutputStream("output.pdf"));

PdfContentByte content = stamper.getOverContent(1); // first page == 1

Image image = Image.createInstance("someImage.png");
image.setAbsolutePosition( x, y );
image.setAbsoluteHeight( hei );
image.setAbsoluteWidth( wid );

content.addImage(image);

// instead of absolutely positioning the image, you can do:
//content.addImage( image, wid, 0f, 0f, hei, x, y );
// that's a transformation matrix, you can skew, rotate, scale, etc.

stamper.close();

If you don't know the exact location, you have a couple options.

1) Replace an existing image.

With this option you can actually have the template overhang the image a bit, use alpha blending, and so on.  Get Fancy.  You could do the same thing with the above code if you used stamper.getUnderContent(1) and built your template with a transparent background.  I just answered a replace an image question that should help on that front.

The new image will inherit all the placeholder image's graphic state.  x,y,wid,hei, optional content groups, transparency, all manner of things.

2) Add an annotation (fields are easy to access) to the template in Acrobat (or with iText I suppose) and use it's RECT to provide x,y,wid,hei for the above code.

// given the above stamper
AcroFields fields = stamper.getAcroFields();
PdfDictionary replaceAnnot = fields.getFieldItem("ReplaceMe").getMerged(0);

//we can remove the field from the PDF without breaking the info in replaceAnnot.
fields.removeField("ReplaceMe");

// rects are laid out [llx, lly, urx, ury]
PdfArray rect = replaceAnnot.getAsArray(PdfName.RECT);
float x = rect.getAsNumber(0).floatValue();
float y = rect.getAsNumber(1).floatValue();
float width = rect.getAsNumber(2).floatValue() - x;
float height = rect.getAsNumber(3).floatValue() - y;

Feed those coordinates to the above image code and you're good to go.


问:
How to implement Google API in my Website
enter link description here http://www.sevenieslab.com.

how can i add google API to allow my user to signup through their gmail account in my website

答:
For Web applications you can use the Goole Sign-In api.

This sample code can help you get started.
It will return basic user details like : name, profile picture, etc.
You can find more details here:
https://developers.google.com/identity/

```<code><html lang="en">
  <head>
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
  </head>
  <body>
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    <script>
      function onSignIn(googleUser) {
        // Useful data for your client-side scripts:
        var profile = googleUser.getBasicProfile();
        console.log("ID: " + profile.getId()); // Don't send this directly         to your server!
        console.log('Full Name: ' + profile.getName());
        console.log('Given Name: ' + profile.getGivenName());
        console.log('Family Name: ' + profile.getFamilyName());
        console.log("Image URL: " + profile.getImageUrl());
        console.log("Email: " + profile.getEmail());

        // The ID token you need to pass to your backend:
        var id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);
      };
    </script>
  </body>
</html>
</code>```

Body:
For Web applications you can use the Goole Sign-In api.

This sample code can help you get started.
It will return basic user details like : name, profile picture, etc.
You can find more details here:
https://developers.google.com/identity/

<html lang="en">
  <head>
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
  </head>
  <body>
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    <script>
      function onSignIn(googleUser) {
        // Useful data for your client-side scripts:
        var profile = googleUser.getBasicProfile();
        console.log("ID: " + profile.getId()); // Don't send this directly         to your server!
        console.log('Full Name: ' + profile.getName());
        console.log('Given Name: ' + profile.getGivenName());
        console.log('Family Name: ' + profile.getFamilyName());
        console.log("Image URL: " + profile.getImageUrl());
        console.log("Email: " + profile.getEmail());

        // The ID token you need to pass to your backend:
        var id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);
      };
    </script>
  </body>
</html>


问:
C# Elevate Current Running Process as SYSTEM
How can I elevate current running process as system, not administrator.

```<code>try
        {
            var ps = new ProcessStartInfo();
            ps.FileName = Process.GetCurrentProcess().ProcessName.ToString() + ".exe";
            ps.Verb = "runas";
            this.Close();

            var process = new Process();
            process.StartInfo = ps;
            process.Start();
        }
        catch (Exception re)
        {
            this.TopMost = true;
            MessageBox.Show(re.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        finally
        {
            Application.Exit();
        }
</code>```

above code restarts current running program to administrator privilege, like wise how can I get SYSTEM privilege?

c# 4.5

Any chance to create a new process as SYSTEM ? cause I see some apps(RunAsSystem) can make a file start as SYSTEM process.

Thanks.

答:
There is no way starting a process as system. This can be achieved only for boot time/kernel level scenarios, drivers, services etc.
It would be a security risk if that could be done. Create windows service if it is cruicial to you to run your logic as system.</p>

Body:
How can I elevate current running process as system, not administrator.

try
        {
            var ps = new ProcessStartInfo();
            ps.FileName = Process.GetCurrentProcess().ProcessName.ToString() + ".exe";
            ps.Verb = "runas";
            this.Close();

            var process = new Process();
            process.StartInfo = ps;
            process.Start();
        }
        catch (Exception re)
        {
            this.TopMost = true;
            MessageBox.Show(re.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        finally
        {
            Application.Exit();
        }

above code restarts current running program to administrator privilege, like wise how can I get SYSTEM privilege?

c# 4.5

Any chance to create a new process as SYSTEM ? cause I see some apps(RunAsSystem) can make a file start as SYSTEM process.

Thanks.


问:
How to get file contents by inode in Bash?
How can I retrieve file contents in Bash by knowing only the inode of the file?</p>

答:
The portable but slow way is using the find -inum ..., for getting the filename for the given inode and in the next step use the found filename.

If you need just the content of the file (by the inode number), exists some file-system/OS specific solutions.

For the macOS it is simple as:

```<code>inode=48747714
eval "$(stat -s "/Volumes/volume_name")"
cat /.vol/$st_dev/$inode
</code>```

E.g. In the OS X's HFS filesystem exists the pseudo directory /.vol, and you can use for accessing file contents by their inode number as:

```<code>/.vol/device_id/inode_number
</code>```

the device_id is is obtainable from the stat for the given volume_name in the /Volumes, (check ls /Volumes).

Body:
The portable but slow way is using the find -inum ..., for getting the filename for the given inode and in the next step use the found filename.

If you need just the content of the file (by the inode number), exists some file-system/OS specific solutions.

For the macOS it is simple as:

inode=48747714
eval "$(stat -s "/Volumes/volume_name")"
cat /.vol/$st_dev/$inode

E.g. In the OS X's HFS filesystem exists the pseudo directory /.vol, and you can use for accessing file contents by their inode number as:

/.vol/device_id/inode_number

the device_id is is obtainable from the stat for the given volume_name in the /Volumes, (check ls /Volumes).