问:
Express JS Doesen't Work
I have a weird problem about Express.js

I have code like this

```<code>app.get('/', function(req, res) {

  res.send('Homepage');

});

app.get('/developers', function(req, res) {

  res.send('Developers');

});
</code>```

When i go to my localhost, i see Homepage text, when i go to /developers page, i see developers text, but when i go to /developers/developer page, i can't see the result.

```<code>app.get('/developers/developer', function(req, res) {

  res.send('Developer test');

});
</code>```

Why first and second routes work and why third route doesen't work?

答:
This is because of the order of the route you have entered. app.get matches /developers first and follows the callback for it only. Try passing /developers/developer route above the /developers route. It will work.

Like this

```<code>app.get('/', function(req, res) {

  res.send('Homepage');

});
app.get('/developers/developer', function(req, res) {

  res.send('Developer test');

});
app.get('/developers', function(req, res) {

  res.send('Developers');

});
</code>```

Also, you can inline the /developers/developer within the /developers route

index.js

```<code>var developer = require('developer');

app.get('/', function(req, res) {

      res.send('Homepage');

});
app.use('/developers', developer());
</code>```

developer.js

```<code>var router = express.Router();
var developer = function() {
    var api = router();
    api.get('/', function(req, res) {
        res.send('Developers');
    });
    api.get('/developer', function(req, res) {
        res.send('Developer test');
    });
};
module.exports = developer;
</code>```

Title: Express JS Doesen't Work

Body:
I have a weird problem about Express.js

I have code like this

app.get('/', function(req, res) {

  res.send('Homepage');

});

app.get('/developers', function(req, res) {

  res.send('Developers');

});

When i go to my localhost, i see Homepage text, when i go to /developers page, i see developers text, but when i go to /developers/developer page, i can't see the result.

app.get('/developers/developer', function(req, res) {

  res.send('Developer test');

});

Why first and second routes work and why third route doesen't work?

Body:
This is because of the order of the route you have entered. app.get matches /developers first and follows the callback for it only. Try passing /developers/developer route above the /developers route. It will work.

Like this

app.get('/', function(req, res) {

  res.send('Homepage');

});
app.get('/developers/developer', function(req, res) {

  res.send('Developer test');

});
app.get('/developers', function(req, res) {

  res.send('Developers');

});

Also, you can inline the /developers/developer within the /developers route

index.js

var developer = require('developer');

app.get('/', function(req, res) {

      res.send('Homepage');

});
app.use('/developers', developer());

developer.js

var router = express.Router();
var developer = function() {
    var api = router();
    api.get('/', function(req, res) {
        res.send('Developers');
    });
    api.get('/developer', function(req, res) {
        res.send('Developer test');
    });
};
module.exports = developer;


来源: stackexchange

问:
Dynamic Programming Solution for TSP in C++
I have been trying to implement Dynamic Programming solution for TSP (Travelling Salesperson Problem) in C++. My code compiles but when I try to run the object file the program stops working and I am forced to close it.

Here is the code:

```<code>int tsp(std::vector<std::vector<int>> matrix) {

   int n = matrix[0].size();
   std::vector<std::vector<int>> A;  // Vertex, Set-Size
   std::set<int> S;

   for(int i = 0; i < n; ++i) {
       S.insert(i);
   }

   for(int i = 0; i < n; i++) {
       if(S.size() == 2) {
           A[i][2] = matrix[1][i];
       }
       else if(S.size() > 2) {
           std::set<int>::iterator it;
           for(it = S.begin(); it != S.end(); ++it) {
               int s = S.size();
               S.erase(i);
               int sd = S.size();
               int k = *it;
               if((k != i) && (k != 1) && (A[i][s] > (matrix[k][i] + A[k][sd]))) {
                   A[i][s] = matrix[k][i] + A[k][sd];
               }
           }
       }
   }

   return A[1][n];
}
</code>```

Can someone please point out what mistake I am making.

答:
You need to fill or resize a std::vector before calling operator[int] on it. A vector is basically an array that holds its size. So any out of bound access will cause a segmentation fault in runtime (if you are lucky) or will corrupt your memory.

You have a vector of vectors here, so you will need to iterate over two ranges and fill (or resize) vectors properly:

```<code>std::vector<std::vector<int>> A;  // Vertex, Set-Size
for(int i=size; i>0; --i)
   A.push_back(std::vector<int>);
for(int i=size; i>0; --i)
   for(int j=size; j>0; --j)
     A[i][j] = 0;
</code>```

Even better:

```<code>A.resize(size);
for(auto& v : a)        // (since you already have c++11)
  v.resize(size, val);  // fill with val
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to implement Dynamic Programming solution for TSP (Travelling Salesperson Problem) in C++. My code compiles but when I try to run the object file the program stops working and I am forced to close it.

Here is the code:

int tsp(std::vector<std::vector<int>> matrix) {

   int n = matrix[0].size();
   std::vector<std::vector<int>> A;  // Vertex, Set-Size
   std::set<int> S;

   for(int i = 0; i < n; ++i) {
       S.insert(i);
   }

   for(int i = 0; i < n; i++) {
       if(S.size() == 2) {
           A[i][2] = matrix[1][i];
       }
       else if(S.size() > 2) {
           std::set<int>::iterator it;
           for(it = S.begin(); it != S.end(); ++it) {
               int s = S.size();
               S.erase(i);
               int sd = S.size();
               int k = *it;
               if((k != i) && (k != 1) && (A[i][s] > (matrix[k][i] + A[k][sd]))) {
                   A[i][s] = matrix[k][i] + A[k][sd];
               }
           }
       }
   }

   return A[1][n];
}

Can someone please point out what mistake I am making.

Body:
You need to fill or resize a std::vector before calling operator[int] on it. A vector is basically an array that holds its size. So any out of bound access will cause a segmentation fault in runtime (if you are lucky) or will corrupt your memory.

You have a vector of vectors here, so you will need to iterate over two ranges and fill (or resize) vectors properly:

std::vector<std::vector<int>> A;  // Vertex, Set-Size
for(int i=size; i>0; --i)
   A.push_back(std::vector<int>);
for(int i=size; i>0; --i)
   for(int j=size; j>0; --j)
     A[i][j] = 0;

Even better:

A.resize(size);
for(auto& v : a)        // (since you already have c++11)
  v.resize(size, val);  // fill with val


问:
Make change for n dollars with m coins
I'm trying to implement a solution to the following problem:

Given a number of dollars, n, and a list of dollar values for m
distinct coins, find and print the number of different ways you can
make change for n dollars if each coin is available in an infinite
quantity.

The complete problem statement is here

Before presenting my solution, I should say that I know dynamic programming is probably the optimal way to solve this problem. The solution I've come up with does not use dynamic programming, and I know it is far from the most efficient solution out there. However, as far as I can tell it is correct.

The problem is that my solution underestimates the number of ways to make change. For example given n = 75 and {25 10 11 29 49 31 33 39 12 36 40 22 21 16 37 8 18 4 27 17 26 32 6 38 2 30 34} as coin values, the solution returns 182 when it should return 16694. It seems to work for smaller test cases, though.

```<code>def make_change(coins, n):
    solns = 0
    num_coins = len(coins)
    for i in range(num_coins):
        solns = solns + make_change_rec(coins, n-coins[0], coins[0])

        # We've found all solutions involving coin. Remove it
        # from consideration
        coins.pop(0)

    return solns

def make_change_rec(coins, n, parent):
    # If n == 0 we've found a solution
    if n == 0:
        return 1

    solns = 0
    # For each coin
    for coin in coins:
        # If coin > n, can't make change using coin
        if coin > n or coin < parent: # coin < parent rule ensures we don't count same solution twice
            continue

        # Use the coin to make change
        solns = solns + make_change_rec(coins, n-coin, coin)

    return solns
</code>```

Can someone help me understand what I'm doing wrong? I'm using Python 3.

答:
I think the only change you need to do is to sort the coins array. Now your recursion its going to run out of time for sure. So I recommend you to go with classic dynamic programming.

```<code>def make_change(coins, n):
    dp = [1] + [0] * n
    for coin in coins:
        for i in range(coin, n + 1):
            dp[i] += dp[i - coin]
    return dp[n]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Make change for n dollars with m coins

Body:
I'm trying to implement a solution to the following problem:

Given a number of dollars, n, and a list of dollar values for m
distinct coins, find and print the number of different ways you can
make change for n dollars if each coin is available in an infinite
quantity.

The complete problem statement is here

Before presenting my solution, I should say that I know dynamic programming is probably the optimal way to solve this problem. The solution I've come up with does not use dynamic programming, and I know it is far from the most efficient solution out there. However, as far as I can tell it is correct.

The problem is that my solution underestimates the number of ways to make change. For example given n = 75 and {25 10 11 29 49 31 33 39 12 36 40 22 21 16 37 8 18 4 27 17 26 32 6 38 2 30 34} as coin values, the solution returns 182 when it should return 16694. It seems to work for smaller test cases, though.

def make_change(coins, n):
    solns = 0
    num_coins = len(coins)
    for i in range(num_coins):
        solns = solns + make_change_rec(coins, n-coins[0], coins[0])

        # We've found all solutions involving coin. Remove it
        # from consideration
        coins.pop(0)

    return solns

