text:
Q: Help understanding segfault with std::map/boost::unordered_map I have some code to handle resource (images, fonts, mesh data, etc.) management using a template'd static class, allowing client code to do something like:
ResourceManager<Texture>::init("data/textures");
ResourceManager<Font>::init("data/fonts");
// later ...
boost::shared_ptr<const Texture> tex = ResourceManager<Texture>::getResource("wall.png");
boost::shared_ptr<const Font> font = ResourceManager<Font>::getResource("Arial.ttf");
// later ...
ResourceManager<Texture>::release();

The "resource type" must have a constructor taking a const std::string&.
getResource is implemented as follows:
static boost::shared_ptr<const ResourceType> getResource(const std::string& fileName)
{
    boost::shared_ptr<ResourceType> resource;

    typename table_t::const_iterator itr = _resources.find(fileName);
    if (itr == _resources.end()) {
        resource.reset(new ResourceType(_dataDirectory + fileName));
        _resources[fileName] = resource;
    } else {
        resource = itr->second;
    }

    return resource;
}

table_t is defined as typedef typename boost::unordered_map< std::string, boost::shared_ptr<ResourceType> > table_t;
_resources is of type table_t.
The problem is with boost::unordered_map I get a segfault on the call to find (originating from find_iterator). However, with std::map instead, I either get a segfault on the insert operation (originating from _Rb_tree_decrement), or on the call to find (originating from string::compare).
The problem only occurs the 2nd time a resource is requested (fileName is valid when the failure occurs).
As this is happening with both map and unordered_map I'm assuming I must be doing something bizarre somewhere to cause this, any ideas?
Thanks.
EDIT: Still having the problem, I was wrong about it only happening the 2nd time a resource is requested. However, the first 2 calls to get a resource are successful, it's the 3rd call that is causing the segfault (each call is for a different resource).
Here is a stack trace:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004b4978 in boost::unordered_detail::hash_table<boost::unordered_detail::map<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::pair<std::string const, boost::shared_ptr<Texture> > > > >::find_iterator (this=0x7aed80, bucket=0x38, k=...)
    at /usr/local/include/boost/unordered/detail/table.hpp:55
55          node_ptr it = bucket->next_;
(gdb) bt
#0  0x00000000004b4978 in boost::unordered_detail::hash_table<boost::unordered_detail::map<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::pair<std::string const, boost::shared_ptr<Texture> > > > >::find_iterator (this=0x7aed80, bucket=0x38, k=...)
    at /usr/local/include/boost/unordered/detail/table.hpp:55
#1  0x00000000004b294c in boost::unordered_detail::hash_table<boost::unordered_detail::map<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::pair<std::string const, boost::shared_ptr<Texture> > > > >::find (this=0x7aed80, k=...)
    at /usr/local/include/boost/unordered/detail/table.hpp:583
#2  0x00000000004b07c1 in boost::unordered_map<std::string, boost::shared_ptr<Texture>, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::pair<std::string const, boost::shared_ptr<Texture> > > >::find (this=0x7aed80, k=...)
    at /usr/local/include/boost/unordered/unordered_map.hpp:423
#3  0x00000000004ae7c6 in ResourceManager<Texture>::getResource (fileName=...) at /home/tim/Projects/gameproj/app/ResourceManager.hpp:52
#4  0x00000000004ce7fc in Map::loadCellTextures (this=0x7fffffffdfc0, in=...) at /home/tim/Projects/gameproj/app/Map.cpp:57
#5  0x00000000004ce632 in Map (this=0x7fffffffdfc0, fileName=...) at /home/tim/Projects/gameproj/app/Map.cpp:30
#6  0x0000000000495702 in Game::init (xResolution=1024, yResolution=768) at /home/tim/Projects/gameproj/app/Game.cpp:116
#7  0x0000000000494fa0 in Game::run (xResolution=1024, yResolution=768) at /home/tim/Projects/gameproj/app/Game.cpp:38
#8  0x0000000000487f1d in Main::run (xResolution=1024, yResolution=768) at /home/tim/Projects/gameproj/app/Main.cpp:28
#9  0x0000000000487db5 in main (argc=1, argv=0x7fffffffe398) at /home/tim/Projects/gameproj/app/main.cpp:10

A: I can't spot any obvious errors, have you tried Valgrind (assuming you run some kind of *nix system)? It's an invaluable tool for finding memory errors, and this looks like it might be one of those.

A:
The problem only occurs the 2nd time a resource is requested

This suggests to me that your code might be freeing the resource - the first time it's all fine, then you free it, then the next time the container tries to access that memory, it segfaults.

A: Look i was having a similar problem.
My class worked great on BlackBerry's compiler and qmake 4. but on qtcreator 5 (64 and 32b) i was having the same issue.
i traced this
http://www.instructables.com/answers/Why-would-an-empty-stdmap-seg-fault-on-the-first/#CXBBGN4GQO92M2Q
looks like the default constructor doesn't initialize correctly on some compiler.
i added a clear() on the parent class constructor and now seems to work.
It also can happen if you have some static declarations (or worse extern) and the time in when the map should be instantiated is not the expected.
i hope it helps.


text:
Q: Facebook logout/disconnect FB.login() called when user is already connected

      <title>My Facebook Login Page</title>

Login with Facebook

Every time when i click on [Login with Facebook] button i see in JS Console this message "FB.login() called when user is already connected."
How to disconnect user?

A: Good answer from Abirami, one additional item.

How to disconnect user?

Disconnecting a user is done with a call similar to FB.login() called FB.logout() See: http://developers.facebook.com/docs/reference/javascript/FB.logout/

A: Use FB.getLoginStatus method to find whether the user in logged in or not.
If they already logged in, try to hide the Login button. Because the login button will be visible always and do nothing on click when the user already logged in.
Refer this link for FB.getLoginStatus

A: This IS the solution that no one is telling anyone because it highlights a Facebook bug so be prepared for me to get voted down...
FB.login() will get called after any user tries to logout if the 'autologoutlink' parameter on the Javascript facebook button is set to true.
The problem is this:
    <fb:login-button autologoutlink="true" width="200" max-rows="1"></fb:login-button>

(((autologoutlink="true")))
When true is set the login button is always called after the user logs out (FB.login) and you have set your window.location to some other page which gets redirected back to the login page, FB.login it is treated like an object, much like an app developer is.
On a console you will see that FB.login() always gets called after the user logs out because of this 'autologoutlink' parameter on the Javascript facebook login button bug.
I now fear for the moron that voted me down lol...
YES this is a bug with the javascipt SDK asynchronously all.js script
The secret would be to load the javascript Facebook button without the autologoutlink="true" parameter but use the php sdk to load the logout button afterwards.
Something like this in php to put a javascript sdk login button but then post a php logout button to get around the asynchronous bug in the Facebook code:
$user = $facebook->getUser();
$logoutUrl=null;
$login_page='replace this for logged in page redirect'; //http://domain.com/loggedin
$logout_page='replace this for logged out page redirect'; //http://domain.com/loggedout

If ($user){
  $logoutUrl = $facebook->getLogoutUrl(array(
  'next'=>$logout_page
  ));
  $fb_login='Logout';
}else{
  $fb_login='<fb:login-button width="200" max-rows="1"></fb:login-button>';
}

Use the javascript SDK and
FB.Event.subscribe('auth.login', function(response) {
  window.location='$login_page';
});

and somewhere on your page
echo $fb_login;

So you use the Javascript login and the php logout redirect methods and it will patch the bug on the Javascript login button autologoutlink="true" parameter which we will not use, you will just need a logout button image and css and FB.login() will not get called anymore after FB.logout() each time.
You can see how to shorten this a whole bunch I'm sure but this is the fix that no one wants to tell you for looking.
And now for my Pointless Rant...
In short, if they run a totally unsecure session in the PHP SDK and they can not even make a button work then don't look to them for answers!.
You are forced to use what Facebook are defining as asynchronous scripts however they are only one sided security, anyone can spoof a domain or hijack an unsecure session where all payments are handled by said spoofed domain ergo any app  on Facebook is totally and utterly hackable and they know it, they just haven't figured out a way to shovel you their BS apart from the word asynchronous which is NOT two way security is it.
Try design anything that is hooked using an asynchronous JAVASCRIPT and then make is secure, they can always blame YOU for the fact they can not deliver a button that says the user is or is not connected in any simple terms with today's scripting and technology.
I'm laughing right now.
I guess that's why we are on stackoverflow...
Personally I think the Facebook javascript and php SDk should be simple and not force the designer to learn their own insane methods in social design but simply provide a method that says YES the user is logged in so... or NO the user isn't so... but Facebook seem to think they are adobe and con-volute everything with kak leaving us to read a four story building of books on their personal philosophy of design to only be left with no examples and code that you would have to be psychic to debug for which will only be changed two days after you finish building your app which took fourteen years just because they fail to deliver and instead like to sound like they know what they are doing to cover so many revisions that are made to remove said bugs.
Like adobe, if it worked, we wouldn't have to do a course in it's design would we ?
But as it is shite and wastes billions of hours of human resources then I'm sure at some point you will be forced to pay for a qualification in it because that means more money right ?.
I mean you have to pass all payments through Facebook already in such a way that they can remotely edit your sessions ergo your app ergo your database ergo your payments.
What TF has your payments got to do with Facebook when what you deliver is what they should be paying you for and ultimately brings, keeps and delivers them more users.
Same with Hollywood, they call piracy a free film on the internet instead of paying you for the free advertising of their products while Hollywood take 80 billion and hour in interest, ban interest!.
Piracy is making money from others work not slavery and to be sued for it or actually pay for doing it.
Remember this lecture it will do you well.
I said to much LOL...
When it is all clear you will see just where the road is taking us.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Predict the number from addition of numbers Somebody asked me this algorithmic question and as usual, I failed to answer this. :) Let us say, you have one number (call it a)
504

Next time, you see it, you delete the last digit of the number. It becomes (call it b)
50

Next time, you see it, you delete the last digit of the number. It becomes (call it c)
5

Now, add all of the three numbers(a+b+c). It becomes :
504 + 50 + 5 = 559

Alright, by now you might have understand the problem statement quite well.
Question is : Given the addition of three numbers a + b + c to you(in this case 559), how can you go back to the original number(in this case 504)? All solutions would be appreciated.

A: Suppose the number you started with looks like xyz. That is, its last (decimal) digit is z, its penultimate digit is y, and the rest is x. In your example, if you started with 504, then x=5, y=0, z=4. The value of your original number is 100x+10y+z.
The number you end up with is the sum of (100x+10y+z), (10x+y), and x. This is 111x+11y+z.
Note that our constraints were that 0≤y≤9 and 0≤z≤9. Even with their largest values, we have 11y+z ≤ 11(9) + 9 < 111. So we can invert the transformation: pull out the largest multiple of 111, then pull out the largest multiple of 11 from the remaining, and then what's left.
def transform(n):
    return n + (n/10) + (n/100)

def invert(m):
    [x, y, z] = [m/111, (m%111)/11, (m%111)%11]
    return 100*x + 10*y + z

assert transform(504) == 559
assert invert(559) == 504

(Try the above in a Python shell. Note that this works even if x is not a single-digit number: transform(12345) gives 13702, and invert(13702) gives 12345, as expected.)

Edit: An alternative solution, based on the idea in Paul Hankin's answer (please upvote it) of using m*100/111 as a starting point. You can certainly use (the ceiling of) that value as a rough answer and try adding 1 and 2 to get the exact answer, but you can also precompute the "offset" needed from the rough answer.
# Precomputation, to populate the "offset" dictionary
def sane_mod(a, m): return ((a % m) + m) % m
offset = {}
for y in range(10):
    for z in range(10):
        add = 10*y + 11*z
        offset[sane_mod(-add, 111)] = add

