问:
Submitting Coldbox RC scope on form input change via AJAX and returning string to display on page
I need to pass in form variables via AJAX every time a select box value is changed, and get a returned string from the AJAX call to display on the page. Here's the situation:

I built a form which is dynamically built by the user for a set of compliance rules. This allows the user to have multiple select boxes to generate a logic statement such as the following:

```<code>(
  ( 6779 AND 10852 AND 10845 )
  AND
  (
    ( 8260 AND 8258 )
  )
)
OR
( 6780 OR 10845 OR 8258 OR 12893 )
</code>```

I've written a function that returns this logic statement as a string after submission of the form, but would like to dynamically populate a div (#logicblock) on the form page BEFORE submitting, so that the user can verify the logic before submission of the information into our database.

I tried to use the following:

```<code> ('##logicblock').load("#getmodel('model.compliance').BuildLogic(rc)#", function(response){
     $('##logicblock').html(response);
 })
</code>```

... but this does not properly pass in the RC scope into my model. I've searched and can't find a way that makes sense to me to send the entire form scope into a method that returns a value for display on the page.

答:
I got it figured out. Because the form fields are dynamically generated, I found that I couldn't use a $('select').change() event to call the method, so I wrote a handler method to generate the data and serialized the form to pass in to the handler. I was able to use the following to get the desired response:

```<code>function updateLogicBlock(){
    var serialform = $('form').serialize();
    $.get("#event.buildLink('handler.buildComplianceLogic')#?" + serialform,
      function(data) {
        $('##logicblock').html(data);
    });
};
</code>```

Then I simply added onChange="updateLogicBlock();" to every select box on the form.

Body:
I need to pass in form variables via AJAX every time a select box value is changed, and get a returned string from the AJAX call to display on the page. Here's the situation:

I built a form which is dynamically built by the user for a set of compliance rules. This allows the user to have multiple select boxes to generate a logic statement such as the following:

(
  ( 6779 AND 10852 AND 10845 )
  AND
  (
    ( 8260 AND 8258 )
  )
)
OR
( 6780 OR 10845 OR 8258 OR 12893 )

I've written a function that returns this logic statement as a string after submission of the form, but would like to dynamically populate a div (#logicblock) on the form page BEFORE submitting, so that the user can verify the logic before submission of the information into our database.

I tried to use the following:

 ('##logicblock').load("#getmodel('model.compliance').BuildLogic(rc)#", function(response){
     $('##logicblock').html(response);
 })

... but this does not properly pass in the RC scope into my model. I've searched and can't find a way that makes sense to me to send the entire form scope into a method that returns a value for display on the page.

Body:
I got it figured out. Because the form fields are dynamically generated, I found that I couldn't use a $('select').change() event to call the method, so I wrote a handler method to generate the data and serialized the form to pass in to the handler. I was able to use the following to get the desired response:

function updateLogicBlock(){
    var serialform = $('form').serialize();
    $.get("#event.buildLink('handler.buildComplianceLogic')#?" + serialform,
      function(data) {
        $('##logicblock').html(data);
    });
};

Then I simply added onChange="updateLogicBlock();" to every select box on the form.


来源: stackexchange

问:
Does anyone see the error in this simple Ruby function?
This function is supposed to take a string and return the characters in reverse order.

```<code>def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end
</code>```

however all the tests return false:

```<code>puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)
</code>```

Does anyone see what the problem is?

答:
puts prints and returns nil, so the whole method returns nil. If, for debugging reasons , you want to inspect what your method is returning, use p which returns it's argument (reversedString in this case).

```<code>def reverse(string)

    reversedString = ""
    i = string.length - 1
    while i >= 0
      reversedString = reversedString + string[i]
      i -= 1
    end
    p reversedString  # !!!

end
</code>```

And all 3 tests return true

ContentLicense: CC BY-SA 3.0

Body:
This function is supposed to take a string and return the characters in reverse order.

def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end

however all the tests return false:

puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)

Does anyone see what the problem is?

Body:
puts prints and returns nil, so the whole method returns nil. If, for debugging reasons , you want to inspect what your method is returning, use p which returns it's argument (reversedString in this case).

def reverse(string)

    reversedString = ""
    i = string.length - 1
    while i >= 0
      reversedString = reversedString + string[i]
      i -= 1
    end
    p reversedString  # !!!

end

And all 3 tests return true


问:
Common libraries in a large team
Assume you have five products, and all of them use one or more of the company's internal libraries, written by individual developers.

It sounds simple but in practice, I found it to be very difficult to maintain.

How do you deal with the following scenarios:

A developer unintentionally introduces a bug and breaks everything in production.

Every library has to mature, That means the API needs to evolve, so how do you deploy the updated version to production if every developer needs to update/test their code while they are extremely busy on other projects? Is this a resource and time issue?

Version control, deployment,and usage. Would you store this in one global location or force each project to use, say, svn:externals to "tie" a library?

I've found that it is extremely hard to come up with a good strategy. My own pet theory is this:

Each common library has to have a super-thorough set of tests or else it should never be common, even if it means someone else duplicates the effort. Duplicate untested code is better than common untested code (you break only one project).

Each common library has to have a dedicated maintainer (can be offset by a really good test suite in a smaller team).

Each project should check out the version of the library that is known to work with it. This means a developer does not have to get pulled away to update API usage, as the common code gets updated. Which it will be. Every non-trivial piece of code evolves over months and years.

Thank you for your thoughts on this!

答:
I think that one shared library is better than 3 duplicate ones (and 1 tested is definitely better than 3 untested). That's because when you find and fix problem, this makes the whole application area more solid (and development and maintenance are more efficient).

BTW, that't one of the reasons (apart from contributing back to the community) why our company exposes our .NET shared libraries to the public as open-source.

Plus, there's less code to write. And you can designate one dev to enforce good development practices on the library and its usages (i.e. through code contracts enforced on the unit tests within library consumers). This improves quality and and reduces maintenance costs.

We store shared libraries as binaries in the solution. That comes from the logical requirement that any solution has to be atomic and independent (this rules out svn:externals links).

API compatibility is not an issue at all. Just let your integration server rebuild and retest the whole product stack (while updating all the inner references and propagating changes) and you'll always be sure that all internal API's are solid. And whomever breaks the API has to either fix it or update the usages.

OwnerDisplayName: Andrei

ContentLicense: CC BY-SA 2.5

Title: Common libraries in a large team

LastEditorDisplayName: Roger Lipscombe

OwnerDisplayName: Rinat Abdullin


问:
How do I get basic jQuery tabs to work inside a .Net modal popup?
Really simple question: Am I missing something?  Seems like this should be all that is necessary for the basic setup...  currently I'm getting an un-stylized version (i.e. no tabs, just plain text/html).  So they don't look like tabs and when you click them nothing hides/shows as would be expected with tabs. Do I have to manually hook up javascript to show and hide the contents of the tabs or does the framework do this for me?

Update:

So I tested the code out and
  this works fine for basic tabs.
  However, I need to use this inside a
  .Net modal popup using their "Ajax"
  toolkit.  Essentially this is doing a
  postback which I've noticed tends to
  fight with jQuery.  In the past, I've
  used the jQuery live events, but
  I'm not sure what to bind it to...
  Usually you bind to an event on an
  object, like a click handler for a
  button.  Here, I need to attach the
  tab assignment/binding ( using .tabs()
  ) via a live event but I'm not sure
  which one.  I tried binding to the
  document load event but no luck with
  that:

```<code>$(document).live('load', bind_tabs);
</code>```

Any ideas?

Style sheet and Javascript links included on page:

```<code>https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
</code>```

Added the following line to my stylesheet:

```<code>.ui-tabs .ui-tabs-hide { display: none; }
</code>```

Added the following script to the page:

```<code><script type="text/javascript">
  $(function () {
  $("#tabs2").tabs();
  $("#tabs").tabs();
  });
</script>
</code>```

HTML:

```<code><div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
</code>```