def make_change_rec(coins, n, parent):
    # If n == 0 we've found a solution
    if n == 0:
        return 1

    solns = 0
    # For each coin
    for coin in coins:
        # If coin > n, can't make change using coin
        if coin > n or coin < parent: # coin < parent rule ensures we don't count same solution twice
            continue

        # Use the coin to make change
        solns = solns + make_change_rec(coins, n-coin, coin)

    return solns

Can someone help me understand what I'm doing wrong? I'm using Python 3.

Body:
I think the only change you need to do is to sort the coins array. Now your recursion its going to run out of time for sure. So I recommend you to go with classic dynamic programming.

def make_change(coins, n):
    dp = [1] + [0] * n
    for coin in coins:
        for i in range(coin, n + 1):
            dp[i] += dp[i - coin]
    return dp[n]


问:
Nightmare not resolving Adidas Site
I'm trying out NightmareJS for a few automations I'd like to accomplish. An issue I've encountered though is that Nightmare/Electron cannot resolve the adidas website, however it can resolve and visit any other web page.

This is what it looks like when it trys to visit adidas.

Does anybody know how to fix this? Every other site works perfectly. Here's how I'm trying to connect.

```<code>const Nightmare = require("nightmare");
const nightmare = Nightmare({ show: true });

nightmare
    .goto('https://adidas.com')
    .wait('#r1-0 a.result__a')
    .evaluate(() => document.querySelector('#r1-0 a.result__a').href)
    .end()
    .then(console.log)
    .catch((error) => {
        console.error('Search failed:', error);
    });
</code>```

答:
The url worked for me was http://www.global.adidas.com/ and http://www.adidas.com/us/,
the https version did not work for me on the browser, It is down for other tools too.

You can try to use the following switch when launching nightmare,

```<code>var nightmare = Nightmare({
  switches: {
    'ignore-certificate-errors': true
  }
});
</code>```

and also you can use DEBUG=* node app.js to find out more about the problem.

Title: Nightmare not resolving Adidas Site

Body:
I'm trying out NightmareJS for a few automations I'd like to accomplish. An issue I've encountered though is that Nightmare/Electron cannot resolve the adidas website, however it can resolve and visit any other web page.

This is what it looks like when it trys to visit adidas.

Does anybody know how to fix this? Every other site works perfectly. Here's how I'm trying to connect.

const Nightmare = require("nightmare");
const nightmare = Nightmare({ show: true });

nightmare
    .goto('https://adidas.com')
    .wait('#r1-0 a.result__a')
    .evaluate(() => document.querySelector('#r1-0 a.result__a').href)
    .end()
    .then(console.log)
    .catch((error) => {
        console.error('Search failed:', error);
    });

Body:
The url worked for me was http://www.global.adidas.com/ and http://www.adidas.com/us/,
the https version did not work for me on the browser, It is down for other tools too.

You can try to use the following switch when launching nightmare,

var nightmare = Nightmare({
  switches: {
    'ignore-certificate-errors': true
  }
});

and also you can use DEBUG=* node app.js to find out more about the problem.


问:
How to include dependent jar in maven jar
I have two queries:

1) I have build a maven project and when I am tying to deploy jar on server it shows some error related to driver not found. Then I decompiled my jar and found that dependent database jar jconn jar is not in that. But I have that jar in my code and I am using following in my pom.xml to get that dependent jar with my jar but still it is not able to get dependent jar. Somewhere, I read on stackoverflow to add following to my pom.xml

```<code><artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
    <addClasspath>true</addClasspath>
<classpathPrefix>./</classpathPrefix>
            <mainClass>com.launcher.Main</mainClass>
  </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
</code>```

Still it is giving the same thing and jconn jar was not in jar when decompiled. Please help.

2) I have some some key value pair in a property file and values are in comma separated form. I want to take all values of that key in a list. how can i do that. Please help

答:
To include other jars to your own ( it's called uber jar) you could use maven shade plugin

Example from their doc:

```<code>  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</code>```

It will create two jars. Original one with only yours content and uber with all other jars. It's possible to filter content, that will be included. For more examples please check:

https://maven.apache.org/plugins/maven-shade-plugin/

https://maven.apache.org/plugins/maven-shade-plugin/examples/includes-excludes.html

Body:
I have two queries:

1) I have build a maven project and when I am tying to deploy jar on server it shows some error related to driver not found. Then I decompiled my jar and found that dependent database jar jconn jar is not in that. But I have that jar in my code and I am using following in my pom.xml to get that dependent jar with my jar but still it is not able to get dependent jar. Somewhere, I read on stackoverflow to add following to my pom.xml

<artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
    <addClasspath>true</addClasspath>
<classpathPrefix>./</classpathPrefix>
            <mainClass>com.launcher.Main</mainClass>
  </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>

Still it is giving the same thing and jconn jar was not in jar when decompiled. Please help.

2) I have some some key value pair in a property file and values are in comma separated form. I want to take all values of that key in a list. how can i do that. Please help

Body:
To include other jars to your own ( it's called uber jar) you could use maven shade plugin

Example from their doc:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

It will create two jars. Original one with only yours content and uber with all other jars. It's possible to filter content, that will be included. For more examples please check:

https://maven.apache.org/plugins/maven-shade-plugin/

https://maven.apache.org/plugins/maven-shade-plugin/examples/includes-excludes.html


问:
Opening a new form using windows form c++
I'm a new programmer trying to have a multiple form.

I tried to open a new form using a button:

```<code>{
//This will open the ordering widow
NewOrder^ order = gcnew NewOrder;
order->Show();
//This one is to hide the current form
this->Hide();
</code>```

}

but it gives me an error message says that:

\projects\cppwinform1\cppwinform1\MyForm.h(135): error C2227: left of '->Show' must point to class/struct/union/generic type

\projects\cppwinform1\cppwinform1\MyForm.h(135): note: type is 'unknown-type

where line 135 is order->Show();
Please if someone can help me fixing that, and just open my other form

thnx

答: Might you need to put brackets after gcnew's classname? </p>

Body:
I'm a new programmer trying to have a multiple form.

I tried to open a new form using a button:

{
//This will open the ordering widow
NewOrder^ order = gcnew NewOrder;
order->Show();
//This one is to hide the current form
this->Hide();

}

but it gives me an error message says that:

\projects\cppwinform1\cppwinform1\MyForm.h(135): error C2227: left of '->Show' must point to class/struct/union/generic type

\projects\cppwinform1\cppwinform1\MyForm.h(135): note: type is 'unknown-type

where line 135 is order->Show();
Please if someone can help me fixing that, and just open my other form

thnx


问:
Entity Framework CTP4: where to put SetInitializer?
I am attempting to add Entity Framework, code first, to an MVC application that's been running with test data, using the CTP4 preview.

I am currently getting this error:

The model backing the 'SchedulerContext' context has changed since the database was created.  Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance.  For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

I do not want to generate a database at all, as I already have a database. So I tried adding the following to the SchedulerContext constructor:

```<code>Database.SetInitializer<SchedulerContext>(new CreateDatabaseOnlyIfNotExists<SchedulerContext>());
</code>```

which had no effect at all -- I got the same error the next time it ran. The error seems to occur when it is executing a LINQ statement that accesses the database -- the first, I think.

Where should I put this statement, or is this statement the answer to this problem at all?

答:
Btw, as of CTP5, this is the proper way of setting the initializer in Global.asax

protected void Application_Start()
{
System.Data.Entity.Database.DbDatabase.SetInitializer<NerdDinners>(new System.Data.Entity.Database.DropCreateDatabaseIfModelChanges<NerdDinners>());
}

Body:
I am attempting to add Entity Framework, code first, to an MVC application that's been running with test data, using the CTP4 preview.

I am currently getting this error:

The model backing the 'SchedulerContext' context has changed since the database was created.  Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance.  For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

I do not want to generate a database at all, as I already have a database. So I tried adding the following to the SchedulerContext constructor:

Database.SetInitializer<SchedulerContext>(new CreateDatabaseOnlyIfNotExists<SchedulerContext>());

which had no effect at all -- I got the same error the next time it ran. The error seems to occur when it is executing a LINQ statement that accesses the database -- the first, I think.

Where should I put this statement, or is this statement the answer to this problem at all?

ContentLicense: CC BY-SA 2.5


问:
Find specific attribute and get its value
I have this:

```<code><button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>
</code>```

and need to find the "voice" attribute and fetch its value "next"
I tried this by looking all the question but it shows undefined.

```<code>$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});
</code>```

答:
You don't need to use the .find as you can see in this example:

```<code><p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p
 <script>
 var title = $( "em" ).attr( "title" );
 console.log(title);
 </script>
</code>```

You should only do this:

```<code><p class="intro" voice="next,1">My name is Donald.</p>
 <script>
 var title = $( "p" ).attr( "voice" );
 console.log(title);
  </script>
</code>```

Body:
I have this:

<button>Click</button>

My name is Donald.

and need to find the "voice" attribute and fetch its value "next"
I tried this by looking all the question but it shows undefined.

$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});

Body:
You don't need to use the .find as you can see in this example:

<p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p
 <script>
 var title = $( "em" ).attr( "title" );
 console.log(title);
 </script>

You should only do this:

<p class="intro" voice="next,1">My name is Donald.</p>
 <script>
 var title = $( "p" ).attr( "voice" );
 console.log(title);
  </script>