# Actual function
def invert2(m):
    rough = m * 100
    return (rough + offset[rough % 111]) / 111
assert invert2(559) == 504

A: a+b+c is a + a//10 + a//100 (where // denotes rounding-down division). This is somewhere between a * 111/100 - 1.89 and a * 111/100. (1.89 because the maximum fraction discarded from a//10 is 0.9 and the maximum fraction discarded from a//100 is 0.99, and 1.89 = 0.9 + 0.99).
So, given a+b+c, we're looking for integer a such that:
a * 111/100 - 1.89 <= a + b + c <= a * 111/100
a - 2.0979 <= (a + b + c) * 100 / 111 <= a

Thus, let x = ceil((a + b + c) * 100 / 111), and one of x, x+1 or x+2 must be the solution.


text:
Q: How do I select top ranker by date in MySQL I do have a user data base with rank.what I am looking is how do I select top rank person based on today's search?? and I need to do this in daily basis.

A: This will do:
SELECT id, rank, something
FROM person
WHERE date = DATE(NOW())
ORDER BY rank DESC LIMIT 1;

A: Try:
SELECT MAX(rank), id
  FROM mytbl
 WHERE date = mydate
 GROUP BY id


text:
Q: bq tool, bat file | escaping characters not working when CALL Using bq tool I have no problem escaping the > operator with a caret ^:
bq query "SELECT x FROM [presentation_dim.dim_events] WHERE event^>1"
However, when I CALL the exact same command through a bat file whe whole thing breaks down.
call bq query "SELECT x FROM [presentation_dim.dim_events] WHERE event^>1"
I understand call is the problem here. I can't remove it, since I need to run additional commands after it (bq extract and gsutil cp). I've tried adaptations of what is shown on Escape user input in windows batch file, to no avail.
What's wrong here?
Thanks in advance.

A: I suppose bq.cmd itself contains something like this
set param1=%1
set SQL=%~2
python bigQuery.py --%param1% "%SQL%"

So the line set SQL=%1 requires escaping the special characters.
But when you use CALL, the batch parser has an additional phase of escaping but before it also has a phase of doubling all carets!
So your string in call bq query "SELECT x FROM [presentation_dim.dim_events] WHERE event^>1" is converted to
"SELECT x FROM [presentation_dim.dim_events] WHERE event^^>1"
I think there is no solution with only carets to solve this problem.
But you can avoid this by simply defining a variable containing one caret
set "caret=^"
call bq query "SELECT x FROM [presentation_dim.dim_events] WHERE event%%CARET%%>1"

A: Excuse me. I think there is a confusion here.
When a parameter is enclosed in quotes, it may include special Batch characters with no need to escape they; the only problematic case is when Delayed Expansion is enabled and the parameter include an exclamation-mark or caret. For example, this line works correctly:
bq query "SELECT x FROM [presentation_dim.dim_events] WHERE event>1"

This way, the same line with a CALL command also works correctly:
call bq query "SELECT x FROM [presentation_dim.dim_events] WHERE event>1"

If you escape the greater-than sign this way ^> and don't use CALL, the character passed is the same ^> that is processed as a single > in bq.bat. However, if you use CALL, then the escape is duplicated and ^^> is passed.
Conclusion: Don't escape the > character.


text:
Q: Button in highlighted state till API call finishes I have a button in my react application, on click of that button I make an API call, and wait for this API call to finish before updating the redux store.
My button looks highlighted until the API call finishes and it gives an impression that UI is freezed.
// Button Class

onButtonClick(action) {
   this.props.executeAction();
}

// Action creator
export function executeAction() {
   return (dispatch) => {
           serverCall().catch((err) => console.log(err))
   }
}

serverCall = () => {
  const req = request.post(`${DATA_URL}`);
  return req.endAsync();
}

How can I ensure that button is not highlighted for that long.

Button in normal state

Button in highlighted state
Leads here is appreciated.
Thanks!


text:
Q: SVG Animation: Object along a path on a scroll I have created an SVG animation: Object along a path on a scroll.
Please check the below code and Codepen demo
HTML

    <circle r="2" cy="18.591" cx="169.887" fill="red" fill-opacity=".96" fill-rule="evenodd" stroke="red" stroke-width=".55"/>
    <circle r="2" id="dot" cy="-5" cx="0"  fill="red" fill-opacity=".96" fill-rule="evenodd" stroke="red" stroke-width=".55"/>

    <path id="c" d="M174.093 22.89a.384.384 0 0 0-.148.037l-.921.437-.002-.009a.113.113 0 0 0-.151-.054l-.978.463a.113.113 0 0 0-.054.151l.005.007-1.049.497a.384.384 0 0 0-.183.512l2.25 4.747c.066.14.205.22.35.219-.056.058-.101.15-.04.28l1.395 2.942-.498-.03a.134.134 0 0 0-.016.267l.644.04.602 1.27c.25.527.874.75 1.4.5l.346-.164a.113.113 0 0 0 .155.14l.978-.463a.113.113 0 0 0-.01-.209l.346-.164c.527-.249.75-.874.5-1.4l-.68-1.437.439-.45a.133.133 0 0 0-.003-.189.133.133 0 0 0-.19.002l-.369.379-1.306-2.757c-.069-.155-.164-.195-.25-.193a.382.382 0 0 0 .048-.404l-2.248-4.747a.384.384 0 0 0-.363-.22z" fill="#1a1a1a" fill-rule="evenodd"/>
</svg>

CSS
#route {
  margin-top: 200px;
}

.code {
  height:150px;
  width:250px;
  background:#000;
  color:#fff;
  margin:20px;
  width: 40%;
  clear: both;
  height: 200px;
  background: #000;
  border-radius: 2px;
  margin: 100vh 0;
  padding: 10px;
}

JS
$(document).ready(function(){
    $(window).scroll(function() {
        drawLine( $('#bx_a'),document.getElementById('path') );
        positionTheDot();
        //positionCar();
    });

    // init the line length
    drawLine( $('#bx_a'),document.getElementById('path') );
    positionTheDot();
    //positionCar();

    function positionTheDot() {
    // What percentage down the page are we?
    var scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
    // Get path length
    var path = document.getElementById("path");
    var pathLen = path.getTotalLength();
    // Get the position of a point at <scrollPercentage> along the path.
    var pt = path.getPointAtLength(scrollPercentage * pathLen);
    var  scrollY = window.scrollY || window.pageYOffset;
    var  maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
   var  path = document.getElementById("path");
   // Calculate distance along the path the car should be for the current scroll amount
   var  pathLen = path.getTotalLength();
   var  dist = pathLen * scrollY / maxScrollY;
   var  pos = path.getPointAtLength(dist);
   // Calculate position a little ahead of the car (or behind if we are at the end), so we can calculate car angle
   if (dist + 1 <= pathLen) {
    var  posAhead = path.getPointAtLength(dist + 1);
    var  angle = Math.atan2(posAhead.y - pos.y, posAhead.x - pos.x);
   } else {
    var  posBehind = path.getPointAtLength(dist - 1);
    var  angle = Math.atan2(pos.y - posBehind.y, pos.x - posBehind.x);
   }

   // Position the red dot at this point
   var dot = document.getElementById("dot");
   dot.setAttribute("transform", "translate("+ pt.x + "," + (pt.y+5) + ")");
   var  car = document.getElementById("c");
   car.setAttribute("transform", "translate(" + (pt.x-171) + "," + (pt.y-21) + ")");
   //car.setAttribute("transform", "translate(" + (pt.x-171) + "," + (pt.y) + ") rotate(" + (rad2deg(angle)) + ")");
   };

   //draw the line
   function drawLine(container, line) {
    var pathLength = line.getTotalLength(),
    maxScrollTop = $(document).height() - $(window).height(),
    percentDone = $(window).scrollTop() / maxScrollTop,
    length = percentDone * pathLength;
    line.style.strokeDasharray = [ length,pathLength].join(' ');
   }

   function positionCar() {
    var  scrollY = window.scrollY || window.pageYOffset;
    var  maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
    var  path = document.getElementById("path");
    // Calculate distance along the path the car should be for the current scroll amount
    var  pathLen = path.getTotalLength();
    var  dist = pathLen * scrollY / maxScrollY;
    var  pos = path.getPointAtLength(dist);
    // Calculate position a little ahead of the car (or behind if we are at the end), so we can calculate car angle
    if (dist + 1 <= pathLen) {
        var  posAhead = path.getPointAtLength(dist + 1);
        var  angle = Math.atan2(posAhead.y - pos.y, posAhead.x - pos.x);
    } else {
        var  posBehind = path.getPointAtLength(dist - 1);
        var  angle = Math.atan2(pos.y - posBehind.y, pos.x - posBehind.x);
    }
    // Position the car at "pos" totated by "angle"
    var  car = document.getElementById("c");
    car.setAttribute("transform", "translate(" + (pos.x) + "," + (pos.y) + ") rotate(" + (rad2deg(angle)) + ")");
    }

    function rad2deg(rad) {
        return 180 * rad / Math.PI;
    }
});

Please check the Codepen demo: https://codepen.io/yesvin/pen/XymwvX
The problem is that the object (ex: Car) inside the SVG is not rotating itself along the path. I tried with the transform rotation but it is not working. Please check the commented line of the SVG set attribute function.
So, How to achieve, that the object has to rotate itself along a path on a scroll? Is there any other calculations to calculate the objects angle and path's length?
Thanks in advance.

A: The issue is the center of rotation, and the initial angle. Currently, the initial position of the car is such that its rotation center should be at (171, 21). You could start out with translating that point to (0, 0), and then rotate it by -65deg so that it points to the right. In this case, it is easier to rewrite the path data to incorporate these transformations:
d="M 3.02008,-2.00446 A 0.384,0.384 0 0 0 2.99106,-1.85469 L 2.99789,-0.835296 2.98889,-0.837286 A 0.113,0.113 0 0 0 2.87613,-0.723255 L 2.88243,0.358786 A 0.113,0.113 0 0 0 2.99646,0.471542 L 3.00492,0.469969 3.01203,1.63073 A 0.384,0.384 0 0 0 3.39872,2.01296 L 8.65185,1.97994 C 8.80663,1.97929 8.93788,1.88712 8.99825,1.75528 9.02715,1.83055 9.09151,1.91021 9.23511,1.90987 L 12.491,1.88891 12.2534,2.32758 A 0.134,0.134 0 0 0 12.4886,2.45492 L 12.797,1.88816 14.2024,1.87929 C 14.7857,1.87543 15.2515,1.40414 15.2473,0.821764 L 15.2448,0.438872 A 0.113,0.113 0 0 0 15.4372,0.357561 L 15.4309,-0.72448 A 0.113,0.113 0 0 0 15.2373,-0.803744 L 15.2349,-1.18664 C 15.2319,-1.76949 14.7597,-2.23574 14.1774,-2.23146 L 12.5876,-2.22247 12.3653,-2.81052 A 0.133,0.133 0 0 0 12.1927,-2.88767 0.133,0.133 0 0 0 12.1143,-2.71463 L 12.3018,-2.22003 9.25118,-2.20155 C 9.08154,-2.20452 9.00514,-2.13533 8.9706,-2.05654 A 0.382,0.382 45 0 0 8.62474,-2.27078 L 3.37245,-2.23957 A 0.384,0.384 0 0 0 3.01965,-2.00355 Z"