Also noticed on the "theming" documentation on the page (http://jqueryui.com/demos/tabs/#theming) that it states the following. Should I manually put in all those styles (like ui-widget) or rely on the framework to do it?

Sample markup with jQuery UI CSS
  Framework classes

```<code><div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs">
   <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
     <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">Nunc tincidunt</a></li>
      <li class="ui-state-default ui-corner-top"><a href="#tabs-2">Proin dolor</a></li>
   <div class="ui-tabs-panel ui-widget-content ui-corner-bottom" id="tabs-1">
      <p>Tab one content goes here.</p>
   </div>
    ...
</div>
</code>```

Note: This is a sample of markup
  generated by the tabs plugin, not
  markup you should use to create a
  tabs. The only markup needed for that
  is

```<code><div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
</code>```

答:
This may not help with the use of .tabs() [your code looks ok to me], but it might help you track down the problem. Try ruling things in or out one at a time:

Using an appropriate debugger (firebug, IE Developer Tools, Chrome Developer tools, etc), put a breakpoint on the  $("#tabs").tabs(); line. If you hit the breakpoint, you know that jquery framework has loaded correctly and you can rule that out.

To validate that the JqueryUI framework loaded correctly, apply some other jqueryUI specific feature to an element - such as turning a  element into a button with the $('#element').button() method.  If that works, you know the jQueryUI framework is loaded correctly.

To validate that the .css files have been loaded correctly, add an additional html element to the page and add one of the jquery UI classes to it (ui-state-highlight for example) - if the style changes, then the .css file is loaded correctly.

Then, evaluate the length property of the jquery object to see if the selector successfully found the elements you intended to find or add a 'watch' expression for $("#tabs") and check out what it found.

Body:
Really simple question: Am I missing something?  Seems like this should be all that is necessary for the basic setup...  currently I'm getting an un-stylized version (i.e. no tabs, just plain text/html).  So they don't look like tabs and when you click them nothing hides/shows as would be expected with tabs. Do I have to manually hook up javascript to show and hide the contents of the tabs or does the framework do this for me?

Update:

So I tested the code out and
  this works fine for basic tabs.
  However, I need to use this inside a
  .Net modal popup using their "Ajax"
  toolkit.  Essentially this is doing a
  postback which I've noticed tends to
  fight with jQuery.  In the past, I've
  used the jQuery live events, but
  I'm not sure what to bind it to...
  Usually you bind to an event on an
  object, like a click handler for a
  button.  Here, I need to attach the
  tab assignment/binding ( using .tabs()
  ) via a live event but I'm not sure
  which one.  I tried binding to the
  document load event but no luck with
  that:

$(document).live('load', bind_tabs);

Any ideas?

Style sheet and Javascript links included on page:

https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

Added the following line to my stylesheet:

.ui-tabs .ui-tabs-hide { display: none; }

Added the following script to the page:

HTML:

Nunc tincidunt

Proin dolor

Aenean lacinia

Tab 1 content

Tab 2 content

Tab 3 content

Also noticed on the "theming" documentation on the page (http://jqueryui.com/demos/tabs/#theming) that it states the following. Should I manually put in all those styles (like ui-widget) or rely on the framework to do it?

Sample markup with jQuery UI CSS
  Framework classes

Nunc tincidunt

Proin dolor

Tab one content goes here.

    ...

Note: This is a sample of markup
  generated by the tabs plugin, not
  markup you should use to create a
  tabs. The only markup needed for that
  is

Nunc tincidunt

Proin dolor

Aenean lacinia

Tab 1 content

Tab 2 content

Tab 3 content


问:
Setup a thirdparty dependency repository on Artifactory
I'm quite new to the JFrog Artifactory, but here is my requirement : I want to resolve my compile dependencies using Artifactory and publish the built artifacts to the Artifactory. Now I use gradle for my build. Also going through the initial tutorial I'm able to publish my artifacts to the repository. However now I want to be able to compile my project using the Artifactory. My project has some thirdparty dependencies lets say commons-logging and antlr. The script that i have is as follows

```<code>artifactory {
    contextUrl = 'http://localhostr:8081/artifactory'   //The base Artifactory URL if not overridden by the publisher/resolver
    publish {
        repository {
            repoKey = 'gradle-dev-local'
            username = "${artifactory_user}"
            password = "${artifactory_password}"
            maven = true

        }
        defaults {
            publications ('mavenJava')
            publishPom = false
        }
    }
    resolve {
        repository {
            repoKey = 'gradle-dev'
            username = "${artifactory_user}"
            password = "${artifactory_password}"
            maven = true
        }
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.web
        }
    }
}

dependencies {
    compile 'antlr:antlr:2.7.6',
    'commons-logging:commons-logging:1.1'
}
</code>```

Now i want to know is how do I have these thirdparty dependecnies in my gradle-dev repository in the gradle format. Altogether my gradle projects use around 40-50 such thirdparties. Is there a simpler way to copy all these dependecnies to my Artifactory ?

Thanks in advance

答:
You will want to setup a remote repository:

https://www.jfrog.com/confluence/display/RTF/Remote+Repositories

Body:
I'm quite new to the JFrog Artifactory, but here is my requirement : I want to resolve my compile dependencies using Artifactory and publish the built artifacts to the Artifactory. Now I use gradle for my build. Also going through the initial tutorial I'm able to publish my artifacts to the repository. However now I want to be able to compile my project using the Artifactory. My project has some thirdparty dependencies lets say commons-logging and antlr. The script that i have is as follows

artifactory {
    contextUrl = 'http://localhostr:8081/artifactory'   //The base Artifactory URL if not overridden by the publisher/resolver
    publish {
        repository {
            repoKey = 'gradle-dev-local'
            username = "${artifactory_user}"
            password = "${artifactory_password}"
            maven = true

        }
        defaults {
            publications ('mavenJava')
            publishPom = false
        }
    }
    resolve {
        repository {
            repoKey = 'gradle-dev'
            username = "${artifactory_user}"
            password = "${artifactory_password}"
            maven = true
        }
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.web
        }
    }
}

dependencies {
    compile 'antlr:antlr:2.7.6',
    'commons-logging:commons-logging:1.1'
}

Now i want to know is how do I have these thirdparty dependecnies in my gradle-dev repository in the gradle format. Altogether my gradle projects use around 40-50 such thirdparties. Is there a simpler way to copy all these dependecnies to my Artifactory ?

Thanks in advance


问:
Allow a function to be called only after a set amount of time has passed
To provide context, here's the problem I'm attempting to solve:

I've made a giphy bot for a casual groupchat with friends of mine. By typing /giphy [terms] in a message, it will automatically post the top result for [terms]. My friends, being the rambunctious assholes that they are, quickly started abusing it to spam the groupchat. What I would like to do to prevent this is only allow my postMessage function to be called once per minute.

What I've tried:

Using setTimeout(), which doesn't do exactly what I'd like, since it will only call the function after the amount of time specified in the argument has passed. As far as I can tell, this will cause a delay in messages from the time the bot is called, but it won't actually prevent the bot from accepting new postMessage() calls in that time.

Using setInterval(), which just causes the function to be called forever at a certain interval.

What I think might work:

Right now, I'm working with two .js files.

Index.js

```<code>var http, director, cool, bot, router, server, port;

http        = require('http');
director    = require('director');
bot         = require('./bot.js');

router = new director.http.Router({
  '/' : {
    post: bot.respond,
    get: ping
  }
});

server = http.createServer(function (req, res) {
  req.chunks = [];
  req.on('data', function (chunk) {
    req.chunks.push(chunk.toString());
  });

  router.dispatch(req, res, function(err) {
    res.writeHead(err.status, {"Content-Type": "text/plain"});
    res.end(err.message);
  });
});

port = Number(process.env.PORT || 5000);
server.listen(port);

function ping() {
  this.res.writeHead(200);
  this.res.end("This is my giphy side project!");
}
</code>```

Bot.js

```<code>var HTTPS = require('https');
var botID = process.env.BOT_ID;
var giphy = require('giphy-api')();

function respond() {
  var request = JSON.parse(this.req.chunks[0]);
  var giphyRegex = /^\/giphy (.*)$/;
  var botMessage = giphyRegex.exec(request.text);
  var offset = Math.floor(Math.random() * 10);

  if(request.text && giphyRegex.test(request.text) && botMessage != null) {
    this.res.writeHead(200);
    giphy.search({
      q: botMessage[1],
      rating: 'pg-13'
    }, function (err, res) {
      try {
        postMessage(res.data[offset].images.downsized.url);
      } catch (err) {
        postMessage("There is no gif of that.");
      }
    });
    this.res.end();
  } else {
    this.res.writeHead(200);
    this.res.end();
  }

function postMessage(phrase) {
  var botResponse, options, body, botReq;
  botResponse = phrase;

  options = {
    hostname: 'api.groupme.com',
    path: '/v3/bots/post',
    method: 'POST'
  };

  body = {
    "bot_id" : botID,
    "text" : botResponse
  };

  botReq = HTTPS.request(options, function(res) {
      if(res.statusCode == 202) {
      } else {
        console.log('Rejecting bad status code: ' + res.statusCode);
      }
  });

  botReq.on('error', function(err) {
    console.log('Error posting message: '  + JSON.stringify(err));
  });

  botReq.on('timeout', function(err) {
    console.log('Timeout posting message: '  + JSON.stringify(err));
  });

  botReq.end(JSON.stringify(body));
}
exports.respond = respond;
</code>```

Basically, I'm wondering where would be the ideal place to implement the timer that I'm envisioning. It seems like I would want to have it only listen for /giphy [terms] after one minute, rather than waiting one minute to post.

My Question(s):

Would the best way to go about this be to set a timer on the response() function, since then it will only actually parse the incoming information once per minute? Is there a more elegant place to put this?

How should the timer work on that function? I don't think I can just run response() once every minute, since that seems to mean it'll only parse incoming json from the GroupMe API once per minute, so it could potentially miss incoming messages that I would want it to capture.

答:
Store the time when a request is made and then use that to see if subsequent requests should be ignored if these are executed to fast.  </p>

```<code>var waitTime = 10*1000; // 10 s in millis
var lastRequestTime = null;
function respond() {
  if(lastRequestTime){
    var now = new Date();
    if(now.getTime() - lastRequestTime.getTime() <= waitTime){
        this.res.writeHead(200);
        this.res.end("You have to wait "+waitTime/1000+" seconds.");
        return;
    }
  }
  lastRequestTime = new Date();
  postMessage();
}
</code>```

Body:
To provide context, here's the problem I'm attempting to solve:

I've made a giphy bot for a casual groupchat with friends of mine. By typing /giphy [terms] in a message, it will automatically post the top result for [terms]. My friends, being the rambunctious assholes that they are, quickly started abusing it to spam the groupchat. What I would like to do to prevent this is only allow my postMessage function to be called once per minute.

What I've tried:

Using setTimeout(), which doesn't do exactly what I'd like, since it will only call the function after the amount of time specified in the argument has passed. As far as I can tell, this will cause a delay in messages from the time the bot is called, but it won't actually prevent the bot from accepting new postMessage() calls in that time.

Using setInterval(), which just causes the function to be called forever at a certain interval.

What I think might work:

Right now, I'm working with two .js files.

Index.js

var http, director, cool, bot, router, server, port;

http        = require('http');
director    = require('director');
bot         = require('./bot.js');

router = new director.http.Router({
  '/' : {
    post: bot.respond,
    get: ping
  }
});

server = http.createServer(function (req, res) {
  req.chunks = [];
  req.on('data', function (chunk) {
    req.chunks.push(chunk.toString());
  });

  router.dispatch(req, res, function(err) {
    res.writeHead(err.status, {"Content-Type": "text/plain"});
    res.end(err.message);
  });
});

port = Number(process.env.PORT || 5000);
server.listen(port);

function ping() {
  this.res.writeHead(200);
  this.res.end("This is my giphy side project!");
}

Bot.js

var HTTPS = require('https');
var botID = process.env.BOT_ID;
var giphy = require('giphy-api')();

function respond() {
  var request = JSON.parse(this.req.chunks[0]);
  var giphyRegex = /^\/giphy (.*)$/;
  var botMessage = giphyRegex.exec(request.text);
  var offset = Math.floor(Math.random() * 10);

  if(request.text && giphyRegex.test(request.text) && botMessage != null) {
    this.res.writeHead(200);
    giphy.search({
      q: botMessage[1],
      rating: 'pg-13'
    }, function (err, res) {
      try {
        postMessage(res.data[offset].images.downsized.url);
      } catch (err) {
        postMessage("There is no gif of that.");
      }
    });
    this.res.end();
  } else {
    this.res.writeHead(200);
    this.res.end();
  }

function postMessage(phrase) {
  var botResponse, options, body, botReq;
  botResponse = phrase;

  options = {
    hostname: 'api.groupme.com',
    path: '/v3/bots/post',
    method: 'POST'
  };

  body = {
    "bot_id" : botID,
    "text" : botResponse
  };

  botReq = HTTPS.request(options, function(res) {
      if(res.statusCode == 202) {
      } else {
        console.log('Rejecting bad status code: ' + res.statusCode);
      }
  });

  botReq.on('error', function(err) {
    console.log('Error posting message: '  + JSON.stringify(err));
  });

  botReq.on('timeout', function(err) {
    console.log('Timeout posting message: '  + JSON.stringify(err));
  });

  botReq.end(JSON.stringify(body));
}
exports.respond = respond;

Basically, I'm wondering where would be the ideal place to implement the timer that I'm envisioning. It seems like I would want to have it only listen for /giphy [terms] after one minute, rather than waiting one minute to post.

My Question(s):

Would the best way to go about this be to set a timer on the response() function, since then it will only actually parse the incoming information once per minute? Is there a more elegant place to put this?

How should the timer work on that function? I don't think I can just run response() once every minute, since that seems to mean it'll only parse incoming json from the GroupMe API once per minute, so it could potentially miss incoming messages that I would want it to capture.

Body:
Store the time when a request is made and then use that to see if subsequent requests should be ignored if these are executed to fast.

var waitTime = 10*1000; // 10 s in millis
var lastRequestTime = null;
function respond() {
  if(lastRequestTime){
    var now = new Date();
    if(now.getTime() - lastRequestTime.getTime() <= waitTime){
        this.res.writeHead(200);
        this.res.end("You have to wait "+waitTime/1000+" seconds.");
        return;
    }
  }
  lastRequestTime = new Date();
  postMessage();
}


问:
nginx server_name regex
server_name in nginx does not match

I want to match with such FQDNs
I came up with

```<code>server_name "~^(www.)?ucwebapi-uccore(\d{0,3})-(\d{0,3})\.testme\.net";
</code>```

To Match

```<code>ucwebapi.testme.net
ucwebapi-uccore.testme.net
ucwebapi-uccore1-0.testme.net
ucwebapi-uccore999-999.testme.net
</code>```

Validated with https://regex101.com/r/tAwEp9/2

Tested with

```<code>server_name "~^(www.)?ucwebapi-uccore(\d{0,3})-(\d{0,3})\.testme\.net ucwebapi1.testme.net";
</code>```

to see if ucwebapi1.testme.de server is reachable at all.

Is there any restriction im not aware of?
Thank you.

答:
Try this:

```<code>server_name "~^(www.)?ucwebapi(-uccore)?(\d{1,3}-\d{1,3})?\.testme\.net";
</code>```

It looks like there are some missing characters between your regex101 page and what ended up in your config.

I've also tuned it a bit so that it will NOT match:

```<code>ucwebapi-uccore999.testme.net
ucwebapi-uccore-.testme.net
ucwebapi-uccore-999.testme.net
</code>```

Title: nginx server_name regex

Body:
server_name in nginx does not match

I want to match with such FQDNs
I came up with

server_name "~^(www.)?ucwebapi-uccore(\d{0,3})-(\d{0,3})\.testme\.net";

To Match

ucwebapi.testme.net
ucwebapi-uccore.testme.net
ucwebapi-uccore1-0.testme.net
ucwebapi-uccore999-999.testme.net

Validated with https://regex101.com/r/tAwEp9/2

Tested with

server_name "~^(www.)?ucwebapi-uccore(\d{0,3})-(\d{0,3})\.testme\.net ucwebapi1.testme.net";

to see if ucwebapi1.testme.de server is reachable at all.

Is there any restriction im not aware of?
Thank you.

Body:
Try this:

server_name "~^(www.)?ucwebapi(-uccore)?(\d{1,3}-\d{1,3})?\.testme\.net";

It looks like there are some missing characters between your regex101 page and what ended up in your config.

I've also tuned it a bit so that it will NOT match:

ucwebapi-uccore999.testme.net
ucwebapi-uccore-.testme.net
ucwebapi-uccore-999.testme.net


问:
Android SwipeRefreshLayout refresh listview with blinks
I have a listview wrapped in a SwipeRefreshLayout. The listview renders very smoothly in anytime I update it with new data. But whenever I pull down SwipeRefreshLayout to get new messages,the listview gives me a blink effect which is negative in terms of user experience. I found nothing useful to fix this issue after searching a lot on the internet.Can any one teach me how to resolve this problem.

Below is part of my code:

```<code>    public void fetchMoreMsgs(){
    sizeOfChatLV=chatLVArray.size();
    if(lvPos==0){
        toast = Toast.makeText(ma,"No more messages",Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
        return;
    }else {
        if(lvPos-fetchStep>=0){
            arrayList = chatLVArray.subList(lvPos-fetchStep, lvPos);
            msgsList.addAll(0, arrayList);
            chatLVArrayAdapter = new ChatLVArrayAdapter(ma, msgsList);
            ma.chatListViewIMP2P.setAdapter(chatLVArrayAdapter);
            ma.chatListViewIMP2P.setSelection(fetchStep);
            lvPos-=fetchStep;
        }else {
            arrayList = chatLVArray.subList(0, lvPos);
            msgsList.addAll(0, arrayList);
            chatLVArrayAdapter = new ChatLVArrayAdapter(ma, msgsList);
            ma.chatListViewIMP2P.setAdapter(chatLVArrayAdapter);
            ma.chatListViewIMP2P.setSelection(lvPos);
            lvPos=0;
        }
    }
}
</code>```

The fetchMoreMsgs method is called when I pull down the listview(wrapped in a SwipeRefreshLayout).Any help is much appreciated!

答:
Whenever you call setAdapter, it completely destroys every view in the ListView and then creates it anew. This is what causes your blinking effect.

Instead, your chatLVArrayAdapter should have a way to updating the underlying list and then you should call your adapter's notifyDataSetChanged() to tell ListView the data has changed.

Body:
I have a listview wrapped in a SwipeRefreshLayout. The listview renders very smoothly in anytime I update it with new data. But whenever I pull down SwipeRefreshLayout to get new messages,the listview gives me a blink effect which is negative in terms of user experience. I found nothing useful to fix this issue after searching a lot on the internet.Can any one teach me how to resolve this problem.

Below is part of my code:

    public void fetchMoreMsgs(){
    sizeOfChatLV=chatLVArray.size();
    if(lvPos==0){
        toast = Toast.makeText(ma,"No more messages",Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
        return;
    }else {
        if(lvPos-fetchStep>=0){
            arrayList = chatLVArray.subList(lvPos-fetchStep, lvPos);
            msgsList.addAll(0, arrayList);
            chatLVArrayAdapter = new ChatLVArrayAdapter(ma, msgsList);
            ma.chatListViewIMP2P.setAdapter(chatLVArrayAdapter);
            ma.chatListViewIMP2P.setSelection(fetchStep);
            lvPos-=fetchStep;
        }else {
            arrayList = chatLVArray.subList(0, lvPos);
            msgsList.addAll(0, arrayList);
            chatLVArrayAdapter = new ChatLVArrayAdapter(ma, msgsList);
            ma.chatListViewIMP2P.setAdapter(chatLVArrayAdapter);
            ma.chatListViewIMP2P.setSelection(lvPos);
            lvPos=0;
        }
    }
}

The fetchMoreMsgs method is called when I pull down the listview(wrapped in a SwipeRefreshLayout).Any help is much appreciated!


问:
android app freezes on activity switch
I've got myself a mediocre game going for myself. It has a main menu activity that when you click play starts a new game play activity. When you lose the game you can either retry or go back to the main menu. the back button on the gameplay activity is just a ractangle with this coding.

```<code>if (GlobalVariables.GAMEOVER && backButton.contains((int)(event.getX()), (int)(event.getY())))
            {
                Intent backButtonIntent = new Intent(context, MainMenuActivity.class);
                context.startActivity(backButtonIntent);
            }
</code>```

The program does not crash and it does switch to the mainmenu activity but it is frozen and no buttons are clickable. and here is the error i get.

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int, android.graphics.PorterDuff$Mode)' on a null object reference
 at android.view.SurfaceView.dispatchDraw(SurfaceView.java:451)
 at android.view.View.draw(View.java:17472)
 at android.view.SurfaceView.draw(SurfaceView.java:442)
 at com.example.jordanschanzenbach.myapplication.GamePanel.draw(GamePanel.java:84)
 at com.example.jordanschanzenbach.myapplication.MainThread.run(MainThread.java:52)
</code>```

here is the code that it is pointing to in the game panel. "super.draw(canvas)"

```<code>public void draw(Canvas canvas)
{
    super.draw(canvas);
    backGround.draw(canvas);
    gameFloor.draw(canvas);
    gamePlayScene.draw(canvas);
}
</code>```

i understand that this is a nullpointerexception and a duplicate question. but i dont understand why when i switch to my main menu activity it is causing this error when the game panel isn't even linked to the main menu activity. Please help a young student :) thank you and if you would like to see any other code i will edit this post immediately.

答:
Check if the thread responsible for calling the draw method was left running before starting another activity. I'm not quite sure but it probably still tries to render on the SurfaceView even if it has already been detached from the window.

Edit:

I was able to replicate your problem. The thread that handles the drawing does not always instantly get the updated value of the variable you use as a while loop condition. You can choose to perform synchronization and/or other threading stuff, but you can simply try to break the while loop like how I did in the code below. Also, try to stop your drawing thread by making your while loop condition false inside the SurfaceHolder.Callback#surfaceDestroyed(SurfaceHolder).

```<code>public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
    private TextPaint paint;
    private volatile boolean isDrawing;
    private DrawingThread drawingThread;

    public GamePanel(Context context) {
        super(context);
        initialize();
    }

    // omitted the other constructors for brevity

    private void initialize() {
        ...
        drawingThread = new DrawingThread();

        // do this so that you can get an surface updates
        getHolder().addCallback(this);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        canvas.drawText("Hello, world", 20, 20, paint);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDrawing = true;
        drawingThread.start();
        // start drawing only after the surface was created
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDrawing = false;
        // try to stop the drawing thread when the surface
        // is destroyed
    }

    private class DrawingThread extends Thread {
        @Override
        public void run() {
            while (isDrawing) {
                try {
                    Canvas canvas = getHolder().lockCanvas();
                    // check if canvas is null just to make sure
                    if (canvas == null) break;
                    draw(canvas);
                    getHolder().unlockCanvasAndPost(canvas);
                } catch (IllegalArgumentException e) {
                    // This is thrown by SurfaceHolder#lockCanvas().
                    // Break when the surface has already been destroyed
                    // but the variable `isDrawing` is still true.
                    break;
                }
            }
        }
    }
}
</code>```

Title: android app freezes on activity switch

Body:
I've got myself a mediocre game going for myself. It has a main menu activity that when you click play starts a new game play activity. When you lose the game you can either retry or go back to the main menu. the back button on the gameplay activity is just a ractangle with this coding.

if (GlobalVariables.GAMEOVER && backButton.contains((int)(event.getX()), (int)(event.getY())))
            {
                Intent backButtonIntent = new Intent(context, MainMenuActivity.class);
                context.startActivity(backButtonIntent);
            }

The program does not crash and it does switch to the mainmenu activity but it is frozen and no buttons are clickable. and here is the error i get.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int, android.graphics.PorterDuff$Mode)' on a null object reference
 at android.view.SurfaceView.dispatchDraw(SurfaceView.java:451)
 at android.view.View.draw(View.java:17472)
 at android.view.SurfaceView.draw(SurfaceView.java:442)
 at com.example.jordanschanzenbach.myapplication.GamePanel.draw(GamePanel.java:84)
 at com.example.jordanschanzenbach.myapplication.MainThread.run(MainThread.java:52)

here is the code that it is pointing to in the game panel. "super.draw(canvas)"

public void draw(Canvas canvas)
{
    super.draw(canvas);
    backGround.draw(canvas);
    gameFloor.draw(canvas);
    gamePlayScene.draw(canvas);
}

i understand that this is a nullpointerexception and a duplicate question. but i dont understand why when i switch to my main menu activity it is causing this error when the game panel isn't even linked to the main menu activity. Please help a young student :) thank you and if you would like to see any other code i will edit this post immediately.

Body:
Check if the thread responsible for calling the draw method was left running before starting another activity. I'm not quite sure but it probably still tries to render on the SurfaceView even if it has already been detached from the window.

Edit:

I was able to replicate your problem. The thread that handles the drawing does not always instantly get the updated value of the variable you use as a while loop condition. You can choose to perform synchronization and/or other threading stuff, but you can simply try to break the while loop like how I did in the code below. Also, try to stop your drawing thread by making your while loop condition false inside the SurfaceHolder.Callback#surfaceDestroyed(SurfaceHolder).

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
    private TextPaint paint;
    private volatile boolean isDrawing;
    private DrawingThread drawingThread;

    public GamePanel(Context context) {
        super(context);
        initialize();
    }

    // omitted the other constructors for brevity

    private void initialize() {
        ...
        drawingThread = new DrawingThread();

        // do this so that you can get an surface updates
        getHolder().addCallback(this);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        canvas.drawText("Hello, world", 20, 20, paint);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDrawing = true;
        drawingThread.start();
        // start drawing only after the surface was created
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDrawing = false;
        // try to stop the drawing thread when the surface
        // is destroyed
    }

    private class DrawingThread extends Thread {
        @Override
        public void run() {
            while (isDrawing) {
                try {
                    Canvas canvas = getHolder().lockCanvas();
                    // check if canvas is null just to make sure
                    if (canvas == null) break;
                    draw(canvas);
                    getHolder().unlockCanvasAndPost(canvas);
                } catch (IllegalArgumentException e) {
                    // This is thrown by SurfaceHolder#lockCanvas().
                    // Break when the surface has already been destroyed
                    // but the variable `isDrawing` is still true.
                    break;
                }
            }
        }
    }
}


问:
A dynamically resizing shiny textAreaInput box?
I am trying to make a textAreaInput box in shiny that spans 100% of my webpage and resizes when the browser is min/maximised. I can make a simple textInput with this behavior by supplying the argument width = 100%. Supplying the same argument to textAreaInput does not produce the same behavior even though width has the same description on the textInput and textAreaInput man pages. Is this desired behavour or a bug?

A minimal working example -

```<code>library(shiny)

shinyApp(
    #UI
    ui = fluidPage(
        fluidRow(
            column(12,
                textAreaInput("big_box", "Big box", value = "", width = '100%', rows = 5, resize = "both")
            )
        ),
        fluidRow(
            column(12,
                textInput("long_box", "Long box", value = "", width = '100%')
            )
        )
    ),
    #Server
    server = function(input, output) {
    }
)
</code>```

Example output -

Cheers

答:
Or you could just override the css by using a header tag within your ui function e.g:</p>

```<code>tags$style(HTML("
  .shiny-input-container:not(.shiny-input-container-inline) {
  width: 100%;
}"))
</code>```

Body:
I am trying to make a textAreaInput box in shiny that spans 100% of my webpage and resizes when the browser is min/maximised. I can make a simple textInput with this behavior by supplying the argument width = 100%. Supplying the same argument to textAreaInput does not produce the same behavior even though width has the same description on the textInput and textAreaInput man pages. Is this desired behavour or a bug?

A minimal working example -

library(shiny)

shinyApp(
    #UI
    ui = fluidPage(
        fluidRow(
            column(12,
                textAreaInput("big_box", "Big box", value = "", width = '100%', rows = 5, resize = "both")
            )
        ),
        fluidRow(
            column(12,
                textInput("long_box", "Long box", value = "", width = '100%')
            )
        )
    ),
    #Server
    server = function(input, output) {
    }
)

Example output -

Cheers

Body:
Or you could just override the css by using a header tag within your ui function e.g:

tags$style(HTML("
  .shiny-input-container:not(.shiny-input-container-inline) {
  width: 100%;
}"))


答:
Try to use the default String class reverse method like this:

```<code>"Hello World".reverse
"Hello World".reverse!
</code>```

Check Ruby's String class API at https://ruby-doc.org/core-2.4.0/String.html

If you want to make your custom method, you could use a map like this:

```<code>string = String.new
"Hello World".chars.each { | c | string.prepend c }
</code>```

Title: Does anyone see the error in this simple Ruby function?

Body:
Try to use the default String class reverse method like this:

"Hello World".reverse
"Hello World".reverse!

Check Ruby's String class API at https://ruby-doc.org/core-2.4.0/String.html

If you want to make your custom method, you could use a map like this:

string = String.new
"Hello World".chars.each { | c | string.prepend c }


问:
Authentication failed! Facebook returned an invalid user id
I am using a module on opencart 2.0.1.1 named Social Login Free and using facebook-php-3.2 Login with facebook was working correctly but now when a user clicks on login with facebook it takes it correctly to the
facebook oath login dialog and when user clicks continue it returns this error
Authentification failed. The user has canceled the authentication or the provider refused the connection. Ooophs, we got an error: Authentication failed! Facebook returned an invalid user id.  I have tried several solutions but failed.

```<code>  public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 60,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-3.2',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
  );

protected $trustForwarded = true;
protected $allowSignedRequest = false;
</code>```

Nothing is working please help.

Update :

It is not a duplicate as in my case I had to upgrade facebook-php-sdk to v5 and it solved my problem! tada...

答:
Facebook upgraded api graph version from 2.2 to 2.3 what i did read so far is that the access token is now different than before and json encoded. The change did happen on 03.25.2017 I have the same problem with hybridauth but no idea how to solve. I hope that helps.

facebook graph api not work from 2.2 to 2.3

Body:
I am using a module on opencart 2.0.1.1 named Social Login Free and using facebook-php-3.2 Login with facebook was working correctly but now when a user clicks on login with facebook it takes it correctly to the
facebook oath login dialog and when user clicks continue it returns this error
Authentification failed. The user has canceled the authentication or the provider refused the connection. Ooophs, we got an error: Authentication failed! Facebook returned an invalid user id.  I have tried several solutions but failed.

  public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 60,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-3.2',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
  );

protected $trustForwarded = true;
protected $allowSignedRequest = false;

Nothing is working please help.

Update :

It is not a duplicate as in my case I had to upgrade facebook-php-sdk to v5 and it solved my problem! tada...


问:
Configuring Spring Boot with Spring-Cloud-Connectors to use the PWS Config-Server
I am having a hard time to configure my Spring Boot application to connect to the PWS (Pivotal Web Services) provided Config-Server via Spring-Cloud-Connectors.

In the manifest.yml the config server is bound to the application, which is correctly reflected by the corresponding, VCAP_SERVICES entry:

```<code>applications:
- name: edge-service-webapp-myapp
  services:
  - infrastructure-config-server
  memory: 512M
  env:
    TRUST_CERTS: api.run.pivotal.io
    SPRING_PROFILES_DEFAULT: cloud
  instances: 1
  host: edge-service-webapp-myapp
  domain: cfapps.io
  buildpack: java_buildpack

{
 "VCAP_SERVICES": {
  "p-config-server": [
   {
    "credentials": {
     "access_token_uri": "https://p-spring-cloud-services.uaa.run.pivotal.io/oauth/token",
     "client_id": "p-config-server-84d66ea6-ebc6-xxx",
     "client_secret": "***",
     "uri": "https://config-b4320676-xxx.cfapps.io"
    }, ...
}
</code>```

The application is build with spring-boot-starter-parent 1.5.2.RELEASE, spring-cloud-dependencies Camden.SR5 and spring-cloud-services-dependencies 1.4.1.RELEASE. Also I am using spring-cloud-starter-config and spring-boot-starter-cloud-connectors as explicit dependencies.

```<code><dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.pivotal.spring.cloud</groupId>
                <artifactId>spring-cloud-services-dependencies</artifactId>
                <version>1.4.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
             ....
        </dependencies>
    </dependencyManagement>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
       ...
</code>```

When I curl the config server I can see the application version available for the application-name (my-app) and the active 'cloud' profile.

```<code>spring:
  application:
    name: my-app
  cloud:
    config:
      enabled: true

curl -H "Authorization: Bearer XXX" https://config-b4320676-xxx.cfapps.io/tradefoundry/cloud
{"name":"my-app","profiles":["cloud"],"label":"master","version":"389e4f909ff1303332167b2159b4d75201109d69","state":null,"propertySources":[{"name":"https://gitlab.com/myapp/configuration.git/myapp-cloud.properties","source":{"spring.thymeleaf.cache":"true","message":"Hello Cloud!"}},{"name":"https://gitlab.com/myapp/configuration.git/myapp.properties","source":{"server.compression.enabled":"true","spring.thymeleaf.cache":"true","application.version":"0.0.1"}},{"name":"https://gitlab.com/myapp/configuration.git/application.properties","source":{"server.compression.enabled":"true","spring.thymeleaf.cache":"true","application.cache.busting.enabled":"false","application.version":"0.0.1-20170202195700","server.compression.mime-types":"application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript"}}]}
</code>```

But still the application fails at startup, complaining about the missing property application.version.

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myWebappApplication': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'application.version' in value "${application.version}"
</code>```

What am I missing here? I thought the cloud connectors were all plug-and-play through autoconfiguration!?

Any help is welcome!

答:
To use the Spring Cloud Services config server provided on PWS, you need to use a different set of client libraries as shown in the PWS docs.

Replace the dependencies on spring-boot-starter-cloud-connectors and spring-cloud-starter-config with just this one dependency:

```<code><dependency>
  <groupId>io.pivotal.spring.cloud</groupId>
  <artifactId>spring-cloud-services-starter-config-client</artifactId>
</dependency>
</code>```

The Spring Cloud Services config server adds additional OAuth2-based security on top of the open-source Spring Cloud Config server. This client-side library does the OAuth negotiation automatically.

Body:
I am having a hard time to configure my Spring Boot application to connect to the PWS (Pivotal Web Services) provided Config-Server via Spring-Cloud-Connectors.

In the manifest.yml the config server is bound to the application, which is correctly reflected by the corresponding, VCAP_SERVICES entry:

applications:
- name: edge-service-webapp-myapp
  services:
  - infrastructure-config-server
  memory: 512M
  env:
    TRUST_CERTS: api.run.pivotal.io
    SPRING_PROFILES_DEFAULT: cloud
  instances: 1
  host: edge-service-webapp-myapp
  domain: cfapps.io
  buildpack: java_buildpack

{
 "VCAP_SERVICES": {
  "p-config-server": [
   {
    "credentials": {
     "access_token_uri": "https://p-spring-cloud-services.uaa.run.pivotal.io/oauth/token",
     "client_id": "p-config-server-84d66ea6-ebc6-xxx",
     "client_secret": "***",
     "uri": "https://config-b4320676-xxx.cfapps.io"
    }, ...
}

The application is build with spring-boot-starter-parent 1.5.2.RELEASE, spring-cloud-dependencies Camden.SR5 and spring-cloud-services-dependencies 1.4.1.RELEASE. Also I am using spring-cloud-starter-config and spring-boot-starter-cloud-connectors as explicit dependencies.

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.pivotal.spring.cloud</groupId>
                <artifactId>spring-cloud-services-dependencies</artifactId>
                <version>1.4.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
             ....
        </dependencies>
    </dependencyManagement>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
       ...

When I curl the config server I can see the application version available for the application-name (my-app) and the active 'cloud' profile.

spring:
  application:
    name: my-app
  cloud:
    config:
      enabled: true

curl -H "Authorization: Bearer XXX" https://config-b4320676-xxx.cfapps.io/tradefoundry/cloud
{"name":"my-app","profiles":["cloud"],"label":"master","version":"389e4f909ff1303332167b2159b4d75201109d69","state":null,"propertySources":[{"name":"https://gitlab.com/myapp/configuration.git/myapp-cloud.properties","source":{"spring.thymeleaf.cache":"true","message":"Hello Cloud!"}},{"name":"https://gitlab.com/myapp/configuration.git/myapp.properties","source":{"server.compression.enabled":"true","spring.thymeleaf.cache":"true","application.version":"0.0.1"}},{"name":"https://gitlab.com/myapp/configuration.git/application.properties","source":{"server.compression.enabled":"true","spring.thymeleaf.cache":"true","application.cache.busting.enabled":"false","application.version":"0.0.1-20170202195700","server.compression.mime-types":"application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript"}}]}

But still the application fails at startup, complaining about the missing property application.version.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myWebappApplication': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'application.version' in value "${application.version}"

What am I missing here? I thought the cloud connectors were all plug-and-play through autoconfiguration!?

Any help is welcome!

Body:
To use the Spring Cloud Services config server provided on PWS, you need to use a different set of client libraries as shown in the PWS docs.

Replace the dependencies on spring-boot-starter-cloud-connectors and spring-cloud-starter-config with just this one dependency:

<dependency>
  <groupId>io.pivotal.spring.cloud</groupId>
  <artifactId>spring-cloud-services-starter-config-client</artifactId>
</dependency>

The Spring Cloud Services config server adds additional OAuth2-based security on top of the open-source Spring Cloud Config server. This client-side library does the OAuth negotiation automatically.


问:
How to set margin programmatically in android for a textview inside linearlayout?
I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.</p>

```<code>import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ScrollView mainScrollView;
    LinearLayout scrollViewContainer;
    ArrayList<String> stringArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
        scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);

        stringArr = new ArrayList<String>();
        String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
                "The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
        String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
                "in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
                " use of this constructor is unnecessary since Strings are immutable.";

        for(int ii = 0; ii < 10; ii++){
            if(ii%2 ==  0) {
                stringArr.add(str1);
            }else{
                stringArr.add(str2);
            }
        }
        Resources r = getResources();
        float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
        float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int ii = 0; ii < stringArr.size(); ii++){
            TextView textView = new TextView(this);
            textView.setTextSize(12f);
            textView.setText(stringArr.get(ii));
            textView.setLayoutParams(textViewLayoutParams);
            textViewLayoutParams.setMargins(10,30,10,30);
            textView.requestLayout();
            scrollViewContainer.addView(textView);
        }

    }
}
</code>```

答: You are using LinearLayout so try to use  LinearLayout.LayoutParams</p>

Body:
I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ScrollView mainScrollView;
    LinearLayout scrollViewContainer;
    ArrayList<String> stringArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
        scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);

        stringArr = new ArrayList<String>();
        String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
                "The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
        String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
                "in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
                " use of this constructor is unnecessary since Strings are immutable.";

        for(int ii = 0; ii < 10; ii++){
            if(ii%2 ==  0) {
                stringArr.add(str1);
            }else{
                stringArr.add(str2);
            }
        }
        Resources r = getResources();
        float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
        float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int ii = 0; ii < stringArr.size(); ii++){
            TextView textView = new TextView(this);
            textView.setTextSize(12f);
            textView.setText(stringArr.get(ii));
            textView.setLayoutParams(textViewLayoutParams);
            textViewLayoutParams.setMargins(10,30,10,30);
            textView.requestLayout();
            scrollViewContainer.addView(textView);
        }

    }
}


问:
Property Sheet (.prop) : how to refactor its filename and not break VS project?
If I rename a property sheet, the text of the property sheet will be changed.

However, the filename of property sheet will not be changed.

How to make the filename change along with the text automatically?

Example

First, I create foo worksheet.

It will be saved as foo.props.

After that, I think foo is not a suitable name, so I rename foo to bar in the project manager :-

(left to right)

However, foo.props-file will still be there, not renamed into bar.props automatically :-

Thus, when I want to add bar to any configuration, my eyes have to search for foo.props in system folder.  (Actually, I should search for bar.props.)

This is error-prone.

The inconsistency makes me nervous.

My workaround

Whenever I rename it, I have to delete the old foo.props in Window Explorer manually, then save the bar worksheet as a new bar.props manually.

However, others work-sheet reference in my projects will be broken.

I will have to add bar.props to all related configuration of all related project again, otherwise the project will be invalid (unloadable) : can't find foo.props.

Question

Are there any better workflow?  What is it?

答: The best workflow is to set the right name from the very beginning. </p>


问:
Need help solving C++ boost compilation error
I am trying to build a sample C++ Circular buffer code but keep running into the issue of declaration of anonymous class must be a definition
The sad part is that I was able to run this code earlier on my Mac but can't do so now, can you suggest can be done to find the root cause.

Compilation

```<code>g++ temp.cpp
In file included from temp.cpp:1:
In file included from /usr/local/include/boost/circular_buffer.hpp:55:
/usr/local/include/boost/circular_buffer/base.hpp:72:1: error: declaration of anonymous class must be a definition
class <int>
^
temp.cpp:9:35: error: implicit instantiation of undefined template 'boost::circular_buffer<int, std::__1::allocator<int> >'
      boost::circular_buffer<int> cb(3);
                                  ^
/usr/local/include/boost/circular_buffer_fwd.hpp:34:7: note: template is declared here
class circular_buffer;
      ^
2 errors generated.
</code>```

CODE

```<code>   #include <boost/circular_buffer.hpp>
   #include <numeric>
   #include <assert.h>

    int main(int /*argc*/, char* /*argv*/[])
   {
      // create a circular buffer of capacity 3
      boost::circular_buffer<int> cb(3);

      // insert some elements into the circular buffer
      cb.push_back(1);
      cb.push_back(2);

      // assertions
      assert(cb[0] == 1);
      assert(cb[1] == 2);
      assert(!cb.full());
      assert(cb.size() == 2);
      assert(cb.capacity() == 3);

      // insert some other elements
      cb.push_back(3);
      cb.push_back(4);

      // evaluate the sum
      int sum = std::accumulate(cb.begin(), cb.end(), 0);

      // assertions
      assert(cb[0] == 2);
      assert(cb[1] == 3);
      assert(cb[2] == 4);
      assert(*cb.begin() == 2);
      assert(cb.front() == 2);
      assert(cb.back() == 4);
      assert(sum == 9);
      assert(cb.full());
      assert(cb.size() == 3);
      assert(cb.capacity() == 3);

      return 0;
   }
</code>```

G++ Version

```<code>g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
</code>```

Boost Version is 1.63.0

=============== SOLVED ====================

答:
It seems that for some reason the definition

```<code>template <class T, class Alloc>
class circular_buffer                          // circular_buffer/base.hpp line 72
/*! \cond */
#if BOOST_CB_ENABLE_DEBUG
: public cb_details::debug_iterator_registry
#endif
/*! \endcond */
{ /* ... */ };
</code>```

is corrupted. Presumably, you have some macros defined, such as

```<code>#define circular_buffer <int>
</code>```

Body:
I am trying to build a sample C++ Circular buffer code but keep running into the issue of declaration of anonymous class must be a definition
The sad part is that I was able to run this code earlier on my Mac but can't do so now, can you suggest can be done to find the root cause.

Compilation

g++ temp.cpp
In file included from temp.cpp:1:
In file included from /usr/local/include/boost/circular_buffer.hpp:55:
/usr/local/include/boost/circular_buffer/base.hpp:72:1: error: declaration of anonymous class must be a definition
class <int>
^
temp.cpp:9:35: error: implicit instantiation of undefined template 'boost::circular_buffer<int, std::__1::allocator<int> >'
      boost::circular_buffer<int> cb(3);
                                  ^
/usr/local/include/boost/circular_buffer_fwd.hpp:34:7: note: template is declared here
class circular_buffer;
      ^
2 errors generated.

CODE

   #include <boost/circular_buffer.hpp>
   #include <numeric>
   #include <assert.h>

    int main(int /*argc*/, char* /*argv*/[])
   {
      // create a circular buffer of capacity 3
      boost::circular_buffer<int> cb(3);

      // insert some elements into the circular buffer
      cb.push_back(1);
      cb.push_back(2);

      // assertions
      assert(cb[0] == 1);
      assert(cb[1] == 2);
      assert(!cb.full());
      assert(cb.size() == 2);
      assert(cb.capacity() == 3);

      // insert some other elements
      cb.push_back(3);
      cb.push_back(4);

      // evaluate the sum
      int sum = std::accumulate(cb.begin(), cb.end(), 0);

      // assertions
      assert(cb[0] == 2);
      assert(cb[1] == 3);
      assert(cb[2] == 4);
      assert(*cb.begin() == 2);
      assert(cb.front() == 2);
      assert(cb.back() == 4);
      assert(sum == 9);
      assert(cb.full());
      assert(cb.size() == 3);
      assert(cb.capacity() == 3);

      return 0;
   }

G++ Version

g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Boost Version is 1.63.0

=============== SOLVED ====================

Body:
It seems that for some reason the definition

template <class T, class Alloc>
class circular_buffer                          // circular_buffer/base.hpp line 72
/*! \cond */
#if BOOST_CB_ENABLE_DEBUG
: public cb_details::debug_iterator_registry
#endif
/*! \endcond */
{ /* ... */ };

is corrupted. Presumably, you have some macros defined, such as

#define circular_buffer <int>


问:
GraphView Android, How to change thickness of original x-axis and y-axis?
I am using the GraphView library for drawing graphs in an Android app and I am very pleased with the library so far. I am using it in a fixed frame realtime scenario and have noticed that the x-axis and y-axis grid lines are thicker thatn the other unit grid lines. Is there any way I can make them similar to the other lines?

```<code>GraphView graph = (GraphView) cardView.findViewById(R.id.graph);

// Set manual X bounds
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(40);

// Set manual Y bounds
graph.getViewport().setYAxisBoundsManual(true);
graph.getViewport().setMinY(-40);
graph.getViewport().setMaxY(60);

// Draw a border between between labels and viewport
graph.getViewport().setDrawBorder(false);

graph.getGridLabelRenderer().setHumanRounding(false);
graph.getGridLabelRenderer().setNumHorizontalLabels(11);
graph.getGridLabelRenderer().setNumVerticalLabels(6);
</code>```

Basically I would like to change this:

to this:

Thanks in advance!

答:
There is a setHighlightZeroLines method for the GridLabelRenderer class that is true by default. Code something like:

graphView.getGridLabelRenderer().setHighlightZeroLines(false);

should do what you want.

Body:
I am using the GraphView library for drawing graphs in an Android app and I am very pleased with the library so far. I am using it in a fixed frame realtime scenario and have noticed that the x-axis and y-axis grid lines are thicker thatn the other unit grid lines. Is there any way I can make them similar to the other lines?

GraphView graph = (GraphView) cardView.findViewById(R.id.graph);

// Set manual X bounds
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(40);

// Set manual Y bounds
graph.getViewport().setYAxisBoundsManual(true);
graph.getViewport().setMinY(-40);
graph.getViewport().setMaxY(60);

// Draw a border between between labels and viewport
graph.getViewport().setDrawBorder(false);

graph.getGridLabelRenderer().setHumanRounding(false);
graph.getGridLabelRenderer().setNumHorizontalLabels(11);
graph.getGridLabelRenderer().setNumVerticalLabels(6);

Basically I would like to change this:

to this:

Thanks in advance!


问:
Regex - Find Name With No Middle Initial
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

答:
You can make a rather simple one:</p>

```<code>^([A-Za-z]+) ([A-Za-z]+)$
</code>```

Body:
You can make a rather simple one:

^([A-Za-z]+) ([A-Za-z]+)$


答:
```<code>`<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:background="#fff"
 tools:context="com.example.sheheryar.quicktransport.Signin">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="false">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"            >

        <ImageView
            android:layout_width="250dp"
            android:layout_height="155dp"
            android:id="@+id/imageView2"
            android:background="@drawable/logo1"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal" />

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40px">
            <EditText
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:textSize="15dp"
                android:inputType="textEmailAddress"
                android:ems="10"
                android:id="@+id/editTextemail"
                android:hint="Enter email"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp">
            <EditText
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:textSize="15dp"
                android:inputType="textPassword"
                android:ems="10"
                android:id="@+id/editTextpassword"
                android:hint="Password"/>
        </android.support.design.widget.TextInputLayout>

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Remember Password"
            android:textColor="#6b6b6b"
            android:id="@+id/cbRemberPassword"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:checked="false" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Sign in"
            android:id="@+id/buttonsigin"
            android:textColor="#ffffff"
            android:onClick="userlogin"
            android:background="@drawable/button_styles1"
            android:layout_marginTop="20dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OR"
            android:id="@+id/textView1"
            android:textColor="#f99906"
            android:textStyle="bold"
            android:textSize="18dp"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Create New Account"
            android:id="@+id/textView"
            android:textColor="#6b6b6b"
            android:textSize="18dp"
            android:layout_marginTop="5dp"
            android:layout_gravity="center_horizontal" />

    </LinearLayout>
  </ScrollView>

</RelativeLayout>`
</code>```

Check in XML file. Under resources > layouts. Set the margins.
Maybe this can help.

Title: How to set margin programmatically in android for a textview inside linearlayout?

Body:
`<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:background="#fff"
 tools:context="com.example.sheheryar.quicktransport.Signin">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="false">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"            >

        <ImageView
            android:layout_width="250dp"
            android:layout_height="155dp"
            android:id="@+id/imageView2"
            android:background="@drawable/logo1"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal" />

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40px">
            <EditText
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:textSize="15dp"
                android:inputType="textEmailAddress"
                android:ems="10"
                android:id="@+id/editTextemail"
                android:hint="Enter email"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp">
            <EditText
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:textSize="15dp"
                android:inputType="textPassword"
                android:ems="10"
                android:id="@+id/editTextpassword"
                android:hint="Password"/>
        </android.support.design.widget.TextInputLayout>

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Remember Password"
            android:textColor="#6b6b6b"
            android:id="@+id/cbRemberPassword"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:checked="false" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Sign in"
            android:id="@+id/buttonsigin"
            android:textColor="#ffffff"
            android:onClick="userlogin"
            android:background="@drawable/button_styles1"
            android:layout_marginTop="20dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OR"
            android:id="@+id/textView1"
            android:textColor="#f99906"
            android:textStyle="bold"
            android:textSize="18dp"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Create New Account"
            android:id="@+id/textView"
            android:textColor="#6b6b6b"
            android:textSize="18dp"
            android:layout_marginTop="5dp"
            android:layout_gravity="center_horizontal" />

    </LinearLayout>
  </ScrollView>

</RelativeLayout>`

Check in XML file. Under resources > layouts. Set the margins.
Maybe this can help.


问:
Scroll Positioning for Overflow Container
How to set (horizontal) scroll position of overflow container?

JsFiddle:

http://jsfiddle.net/JeaffreyGilbert/FVrtx/

Preview:

答: container.scrollLeft = 1000;

Body: container.scrollLeft = 1000;


问:
What is the proper syntax to combine text with HTML?
I have a C# foreach loop with the following:

```<code>lblCheckedNodes.Text += node.Text + "&#x25BA< br />";
</code>```

That displays like this: myCheckedNodeText►
 .  Which shows the line break characters instead of actually doing the line break, but if I do:

```<code>lblCheckedNodes.Text += node.Text + "<br />";
</code>```

the line return works, but i can't seem to get both working.

答:
Missing Semicolon in HTML Entity

HTML entities like &#x25BA require a trailing semicolon to indicate the end of the entity itself, so you need to ensure that is present:

```<code>lblCheckedNodes.Text += node.Text + "►<br />";
</code>```

Consider a StringBuilder

As mentioned in the comments, if you are continually concatenating strings together, you may be better off using the StringBuilder class, which is far more efficient at handling that type of activity:

```<code>StringBuilder nodes = new StringBuilder("");
// Build your strings here
foreach (var node in nodes)
{
     // You have a few options for concatenation here
     // Basic Concatenation -> nodes.Append(node.Text + " ► <br />");
     // String.Format() -> nodes.Append(String.Format("{0} ► <br />", node.Text));
     // String Iterpolation (seen below)
     nodes.Append($"{node.Text} ► <br />");
}
// Set your label content
lblCheckedNodes.Text = nodes.ToString();
</code>```

Body:
I have a C# foreach loop with the following:

lblCheckedNodes.Text += node.Text + "&#x25BA
";

That displays like this: myCheckedNodeText►
 .  Which shows the line break characters instead of actually doing the line break, but if I do:

lblCheckedNodes.Text += node.Text + "
";

the line return works, but i can't seem to get both working.

Body:
Missing Semicolon in HTML Entity

HTML entities like &#x25BA require a trailing semicolon to indicate the end of the entity itself, so you need to ensure that is present:

lblCheckedNodes.Text += node.Text + "&#x25BA;<br />";

Consider a StringBuilder

As mentioned in the comments, if you are continually concatenating strings together, you may be better off using the StringBuilder class, which is far more efficient at handling that type of activity:

StringBuilder nodes = new StringBuilder("");
// Build your strings here
foreach (var node in nodes)
{
     // You have a few options for concatenation here
     // Basic Concatenation -> nodes.Append(node.Text + " &#x25BA; <br />");
     // String.Format() -> nodes.Append(String.Format("{0} &#x25BA; <br />", node.Text));
     // String Iterpolation (seen below)
     nodes.Append($"{node.Text} &#x25BA; <br />");
}
// Set your label content
lblCheckedNodes.Text = nodes.ToString();


问:
Max pool operation in Matlab?
Is there a function that allows to compute a 2d max-pooling with predefined, kernel size and window stride in Matlab?

I was looking around but couldn't find anything so far...

Say I have a 3D cube of data [HxWxC], I'd like to run a 2d max-pooling on every channel separately (similar to the max-pool operation known from neural networks).

A similar opencv function would also help me out...

答:
I ended up using matconvnet</p>

```<code>k = 3; % kernel_size
p = 1; % padding size
data_pooled = vl_nnpool(single(data),[k,k],'Pad',[p,p,p,p]);
</code>```

Title: Max pool operation in Matlab?

Body:
I ended up using matconvnet

k = 3; % kernel_size
p = 1; % padding size
data_pooled = vl_nnpool(single(data),[k,k],'Pad',[p,p,p,p]);


问:
Double integral of objective function
I want to evaluate the double integral of my objective function (named myfunction, see below) using the build-in-function integral2.

I have tried to run this script;

```<code>f = @(r,theta) myfunction(r,theta);
integral2(f,0,2,0,2*pi);
</code>```

where myfunction is the following function:

```<code>function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
los(:,1)=x;
los(:,2)=y;
norm = (sum( sqrt( los(:,1).^2 + los(:,2).^2)));
fkt=norm*r;
end
</code>```

I am making the integral in polar coordinates, that why  fkt=norm*r.

Matlab gives me the following error message:

```<code>>> untitled2
Subscripted assignment dimension mismatch.

Error in myfunction (line 8)
los(:,1)=x;
</code>```

I can't figure out, what the problem is.

答:
There are two things that can be improved:

los is undefined

los(:,1) is a column while x is a row, so the assignment has to fail.

You can correct this by defining los and change your assignment. For instance:

```<code>los = NaN(numel(r), 2);
los(:,1) = x';
los(:,2) = y';
</code>```

But, why do you need the variable los? Just remove it and the error will be gone:

```<code>function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
norm = (sum( sqrt(x.^2 + y.^2)));
fkt=norm*r;
end
</code>```

Best,

Title: Double integral of objective function

Body:
I want to evaluate the double integral of my objective function (named myfunction, see below) using the build-in-function integral2.

I have tried to run this script;

f = @(r,theta) myfunction(r,theta);
integral2(f,0,2,0,2*pi);

where myfunction is the following function:

function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
los(:,1)=x;
los(:,2)=y;
norm = (sum( sqrt( los(:,1).^2 + los(:,2).^2)));
fkt=norm*r;
end

I am making the integral in polar coordinates, that why  fkt=norm*r.

Matlab gives me the following error message:

>> untitled2
Subscripted assignment dimension mismatch.

Error in myfunction (line 8)
los(:,1)=x;

I can't figure out, what the problem is.

Body:
There are two things that can be improved:

los is undefined

los(:,1) is a column while x is a row, so the assignment has to fail.

You can correct this by defining los and change your assignment. For instance:

los = NaN(numel(r), 2);
los(:,1) = x';
los(:,2) = y';

But, why do you need the variable los? Just remove it and the error will be gone:

function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
norm = (sum( sqrt(x.^2 + y.^2)));
fkt=norm*r;
end

Best,


问:
Set div width using D3
I created a div in my html,

```<code><div id="search"></div>
</code>```

I want to set its width to 15% of my window width in my Javascript. I'm attempting to use D3 to do this:

```<code>var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .attr("width", width)
                    .attr("height", height);
</code>```

I can see in the DOM, the width and height of my div has been changed:

However, in the rendered html the div is just 10px x 10px.

Why does this happen? I do not have any CSS that overwrites the size of the div. How do I set my div to my desired width?

答:
You can simply do the following when you want to set multiple style attributes instead of repeating style(" ", " ") n times:

```<code>d3.select("#search").style({
  'height': height+'px',
  'width': width+'px'
});
</code>```

Hope that helps.

Title: Set div width using D3

Body:
I created a div in my html,

I want to set its width to 15% of my window width in my Javascript. I'm attempting to use D3 to do this:

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .attr("width", width)
                    .attr("height", height);

I can see in the DOM, the width and height of my div has been changed:

However, in the rendered html the div is just 10px x 10px.

Why does this happen? I do not have any CSS that overwrites the size of the div. How do I set my div to my desired width?

Body:
You can simply do the following when you want to set multiple style attributes instead of repeating style(" ", " ") n times:

d3.select("#search").style({
  'height': height+'px',
  'width': width+'px'
});

Hope that helps.


问:
Batch rename and compress (combining separate working commands- .ps1 & .bat)
I figured out how to batch-rename files in a directory to my liking using powershell:

```<code>dir | rename-item -NewName {$_.name -replace "\s\((.*)",$_.extension}
</code>```

I also figured out how to batch-compress each file using the command prompt:

```<code>for %%X in (*.*) do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%X.zip" "%%X"
</code>```

I'd like to combine these two operations in a single .ps1 or .bat but am unsure how to proceed. (i.e. rename, then compress each file individually).

答:
I have this archiving command from Powershell, try to insert it in the example  above</p>

```<code>& "C:\Program Files\7-Zip\7z.exe" a -tzip "d:\1.zip" "C:\Program Files\7-Zip\readme.txt"
</code>```

Body:
I figured out how to batch-rename files in a directory to my liking using powershell:

dir | rename-item -NewName {$_.name -replace "\s\((.*)",$_.extension}

I also figured out how to batch-compress each file using the command prompt:

for %%X in (*.*) do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%X.zip" "%%X"

I'd like to combine these two operations in a single .ps1 or .bat but am unsure how to proceed. (i.e. rename, then compress each file individually).

Body:
I have this archiving command from Powershell, try to insert it in the example  above

& "C:\Program Files\7-Zip\7z.exe" a -tzip "d:\1.zip" "C:\Program Files\7-Zip\readme.txt"


问:
Best way to store large data in mysql
I need to store large amount of data every hour in the database. What kind of data? Text data.

What is the best way? Store on multiple table or 1 large table?

Edit: I just said, large text data. 10000 times the word "data"

Every hour a new line is added like:
hour - data

Edit 2: Just because you can't understood the question, and also i said, "EVERY HOUR", so you imagine every hour for the next 10 years a new line will be created, does not mean its not a readable question.

答:
MySql have added many feature in MySql 5.7. Now you can do it in many way.

Oracle like Big Data is now Integrating in MySQL.

MySql have Unlocked New Big Data Insights with MySQL & Hadoop.

Soluation 1: You can use MySQL as a Document Store. There are possible to store many many object as JSON. It highly recommended and Extendable.

MySQL Document Store = (MySql + NoSql).

X Dev API will help to produce JSON with SQL and CRUD operation over X
  Protocol. Also there is possible to maintain X Session.

It will be best for transparent data sanding and sharing for chat application or group Application.

Soluation 2: MySql Sysbench: Read Only is another best solution. It will be very very fast and scalable to make group chat Application.

Soluation 3: Use MySql 5.7 : InnoDB, NoSql with Memcached API which will interact directly with storage engine InnoDB. It is 6X faster than MySql 5.6.

Still Now FaceBook is using this technology. Because it is very fast.

For more details:

```<code>https://www.mysql.com/news-and-events/web-seminars/introducing-mysql-document-store/
https://dev.mysql.com/doc/refman/5.7/en/document-store-setting-up.html
About Big Data: https://www.oracle.com/big-data/index.html
https://www.youtube.com/watch?v=1Dk517M-_7o
</code>```

Title: Best way to store large data in mysql

Body:
MySql have added many feature in MySql 5.7. Now you can do it in many way.

Oracle like Big Data is now Integrating in MySQL.

MySql have Unlocked New Big Data Insights with MySQL & Hadoop.

Soluation 1: You can use MySQL as a Document Store. There are possible to store many many object as JSON. It highly recommended and Extendable.

MySQL Document Store = (MySql + NoSql).

X Dev API will help to produce JSON with SQL and CRUD operation over X
  Protocol. Also there is possible to maintain X Session.

It will be best for transparent data sanding and sharing for chat application or group Application.

Soluation 2: MySql Sysbench: Read Only is another best solution. It will be very very fast and scalable to make group chat Application.

Soluation 3: Use MySql 5.7 : InnoDB, NoSql with Memcached API which will interact directly with storage engine InnoDB. It is 6X faster than MySql 5.6.

Still Now FaceBook is using this technology. Because it is very fast.

For more details:

https://www.mysql.com/news-and-events/web-seminars/introducing-mysql-document-store/
https://dev.mysql.com/doc/refman/5.7/en/document-store-setting-up.html
About Big Data: https://www.oracle.com/big-data/index.html
https://www.youtube.com/watch?v=1Dk517M-_7o


问:
What's easiest way to start a spring project?
The STS tool is not working in Eclipse Neon and I'm wondering what's the easiest way to start a spring project in Eclipse.</p>

答:
Have you tried using spring's initializer site https://start.spring.io/ ?
The basic template created there can be imported as an existing project in most IDEs.</p>


问:
Rescheduling an at job
Is there a way to change the date of a job that has been issued with the unix at command?

I need to do this because my Application has scheduled too many jobs at the same time which will bring the machine to a grinding halt.

答:
This will assign the job a new id for its new time.</p>

```<code>at -c OLDJOBID | at NEWTIME
atrm OLDJOBID
</code>```

Title: Rescheduling an at job

Body:
This will assign the job a new id for its new time.

at -c OLDJOBID | at NEWTIME
atrm OLDJOBID


问:
Most efficient way to create an array of length n filled with unique symbols
I need to create an array of variable length where each element is a unique symbol. Is there a built-in (ES6) or lodash method to easily do this? What I have currently is _.map(range(n), () => Symbol()) which is fairly efficient text and timewise, but I would prefer to replace map with a different function that allows me to replace range(n) with just n.

答:
You could use times:

```<code>let result = _.times(5, () => Symbol())
</code>```

Body:
You could use times:

let result = _.times(5, () => Symbol())


问:
How to use $scope.eval() in angularjs to set $scope variable
I'm trying to figure out how eval() works in AngularJS, but I can't seem get my head around it.

I have the following:

```<code>$scope.salaryRate, $scope.priceRate = {
    number: undefined,
    type: undefined,
    from: undefined,
    to: undefined,
    rate: undefined
}

$scope.addRate = function (variable) {
    eval('$scope.' + variable).push({
        'number': eval('$scope.' + variable + 'Rate').number,
        'type': eval('$scope.' + variable + 'Rate').type,
        'days': {
        'days': eval('$scope.' + variable + 'SelectedDay'),
        'daynames': displayDayNames($scope.dayNames, eval('$scope.' + variable + 'SelectedDay'))},
         'from': eval('$scope.' + variable + 'Rate').from,
         'to': eval('$scope.' + variable + 'Rate').to,
         'rate': eval('$scope.' + variable + 'Rate').rate,
         'id': eval(variable + 'Number')
    });
    eval('$scope.' + variable + 'Rate') = {
        number: undefined,
        type: undefined,
        from: undefined,
        to: undefined,
        rate: undefined
    };
}
</code>```

For some reason eval works fine when I am pushing values to a variable array. However for some reason eval('$scope.' + variable + 'Rate') = doesnt work and I get the error ReferenceError: Invalid left-hand side in assignment.
I am trying to make my function dynamic, so that I can use it for more than one $scope. How do I solve this with AngularJS?

It also happens to fail at this point

```<code>function findRowIndex(variable, id){
    eval('var ' + variable + 'Rows') = eval('$scope.' + variable);
}
</code>```

答:
Why wouldn't you just use bracket notation? https://jsfiddle.net/duoxoq8j/2/

```<code>$scope.addRate = function (variable) {
    $scope[variable].push({
        ...
    });
    $scope[variable + "Rate"] = {
        number: undefined,
        type: undefined,
        from: undefined,
        to: undefined,
        rate: undefined
    };
}
</code>```

This is just basic javascript functionality and has nothing to do with Angular or scopes in particular.

Body:
I'm trying to figure out how eval() works in AngularJS, but I can't seem get my head around it.

I have the following:

$scope.salaryRate, $scope.priceRate = {
    number: undefined,
    type: undefined,
    from: undefined,
    to: undefined,
    rate: undefined
}

$scope.addRate = function (variable) {
    eval('$scope.' + variable).push({
        'number': eval('$scope.' + variable + 'Rate').number,
        'type': eval('$scope.' + variable + 'Rate').type,
        'days': {
        'days': eval('$scope.' + variable + 'SelectedDay'),
        'daynames': displayDayNames($scope.dayNames, eval('$scope.' + variable + 'SelectedDay'))},
         'from': eval('$scope.' + variable + 'Rate').from,
         'to': eval('$scope.' + variable + 'Rate').to,
         'rate': eval('$scope.' + variable + 'Rate').rate,
         'id': eval(variable + 'Number')
    });
    eval('$scope.' + variable + 'Rate') = {
        number: undefined,
        type: undefined,
        from: undefined,
        to: undefined,
        rate: undefined
    };
}

For some reason eval works fine when I am pushing values to a variable array. However for some reason eval('$scope.' + variable + 'Rate') = doesnt work and I get the error ReferenceError: Invalid left-hand side in assignment.
I am trying to make my function dynamic, so that I can use it for more than one $scope. How do I solve this with AngularJS?

It also happens to fail at this point

function findRowIndex(variable, id){
    eval('var ' + variable + 'Rows') = eval('$scope.' + variable);
}

Body:
Why wouldn't you just use bracket notation? https://jsfiddle.net/duoxoq8j/2/

$scope.addRate = function (variable) {
    $scope[variable].push({
        ...
    });
    $scope[variable + "Rate"] = {
        number: undefined,
        type: undefined,
        from: undefined,
        to: undefined,
        rate: undefined
    };
}

This is just basic javascript functionality and has nothing to do with Angular or scopes in particular.