问:
React contenteditable cursor jumps to beginning
I am using the module react-simple-contenteditable to enable editing of a fill in the blank worksheet. The reason I must use a content editable element instead of an input element is because I want the text of the problem to wrap. For example, if a problem has one blank, it divides the text into three sections the part before the blank, the blank, and the part after. If I were to represent the outer two as separate divs (or input fields), then the text would not wrap like a paragraph. Instead, I must have a single contenteditable  div that contains an input field for the blank and free text on either side.

The text is wrapping like I want it, but when I type text in the contenteditable field, the cursor jumps to the beginning. I don't understand why because I tried the example on the module's github site and it works perfectly, and although my implementation is a bit more complicated, it works essentially the same.

Here is my render function that uses <ContentEditable /> :

```<code>render() {
    const textPieces =
      <div className='new-form-text-pieces'>
        {
          this.props.problem.textPieces.map( (textPiece, idx) => {
            if (textPiece.blank) {
              return (
                  <div data-blank={true} className='blank' key={ textPiece.id } style={{display: 'inline'}}>
                    <input
                      placeholder="Answer blank"
                      className='new-form-answer-input'
                      value={ this.props.problem.textPieces[idx].text }
                      onChange={ (event) => this.props.handleTextPiecesInput(this.props.problemIdx, idx, event.target.value) }
                    />
                    <button className='modify-blank remove-blank' onClick={ (event) => this.props.removeBlank(this.props.problemIdx, idx) }>-</button>

                  </div>
              );
            } else {
              let text = this.props.problem.textPieces[idx].text;
              const placeholder = idx === 0 ? 'Problem text' : '...continue text';
              // text = text === '' ? placeholder : text;
              if (text === '') {
                text = <span style={{color:'gray'}}>{placeholder}</span>;
              } else {

              }
              return (
                this.props.isTextSplit ?
                  <TextPiece
                    key={ textPiece.id }
                    problemIdx={this.props.problemIdx}
                    textPieceIdx={idx}
                    dropBlank={this.props.dropBlank}
                    moveBlank={this.props.moveBlank}
                  >
                    <div style={{display: 'inline-block', }}>{text}</div>
                  </TextPiece>
                : text

              );
            }
          })
        }
      </div>;

    return (
       this.props.isTextSplit ? textPieces :
        <ContentEditable
          html={ReactDOMServer.renderToStaticMarkup(textPieces)}
          className="my-class"
          tagName="div"
          onChange={ (event, value) => this.props.handleProblemChange(event, this.props.problemIdx, value) }
          contentEditable='plaintext-only'
        />
    );

  }
</code>```

Here is the onChange function:

```<code>handleProblemChange(event, problemIdx) {
    const problems = cloneDeep(this.state.problems);
    event.target.children[0].childNodes.forEach( (textPieceNode, idx) => {
      if (textPieceNode.constructor === Text) {
        problems[problemIdx].textPieces[idx].text = textPieceNode.wholeText;
      } else {
        problems[problemIdx].textPieces[idx].text = textPieceNode.childNodes[0].value;
      }
    });
    this.setState({ problems });
  }
</code>```

And here is the state it refers to, just to make thing clear:

```<code>this.state = {
  problems: [
    {
      id: shortid.generate(),
      textPieces: [
        {
          text : "Three days was simply not a(n)",
          blank : false,
          id: shortid.generate(),
        },
        {
          text : "acceptable",
          blank : true,
          id: shortid.generate(),
        },
        {
          text : "amount of time to complete such a lot of work.",
          blank : false,
          id: shortid.generate(),
        }
      ]
    }
</code>```

Thanks so much

答:
Long story short, there is no easy way to do this. I have tried this myself and spent days trying. Basically you have to save the cursor position and reposition it yourself after the update. All of this can be achieved with window.getSelection()

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

But it can get really tricky depending on how much your content has changed.

I ended up using draftJS instead. Which is an abstraction over contenteditable div by facebook themselves.

https://draftjs.org/docs/overview.html#content

A bit longer to pick up but you will be able to do a lot more

Body:
I am using the module react-simple-contenteditable to enable editing of a fill in the blank worksheet. The reason I must use a content editable element instead of an input element is because I want the text of the problem to wrap. For example, if a problem has one blank, it divides the text into three sections the part before the blank, the blank, and the part after. If I were to represent the outer two as separate divs (or input fields), then the text would not wrap like a paragraph. Instead, I must have a single contenteditable  div that contains an input field for the blank and free text on either side.

The text is wrapping like I want it, but when I type text in the contenteditable field, the cursor jumps to the beginning. I don't understand why because I tried the example on the module's github site and it works perfectly, and although my implementation is a bit more complicated, it works essentially the same.

Here is my render function that uses <ContentEditable /> :

render() {
    const textPieces =

        {
          this.props.problem.textPieces.map( (textPiece, idx) => {
            if (textPiece.blank) {
              return (

                    <input
                      placeholder="Answer blank"
                      className='new-form-answer-input'
                      value={ this.props.problem.textPieces[idx].text }
                      onChange={ (event) => this.props.handleTextPiecesInput(this.props.problemIdx, idx, event.target.value) }
                    />
                    <button className='modify-blank remove-blank' onClick={ (event) => this.props.removeBlank(this.props.problemIdx, idx) }>-</button>

              );
            } else {
              let text = this.props.problem.textPieces[idx].text;
              const placeholder = idx === 0 ? 'Problem text' : '...continue text';
              // text = text === '' ? placeholder : text;
              if (text === '') {
                text = {placeholder};
              } else {

              }
              return (
                this.props.isTextSplit ?
                  <TextPiece
                    key={ textPiece.id }
                    problemIdx={this.props.problemIdx}
                    textPieceIdx={idx}
                    dropBlank={this.props.dropBlank}
                    moveBlank={this.props.moveBlank}
                  >

{text}

                  </TextPiece>
                : text

              );
            }
          })
        }

;

    return (
       this.props.isTextSplit ? textPieces :
        <ContentEditable
          html={ReactDOMServer.renderToStaticMarkup(textPieces)}
          className="my-class"
          tagName="div"
          onChange={ (event, value) => this.props.handleProblemChange(event, this.props.problemIdx, value) }
          contentEditable='plaintext-only'
        />
    );

  }

Here is the onChange function:

handleProblemChange(event, problemIdx) {
    const problems = cloneDeep(this.state.problems);
    event.target.children[0].childNodes.forEach( (textPieceNode, idx) => {
      if (textPieceNode.constructor === Text) {
        problems[problemIdx].textPieces[idx].text = textPieceNode.wholeText;
      } else {
        problems[problemIdx].textPieces[idx].text = textPieceNode.childNodes[0].value;
      }
    });
    this.setState({ problems });
  }

And here is the state it refers to, just to make thing clear:

this.state = {
  problems: [
    {
      id: shortid.generate(),
      textPieces: [
        {
          text : "Three days was simply not a(n)",
          blank : false,
          id: shortid.generate(),
        },
        {
          text : "acceptable",
          blank : true,
          id: shortid.generate(),
        },
        {
          text : "amount of time to complete such a lot of work.",
          blank : false,
          id: shortid.generate(),
        }
      ]
    }

Thanks so much


问:
Identifying targetList in ember-drag-sort
I am currently trying to implement an ember-drag-sort nested list into my Ember.js app.

Is there a way to determine in the dragEnd action which "sub-list" the item has been dropped into? (e.g. a class name, id etc)

In my scenario, I am sorting ember data records that can belong to each other (i.e. a nested, 'tree' structure). When I drag one nested record "into" another (making the dragged record a child of the second record), I need to update the parent attribute in ember-data. My question is, how do you pass some id of the second record (the new parent) to the dragEnd action?

Is this even possible?

EDIT:

To put it another way, I want to be able to identify which list I have dropped the item into.

答: targetList refers to the array on the dragged side of the component. For pushing the parent to the target list alongside the child, you can take a look at this twiddle.


问:
How to show only 7 days in a calender from current date to next 6 days
i'm developing android app which requires calender with Only 7 days from current date : if Today is Wed day, so results will be wed -- till tuesday i need to show in view of my calender.</p>

```<code>Calendar instance = Calendar.getInstance();
widget.setSelectedDate(instance.getTime());
Calendar instance1 = Calendar.getInstance();
instance1.set(instance1.get(Calendar.YEAR), Calendar.JANUARY, 1);
Calendar instance2 = Calendar.getInstance();
instance2.set(instance2.get(Calendar.YEAR), Calendar.DECEMBER, 31);
widget.state().edit()
        .setMinimumDate(instance1.getTime())
        .setMaximumDate(instance2.getTime())
        .commit();
widget.addDecorators(
        new MySelectorDecorator(this),
        new HighlightWeekendsDecorator(),
        oneDayDecorator);
</code>```

答:
You leave your code exactly how it is and just remove your set call. When you call getInstance for a calendar you will get back a calendar instance that is set to the current date and time.

Ex:

```<code>SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar date = Calendar.getInstance();

for(int i = 0; i < 7;i++){
    Calendar[i] = format.format(date.getTime());
    date.add(Calendar.DATE  , 1);
    System.out.println("date :" + Calendar[i]);
}
</code>```

Body:
i'm developing android app which requires calender with Only 7 days from current date : if Today is Wed day, so results will be wed -- till tuesday i need to show in view of my calender.

Calendar instance = Calendar.getInstance();
widget.setSelectedDate(instance.getTime());
Calendar instance1 = Calendar.getInstance();
instance1.set(instance1.get(Calendar.YEAR), Calendar.JANUARY, 1);
Calendar instance2 = Calendar.getInstance();
instance2.set(instance2.get(Calendar.YEAR), Calendar.DECEMBER, 31);
widget.state().edit()
        .setMinimumDate(instance1.getTime())
        .setMaximumDate(instance2.getTime())
        .commit();
widget.addDecorators(
        new MySelectorDecorator(this),
        new HighlightWeekendsDecorator(),
        oneDayDecorator);

Body:
You leave your code exactly how it is and just remove your set call. When you call getInstance for a calendar you will get back a calendar instance that is set to the current date and time.

Ex:

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar date = Calendar.getInstance();

for(int i = 0; i < 7;i++){
    Calendar[i] = format.format(date.getTime());
    date.add(Calendar.DATE  , 1);
    System.out.println("date :" + Calendar[i]);
}


问:
wildcard loading for every route in angular
I have added the wildcard route to my application in angular .
The issue is after adding the wildcard.

I'm not sure what is the issue!
 below id the routes array:

```<code>const appRoutes: Routes = [
    { path: 'login', redirectTo: '/login', pathMatch: 'full' },
    { path: 'settings', redirectTo: '/settings', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];
</code>```

Login and setting are modules and they have their own routing files.
Before adding the wildcard and default route, on start the app was redirected to login screen .

But now every url is redirected to PageNotFoundComponent .

The order of the routes in the configuration matters and this is by
  design. The router uses a first-match wins strategy when matching
  routes, so more specific routes should be placed above less specific
  routes. In the configuration above, routes with a static path are
  listed first, followed by an empty path route, that matches the
  default route. The wildcard route comes last because it matches every
  URL and should be selected only if no other routes are matched first.

Please guide!
Thanks

答:
The wildcard route needs to be the last one in the array. Right now, when your app boots up, the path is empty, so the router routes to the first specific path that matches the application's routes, i.e. the wildcard route. When you change the order such that the wildcard route is the last one, when your app boots, it will see that it needs to redirect to login on an empty path, BEFORE it sees the wildcard route and it will work as intended. Secondly, do not redirect to the same route. Use the specific component for each route that targets a component. Update your routes array like this.

```<code>const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'settings', component: SettingsComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full'},
  { path: '**', component: PageNotFoundComponent }
];
</code>```

EDIT

OP has indicated that they want to use separate routing modules for the different features modules they have in their App. For this, you have two options that I know of. You can either use Lazy Loading, OR you can declare the routes pertaining to each feature module in its own Routing Module and then IMPORT the feature module into your app.module. The approach is demonstrated in the following stackblitz: https://stackblitz.com/edit/angular-q8mkac

Body:
I have added the wildcard route to my application in angular .
The issue is after adding the wildcard.

I'm not sure what is the issue!
 below id the routes array:

const appRoutes: Routes = [
    { path: 'login', redirectTo: '/login', pathMatch: 'full' },
    { path: 'settings', redirectTo: '/settings', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

Login and setting are modules and they have their own routing files.
Before adding the wildcard and default route, on start the app was redirected to login screen .

But now every url is redirected to PageNotFoundComponent .

The order of the routes in the configuration matters and this is by
  design. The router uses a first-match wins strategy when matching
  routes, so more specific routes should be placed above less specific
  routes. In the configuration above, routes with a static path are
  listed first, followed by an empty path route, that matches the
  default route. The wildcard route comes last because it matches every
  URL and should be selected only if no other routes are matched first.

Please guide!
Thanks

Body:
The wildcard route needs to be the last one in the array. Right now, when your app boots up, the path is empty, so the router routes to the first specific path that matches the application's routes, i.e. the wildcard route. When you change the order such that the wildcard route is the last one, when your app boots, it will see that it needs to redirect to login on an empty path, BEFORE it sees the wildcard route and it will work as intended. Secondly, do not redirect to the same route. Use the specific component for each route that targets a component. Update your routes array like this.

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'settings', component: SettingsComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full'},
  { path: '**', component: PageNotFoundComponent }
];

EDIT

OP has indicated that they want to use separate routing modules for the different features modules they have in their App. For this, you have two options that I know of. You can either use Lazy Loading, OR you can declare the routes pertaining to each feature module in its own Routing Module and then IMPORT the feature module into your app.module. The approach is demonstrated in the following stackblitz: https://stackblitz.com/edit/angular-q8mkac


问:
Is there any standard fileopen dialog in iphone programming?
I want to create application, that will process images(mostly - photographs from mobile camera).

So i need at first to provide the way to open image file from phone memory.
how can i do that?
Sorry for such a stupid question, but i am newbie in iphone programming(yet:)).

P.S. I use xcode, cocoa

答: You can use UIImagePickerController to get a standard interface for selecting a photo from the user's library or camera roll. Depending on the configuration, it can also be used to capture a new image with the camera. Note however that you get a UIImage back, not a file, if you want to upload it somewhere, you will first have to create a file or NSData object from the image, using either UIImagePNGRepresentation() or UIImageJPEGRepresentation().


问:
i want the link style like in the picture
html code:

```<code> <ul class="info-link">
   <li><a href="#"><i class="fa fa-map-marker"></i>  3588 N Stelling road, Brooklyn, NYC, United State.</a> </li>
   <li><a href="#"><i class="fa fa-phone"></i>  1900-167-168-99 EXT: 001</a></li>
   <li><a href="#"><i class="fa fa-mobile"></i>  (05) 132-564-3333</a></li>
   <li><a href="#"><i class="fa fa-envelope"></i>  logohere@support.com</a></li>
 </ul>
</code>```

css code :

```<code>ul li {
  list-style: none;
}
</code>```

result picture:
code-result

desire result picture:
desire-result

答:
You can achieve that by positioning the i element with position: absolute; and adding a padding from left for the li.

ul {
  list-style: none;
  padding: 0;
}

li {
  position: relative;
  padding-left: 25px;
}

li i.fa {
  position: absolute;
  left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<ul class="info-link">
  <li><i class="fa fa-map-marker"></i>3588 N Stelling road, Brooklyn, NYC, United State. </li>
  <li><i class="fa fa-phone"></i>1900-167-168-99 EXT: 001</li>
  <li><i class="fa fa-mobile"></i>(05) 132-564-3333</li>
  <li><i class="fa fa-envelope"></i>logohere@support.com</li>
</ul></code>```

Body:
html code:

  3588 N Stelling road, Brooklyn, NYC, United State.

  1900-167-168-99 EXT: 001

  (05) 132-564-3333

  logohere@support.com

css code :

ul li {
  list-style: none;
}

result picture:
code-result

desire result picture:
desire-result

Body:
You can achieve that by positioning the i element with position: absolute; and adding a padding from left for the li.

ul {
  list-style: none;
  padding: 0;
}

li {
  position: relative;
  padding-left: 25px;
}

li i.fa {
  position: absolute;
  left: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<ul class="info-link">
  <li><a href="#"><i class="fa fa-map-marker"></i>3588 N Stelling road, Brooklyn, NYC, United State.</a> </li>
  <li><a href="#"><i class="fa fa-phone"></i>1900-167-168-99 EXT: 001</a></li>
  <li><a href="#"><i class="fa fa-mobile"></i>(05) 132-564-3333</a></li>
  <li><a href="#"><i class="fa fa-envelope"></i>logohere@support.com</a></li>
</ul>


问:
c++ Unknown values for operand1 operatr, operand2
```<code>#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>

using namespace std;

void getName ( string first1_name, string last1_name, string first2_name, string last2_name );
string getLectureSection ( );
void getLabSection ( string lab_section1, string lab_section2 );
void printIdInfo ( ostream&out, string first1_name, string last1_name, string first2_name,
                  string last2_name, string CLASS, string lecture_section,
                  string lab_section1, string lab_section2, string DUE_DATE );
void readExpression ( ifstream&, double operand1, char operatr, double operand2 );
void echoExpression ( ostream&out, double operand1, char operatr, double operand2 );
void evaluateExpression ( ostream&out, double operand1, char operatr, double operand2 );
void writeFileLocation ( );

int main()
{
   const string CLASS = "C.S.1428",
                DUE_DATE = "11/15/17";

   string first1_name,
          last1_name,
          first2_name,
          last2_name,
          lecture_section,
          lab_section1,
          lab_section2;

   double   operand1,
            operand2;

   char     operatr;

   ifstream fin;
   fin.open("prog5_002in.txt");

   if(!fin)
   {
        cout << "Program Terminated." << endl
             << "Input file failed to open!" << endl;
        return 1;
   }

   ofstream fout;
   fout.open("prog5_002out.txt");

   if(!fout)
   {
        cout << "Program Terminated." << endl
             << "Output file failed to open!" << endl;
        return 2;
   }

   getName ( first1_name, last1_name, first2_name, last2_name );
   lecture_section = getLectureSection ( );
   getLabSection ( lab_section1, lab_section2 );
   printIdInfo ( fout, first1_name, last1_name, first2_name, last2_name,
                 CLASS, lecture_section,
                 lab_section1, lab_section2, DUE_DATE );

   readExpression ( fin, operand1, operatr, operand2 );
   while ( operatr != '?' )
   {
       echoExpression ( fout, operand1, operatr, operand2 );
       evaluateExpression ( fout, operand1, operatr, operand2 );
       readExpression ( fin, operand1, operatr, operand2 );
   }

   cout << endl << endl;
   printIdInfo ( cout, first1_name, last1_name, first2_name, last2_name,
                 CLASS, lecture_section, lab_section1, lab_section2, DUE_DATE );
   writeFileLocation ( );

   fin.close();
   fout.close();

   system("PAUSE>NUL");

   return 0;
}

    void getName(string first1_name, string last1_name, string first2_name, string last2_name)
    {
        cout << "Enter your first name: ";
        cin >> first1_name;
        cout << endl << "Enter your last name: ";
        cin >> last1_name;
        cout << endl << endl;

        cout << "Enter your first name: ";
        cin >> first2_name;
        cout << endl << "Enter your last name: ";
        cin >> last2_name;
        cout << endl << endl;
    }

    string getLectureSection()
    {
        string lecture_section;

        cout << "Enter your three digit lecture section: ";
        cin >> lecture_section;
        cout << endl << endl;

        return lecture_section;
    }

    void getLabSection(string lab_section1, string lab_section2)
    {
        cout << "Enter your two digit lab section number: ";
        cin >> lab_section1;
        cout << endl;
        cout << "Enter your two digit lab section number: ";
        cin >> lab_section2;
    }

    void printIdInfo ( ostream&out, string first1_name, string last1_name, string first2_name,
                       string last2_name, string CLASS,string lecture_section,string lab_section1,
                       string lab_section2,string DUE_DATE )
    {
        out << first1_name << " " << last1_name << " & "
             << first2_name << " " << last2_name << endl
             << CLASS << lecture_section << endl
             << "Lab Section: " << "L" << lab_section1
             << "L" << lab_section2 << endl
             << DUE_DATE << endl << endl;
    }

    void readExpression (ifstream &fin, double operand1, char operatr, double operand2)
    {
        fin >> operand1, operatr, operand2;
    }

    void echoExpression(ostream&fout, double operand1,char operatr, double operand2)
    {
        fout << operand1 << operatr << operand2;
    }

    void evaluateExpression(ostream&fout, double operand1, char operatr, double operand2)
    {
        double expression;
        switch (operatr)
        {
            case '+' :
            expression = (operand1 + operand2);
            fout << " = " << expression;
            break;

        case '-' :
            expression = (operand1 - operand2);
            fout << " = " << expression;
            break;

        case '*' :
            expression = (operand1 * operand2);
            fout << " = " << expression;
            break;

        case '/' :
            if (operand2 == 0)
            {
                fout << endl << "Division by zero produces an "
                     << "undefined result." << endl;
            }
            else
            {
                expression = (operand1 / operand2);
                fout << " = " << setprecision(1) << fixed << expression;
            }
            break;

        default :
            fout << operand1 << " " << operatr << " " << operand2;
            fout << endl << "Encountered unknown operator.";
        }
    }

void writeFileLocation()
{
    cout << "Program results have been written to Prog5_002out.txt";
}
</code>```

I'm very new to coding in general especially c++ and this is a program I've been working on for an extra credit assignment in my class. For the most part I've gotten it to run but I don't know how to display the statements from the printIdInfo function because I'm not sure how to leave it open ended to call once for fout and then again for cout. So I haven't been able to get the cout call working but it semi works with fout.

I also don't think that I'm doing anything remotely correct with my function call for readExpression, I don't seem to be correctly finding the operand1, operatr, and operand2 from the input file I have. At the moment the output file loops (indefinitely?) just displaying encountered unknown operator which I want it to do in the case of the $ symbol. But I'm really not sure at what point I've gone wrong.

This isn't really "due" but I can turn it in by Friday for bonus points. I'm stumped somewhere along and I think it's just because I rushed through it but any pointers would be appreciated. Thank you.

```<code>(Input File)
123.5 + 59.3

198.7 / -26

125 $ 28

89.3 * 2.5

178.9 - 326.8

198.7 / 0

34.0 ? 10
</code>```

答:
Your readExpression function reads properly from fin, but does nothing with the result.  You define the signature of readExpression as:

```<code>void readExpression(std::ifstream &, double, char, double);
</code>```

You are doing the correct thing with the std::ifstream by passing a reference to that argument (with &).  However, you are passing the last three arguments by value, which essentially means a temporary copy of each argument is being created for use within the function.  You are therefore reading in from fin and putting the results into temporary variables that are obliterated when the function exits.  If you want the function to modify the contents of the last three arguments (similar to how it is modifying the std::ifstream), pass them by reference.  Change the signature to:

```<code>void readExpression(std::ifstream &, double &, char &, double &);
</code>```

Then after the call to readExpression(fin, operand1, operatr, operand2), you should find that operand1, operatr, and operand2 contain what you expect them to contain.

See this Wikipedia article for more info about references.

P.S., Try to avoid using namespace std whenever possible.

Body:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>

using namespace std;

void getName ( string first1_name, string last1_name, string first2_name, string last2_name );
string getLectureSection ( );
void getLabSection ( string lab_section1, string lab_section2 );
void printIdInfo ( ostream&out, string first1_name, string last1_name, string first2_name,
                  string last2_name, string CLASS, string lecture_section,
                  string lab_section1, string lab_section2, string DUE_DATE );
void readExpression ( ifstream&, double operand1, char operatr, double operand2 );
void echoExpression ( ostream&out, double operand1, char operatr, double operand2 );
void evaluateExpression ( ostream&out, double operand1, char operatr, double operand2 );
void writeFileLocation ( );

int main()
{
   const string CLASS = "C.S.1428",
                DUE_DATE = "11/15/17";

   string first1_name,
          last1_name,
          first2_name,
          last2_name,
          lecture_section,
          lab_section1,
          lab_section2;

   double   operand1,
            operand2;

   char     operatr;

   ifstream fin;
   fin.open("prog5_002in.txt");

   if(!fin)
   {
        cout << "Program Terminated." << endl
             << "Input file failed to open!" << endl;
        return 1;
   }

   ofstream fout;
   fout.open("prog5_002out.txt");

   if(!fout)
   {
        cout << "Program Terminated." << endl
             << "Output file failed to open!" << endl;
        return 2;
   }

   getName ( first1_name, last1_name, first2_name, last2_name );
   lecture_section = getLectureSection ( );
   getLabSection ( lab_section1, lab_section2 );
   printIdInfo ( fout, first1_name, last1_name, first2_name, last2_name,
                 CLASS, lecture_section,
                 lab_section1, lab_section2, DUE_DATE );

   readExpression ( fin, operand1, operatr, operand2 );
   while ( operatr != '?' )
   {
       echoExpression ( fout, operand1, operatr, operand2 );
       evaluateExpression ( fout, operand1, operatr, operand2 );
       readExpression ( fin, operand1, operatr, operand2 );
   }

   cout << endl << endl;
   printIdInfo ( cout, first1_name, last1_name, first2_name, last2_name,
                 CLASS, lecture_section, lab_section1, lab_section2, DUE_DATE );
   writeFileLocation ( );

   fin.close();
   fout.close();

   system("PAUSE>NUL");

   return 0;
}

    void getName(string first1_name, string last1_name, string first2_name, string last2_name)
    {
        cout << "Enter your first name: ";
        cin >> first1_name;
        cout << endl << "Enter your last name: ";
        cin >> last1_name;
        cout << endl << endl;

        cout << "Enter your first name: ";
        cin >> first2_name;
        cout << endl << "Enter your last name: ";
        cin >> last2_name;
        cout << endl << endl;
    }

    string getLectureSection()
    {
        string lecture_section;

        cout << "Enter your three digit lecture section: ";
        cin >> lecture_section;
        cout << endl << endl;

        return lecture_section;
    }

    void getLabSection(string lab_section1, string lab_section2)
    {
        cout << "Enter your two digit lab section number: ";
        cin >> lab_section1;
        cout << endl;
        cout << "Enter your two digit lab section number: ";
        cin >> lab_section2;
    }

    void printIdInfo ( ostream&out, string first1_name, string last1_name, string first2_name,
                       string last2_name, string CLASS,string lecture_section,string lab_section1,
                       string lab_section2,string DUE_DATE )
    {
        out << first1_name << " " << last1_name << " & "
             << first2_name << " " << last2_name << endl
             << CLASS << lecture_section << endl
             << "Lab Section: " << "L" << lab_section1
             << "L" << lab_section2 << endl
             << DUE_DATE << endl << endl;
    }

    void readExpression (ifstream &fin, double operand1, char operatr, double operand2)
    {
        fin >> operand1, operatr, operand2;
    }

    void echoExpression(ostream&fout, double operand1,char operatr, double operand2)
    {
        fout << operand1 << operatr << operand2;
    }

    void evaluateExpression(ostream&fout, double operand1, char operatr, double operand2)
    {
        double expression;
        switch (operatr)
        {
            case '+' :
            expression = (operand1 + operand2);
            fout << " = " << expression;
            break;

        case '-' :
            expression = (operand1 - operand2);
            fout << " = " << expression;
            break;

        case '*' :
            expression = (operand1 * operand2);
            fout << " = " << expression;
            break;

        case '/' :
            if (operand2 == 0)
            {
                fout << endl << "Division by zero produces an "
                     << "undefined result." << endl;
            }
            else
            {
                expression = (operand1 / operand2);
                fout << " = " << setprecision(1) << fixed << expression;
            }
            break;

        default :
            fout << operand1 << " " << operatr << " " << operand2;
            fout << endl << "Encountered unknown operator.";
        }
    }

void writeFileLocation()
{
    cout << "Program results have been written to Prog5_002out.txt";
}

I'm very new to coding in general especially c++ and this is a program I've been working on for an extra credit assignment in my class. For the most part I've gotten it to run but I don't know how to display the statements from the printIdInfo function because I'm not sure how to leave it open ended to call once for fout and then again for cout. So I haven't been able to get the cout call working but it semi works with fout.

I also don't think that I'm doing anything remotely correct with my function call for readExpression, I don't seem to be correctly finding the operand1, operatr, and operand2 from the input file I have. At the moment the output file loops (indefinitely?) just displaying encountered unknown operator which I want it to do in the case of the $ symbol. But I'm really not sure at what point I've gone wrong.

This isn't really "due" but I can turn it in by Friday for bonus points. I'm stumped somewhere along and I think it's just because I rushed through it but any pointers would be appreciated. Thank you.

(Input File)
123.5 + 59.3

198.7 / -26

125 $ 28

89.3 * 2.5

178.9 - 326.8

198.7 / 0

34.0 ? 10

Body:
Your readExpression function reads properly from fin, but does nothing with the result.  You define the signature of readExpression as:

void readExpression(std::ifstream &, double, char, double);

You are doing the correct thing with the std::ifstream by passing a reference to that argument (with &).  However, you are passing the last three arguments by value, which essentially means a temporary copy of each argument is being created for use within the function.  You are therefore reading in from fin and putting the results into temporary variables that are obliterated when the function exits.  If you want the function to modify the contents of the last three arguments (similar to how it is modifying the std::ifstream), pass them by reference.  Change the signature to:

void readExpression(std::ifstream &, double &, char &, double &);

Then after the call to readExpression(fin, operand1, operatr, operand2), you should find that operand1, operatr, and operand2 contain what you expect them to contain.

See this Wikipedia article for more info about references.

P.S., Try to avoid using namespace std whenever possible.


问:
The length of the string exceeds the value set on the maxJsonLength property.c#
I am trying to get the result from my wcf service in json as you can see :

```<code>public List<InquiryStatus> SearchInquiryStatus(string userid, string datestart, string dateend)
{
    string result = "";
    using (WebClient ClientRequest = new WebClient())
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        result = ClientRequest.DownloadString(ServiceHostName + "/MonitoringInquiryService.svc/SearchInquiryStatus/" +
                                                userid + "/"
                                                + datestart + "/" + dateend
                                                );
    }
    var javascriptserializer = new JavaScriptSerializer();
    return javascriptserializer.Deserialize<List<InquiryStatus>>(result);
}
</code>```

But i get this error :

```<code>Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input
</code>```

As a note when i call my service url http://reporting.demo.ir/MonitoringInquiryService.svc/SearchInquiryStatus/null/'20171106'/'20171113'
in browser i get the result .
I googled my error and i found this :

```<code><configuration>
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>
</code>```

I added this to my UI web config .but i get same error.

答:
Your UI project seems to be in ASP.NET MVC framework where JavaScriptSerializer MaxJsonLength cannot be read from web.config setting as you've specified in the question.

For setting MaxJsonLength, you need to specify value in the code in following way :

```<code>var javascriptserializer = new JavaScriptSerializer()
{
    MaxJsonLength = Int32.MaxValue // specify length as per your business requirement
};
</code>```

Body:
I am trying to get the result from my wcf service in json as you can see :

public List<InquiryStatus> SearchInquiryStatus(string userid, string datestart, string dateend)
{
    string result = "";
    using (WebClient ClientRequest = new WebClient())
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        result = ClientRequest.DownloadString(ServiceHostName + "/MonitoringInquiryService.svc/SearchInquiryStatus/" +
                                                userid + "/"
                                                + datestart + "/" + dateend
                                                );
    }
    var javascriptserializer = new JavaScriptSerializer();
    return javascriptserializer.Deserialize<List<InquiryStatus>>(result);
}

But i get this error :

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input

As a note when i call my service url http://reporting.demo.ir/MonitoringInquiryService.svc/SearchInquiryStatus/null/'20171106'/'20171113'
in browser i get the result .
I googled my error and i found this :

<configuration>
   <system.web.extensions>

   </system.web.extensions>
</configuration>

I added this to my UI web config .but i get same error.

Body:
Your UI project seems to be in ASP.NET MVC framework where JavaScriptSerializer MaxJsonLength cannot be read from web.config setting as you've specified in the question.

For setting MaxJsonLength, you need to specify value in the code in following way :

var javascriptserializer = new JavaScriptSerializer()
{
    MaxJsonLength = Int32.MaxValue // specify length as per your business requirement
};


问:
How to edit the remote file via SSHLibrary?
I need to edit the remote file.
Right now, I'm logging into the machine via SSH. I can execute commands and get back response etc.

I am facing difficulty to modify the remote file.

```<code>Source Machine : Windows
Destination : Linux
</code>```

Is anything like, get the file to Windows machine and edit it and then again transfer the file to Linux ? or any other better way ?

```<code>import SSHLibrary
s = SSHLibrary.SSHLibrary()
s.open_connection("10.10.10.10",username, password)
#s.write("sudo vi file_name_along_with_path") it has to force edit the file
# any ftp mechanism would be better
</code>```

Can you please help me ?

答:
Use SFTP (SSH file transfer protocol). That's a protocol designed for file transfers.

```<code>import paramiko

host = "sftp.example.com"
transport = paramiko.Transport(host)
transport.connect(username = "username", password = "password")

sftp = paramiko.SFTPClient.from_transport(transport)

# Download

filepath = '/remote/path/file.txt'
localpath = '/tmp/file.txt'
sftp.get(filepath, localpath)

# Open in your favorite editor here

# Upload back

sftp.put(localpath, filepath)

# Close

sftp.close()
transport.close()
</code>```

(base on paramiko's sshclient with sftp)

Body:
I need to edit the remote file.
Right now, I'm logging into the machine via SSH. I can execute commands and get back response etc.

I am facing difficulty to modify the remote file.

Source Machine : Windows
Destination : Linux

Is anything like, get the file to Windows machine and edit it and then again transfer the file to Linux ? or any other better way ?

import SSHLibrary
s = SSHLibrary.SSHLibrary()
s.open_connection("10.10.10.10",username, password)
#s.write("sudo vi file_name_along_with_path") it has to force edit the file
# any ftp mechanism would be better

Can you please help me ?

Body:
Use SFTP (SSH file transfer protocol). That's a protocol designed for file transfers.

import paramiko

host = "sftp.example.com"
transport = paramiko.Transport(host)
transport.connect(username = "username", password = "password")

sftp = paramiko.SFTPClient.from_transport(transport)

# Download

filepath = '/remote/path/file.txt'
localpath = '/tmp/file.txt'
sftp.get(filepath, localpath)

# Open in your favorite editor here

# Upload back

sftp.put(localpath, filepath)

# Close

sftp.close()
transport.close()

(base on paramiko's sshclient with sftp)


问:
Tensorflow: ValueError: Can't load save_path when it is None in single shot detection
I have just started working with tensorflow in python. I am trying to train Single shot detection using tensorflow for pascalvoc dataset. While creating tfrecords and during evaluation using VGG_VOC0712_SSD_300x300_ft_iter_120000.ckpt trained model there was no error. Whereas, when I am trying to train pascalvoc 2007 or 2012 datasets using ssd_300_vgg.ckpt pre-trained model I am getting following error.

```<code>2017-08-25 20:03:03.001268: I tensorflow/core/common_runtime gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro M5000M, pci bus id: 0000:01:00.0)
INFO:tensorflow:Error reported to Coordinator: <type 'exceptions.ValueError'>, Can't load save_path when it is None.
Traceback (most recent call last):
  File "train_ssd_network.py", line 391, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train_ssd_network.py", line 387, in main
    sync_optimizer=None)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/slim/python/slim/learning.py", line 738, in train
    master, start_standard_services=False, config=session_config) as sess:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 965, in managed_session
    self.stop(close_summary_writer=close_summary_writer)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 793, in stop
    stop_grace_period_secs=self._stop_grace_secs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/coordinator.py", line 389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 954, in managed_session
    start_standard_services=start_standard_services)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 709, in prepare_or_wait_for_session
    init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/session_manager.py", line 281, in prepare_session
    init_fn(sess)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/framework/python/ops/variables.py", line 660, in callback
    saver.restore(session, model_path)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1558, in restore
    raise ValueError("Can't load save_path when it is None.")