$(document).ready(function(){

  $(window).scroll(function() {
    drawLine( $('#bx_a'),document.getElementById('path') );
    positionTheDot();
    positionCar();
  });

  // init the line length
  drawLine( $('#bx_a'),document.getElementById('path') );
  positionTheDot();
  positionCar();

  function positionTheDot() {
    // What percentage down the page are we?
    var scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
    // Get path length
    var path = document.getElementById("path");
    var pathLen = path.getTotalLength();
    // Get the position of a point at <scrollPercentage> along the path.
    var pt = path.getPointAtLength(scrollPercentage * pathLen);

    var  scrollY = window.scrollY || window.pageYOffset;
    var  maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
    var  path = document.getElementById("path");
    // Calculate distance along the path the car should be for the current scroll amount
    var  pathLen = path.getTotalLength();
    var  dist = pathLen * scrollY / maxScrollY;
    var  pos = path.getPointAtLength(dist);
    // Calculate position a little ahead of the car (or behind if we are at the end), so we can calculate car angle
    if (dist + 1 <= pathLen) {
      var  posAhead = path.getPointAtLength(dist + 1);
      var  angle = Math.atan2(posAhead.y - pos.y, posAhead.x - pos.x);
    } else {
      var  posBehind = path.getPointAtLength(dist - 1);
      var  angle = Math.atan2(pos.y - posBehind.y, pos.x - posBehind.x);
    }

    // Position the red dot at this point
    var dot = document.getElementById("dot");
    dot.setAttribute("transform", "translate("+ pt.x + "," + (pt.y+5) + ")");
  };

  //draw the line
  function drawLine(container, line) {
    var pathLength = line.getTotalLength(),
    maxScrollTop = $(document).height() - $(window).height(),
    percentDone = $(window).scrollTop() / maxScrollTop,
    length = percentDone * pathLength;
    line.style.strokeDasharray = [ length,pathLength].join(' ');
  }

  function positionCar() {
    var  scrollY = window.scrollY || window.pageYOffset;
    var  maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
    var  path = document.getElementById("path");
    // Calculate distance along the path the car should be for the current scroll amount
    var  pathLen = path.getTotalLength();
    var  dist = pathLen * scrollY / maxScrollY;
    var  pos = path.getPointAtLength(dist);
    // Calculate position a little ahead of the car (or behind if we are at the end), so we can calculate car angle
    if (dist + 1 <= pathLen) {
    var  posAhead = path.getPointAtLength(dist + 1);
    var  angle = Math.atan2(posAhead.y - pos.y, posAhead.x - pos.x);
    } else {
    var  posBehind = path.getPointAtLength(dist - 1);
    var  angle = Math.atan2(pos.y - posBehind.y, pos.x - posBehind.x);
    }
    // Position the car at "pos" totated by "angle"
    var  car = document.getElementById("c");
    car.setAttribute("transform", "translate(" + (pos.x) + "," + (pos.y) + ") rotate(" + (rad2deg(angle)) + ")");
  }

  function rad2deg(rad) {
    return 180 * rad / Math.PI;
  }

});
#route {
  margin-top: 200px;
}
.code {
 height:150px;
 width:250px;
 background:#000;
 color:#fff;
 margin:20px;
 width: 40%;
    clear: both;
    height: 200px;
    background: #000;
    border-radius: 2px;
    margin: 100vh 0;
    padding: 10px;
}
svg {
 /*width:100%;
 height:auto;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position:absolute; top:0; right:0; width:100%; height:auto; background:url('background-map.jpg') no-repeat;" id="route">
 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 334 1426" id="svgRoute">
  <path id="path" d="M170 19s18 32 18 57c0 48-40 51-40 72 0 22 43 31 43 44 0 10-9.4 10-10 23-.7 14 2.3 16 2.2 28-.17 12-14 24-21 32-6.5 7.2-17 15-20 23-2.4 6.8-3.5 23 12 29 16 5.7 32 10 37 24 5.2 13-7.4 26-17 33-9.2 6.6-30 20-26 30 3.5 9.9 27 6.2 27 24 0 18 8.8 13 8.8 24-11 24 16 50 13 71-.46 17-15 23-8.2 42-32 37 1.3 83 26 106 28 20-33 5.7-33 39 2.4 51-28 113-34 139-4.1 18-3.5 41 18 41 8.1-.2 14-6.5 15-14 .37-6.3-6.1-14-16-12-11 1.8-16 11-19 24-1.3 6.6-2.1 17-2.3 28-.43 29 14 36 19 39 2.6 1.8 19 8.8 19 17 10 18-41 7.8-35 28 .61 10 37 22 36 35 8.4 94-128 42-89 130 8.8 36-63 33-60 68-2.1 25 35 32 38 44" stroke="red" fill="none"/>

  <circle r="2" cy="18.591" cx="169.887" fill="red" fill-opacity=".96" fill-rule="evenodd" stroke="red" stroke-width=".55"/>
  <circle r="2" id="dot" cy="-5" cx="0"  fill="red" fill-opacity=".96" fill-rule="evenodd" stroke="red" stroke-width=".55"/>

  <path id="c" d="M 3.02008,-2.00446 A 0.384,0.384 0 0 0 2.99106,-1.85469 L 2.99789,-0.835296 2.98889,-0.837286 A 0.113,0.113 0 0 0 2.87613,-0.723255 L 2.88243,0.358786 A 0.113,0.113 0 0 0 2.99646,0.471542 L 3.00492,0.469969 3.01203,1.63073 A 0.384,0.384 0 0 0 3.39872,2.01296 L 8.65185,1.97994 C 8.80663,1.97929 8.93788,1.88712 8.99825,1.75528 9.02715,1.83055 9.09151,1.91021 9.23511,1.90987 L 12.491,1.88891 12.2534,2.32758 A 0.134,0.134 0 0 0 12.4886,2.45492 L 12.797,1.88816 14.2024,1.87929 C 14.7857,1.87543 15.2515,1.40414 15.2473,0.821764 L 15.2448,0.438872 A 0.113,0.113 0 0 0 15.4372,0.357561 L 15.4309,-0.72448 A 0.113,0.113 0 0 0 15.2373,-0.803744 L 15.2349,-1.18664 C 15.2319,-1.76949 14.7597,-2.23574 14.1774,-2.23146 L 12.5876,-2.22247 12.3653,-2.81052 A 0.133,0.133 0 0 0 12.1927,-2.88767 0.133,0.133 0 0 0 12.1143,-2.71463 L 12.3018,-2.22003 9.25118,-2.20155 C 9.08154,-2.20452 9.00514,-2.13533 8.9706,-2.05654 A 0.382,0.382 45 0 0 8.62474,-2.27078 L 3.37245,-2.23957 A 0.384,0.384 0 0 0 3.01965,-2.00355 Z" fill="#1a1a1a" fill-rule="evenodd"/>
 </svg>
</div>


text:
Q: How to make all the gem classes and modules private? How it is possible to only expose one module or a class from a Ruby gem and close everything else?
For example, in a my-math library, I only want to expose Math module, but not any other, such as Math::Utils or similar.
I want to enforce one and only one way of using the gem.
At least making it hard to access internal classes will help (even munging the names at runtime will be better than open-access).

A: Not clear what you are trying to do, but if you want private constants, why not just declare them as so?
module Namespace
  module Secret
  end
  private_constant :Secret
  Secret # => Namespace::Secret
end

Namespace::Secret # => NameError. Private constant Namespace::Secret referenced.


text:
Q: Can I use Celery v4.0.2 with Django v1.7.1 without using djcelery? Currently I'm working on a Django project which is using version 1.7.1 which cannot be upgraded.
I want to know whether I can use the latest version (4.0.2) of Celery with this project without using django-celery?

A: Since version 3.2 of Celery you need to use django-celery for any Django version <= 1.7 project.
You can see this on django-celery's change log at line 16:

3.2.0
  ===== :release-date: TDB

*

*Now compatible with Django 1.10

*Dropped compatibility with Django 1.7 and earlier.
For older Django versions use django-celery 3.1.x  <- line 16


text:
Q: MySQL Stored Procedure not throwing error if it contains a query that succeeds I am writing a simple MySQL Stored Procedure, and calling it from PHP using PDO.
This is just simple enough to illustrate the problem I'm having.
This procedure test_procedure_2, does not throw any error.
CREATE PROCEDURE `test_procedure_1`()
BEGIN
    select 'gary';

    CALL raise_error;
END

It returns the result set:
[0] => Array
    (
        [0] => Array
            (
                [gary] => gary
            )

    )

However...
CREATE PROCEDURE `test_procedure_2`()
BEGIN
    CALL raise_error;

    select 'gary';
END

...this procedure test_procedure_2, when called, will actually throw an PDOException with the message "SQLSTATE[42000]: Syntax error or access violation: 1305 PROCEDURE vjs_admin_dev.raise_error does not exist". And the select 'gary' query never gets executed. I like that.
Why is it that the first procedure did NOT throw an error when it clearly contained an error? I would like to come up with a stored procedure that, whenever there is an error anywhere in it, it will throw an error. Thanks for your help!
I'm using

*

*Ubuntu: 16.04, and

*PHP: 7.0.15

*mysql: Ver 14.14 Distrib 5.7.21, for Linux (x86_64) using  EditLine wrapper

EDIT:
I have tried this with mysqli, and with PDO, and I get the same results. Here are some simple code examples that show my issue:

*

*Mysqli Version: https://pastebin.com/rATMST4H

*PDO version: https://pastebin.com/Wiq3yFmQ
The output of the Mysqli version is:
Running test_procedure_1
CREATE PROCEDURE `test_procedure_1`()BEGIN  select 'gary';  CALL raise_error;END
RESULTS:Array ( [gary] => gary )
----------
Running test_procedure_2
CREATE PROCEDURE `test_procedure_2`()BEGIN  CALL raise_error;   select 'gary';END
CALL failed: (1305) PROCEDURE vjs_admin_dev.raise_error does not exist
----------

The output of the PDO version is:
Running test_procedure_1
CREATE PROCEDURE `test_procedure_1`()BEGIN  select 'gary';  CALL raise_error;END
RESULTS:Array ( [gary] => gary [0] => gary )
----------
Running test_procedure_2
CREATE PROCEDURE `test_procedure_2`()BEGIN  CALL raise_error;   select 'gary';END
CALL failed: (42000) Array ( [0] => 42000 [1] => 1305 [2] => PROCEDURE vjs_admin_dev.raise_error does not exist )
----------

A: Wow, that's a relevant problem, because you can't identify an error in a procedure, an this passes hidden next to some valid result! I think your question should be more popular.
After many tries and tests I found a way to solve it. You'd expect to loop through the procedure result set, until no more results are available (the PHP Manual way). However, I found an alternate control flow to catch the errors after previous valid results:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $sql="CALL procedureWithErrors()";
    $conn=new mysqli($host,$user,$pass,$db);

    /*The usual way (does not work)*/
    $conn->multi_query($sql);
    do{
        $result=$conn->store_result();
        if($result){
            while($row=$result->fetch_assoc()){
                print_r($row);
            }
            $result->free();
        }
    }while($conn->more_results() && $conn->next_result());

    /*This way works*/
    $conn->multi_query($sql);
    while(($result=$conn->store_result())!==FALSE){
        if($result){
            while($row=$result->fetch_assoc()){
                print_r($row);
            }
            $result->free();
        }
        $conn->next_result();
    }

    /*Just closing and error handling, not relevant code from here*/
    $conn->close();

}catch(mysqli_sql_exception | Exception $e){
    $error="Error #".$e->getCode()." ".$e->getMessage().PHP_EOL;
    if(isset($conn) && get_class($e)=="mysqli_sql_exception")
        $error.="SQLSTATE #".$conn->sqlstate." Statement: $sql".PHP_EOL;
    $error.=$e->getTraceAsString();
    echo(nl2br($error));
}finally{
    if(isset($result) && $result instanceof mysql_result) $result->free();
    if(isset($conn) && is_resource($conn) && get_resource_type($conn)==='mysql link') $conn->close();
}
?>

The problems seems to be that mysqli::more_results and mysql::next_result return FALSE if an error happens, so they can't distinguish between an error and the lack of further results.

A: That's not possible. You can not prevent execution of statements based on if later statements will throw an error in a stored procedure.
The only way to achieve something similar would be something like this:
drop procedure if exists test_procedure_3;
DELIMITER $$
CREATE PROCEDURE `test_procedure_3`()
BEGIN
    if exists (select 1 from information_schema.routines where routine_name = 'raise_error' and routine_schema = database())
    then
    select 'gary';

    CALL raise_error;
    end if;
END$$
DELIMITER ;

call test_procedure_3;

So you just check, if the procedure exists beforehand. There's no other way (I tried with transactions, signal, prepared statements and what not).


text:
Q: Weird Doctrine ODM exception when using references together with inheritance I've got three classes. The File-Class has a reference to Foobar and Game inherits from Foobar. There are some other Classes which also inherit from Foobar but i left them out as they aren't relevant here. I also left out some unrelevant fields and their getters and setters.
The plan is that every Game has two images, the mainImage and the secondaryImage. I've put those fields into a seperate class from which Game inherits because i need them for a few other classes too.
My problem is that if I load the games from the database as soon as i try to iterate over them I get the following exception:

Notice: Undefined index:  in C:\xampp\htdocs\Symfony\vendor\doctrine\mongodb-odm\lib\Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo.php line 1293

For reference here are the lines of ClassMetadataInfo.php
public function getPHPIdentifierValue($id)
{
    $idType = $this->fieldMappings[$this->identifier]['type'];
    return Type::getType($idType)->convertToPHPValue($id);
}

Here are my classes
File-Class:
namespace Project\MainBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class File
{

    /**
     * @MongoDB\Id(strategy="INCREMENT")
     */
    protected $id;

    /**
     * @MongoDB\ReferenceOne(targetDocument="Foobar", inversedBy="mainImage")
     */
    private $mainImage;

    /**
     * @MongoDB\ReferenceOne(targetDocument="Foobar", inversedBy="secondaryImage")
     */
    private $secondaryImage;

    /**
     * Get id
     */
    public function getId()
    {
        return $this->id;
    }

    public function setMainImage($mainImage)
    {
        $this->mainImage = $mainImage;
        return $this;
    }
    public function getMainImage()
    {
        return $this->mainImage;
    }

    public function setSecondaryImage($secondaryImage)
    {
        $this->secondaryImage = $secondaryImage;
        return $this;
    }
    public function getSecondaryImage()
    {
    return $this->secondaryImage;
    }

}

Foobar-Class:
namespace Project\MainBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\MappedSuperclass
 */
abstract class Foobar
{

    /**
     * @MongoDB\Id(strategy="INCREMENT")
     */
    protected $id;

    /**
     * @MongoDB\ReferenceOne(targetDocument="File", mappedBy="mainImage")
     */
    protected $mainImage;

    /**
     * @MongoDB\ReferenceOne(targetDocument="File", mappedBy="secondaryImage")
     */
    protected $secondaryImage;

    /**
     * Get id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set mainImage
     */
    public function setMainImage($file)
    {
        $file->setMainImage($this);
        $this->mainImage = $file;
        return $this;
    }
    /**
     * Get mainImage
     */
    public function getMainImage()
    {
        return $this->mainImage;
    }

    /**
     * Set secondaryImage
     */
    public function setSecondaryImage($file)
    {
        $file->setSecondaryImage($this);
        $this->secondaryImage = $file;
        return $this;
    }
    /**
     * Get secondaryImage
     */
    public function getSecondaryImage()
    {
        return $this->secondaryImage;
    }

}

Game-Class:
namespace Project\MainBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class Game extends Foobar
{

    /**
     * @MongoDB\String
     */
    private $name;

    /**
     * Set name
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }
    /**
     * Get name
     */
    public function getName()
    {
        return $this->name;
    }

}

Though it doesn't really matter but here is my function i want to execute:
    $dm = $this->get('doctrine_mongodb')->getManager();

    $games_all = $dm->getRepository("ProjectMainBundle:Game")->createQueryBuilder()->sort('id', 'ASC')->getQuery()->execute();

    foreach ($games_all as $singlegame) { // it breaks here
        // Here i would do stuff
    }

Is this a bug in Doctrine ODM or am I doing something wrong? Are the classes correct? I have tried everything but it just wont work.

A: I think it is too late for your question, but maybe there are other users having the same problem (as me).
The problem is related to Foobar being a MappedSuperclass. Had the same problem as described by you and at https://github.com/doctrine/mongodb-odm/issues/241.
Solution is to not reference the abstract class Foobar (=MappedSuperclass) but a concrete implementation (=Document) - as in your case - Game.
See also Doctrine ODM returns proxy object for base class instead of sub-classed document


text:
Q: Azure application settings, does not reflect on NodeJs app I understood from 2 answers in SO, this and this, that even if we update the Application Settings, the current portal UI does not reflect those changes, but that if we read through our application, we would get the updated settings...
That is not happening in my NodeJs application for some odd reason:
as a Bitbucket pipeline step, I get the last committed hash and using the Kudo REST API, I update my application setting, and that works fine as seen in the Kudo settings:

The bad is that when requesting such variable through process.env.SOURCE_VERSION I get the string that is in the portal GUI and not this one:

and that, in HTML translates to:

that 123 string is exactly what is in the portal GUI

From the answers I've found, it must be something I'm forgetting ... but I've been stuck on this for some time and I can't figure it out what am I missing :(

As a very weird test, I've updated the portal GUI to 1234 and, even Kudo settings still show the git commit hash, in the HTML page I now get 1234.
So it's definitely showing changes, but not what I dynamically update, just the portal variables :/

A: This was discussed on KUDU REST POST /api/settings won't work how it supposed to? #283. As @ahmelsayed said that settings API *.scm.azurewebsites.net/api/settings is not the same as what you get from /Env.
You have two options to ensure the consistency of app settings.

*

*Set settings through Azure CLI, then get settings through process.env['xxx'] in your Node.js application.

*Set settings by doing a POST to *.scm.azurewebsites.net/api/settings, then get settings by doing a GET to *.scm.azurewebsites.net/api/settings in your Node.js appliction.


text:
Q: How to merge array of objects in one object, including inner objects - JavaScript? Suppose I have the following array of objects:
var list = [
  { a: 1,
    b: { c: 'x', k: []}
  },
  { a: 1,
    b: {c: 'x', d: 8}
  }
];

I want them to be merged into one "generic" object, for this example, it would be:
{a: 1, b: {c: 'x', d:'8', k[]}}

As you can see, all nested objects are merged too. But I can't gain it. If I use Object.assign it creates new nested objects if they are different, that is duplicates them:
var res = Object.assign({}, ...list);
// res: {
    a: 1,
    b: {c: 'x', k: []},
    b: {c: 'x', d: 8}
}

A: You could try the following using the reduce method:

var list = [{
  a: 1,
  b: {
    a: 4,
    k: 3
  }
}, {
  a: 1,
  s: 11,
  b: {
    ab: 4,
    d: 8
  }
}]

var result = list.reduce(function(acc, item) {
  var obj = { ...item
  }
  Object.keys(obj).forEach(function(item) {
    if (acc[item]) { //if a property with the the key, 'item' already exists, then append to that
      Object.assign(acc[item], obj[item]);
    } else { // else add the key-value pair to the accumulator object.
      acc[item] = obj[item];
    }
  })
  return acc;
}, {})

console.log(result);

A: Deep merging is not simple to do yourself, That blog uses deep merge.
If you don't have webpack or nodejs you can use deepmerge like so:

// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7

function isReactElement(value) {
 return value.$$typeof === REACT_ELEMENT_TYPE
}

function isNonNullObject(value) {
 return !!value && typeof value === 'object'
}

function isSpecial(value) {
 var stringValue = Object.prototype.toString.call(value)

 return stringValue === '[object RegExp]'
  || stringValue === '[object Date]'
  || isReactElement(value)
}

function defaultIsMergeableObject(value) {
 return isNonNullObject(value)
  && !isSpecial(value)
}

function emptyTarget(val) {
 return Array.isArray(val) ? [] : {}
}

function cloneUnlessOtherwiseSpecified(value, options) {
 return (options.clone !== false && options.isMergeableObject(value))
  ? deepmerge(emptyTarget(value), value, options)
  : value
}

function defaultArrayMerge(target, source, options) {
 return target.concat(source).map(function(element) {
  return cloneUnlessOtherwiseSpecified(element, options)
 })
}

function mergeObject(target, source, options) {
 var destination = {}
 if (options.isMergeableObject(target)) {
  Object.keys(target).forEach(function(key) {
   destination[key] = cloneUnlessOtherwiseSpecified(target[key], options)
  })
 }
 Object.keys(source).forEach(function(key) {
  if (!options.isMergeableObject(source[key]) || !target[key]) {
   destination[key] = cloneUnlessOtherwiseSpecified(source[key], options)
  } else {
   destination[key] = deepmerge(target[key], source[key], options)
  }
 })
 return destination
}

function deepmerge(target, source, options) {
 options = options || {}
 options.arrayMerge = options.arrayMerge || defaultArrayMerge
 options.isMergeableObject = options.isMergeableObject || defaultIsMergeableObject

 var sourceIsArray = Array.isArray(source)
 var targetIsArray = Array.isArray(target)
 var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray

 if (!sourceAndTargetTypesMatch) {
  return cloneUnlessOtherwiseSpecified(source, options)
 } else if (sourceIsArray) {
  return options.arrayMerge(target, source, options)
 } else {
  return mergeObject(target, source, options)
 }
}

deepmerge.all = function deepmergeAll(array, options) {
 if (!Array.isArray(array)) {
  throw new Error('first argument should be an array')
 }

 return array.reduce(function(prev, next) {
  return deepmerge(prev, next, options)
 }, {})
}
var list = [{
  a: 1,
  b: {
    c: 'x',
    //merging 1,2 and 1,3 results in [1,2,1,3] you can change that in defaultArrayMerge
    k: [1,2]
  }
},
{
  a: 1,
  b: {
    c: 'x',
    k: [1,3],
    d: 8
  }
}];

console.log(
  deepmerge.all(list)
)

A: You can use the reduce method. Remove the first element from the original list , that object will be the base method.

var list = [{
    a: 1,
    b: {
      c: 'x',
      k: []
    }
  },
  {
    a: 1,
    b: {
      c: 'x',
      d: 8
    }
  }
];
// Remove the first element from the array. The first element will be
// the base object
// slice will return a new array without the first object
// apply reduce on this list
let _temp = list.slice(1);
let x = _temp.reduce(function(acc,curr,currIndex){
    for(let keys in curr){
      // checking if the base object have the same key as of current object
      if(acc.hasOwnProperty(keys)){
          // if base object and current object has the key then
         // check if the type is an object
         if(typeof curr[keys] ==='object'){
          // now get the key from both the object
          // & check which one is missong. Add that key and value to the
          // base object
           let keysFromACC = Object.keys(acc[keys]);
          let keysFromCURR = Object.keys(curr[keys]);
          keysFromCURR.forEach(function(item){
           if(keysFromACC.indexOf(item) ===-1){
              acc[keys][item] = curr[keys][item]
           }
          })
         }
      }
      else{
       // if the base object does not have key which current object
       // has then add the key to base object
       acc[keys]= curr[keys]
      }

    }
    return acc;

},list[0]);

console.log(x)