ValueError: Can't load save_path when it is None.
</code>```

I am using following script to fine-tune the model

```<code>DATASET_DIR=./tfrecords
TRAIN_DIR=./logs/
CHECKPOINT_PATH=./checkpoints/ssd_300_vgg.ckpt
python train_ssd_network.py \
    --train_dir=${TRAIN_DIR} \
    --dataset_dir=${DATASET_DIR} \
    --dataset_name=pascalvoc_2012 \
    --dataset_split_name=train \
    --model_name=ssd_300_vgg \
    --checkpoint_path=${CHECKPOINT_PATH} \
    --save_summaries_secs=60 \
    --save_interval_secs=600 \
    --weight_decay=0.0005 \
    --optimizer=adam \
    --learning_rate=0.001 \
    --batch_size=10
</code>```

The model ssd_300_vgg.ckpt is stored at the location ./checkpoints

Please let me know if anyone has the solution.

答: check your path, you might be pointing to a non-existing file.</p>

Body:
I have just started working with tensorflow in python. I am trying to train Single shot detection using tensorflow for pascalvoc dataset. While creating tfrecords and during evaluation using VGG_VOC0712_SSD_300x300_ft_iter_120000.ckpt trained model there was no error. Whereas, when I am trying to train pascalvoc 2007 or 2012 datasets using ssd_300_vgg.ckpt pre-trained model I am getting following error.

2017-08-25 20:03:03.001268: I tensorflow/core/common_runtime gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro M5000M, pci bus id: 0000:01:00.0)
INFO:tensorflow:Error reported to Coordinator: <type 'exceptions.ValueError'>, Can't load save_path when it is None.
Traceback (most recent call last):
  File "train_ssd_network.py", line 391, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train_ssd_network.py", line 387, in main
    sync_optimizer=None)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/slim/python/slim/learning.py", line 738, in train
    master, start_standard_services=False, config=session_config) as sess:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 965, in managed_session
    self.stop(close_summary_writer=close_summary_writer)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 793, in stop
    stop_grace_period_secs=self._stop_grace_secs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/coordinator.py", line 389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 954, in managed_session
    start_standard_services=start_standard_services)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 709, in prepare_or_wait_for_session
    init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/session_manager.py", line 281, in prepare_session
    init_fn(sess)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/framework/python/ops/variables.py", line 660, in callback
    saver.restore(session, model_path)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1558, in restore
    raise ValueError("Can't load save_path when it is None.")
ValueError: Can't load save_path when it is None.

I am using following script to fine-tune the model

DATASET_DIR=./tfrecords
TRAIN_DIR=./logs/
CHECKPOINT_PATH=./checkpoints/ssd_300_vgg.ckpt
python train_ssd_network.py \
    --train_dir=${TRAIN_DIR} \
    --dataset_dir=${DATASET_DIR} \
    --dataset_name=pascalvoc_2012 \
    --dataset_split_name=train \
    --model_name=ssd_300_vgg \
    --checkpoint_path=${CHECKPOINT_PATH} \
    --save_summaries_secs=60 \
    --save_interval_secs=600 \
    --weight_decay=0.0005 \
    --optimizer=adam \
    --learning_rate=0.001 \
    --batch_size=10

The model ssd_300_vgg.ckpt is stored at the location ./checkpoints

Please let me know if anyone has the solution.


问:
Disabled all other radio button if name and value not same
I am making one form where I need to disable all other radio button and submit button if Radio button name or Id or class name not same to each other.

ID or name or class, I am generating through dynamic way. (name=radio_1, id= radio_1).

or

if I click on Group-1 radio button then other group should be disable.

Please have a look.

```<code><label class="radio-inline">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">
</label>