text:
Q: Grizzly Graceful Shutdown throws InterruptedException I'm working with a jersey server and want to be sure that when the server is terminated (usually via SIGTERM), all currently running requests are completed gracefully. If volume is high enough, there will likely be data loss if I don't do this.
So I'm trying to call HttpServer.shutdown() from a runtime shutdown hook.
I think it is working correctly, except for one problem. CompletionHandler.failed() is invoked, with an InterruptedException. shutdownNow is in the stack trace, so it seems like there is just some logical error occurring after the shutdown itself has finished:
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1302)
    at org.glassfish.grizzly.impl.SafeFutureImpl$Sync.innerGet(SafeFutureImpl.java:354)
    at org.glassfish.grizzly.impl.SafeFutureImpl.get(SafeFutureImpl.java:265)
    at org.glassfish.grizzly.impl.SafeFutureImpl.notifyCompletionHandlers(SafeFutureImpl.java:181)
    at org.glassfish.grizzly.impl.SafeFutureImpl.done(SafeFutureImpl.java:287)
    at org.glassfish.grizzly.impl.SafeFutureImpl$Sync.innerSet(SafeFutureImpl.java:383)
    at org.glassfish.grizzly.impl.SafeFutureImpl.result(SafeFutureImpl.java:112)
    at org.glassfish.grizzly.http.server.HttpServer.shutdownNow(HttpServer.java:458)
    at org.glassfish.grizzly.http.server.HttpServer$1.completed(HttpServer.java:384)
    at org.glassfish.grizzly.http.server.HttpServer$1.completed(HttpServer.java:376)
    at org.glassfish.grizzly.impl.SafeFutureImpl.notifyCompletionHandlers(SafeFutureImpl.java:199)
    at org.glassfish.grizzly.impl.SafeFutureImpl.done(SafeFutureImpl.java:287)
    at org.glassfish.grizzly.impl.SafeFutureImpl$Sync.innerSet(SafeFutureImpl.java:383)
    at org.glassfish.grizzly.impl.SafeFutureImpl.result(SafeFutureImpl.java:112)
    at org.glassfish.grizzly.http.server.NetworkListener$1$1.completed(NetworkListener.java:698)
    at org.glassfish.grizzly.http.server.NetworkListener$1$1.completed(NetworkListener.java:693)
    at org.glassfish.grizzly.http.server.HttpServerFilter.prepareForShutdown(HttpServerFilter.java:328)
    at org.glassfish.grizzly.http.server.NetworkListener$1.shutdownRequested(NetworkListener.java:704)
    at org.glassfish.grizzly.nio.GracefulShutdownRunner.run(GracefulShutdownRunner.java:93)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:744)

I boiled it down to this test case which does not use jersey or a shutdown hook. It's very simple and the same exception occurs (in fact, the above is copied from the output of this program):
public class Server {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.createSimpleServer();
        server.start();
        try { Thread.sleep(5000); } catch (InterruptedException ex) {}
        shutdown(server);
    }
    public static void shutdown (HttpServer server) {
        final boolean [] done = {false};
        server.shutdown().addCompletionHandler(new EmptyCompletionHandler<HttpServer>() {
            public void completed (HttpServer arg) {
                System.out.println("Shutdown completed");
                done[0] = true;
            }
            public void failed (Throwable error) {
                System.out.println("Shutdown failed");
                error.printStackTrace(System.out);
                done[0] = true;
            }
        });
        while (!done[0]) {
            try { Thread.sleep(100); } catch (InterruptedException ex) {}
        }
        System.out.println("Goodbye");
    }
}

Where's the bug?


text:
Q: Java no reconoce la instrucción System.out.println(); en el ámbito de mi clase Buen día, tengo un problema con mi proyecto y es que al escribir sout, no me permite autocompletar, y si lo quiero hacer manualmente, al escribir System.out.print(""); no me lo reconoce y me marca error,

A: Cuando defines una clase, declaras las características y comportamientos de una instancia.

*

*Las características son variables de instancia.

*Los comportamientos son métodos.

Por esta razón, Java no reconocerá una instrucción que esté por fuera de sus estándares.
La instrucción de salida estándar de Java está compuesta por:

*

*System es una clase.

*out es una instancia.

*println(); es un método sin retorno (void).

Carece de sentido darle una utilidad en el ámbito de clase, este no seria ejecutado en ningún momento por el programa, por lo tanto el IDE marcará un error de compilación.
Pero, si puedes llamar a un método que tenga un tipo de retorno, ejemplo:
int result = methodTest();

public int methodTest(){
    return 0;
}

Es válido, ya que se estaría inicializando una variable, tiene un sentido de utilidad.
Pero, en cambio:
methodTest(); //Error de compilación

public int methodTest(){
    return 0;
}

Arrojaría un error de compilación al igual que un método sin retorno, porque también carece de sentido su utilidad.
Conclusión:

*

*Una clase está compuesta por instrucciones de declaración.

*System.out.println(); No es una instrucción de declaración.

A: Mete el
System.out.println("Tu mensaje");

dentro de un método

A: No puedes utilizar la clase System afuera de un método es una definición ilegal, tampoco es una clase instanciable.
Te dejo un ejemplo clásico:
public class HolaMundo{
    public static void main(String[] args)
    {
        System.out.println("¡Hola mundo!");
    }
}

En tu caso puedes utilizarlo dentro de tu constructor:
public Pantalla(){

  System.out.println("");

}


text:
Q: Fit sidewaysfigure to page width including caption and source I'm trying to add a sidewaysfigure to my document, but when I set the width to \textwidth it comes out too wide.
This is my code:
\usepackage{rotating}

\begin{sidewaysfigure}
   \centering
   \begin{minipage}{\textwidth}
      \caption{The caption}
      \includegraphics[width=\textwidth]{img/diagramm_hs.png}\\
      \source{The source}
      \label{fig:diagramm_hs}
   \end{minipage}
\end{sidewaysfigure}

And here is the result:

As you can see, the image is wider than the textwidth (textwidth is as wide as the line in the header), especially with the caption and source.
How can I make the image as large as possible on the page while everything, including caption and source, remain in the textarea?
EDIT: The image dimensions are 1327x960 px.
This is my documentclass:
\documentclass[
paper=A4,
fontsize=12pt,
BCOR12mm,
DIV14,
parskip=half*,
headsepline,
listof=totoc,
footinclude=false,
headinclude=true,
final
]{scrartcl}

A: As far as I can tell, you haven't provided any information yet about the natural size of the image (or of its natural height to width ratio), the dimensions of the textblock, or even of the document class you use. It's thus not possible to give very specific advice.
All I can think of suggesting is to set the image's width to \textwidth and its height to something like 0.7\textheight; see the screenshot below. Depending on the natural size of the image, you will probably have to adjust the factor 0.7; it may also be useful to set the option keepaspectratio.

\documentclass{report}
\usepackage{caption}
\captionsetup{justification=raggedright,
               singlelinecheck=false}
\usepackage{rotating}
\usepackage[showframe]{geometry}
\begin{document}

\begin{sidewaysfigure}
   \caption{The caption}
   \label{fig:diagramm_hs}
   \includegraphics[width=\textwidth,
                    height=0.7\textheight,
                    %keepaspectratio  % may need to uncomment this option
                   ]{example-image-a}

   Quelle: The source
\end{sidewaysfigure}
\end{document}

A: First, the original \textwidth is lost using sidewaysfigure.  Second, I needed to test if the total figure was too big.  Finally, I needed the image height using [width=\textwidth] in order to determine what [height=] should be to compensate.
I tested \listoffigures to make sure only one caption showed up.
\documentclass{article}
\usepackage{showframe}
\usepackage[Export]{adjustbox}
\usepackage{rotating}
\usepackage{caption}
\captionsetup{justification=raggedright,
               singlelinecheck=false}

\newcommand{\source}[1]{\ttfamily #1}

\newsavebox{\tempbox}
\newlength{\tempdima}
\newlength{\tempdimb}
\newlength{\tempdimc}

\begin{document}
  \tempdima=\textwidth% inside \textwidth=\linewidth=\textheight
  \begin{sidewaysfigure}
  \textheight=\tempdima
  \settoheight{\tempdimb}{\includegraphics[width=\textwidth]{example-image-a}}% default height
  \savebox{\tempbox}{\begin{minipage}{\textwidth}
    \caption{The caption}
    \addtocounter{figure}{-1}% reset
    \rule{\textwidth}{\tempdimb}% same size but faster
    \par\source{The source}
    \end{minipage}}%
  \tempdima=\ht\tempbox\relax% can't get \dimexpr to work
  \advance\tempdima by \dp\tempbox\relax
  \tempdimc=\tempdimb
  \ifdim\textheight<\tempdima
    \advance\tempdimb by \textheight
    \advance\tempdimb by -\tempdima
  \fi
  \tempdima=\dimexpr \tempdimb*\textwidth/\tempdimc\relax% compute scaled width
  \hfil\begin{minipage}{\tempdima}
  \caption{The caption}
  \includegraphics[width=\textwidth]{example-image-a}\par
  \source{The source}
  \end{minipage}
  \end{sidewaysfigure}
\end{document}

A: Here is a code that works for me (not perfect but I can work with it):
\documentclass[a4paper,twoside]{article}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{rotating}
\usepackage[showframe ,lmargin=1.0783in,rmargin=1.3in,top=2.8cm,bottom=4.15cm]{geometry}
\setlength{\headheight}{40.9461pt}
\usepackage{fancyhdr}
\fancyhead[RE]{}
\fancyhead[RO]{\rightmark}
\fancyhead[LO]{}
\fancyhead[LE]{\leftmark}
\usepackage{hyperref}

\usepackage{lipsum}

%For caption
\def\abcapskip{3.5mm}
\def\belcapskip{4mm}
\usepackage[aboveskip=\abcapskip,belowskip=\belcapskip]{caption}
\renewcommand{\captionfont}{\rmfamily}
\renewcommand{\captionlabelfont}{\bfseries\sffamily}
\captionsetup{labelsep=colon}
\usepackage{amsmath}
\numberwithin{figure}{section}
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thefigure}{\thesection.\arabic{figure}}
\newcounter{nextfigure}
\newcommand*{\PhantomTheFigure}{\setcounter{nextfigure}{\value{figure}}\stepcounter{nextfigure}\Roman{section}.\roman{nextfigure}}
%For sidewaysfigure's height
\newsavebox{\capbox}
\newsavebox{\textbox}
\newlength{\swheight}
\newlength{\mywidth}
\newlength{\myheight}
\setlength{\mywidth}{\textwidth}
\setlength{\myheight}{\textheight}
\newcommand{\swcaption}[4][]{\gdef\FArg{#1}\gdef\SArg{#2}\gdef\TArg{#3}\gdef\FthArg{#4}\savebox\capbox{\vbox{{\bfseries\sffamily Figure\space\PhantomTheFigure:}\space\textrm#2}}\savebox\textbox{\vbox{#4}}\setlength{\swheight}{\mywidth}\ifx\SArg\empty\relax\else\addtolength{\swheight}{-\dimexpr\ht\capbox+\dp\capbox+\abcapskip+\belcapskip}\fi\ifx\FthArg\empty\relax\else\addtolength{\swheight}{-\dimexpr\ht\textbox+\dp\textbox}\fi}
\newcommand{\makeswcap}{\ifx\FArg\empty\captionof{figure}{\SArg}\else\captionof{figure}[\FArg]{\SArg}\fi\TArg}
\newcommand{\makeswtext}{\ifx\FArg\empty\relax\else\par\usebox{\textbox}\par\fi}

\begin{document}
\setlength{\mywidth}{\textwidth}
\setlength{\myheight}{\textheight}
\pagestyle{fancy}
\section{First example with caption below}
\lipsum[1-2]

{\color{red}Here comes the Sidewaysfigure~\ref{fig:A1} with the caption below the figure:}

\begin{sidewaysfigure}
  \swcaption[This is my short caption]{This is my extended caption that will use more than one row and its height will be automatically measured to be used for figure height adjustment}{\label{fig:A1}}{}
  \includegraphics[height=\swheight]{example-image-a}
  \makeswcap
\end{sidewaysfigure}

\clearpage
\subsection{Second example with caption below\ldots Plus text above}
\lipsum[1-2]

{\color{red}Here comes the Sidewaysfigure~\ref{fig:A2} with the caption below the figure and some text above:}

\begin{sidewaysfigure}
  \swcaption[This is my short caption]{This is my extended caption that will use more than one row and its height will be automatically measured to be used for figure height adjustment}{\label{fig:A2}}{Here is a text that will be added in this last sideways figure below the caption and the figure. Here is a text that will be added in this last sideways figure below the caption and the figure.}
  \makeswtext
  \includegraphics[height=\swheight]{example-image-b}
  \makeswcap
\end{sidewaysfigure}

\clearpage
\section{Second example with caption above}
\lipsum[1-2]

{\color{red}Here comes the Sidewaysfigure~\ref{fig:B1} with the caption above the figure:}

\begin{sidewaysfigure}
  \swcaption[This is my short caption]{This is my extended caption that will use more than one row and its height will be automatically measured to be used for figure height adjustment}{\label{fig:B1}}{}
  \makeswcap
  \includegraphics[height=\swheight]{example-image-b}
\end{sidewaysfigure}
\clearpage

\subsection{Second example with caption above\ldots Plus text}
\lipsum[1-2]

{\color{red}Here comes the Sidewaysfigure~\ref{fig:B2} with the caption above the figure and some text below}

\begin{sidewaysfigure}
  \swcaption[This is my short caption]{This is my extended caption that will use more than one row and its height will be automatically measured to be used for figure height adjustment}{\label{fig:B2}}{\vspace*{20pt}Here is a text that will be added in this last sideways figure below the caption and the figure}
\makeswcap
  \includegraphics[height=\swheight]{example-image-b}
\makeswtext
\end{sidewaysfigure}

\end{document}


text:
Q: jenkins in docker - how to change timezone Question:

*

*How do I set the timezone in jenkins in a docker container so that when you reboot the server it retains the setting?

So i'm running RHEL 7 on AWS with docker and jenkins (https://hub.docker.com/r/jenkinsci/blueocean/).
This article talks about how to change the timezone
https://wiki.jenkins.io/display/JENKINS/Change+time+zone
essentially two ways

*

*run System.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', 'America/New_York') in the script console which works but if you reboot the server or jenkins it reverts back

*add it to /etc/sysconfig/jenkins, unfortunately that directory does not exist as it's running in a container

However i have created a volume for the settings folder this way
docker run -d -p 8080:8080 -v $PWD/jenkins:/var/jenkins_home:z -t jenkinsci/blueocean

this makes the home directory "jenkins-blue"
the directory listing is
4 -rw-r--r--.   1 <omitted user>  1647 Feb 27 17:00 config.xml
4 -rw-r--r--.   1 <omitted user>  3982 Feb 27 16:57 copy_reference_file.log
4 -rw-r--r--.   1 <omitted user>   966 Feb 27 17:04 credentials.xml
0 drwxr-xr-x.   3 <omitted user>    16 Feb 27 17:06 fingerprints
4 -rw-r--r--.   1 <omitted user>   156 Feb 27 16:57 hudson.model.UpdateCenter.xml
4 -rw-r--r--.   1 <omitted user>  1230 Feb 27 17:07 hudson.plugins.emailext.ExtendedEmailPublisher.xml
4 -rw-r--r--.   1 <omitted user>   370 Feb 27 16:58 hudson.plugins.git.GitTool.xml
4 -rw-------.   1 <omitted user>  1712 Feb 27 16:57 identity.key.enc
0 drwxr-xr-x.   2 <omitted user>    41 Feb 27 16:57 init.groovy.d
4 -rw-r--r--.   1 <omitted user>    94 Feb 27 16:58 jenkins.CLI.xml
4 -rw-r--r--.   1 <omitted user>     7 Feb 27 17:00 jenkins.install.InstallUtil.lastExecVersion
4 -rw-r--r--.   1 <omitted user>     7 Feb 27 17:00 jenkins.install.UpgradeWizard.state
4 -rw-r--r--.   1 <omitted user>   183 Feb 27 17:00 jenkins.model.JenkinsLocationConfiguration.xml
4 -rw-r--r--.   1 <omitted user>   171 Feb 27 16:57 jenkins.telemetry.Correlator.xml
0 drwxr-xr-x.   3 <omitted user>    18 Feb 27 17:00 jobs
0 drwxr-xr-x.   4 <omitted user>    37 Feb 27 16:58 logs
4 -rw-r--r--.   1 <omitted user>   907 Feb 27 16:58 nodeMonitors.xml
0 drwxr-xr-x.   2 <omitted user>     6 Feb 27 16:58 nodes
20 drwxr-xr-x. 106 <omitted user> 16384 Feb 27 16:59 plugins
4 -rw-r--r--.   1 <omitted user>   129 Feb 28 17:35 queue.xml
4 -rw-r--r--.   1 <omitted user>    64 Feb 27 16:57 secret.key
0 -rw-r--r--.   1 <omitted user>     0 Feb 27 16:57 secret.key.not-so-secret
4 drwx------.   4 <omitted user>  4096 Feb 27 17:14 secrets
0 drwxr-xr-x.   2 <omitted user>   182 Feb 27 16:59 updates
0 drwxr-xr-x.   2 <omitted user>    24 Feb 27 16:58 userContent
0 drwxr-xr-x.   3 <omitted user>    57 Feb 27 17:00 users
4 drwxr-xr-x.  11 <omitted user>  4096 Feb 27 16:57 war
0 drwxr-xr-x.   2 <omitted user>     6 Feb 27 16:58 workflow-libs
0 drwxr-xr-x.   4 <omitted user>    34 Feb 27 17:06 workspace

A: Run it in System Management -> Script command line:
System.setProperty('org.apache.commons.jelly.tags.fmt.timeZone',
'Asia/Shanghai')

https://wiki.jenkins.io/display/JENKINS/Change+time+zone
BTW, I add this in my Timed tasks:
TZ=Asia/Shanghai
40 15 * * 1-5

OR
docker run ... -e JAVA_OPTS=-Duser.timezone=Asia/Shanghai

https://github.com/jenkinsci/docker/issues/45

A: Dockerfile
FROM jenkins/jenkins:2.176.1

USER root

# Configure Timezone
RUN \
rm -f /etc/localtime && \
ln -s /usr/share/zoneinfo/America/Los_Angeles /etc/localtime && \
echo 'America/Los_Angeles' > /etc/timezone && \
dpkg-reconfigure --frontend noninteractive tzdata

A: You may apply a TZ environment into your docker-compose like this:
image: jenkins/jenkins:alpine
container_name: jenkins
hostname: jenkins
restart: always
environment:
  - TZ=Asia/Shanghai
volumes:
  - ./jenkins/data:/var/jenkins_home
  - ./jenkins/bin/jenkins.war:/usr/share/jenkins/jenkins.war

A: Simply Map the volume while running jenkins container
-v /etc/timezone:/etc/timezone:ro

A: environment:

*

*TZ=Asia/Shanghai
This work for me


text:
Q: jzlib 1.0.7: ArrayOutOfBoundException in ZOutputStream.write() I have a simple test case producing a sure ArrayOutOfBoundException in jzlib
1.0.7 depending on the data subsequently written to one and the same instance
of ZOutputStream.
Stacktrace:
java.lang.ArrayIndexOutOfBoundsException: 587
    at com.jcraft.jzlib.Tree.d_code(Tree.java:149)
    at com.jcraft.jzlib.Deflate.compress_block(Deflate.java:691)
    at com.jcraft.jzlib.Deflate._tr_flush_block(Deflate.java:897)
    at com.jcraft.jzlib.Deflate.flush_block_only(Deflate.java:772)
    at com.jcraft.jzlib.Deflate.deflate_slow(Deflate.java:1195)
    at com.jcraft.jzlib.Deflate.deflate(Deflate.java:1567)
    at com.jcraft.jzlib.ZStream.deflate(ZStream.java:133)
    at com.jcraft.jzlib.ZOutputStream.write(ZOutputStream.java:102)
    at com.jcraft.jzlib.JZLibTestCase.main(JZLibTestCase.java:51)
       at JZLibTestCase.main(JZLibTestCase.java:28)

The problem occurs very rarely and depends on the data subsequentially
written to an open ZOutputStream from jzlib.
Do you have a hint how to fix this? Have you ever heard of this?

A: Near as I can tell you might've found a bug with JZlib. While searching around I came across other places that have your post with attached source and data files. It does not appear that you're doing anything wrong. You should be able to stream any sequence of bytes to ZOutputStream.
Is there a particular reason you're using JZlib? The two main reasons I understand to use it are support for Z_PARTIAL_FLUSH mode and licensing. If you don't need that flush mode and you're using the Oracle JVM, you should be just fine with the included DeflaterOutputStream. Substituting it in your code for ZOuputStream works without an exception.

A: I haven't found a concrete reason for using jzlib asking my co-workers, but for sure there has been a bug using java.util.zip somewhen in JRE 1.4 on multi-processor systems, although no one has been able to tell me concretely which one. From that time on we have been using jzlib, which has worked good for many years. Most probably it is already fixed. Nevertheless, using java.util.zip works with my simple test data in the same manner jzlib failed with, that's true.


text:
Q: "warning: database file for 'custom' does not exist" I write this in console:
sudo pacman -S kate

but for any package, I get this error:
warning: database file for 'custom' does not exist
error: failed to prepare transaction (could not find database)

I have tried
sudo pacman -Syu

but I still get the same error.

A: It looks like your pacman configuration has an entry for a repository called "custom", but you don't have any database file for it. Since this is usually the name of the commented out example in the example configuration, I'm guessing this was a mistake.
If you don't intend to use this repository, you can remove it from your /etc/pacman.conf. It will look something like this:
[custom]
Include = ...

Otherwise, if you do intend to use this repository, you should force a resync of your local repository databases:
pacman -Syy


text:
Q: Using assumed-rank Fortran array as derived type component I'm looking for some general advice as to the best approach to creating a derived type that stores arbitrary data with arbitrary rank.
Say I have a derived type Result with a data component (amongst others):
type, public :: Result
    private
    class(*), allocatable :: data
    ...
end type

which is initialised by some procedure (called from an interface Result):
function init(data) result(this)
  type(Result) :: this
  class(*), intent(in) :: data

  allocate(this%data, source=data)
end function

This works fine for scalar data, but I'm unsure about how to go about setting it up for arbitrary-rank data. I know procedures can accept assumed-rank parameters, so data in the init(data) function could be data(..), but I'm not sure it's possible to specify the derived type property this%data as being a assumed rank?
The other way I thought of doing it would be to store the arbitrary rank data as a scalar, if such a thing is possible in Fortran? This would be equivalent to using the serialize() and unserialize() functions in PHP. If anyone has any guidance on a similar approach, I'd be very grateful.
Ultimately I'd like to be able to do something like this:
type(Result) :: scalarResult
type(Result) :: 2DResult

scalarResult = Result(data=1.234)
2DResult = Result(data=[[1,2,3],[4,5,6]])

A: It's not possible to have an assumed rank derived type component. You'll need to find another solution, such as what Vladimir suggests. Another idea, which is sort of a kluge, is to store the C_LOC of the data and the rank, call out to a C routine that constructs an appropriate C descriptor and then calls back in to a Fortran routine with an assumed-rank argument.
Do keep in mind that you can't do a lot with assumed rank in Fortran - SELECT RANK doesn't exist until F2015.


text:
Q: android fonts in xml - how to override default font like calligraphy library does I am trying to swap out calligraphy (very useful library)  for android fonts in xml
but i dont know how to change the default font for all views like with calligraphy.  Calligraphy was able to change the default font at initialization time.  How can i do this with android fonts support library ?
from the fonts in xml article on android developer site i see we can apply a font family to one view like this:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/lobster"/>

but what if i want to change the font of the entire app ?
the reason i'd like to use android xml fonts is due to this error but this is not really relevant to the question.

A: With the Support Library 26.1.0 I managed to have a default font for the whole app by setting the android:fontFamily attribute for the application theme:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
     ...
    <item name="android:fontFamily">@font/proxima_nova</item>
</style>

Where proxima_nova.xml is a font resource file:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="UnusedAttribute">
    <!-- As of Android Support Library 26.0, we must declare both sets of attributes to ensure
         our fonts load on devices running Android 8.0 (API level 26) or lower. -->
    <font
        android:font="@font/proxima_nova_light"
        android:fontStyle="normal"
        android:fontWeight="300"
        app:font="@font/proxima_nova_light"
        app:fontStyle="normal"
        app:fontWeight="300" />
    <font
        android:font="@font/proxima_nova_semibold"
        android:fontWeight="600"
        app:font="@font/proxima_nova_semibold"
        app:fontWeight="600" />
</font-family>


text:
Q: How do you activate the "Scavenger Hunt: Cat School Gear Upgrade Diagrams - Part 1" quest? I usually activate the witcher gear upgrade quests by buying maps for them from vendors, but I haven't been able to find anything that activates the quest for the Enhanced Feline gear, which would be called

Scavenger Hunt: Cat School Gear Upgrade Diagrams - Part 1

I know I can look up the locations for the diagrams online, but I want to be able to locate the diagrams through the in-game quest, not by just googling every diagram.
How do I activate this quest? If there's a map for it, I haven't been able to find it. Does a specific vendor sell the map?

A: I'm pretty sure, there actually aren't maps available for every single witcher gear quest. However, finding one of the diagrams will activate the quest.
So, you can either explore and hope to find one diagram or you google one of them, either option will activate the quest allowing you to find the others.
I deliberately won't post any information on the diagrams, as you stated you want to find it through the ingame quest.


text:
Q: How to get Angular to have a click event bring part of the dom with it to the function? I am creating a small practice to-do list app with Angular. I have created a form for creating new tasks and they are updating fine. I have a button generate for every task that is titled "remove". I'd like to make the button remove specifically that task from the todo list. Here's the html code:

                {{task.name}}: {{task.description}}
                <button ng-click="killtodo()"> Remove </button>

 Display:

                {{task}}: {{taskDescription}}

    <form ng-submit="addto()">
        <input type="text" ng-model="task" placeholder="Enter a task name.">
        <input type="text" ng-model="taskDescription" placeholder="Enter the description.">
        <input class="btn-primary" type="submit" value="add">
    </form>

Javascript code:
function todoListController($scope) {
$scope.taskList = [
{"name": "Task List",
 "description": "Make a Task List."}
];

$scope.addto = function() {
    $scope.taskList.push({name:$scope.task, description:$scope.taskDescription});
    $scope.task = '';
    $scope.taskDescription = '';
};

$scope.killtodo = function(name) {
};

}
Any suggestions would be great, thanks.

A: You have access to a variable called $index while using an ng-repeat so you can do something like this:

        {{task.name}}: {{task.description}}
        <button ng-click="killtodo($index)"> Remove </button>

And then in your controller:
function todoListController($scope) {
    //other code
    $scope.killtodo = function($index){
        $scope.taskList.splice($index, 1);
    }
}

There's more description available in the docs at the top (including other variables you can use): http://docs.angularjs.org/api/ng.directive:ngRepeat


text:
Q: DALEX and step_pca I would like to look at the compound feature importance of the principal components with DALEX model_parts but I am also interested to what extent the results are driven by variation in a specific variable in this principal component. I can look at individual feature influence very neatly when using model_profile but in that case, I cannot investigate the feature importance of the PCA variables. Is it possible to get the best of both world and look at the compound feature importance of a principal component while using model_profile partial dependence plots of individual factors as shown below?
Data:
library(tidymodels)
library(parsnip)
library(DALEXtra)

set.seed(1)
x1 <- rbinom(1000, 5, .1)
x2 <- rbinom(1000, 5, .4)
x3 <- rbinom(1000, 5, .9)
x4 <- rbinom(1000, 5, .6)
# id <- c(1:1000)
y <- as.factor(rbinom(1000, 5, .5))
df <- tibble(y, x1, x2, x3, x4, id)
df[, c("x1", "x2", "x3", "x4", "id")] <- sapply(df[, c("x1", "x2", "x3", "x4", "id")], as.numeric)

Model
# create training and test set
set.seed(20)
split_dat <- initial_split(df, prop = 0.8)
train <- training(split_dat)
test <- testing(split_dat)
# use cross-validation
kfolds <- vfold_cv(df)

# recipe
rec_pca <- recipe(y ~ ., data = train) %>%
  update_role(id, new_role = "id variable") %>%
  step_center(all_predictors()) %>%
  step_scale(all_predictors()) %>%
  step_pca(x1, x2, x3, threshold = 0.9, num_comp = turn_off_pca)

# parsnip engine
boost_model <- boost_tree() %>%
  set_mode("classification") %>%
  set_engine("xgboost")

# create wf
boosted_wf <-
  workflow() %>%
  add_model(boost_model) %>%
  add_recipe(rec_pca)

final_boosted <- generics::fit(boosted_wf, df)

# create an explanation object
explainer_xgb <- DALEXtra::explain_tidymodels(final_boosted,
                                              data = df[,-1],
                                              y = df$y)

# feature importance
model_parts(explainer_xgb) %>% plot()

This gives me the following plot although even if I have reduced x1, x2 and x3 into one component in step_pca above.

I know I could reduce dimensions manually and bind it to the df like so and then look at the feature importance.
rec_pca_2 <- df %>%
  select(x1, x2, x3) %>%
  recipe() %>%
  step_pca(all_numeric(), num_comp = 1)

df <- bind_cols(df, prep(rec_pca_2) %>% juice())
df

> df
# A tibble: 1,000 × 6
   y        x1    x2    x3    x4   PC1
   <fct> <int> <int> <int> <int> <dbl>
 1 2         0     2     4     2 -4.45
 2 3         0     3     3     3 -3.95
 3 0         0     2     4     4 -4.45
 4 2         1     4     5     3 -6.27
 5 4         0     1     5     2 -4.94
 6 2         1     0     5     1 -4.63
 7 3         2     2     5     4 -5.56
 8 3         1     2     5     3 -5.45
 9 2         1     3     5     2 -5.86
10 2         0     2     5     1 -5.35
# … with 990 more rows

I could then estimate a model with PC1 as covariate. Yet, in that case, it would be difficult to interpret what the variation in PC1 substatial means when using model_profile since everything would be collapsed into one component.
model_profile(explainer_xgb) %>% plot()

Thus, my key question is: how can I look at the feature importance of components without compromising on the interpretability of the partial dependence plot?

A: You may be interested in the discussion here on how to get explainability from the original predictors vs. features that have been created via feature engineering (like PCA components). We don't have a super fluent interface yet, so you have to do this is a bit manually:
library(tidymodels)
#> Registered S3 method overwritten by 'tune':
#>   method                   from
#>   required_pkgs.model_spec parsnip
library(parsnip)
library(DALEX)
#> Welcome to DALEX (version: 2.4.0).
#> Find examples and detailed introduction at: http://ema.drwhy.ai/
#>
#> Attaching package: 'DALEX'
#> The following object is masked from 'package:dplyr':
#>
#>     explain

set.seed(1)
x1 <- rbinom(1000, 5, .1)
x2 <- rbinom(1000, 5, .4)
x3 <- rbinom(1000, 5, .9)
x4 <- rbinom(1000, 5, .6)
y <- as.factor(sample(c("yes", "no"), size = 1000, replace = TRUE))
df <- tibble(y, x1, x2, x3, x4) %>% mutate(across(where(is.integer), as.numeric))

# create training and test set
set.seed(20)
split_dat <- initial_split(df, prop = 0.8)
train <- training(split_dat)
test <- testing(split_dat)
# use cross-validation
kfolds <- vfold_cv(df)

# recipe
rec_pca <- recipe(y ~ ., data = train) %>%
    step_center(all_predictors()) %>%
    step_scale(all_predictors()) %>%
    step_pca(x1, x2, x3, threshold = 0.9)

# parsnip engine
boost_model <- boost_tree() %>%
    set_mode("classification") %>%
    set_engine("xgboost")

# create wf
boosted_wf <-
    workflow() %>%
    add_model(boost_model) %>%
    add_recipe(rec_pca)

final_boosted <- generics::fit(boosted_wf, df)
#> [14:00:11] WARNING: amalgamation/../src/learner.cc:1115: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.

Notice that next here I use regular DALEX (not DALEXtra), and that I manually extract out the xgboost model from inside the workflow and apply the feature engineering to the data myself:
# create an explanation object
explainer_xgb <-
    DALEX::explain(
        extract_fit_parsnip(final_boosted),
        data = rec_pca %>% prep() %>% bake(new_data = NULL, all_predictors()),
        y = as.integer(train$y)
    )
#> Preparation of a new explainer is initiated
#>   -> model label       :  model_fit  (  default  )
#>   -> data              :  800  rows  4  cols
#>   -> data              :  tibble converted into a data.frame
#>   -> target variable   :  800  values
#>   -> predict function  :  yhat.model_fit  will be used (  default  )
#>   -> predicted values  :  No value for predict function target column. (  default  )
#>   -> model_info        :  package parsnip , ver. 0.1.7 , task classification (  default  )
#>   -> predicted values  :  numerical, min =  0.1157353 , mean =  0.4626758 , max =  0.8343955
#>   -> residual function :  difference between y and yhat (  default  )
#>   -> residuals         :  numerical, min =  0.1860582 , mean =  0.9985742 , max =  1.884265
#>   A new explainer has been created!

model_parts(explainer_xgb) %>% plot()

Created on 2022-03-11 by the reprex package (v2.0.1)
The only behavior supported right now in DALEXtra is based on using the original predictors so if you want to look at those engineered features, you need to do it yourself. You may be interested in this chapter of our book.


text:
Q: python exceptions: how to print all debug info for nested try? I have code:
try:
    print test.qwerq]
    try:
        print test.sdqwe]
    except:
        pass