<label class="radio-inline">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">
</label>
</code>```

HTML Output:

```<code><label class="radio-inline">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">
</label>

<label class="radio-inline">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">
</label>
</code>```

My Query:

```<code>$(document).ready(function() {
$("input:radio").click(function() {
    var val = $(this).val();
    var name = $(this).attr('name');
    if(val != name){
      $(this).attr("disabled", true);
    }
    else{
    $(this).attr("disabled", false);
    }
});

});
</code>```

Please guide me how can I do this.

答:
```<code>$(document).ready(function(){
    $('input:radio').on('click',function(){
    $('input[name!="'+$(this).val()+'"]').attr('disabled',true);
 });
});
</code>```

try this: https://jsfiddle.net/bch31up4/

Body:
I am making one form where I need to disable all other radio button and submit button if Radio button name or Id or class name not same to each other.

ID or name or class, I am generating through dynamic way. (name=radio_1, id= radio_1).

or

if I click on Group-1 radio button then other group should be disable.

Please have a look.

<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">

<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">

HTML Output:

<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">

<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">

My Query:

$(document).ready(function() {
$("input:radio").click(function() {
    var val = $(this).val();
    var name = $(this).attr('name');
    if(val != name){
      $(this).attr("disabled", true);
    }
    else{
    $(this).attr("disabled", false);
    }
});

});

Please guide me how can I do this.

Body:
$(document).ready(function(){
    $('input:radio').on('click',function(){
    $('input[name!="'+$(this).val()+'"]').attr('disabled',true);
 });
});

try this: https://jsfiddle.net/bch31up4/


问:
Can't access HTTPS from my Android Emulator
I'm behind a corporate proxy and everything that access the internet needs a special configuration regarding Proxy. I'm on a CentOS 7, using CNTLMD to handle proxy tunneling, developing for mobile with React Native. And I'm using the Android Emulator provided by Android Studio.

I first noticed that my emulator can't access any HTTPS protocol when I tried to open Google in the Browser. Internally google redirects to HTTPS and I always get that "Connection Refused" error. Later (this week), trying to use Axios and Fetch to make HTTP/HTTPS requests, this has become a serious problem, since the APIs I'm trying to connect to are under the HTTPS protocol.

A friend of mine who is working in the same project but using Mac has no problems with HTTPS. I have also tried to start the emulator with the following commands:

```<code>emulator -avd myemulator -http-proxy http://127.0.0.1:3128
</code>```

And

```<code>emulator -avd Marshmallow86 -http-proxy http://<network username>:<network password>@<ip>:<port>
</code>```

And they do nothing.

I tried setting up HTTP and HTTPS proxy on Android Studio but this don't seem to be the way (and also didn't work).

@edit

I set the http_proxy on my host and started the emulator without parameters. Didn't work as well.

What am I missing?

答:
I haven't used the software above that isn't android avd or androidstudio,
but it looks like a proxy or CA certificate problem.
Since the difference seems to be by OS, I would guess CA certificate first.

This android page has advice on using openssl from the command line to
explore that and consider importing certificates.

https://developer.android.com/training/articles/security-config.html

This android page has current suggestions for proxy configurations:
https://developer.android.com/studio/run/emulator-networking.html

Note, that the above instructions are updated for new features.
In the past I needed a proxy to a non-ssl appengine development server
which is slightly different from your problem but here's what I used:

For an SSL proxy, used the apache web server, and configured it to use SSL
by installing a self-signed certificate, then added a ProxyPass and ProxyPassReverse
in httpd.conf and a ProxyPass in the httpd-ssl.conf.
    ProxyPass  /    http://127.0.0.1:8080/

Apache as an SSL proxy receives connections to https://127.0.0.1:443 and
passes them to http://127.0.0.1:8080

Then in the application, code that will be running in the emulator
can use address
10.0.2.2 to use android subnet routing table to connect to the dev. OS localhost.

Body:
I'm behind a corporate proxy and everything that access the internet needs a special configuration regarding Proxy. I'm on a CentOS 7, using CNTLMD to handle proxy tunneling, developing for mobile with React Native. And I'm using the Android Emulator provided by Android Studio.

I first noticed that my emulator can't access any HTTPS protocol when I tried to open Google in the Browser. Internally google redirects to HTTPS and I always get that "Connection Refused" error. Later (this week), trying to use Axios and Fetch to make HTTP/HTTPS requests, this has become a serious problem, since the APIs I'm trying to connect to are under the HTTPS protocol.

A friend of mine who is working in the same project but using Mac has no problems with HTTPS. I have also tried to start the emulator with the following commands:

emulator -avd myemulator -http-proxy http://127.0.0.1:3128

And

emulator -avd Marshmallow86 -http-proxy http://<network username>:<network password>@<ip>:<port>

And they do nothing.

I tried setting up HTTP and HTTPS proxy on Android Studio but this don't seem to be the way (and also didn't work).

@edit

I set the http_proxy on my host and started the emulator without parameters. Didn't work as well.

What am I missing?


问:
How to display data with line breaks from MySQL in PHP
I am storing user inputs in my DB unencoded, this includes line breaks in the data.
There are no \n or
's in the inputs when then displaying the data again so the line breaks are lost.

I have tried wrapping the output in htmlspecialchars but it has not made a difference.

How can I accurately display this content?

答:
You Can also Used this.
PHP generates HTML. You may want:

```<code>echo "foo";
echo "<br />\n";
echo "bar";
</code>```

I think, It is used full to you.

Thank You..

Body:
You Can also Used this.
PHP generates HTML. You may want:

echo "foo";
echo "<br />\n";
echo "bar";

I think, It is used full to you.

Thank You..


问:
Cannot launch AVD in emulator:QT library not found
I am new to Android Studio and I am having problems while using the emulator. When I try to run it keeps crashing saying:

"Cannot launch AVD in emulator" [6816]:ERROR:./android/qt/qt_setup.cpp:28:Qt library not found at
  C:\Users\Jay\AppData\Local\Android\Sdk\emulator\lib64\qt\lib

Could not launch 'C:\Users\Jay\AppData\Local\Android\Sdk\emulator/qemu/windows-x86_64/qemu-system-i386.exe':
  No such file or directory

I have enabled VT-x from BIOS settings yet I am having the problem. I have searched a lot and cannot find an answer. Any help will be much appreciated. Can anyone give me a solution?

Screenshot of error

答:
I was facing this issue

```<code>  java.io.IOException: Cannot download
 'https://dl.google.com/android/repository/emulator-windows-4266726.zip'