except:
   pass

How to print debug info for all errors in nested try ?

A: Re-raise exceptions.
try:
    print test[qwerq]
    try:
        print test[qwe]
    except:
        # Do something with the exception.
        raise
except:
   # Do something here too, just for fun.
   raise

It should be noted that in general you don't want to do this. You're better off not catching the exception if you're not going to do anything about it.
If you want to just print the call stack and not crash, look into the traceback module.


text:
Q: Python prime numbers Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far:
numprimes = raw_input('Prime Numbers  ')
count = 0
potentialprime = 2

def primetest(potentialprime):
    divisor = 2
    while divisor <= potentialprime:
        if potentialprime == 2:
            return True
        elif potentialprime % divisor == 0:
            return False
            break
        while potentialprime % divisor != 0:
            if potentialprime - divisor > 1:
                divisor += 1
            else:
                return True

while count < int(numprimes):
    if primetest(potentialprime) == True:
        print potentialprime
        count += 1
        potentialprime += 1
    else:
        potentialprime += 1

But I get the result in a single column. How can I get it in 5 rows?

A: col=0                  #add this line
while count < int(numprimes):
    if primetest(potentialprime) == True:
        print "%5d"%potentialprime, #and this line
        col += 1        #and this block
        if col==5:      #
            print "\n"  #
            col=0       #
        count += 1
        potentialprime += 1
    else:
        potentialprime += 1

A: Add a variable for the number of the current column currentCol initialized to 0 and change the line print potentialprime to the following 5 lines:
print str(potentialprime).ljust(5),
currentCol += 1
if currentCol==5:
    print ""
    currentCol=0

Take notice of the call to ljust and the , at the end of the print line that prevents a newline at the end of printed number. After the 5 columns printed (if currentCol==5) you print a newline and reset currentCol to 0.
See http://ideone.com/WsLnDK for the whole modified program with your intended output.

A: while count < int(numprimes):
    if primetest(potentialprime) == True:
        print "%5d" % potentialprime, #and this line
        col += 1        #and this block

        if col == 5:      #
            print "\n"    #
            col = 0       #

        count += 1
        potentialprime += 1
    else:
        potentialprime += 1

A: # The below code will print 1 prime number or a range of prime numbers if passed
# in the range.

def primeNumber(num):
for i in range(2,num):
    if num%i==0:
        return f"{num} - not a prime number"
        break
else:
    return f"{num} - is a prime number"

mylist = [i for i in range(1,100)]
for i in mylist:
    print(primeNumber(i))


text:
Q: How to properly store a 2D text file in a 2D array? I'm trying to read a text file into a 2D array. The rows and columns are listed in the first 2 lines of the text file so I just:
inFile >> rows;
inFile >> cols;

and that works fine.
However, whenever I initialize the array and print it...it doesn't come out properly. Why? There should be spaces in the maze but everything is filled with # like so:
# # # # # # # # #
# # # # # # # # #
# # # # # s # # #
e # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # #

    void setArray(int rows, int cols)
    {

        for (int i = 0; i < rows; i++)
        {
            grid[i] = new string[cols];
        }

        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < cols; j++)
            {
                inFile >> grid[i][j];
            }
        }

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                cout << grid[i][j] << " ";
            }
            cout << endl;
        }
    }


text:
Q: Grouping FechedResults by Month/Year to display a swiftui list with sections I have a core data entity (LogEntry) that includes a date attribute. I'm trying to migrate a view to SwiftUI and the view must show all the log entries grouped by Year Month (and sorted chronologically) like so:
JUN 2017

*

*Log Entry 1 (June 10)

*Log Entry 2 (June 16)

*Log Entry 3 (June 17)

JUL 2017

*

*Log Entry 1 (July 1)

*Log Entry 2 (July 3)

*etc.

I have been able to achieve the desired grouping with this code:
func group(_ result : FetchedResults<LogEntry>) -> [[LogEntry]] {
    return  Dictionary(grouping: result){ (element : LogEntry)  in
        sectionDateFormatter.string(from: element.date as Date)
    }.values.map{$0}
}

var body: some View {
    NavigationView {
        List {
            ForEach(group(logEntries), id: \.self) { (section: [LogEntry]) in  //Works but not ordered
                Section(header: Text( self.sectionDateFormatter.string(from: section[0].date as Date))) {
                    ForEach(section, id: \.self) { logEntry in
                        HStack {
                            Text("\(self.logDateFormatter.string(from: logEntry.date as Date))")
                            Spacer()
                            Text("\(logEntry.total) m").font(.subheadline)
                        }
                    }
                }
            }.id(logEntries.count)
        }
        .listStyle(PlainListStyle())
    }
}

I have been trying to add the sorting for a while and I can't seem to find the right way to do it in the context of SwiftUI.
I tried this:
func update(_ result : FetchedResults<LogEntry>)-> [[LogEntry]]{
        return  Dictionary(grouping: result){ (element : LogEntry)  in
            sectionDateFormatter.string(from: element.date as Date)
        }.values.sorted() { $0[0].date! < $1[0].date! }
    }

... but I get a "Type of expression is ambiguous without more context" error and it fails to compile.
I also tried this:
func groupedByYearMonth(_ result: FetchedResults<LogEntry>) -> [Date: [LogEntry]] {
      let empty: [Date: [LogEntry]] = [:]
      return logEntries.reduce(into: empty) { acc, cur in
        let components = Calendar.current.dateComponents([.year, .month], from: cur.date as Date)
          let date = Calendar.current.date(from: components)!
          let existing = acc[date] ?? []
          acc[date] = existing + [cur]
      }
    }

... but in this case, I couldn't figure out how to tweak the SwiftUI list ForEach to work with it.
Any pointers would be greatly appreciated!

A: You can sort the the fetched results if you use a different key in the temporary dictionary that can be properly sorted. So for the DateFormatter used in the function I set the format to "yyyy-MM" instead.
Note that I start by sorting the input to the function but this step is not needed if the fetched result is already sorted on date which I recommend.
func group(_ result : FetchedResults<LogEntry>) -> [[LogEntry]] {
    let sorted = result.sorted { $0.date < $1.date }

    return Dictionary(grouping: sorted) { (element : LogEntry)  in
        dictionaryDateFormatter.string(from: element.date as Date)
    }.sorted { $0.key < $1.key }.map(\.value)
}


text:
Q: The role of OpenFire in an XMPP chat android app I am trying to create an XMPP client via the Smack library for my android app.
The goal is to use GCM-XMPP in my implementation of chatting functionality in my app. From what i've been reading I could use Smack classes such as ChatManager, Chat and Message to create chats between users and also to add chat message listeners. On the other hand, i see that i can do the same i did with the ChatManager, Chat and Message classes using packets in order to create stanzas. From what I understand from GCM documentation, these stanzas will be needed to verify ACK and NACK messages between my app server and GCM CCS servers. Please correct me if I am wrong. It seems to me that creating these packets/stanzas will be more useful once i implement GCM functionality in my chat app.
Also, I still dont understand the role of OpenFire. I have OpenFire installed in my Localhost for testing purposes. To me it seems more like an interface where I can debug chat errors created by the Smack classes. Should this OpenFire be opened in my computer while I test my app chat functionality. I've downloaded OpenFire already and it created the necessary tables in my localhost database.
There's also some code that I am trouble understanding its parameters:
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("username", "password");
configBuilder.setResource("SomeResource");
configBuilder.setServiceName("jabber.org");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
connection.connect();
connection.login();

In the above code, what should be "username" and "password". Should it be the username and password used to log in to my localhost, or a username and password I am using to identify myself as a chatter in my app?
What about .setServiceName("jabber.org")? Should I set 10.0.2.2 in here since I am using localhost tested via android emulator? Should I type OpenFire?
And when this happens: connection.connect() , where is this connection connecting to? OpenFire or Localhost? Where is it login into?
Any advice will be appreciated

A: As mentioned on their site:

Openfire is a real time collaboration (RTC) server . It uses the only
  widely adopted open protocol for instant messaging, XMPP (also called
  Jabber).

In order to make calls from the app server to GCM server, you can follow HTTP or XMPP protocol. HTTP supports downstream (gcm to client) messages only. XMPP supports both downstream and upstream (device to gcm, then from gcm to server) messages. This is where Openfire comes in.

In the above code, what should be "username" and "password"?

username - the username or authorization identity
password - the password or token used to authenticate

What about .setServiceName("jabber.org")?

Set the resource to use.
If resource is null, then the server will automatically create a resource for the client. Default resource is "Smack".

where is this connection connecting to?

This connects to OpenFire.

Should I set 10.0.2.2 in here since I am using localhost tested via
  android emulator?

ports are set in .setPort("8222") part of the XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder().
More of the Getting Started guide here.
Now get started with an XMPP tutorial.


text:
Q: Playing audio - React / NodeJS / MongoDB- GridFS i have the following project structure:

*

*NodeJS is my back-end: used for upload .mp3 on my mongodb and stream this. I used GridFsBucket for upload/stream

*React is my front-end and work with Redux store: so, i've two pages, first for upload .mp3 file with FormData and the second is for stream-playing audio.

My upload stage work good, i push the selected .mp3 file on my back-end and with the help of GridFS create my collections on my MongoDB (fs.files and fs.chunks).
I playing my .mp3 from the backend at the http://site:4000/play/myMp3Code, this create a player that reproduce my .mp3. So it's ok.
My problem is on the stream-playing stage on React, because chunks(is it a chunks?) come on Redux but i don't know how to play it from my React web page.
This is my playing handle on backend
const filename = req.params.filename;

        const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
            chunkSizeBytes: 1024,
            bucketName: 'fs'
        });

        const downloadStream = bucket.openDownloadStreamByName(filename);

        downloadStream.on('data', (chunk) => {
            res.write(chunk);
        });

        downloadStream.on('error', () => {
            res.sendStatus(404);
        });

        downloadStream.on('end', () => {
            res.end();
        });

And my actions on Redux
export const playTrack = (path, id) => {
    return async dispatch => {
        try {
            const track = await api.call('get',`tracks/${path}/${id}`);

            console.log("Track action: ", track);

        dispatch(currentTrack(track));
            dispatch(removeError());
        } catch (err) {
            const {error} = err.response.data;
            dispatch(addError(error.message));
        }
    };
};

Example of console.log output from Redux action
���T!1AQa"q��2�#BR������3brCS��$���4Tcs�D��%��EUd����5����+!1AQ"2aBq#R3�$��?��v�.A  �UY�d[MVj�?�  1u
��D���MM1�u*곧TXR��X��A ,ְ���+#h�J��*)gQ��i�R:�Ut5�9���Ŋ�)ע%�r�X��c�&ȣ�����GD�B=c^�6T� 2y,�F���\*��
�H���*�Lҋ ....

My question is the following: How can i playing my .mp3 directly from my frontend?
Can i play this above data from Reat?
Hope i've explained well.
Thanks for answers and for reading

A: I think the stream is OK, all you need to do is send the response with correct headers: (Content-Type: audio/mpeg) and the browser should play it.


text:
Q: Junk after C++ string when returned I've just finished C++ The Complete Reference and I'm creating a few test classes to learn the language better. The first class I've made mimics the Java StringBuilder class and the method that returns the string is as follows:
char *copy = new char[index];
register int i;
for(i = 0; i <= index; i++) {
    *(copy + i) = *(stringArray + i);
} //f

return copy;

stringArray is the array that holds the string that is being built, index represents the amount of characters that have been entered.
When the string returns there is some junk after it, such as if the string created is abcd the result is abcd with 10 random characters after it. Where is this junk coming from? If you need to see more of the code please ask.

A: You need to null terminate the string. That null character tells the computer when when string  ends.
char * copy = new char[ length + 1];
for(int i = 0; i < length; ++i) copy[i] = stringArray[i];
copy[length] = 0; //null terminate it

Just a few things. Declare the int variable in the tighest scope possible for good practice. It is good practice so that unneeded scope wont' be populate, also easier on debugging and kepping track. And drop the 'register' keyword, let the compiler determine what needs to be optimized. Although the register keyword just hints, unless your code is really tight on performance, ignore stuff like that for now.

A: Does index contain the length of the string you're copying from including the terminating null character? If it doesn't then that's your problem right there.
If stringArrary isn't null-terminated - which can be fine under some circumstances - you need to ensure that you append the null terminator to the string you return, otherwise you don't have a valid C string and as you already noticed, you get a "bunch of junk characters" after it. That's actually a buffer overflow, so it's not quite as harmless as it seems.
You'll have to amend your code as follows:
char *copy = new char[index + 1];

And after the copy loop, you need to add the following line of code to add the null terminator:
 copy[index] = '\0';

In general I would recommend to copy the string out of stringArray using strncpy() instead of hand rolling the loop - in most cases strncpy is optimized by the library vendor for maximum performance. You'll still have to ensure that the resulting string is null terminated, though.