</code>```

I updated to studio 3.0 in windows 10, my emulators stopped working.Things I did for fixing,

Deleted previous installation folders of android studio like 2.0 and 2.1 present under my username alongside .AndroidStudio3.0 folder(leaving it untouched).

Deleted previously installed emulators which any way stopped working.

Downloaded the emulator zip file manually from the link above.
Pasted its contents in emulator folder of

```<code>       C:\Users\myusername\AppData\Local\Android\Sdk\emulator
</code>```

Created a new emulator and started it, Bingo! it is working!!

Body:
I was facing this issue

  java.io.IOException: Cannot download
 'https://dl.google.com/android/repository/emulator-windows-4266726.zip'

I updated to studio 3.0 in windows 10, my emulators stopped working.Things I did for fixing,

Deleted previous installation folders of android studio like 2.0 and 2.1 present under my username alongside .AndroidStudio3.0 folder(leaving it untouched).

Deleted previously installed emulators which any way stopped working.

Downloaded the emulator zip file manually from the link above.
Pasted its contents in emulator folder of

       C:\Users\myusername\AppData\Local\Android\Sdk\emulator

Created a new emulator and started it, Bingo! it is working!!


问:
Fetch array value - JQuery
Consider that i have the following html

```<code><input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
</code>```

To fetch the values i use

```<code>a = $('#other_floor_plans').val()
</code>```

It returns the following

```<code>"["Pool","Office","Sprinkler","Boiler"]"
</code>```

If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.

How to accomplish this?

答:
I think you need to change little bit of your code specially in markup.

changed your input markup into this <input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>

then get value by jQuery

```<code>var a = $('#other_floor_plans').val(),
a = JSON.parse(a);
console.log(a[0]);
</code>```

you need to use JSON.parse because you get json formate value and need to be parsed.

for my recommendation you just comma separate value like

```<code><input type="text" id="other_floor_plans" name="other_floor_plans[]" value="Pool, Office, Sprinkler, Boiler">
</code>```

then get first value by jQuery

```<code>var a = $('#other_floor_plans').val().split(",");
console.log(a[0]);
</code>```

This one is much more readable and easy I guess.

Title: Fetch array value - JQuery

Body:
Consider that i have the following html

<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">

To fetch the values i use

a = $('#other_floor_plans').val()

It returns the following

"["Pool","Office","Sprinkler","Boiler"]"

If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.

How to accomplish this?

Body:
I think you need to change little bit of your code specially in markup.

changed your input markup into this <input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>

then get value by jQuery

var a = $('#other_floor_plans').val(),
a = JSON.parse(a);
console.log(a[0]);

you need to use JSON.parse because you get json formate value and need to be parsed.

for my recommendation you just comma separate value like

<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="Pool, Office, Sprinkler, Boiler">

then get first value by jQuery

var a = $('#other_floor_plans').val().split(",");
console.log(a[0]);

This one is much more readable and easy I guess.


问:
What is a one-sentence explanation of how Accurev works?
I understand git, Subversion, CVS and a myriad of other source control systems.

I've begun using Accurev and it confounds me.

I believe I need to form a mental model that relates it to other SCM's.  Ideally relative to git because I understand git the best.

I would explain git as "a directed graph of commits where a commit is a diff, a parent (or parents) hash, and a hash of itself."  You can easily move on from there to explain concepts like rebase and what merges really are, fast-forward vs. actual merges and so on.  I've found it easy to teach new users complex git concepts in about 15-20 minutes.

I would really like to understand Accurev at that level.  So...

What is the once sentence abstraction of how Accurev works that makes it possible to explain how it behaves?

Some examples of questions I would like my mental model to answer:

What happens when I "keep" some files and then "promote" them?

What if I don't promote the same files as I've just kept?

Why does history sometimes get mis-attributed when non-conflicting (a.k.a. overlapping) updates happen?  This, in particular, is reminiscent of a failure mode of Subversion that, from the basic explanations I've heard, I don't believe should exist with Accurev.

Why do diffs almost never contain what I expect them to?  I believe what's happen is that diff against basis is showing me the diff against the current (moving) parent stream but what I really want is only to see changes I've made since I've last updated.

答:
Disclaimer: The source control system I understand best is SVN.  So that colors my usage of terms such as repo, checkout, etc.  Also, I use Accurev on a daily basis, but I tend not to venture far from the core concepts that I feel I have a firm grasp of.

One sentence (with an asterisk):  Accurev is a time-ordered repository that keeps a revision history of files changed for each stream/workspace, and allows you to develop different versions of the code (in streams) while each stream is transparently updated with the core code from its parent and child* streams.

(*) A stream is updated by a child stream only once a child stream promotes changes into the parent stream.

The main benefit of Accurev is the ability to maintain different versions of code easily.  If you want to grasp it, I wouldn't look for quick abstractions or terms redefined in language you're familiar with.  I'd look for examples and a gentle explanation of terms as they arise.  Unfortunately, I only know what I need to know, but I'll give it a shot...

(I'll get to workspaces later.  Don't worry about them at this point.)

When you create one stream parented off of another, it's like you did an SVN branch to create the child stream, but the (wonderful) difference is that SVN merges are taken care of for you each time you update the parent or child stream (or you are alerted when a conflict exists and you need to resolve it manually).

Let's say you start off with a stream, CompanyStream.  Your codebase is managed by that stream, and it has a history of changes you've made to files.  You then decide to create two child streams below that, ChildStream1, ChildStream2.  Any changes made to files in CompanyStream will trickle down to both child streams, so they always have the latest code that they inherited from CompanyStream.  (Inheritance of revision changes is a staple concept in Accurev.)  Meanwhile, you're doing development specific to one vendor in ChildStream1, and changes specific to another vendor in ChildStream2.  You can selectively decide which code from ChildStream1 and 2 get promoted to CompanyStream, but any changes made in CompanyStream should be things that you want to appear in both child streams.  If you promote code from ChildStream1 into CompanyStream, then those changes will appear in ChildStream2 once it does an update (because again, it inherits CompanyStream)

The stream visualization would look like this:

CompanyStream --

                            |-- ChildStream1

                            |-- ChildStream2

Accurev Overlap = A file in a parent stream has been modified since you've Updated your stream.  Visualize the parent stream as being above you (that's how it'll be displayed in the client), and that stream has progressed horizontally so that it overlaps the point in time that you're at.

Quick mapping of SVN to Accurev concepts:

SVN Checkin - Promote

SVN Checkout - Anchor (Anchoring something makes it a WIP - Work In Progress)

SVN Update - Update

Accurev Workspaces

I haven't mentioned workspaces yet.  A workspace represents the code on your hard drive.  A workspace is similar to a stream in that it can have a history, and it can keep track of changes you have made.  (This is what a Keep does -- it stores a snapshot of the files you specify during that Keep operation in your workspace's history.  You can revert to those file snapshots at any time.  As a result, a workspace can also be viewed as your own personal, private stream, which is a record of changes made to the code within.)

Streams are abstract concepts that represent revision changes, and a history of what has happened.  Streams and workspaces inherit the code from their parent streams.  Unlike streams, however, workspaces cannot have child streams or child workspaces.  Workspaces are like leaves on a tree; streams are like branches.

What happens when I "keep" some files and then "promote" them?

You promote to a stream.  You Keep to a workspace.  Promoted changes are visible to all who can see the stream.  Kept changes are visible only to you, the owner of the workspace.

The Kept files will have snapshots in your workspace (in case you ever want to revert to them).  The promoted files will have snapshots (so to speak) in the stream you promoted them to.  The big difference is that the promoted changes will trickle down to any streams or workspaces that inherit that stream.

What if I don't promote the same files as I've just kept?

Then they will only be in your workspace.  Also, I believe that when you do a promote, Accurev does a keep first (so you have a record of the file change in both your workspace and the stream to which you're promoting).

Why does history sometimes get mis-attributed when non-conflicting (a.k.a. overlapping) updates happen? This, in particular, is reminiscent of a failure mode of Subversion that, from the basic explanations I've heard, I don't believe should exist with Accurev.

Can you give an example?  My grasp of Accurev's file versioning is a little fuzzy.  I believe that the version attribute will be assigned by the workspace or stream from which the most recent change was promoted (not Kept).  It's possible that there are some stream inheritance relationships that cause a file to have attributes that don't seem correct until you trace it out.

Why do diffs almost never contain what I expect them to? I believe what's happen is that diff against basis is showing me the diff against the current (moving) parent stream but what I really want is only to see changes I've made since I've last updated.

Then do a diff against "Backed," not against Basis.

The simple configuration that works for me is:  I always create my own personal, private stream off of some public development stream.  Then when I make changes I want to checkin (or be able to revert to), I promote to my own stream.  I keep working in my workspace, and if I want to diff my workspace against what I've done previously or what's going on above me (changes that other people have made), I do a diff against Backed.

Sorry this is so long.  Hopefully it helps...