text:
Q: Drupal 6 acces denied on page in non drupal folder I have a folder in '/sites/all/libraries/folder'.
In this folder some html files are automatically generated with a drupal module.
In my navigation block a created a link 'mysite.com/folder' that is a redirect from '/sites/all/libraries/folder'.
I can see the index.html. On this page are links to the other files that gets generated, like '2011-05-15_14:00_001.html'.
But when I open the file, I get an acces denied error.
When I go to mysite.com/sites/all/libraries/folder/2011-05-15_14:00_001.html', I don't get the acces denied error.
How can I fix this?
Thanks

A: In your Drupal root there is a .htaccess file that will route all requests through Drupal bootstrap by default, you probably want to either:

*

*Place your generated files outside
the Drupal installation

*Override the .htaccess routes so those are not
checked through the bootstrap

*Set
redirects to each individual file you
have, in the same way you created
your redirect 'mysite.com/folder' to
'/sites/all/libraries/folder'.


text:
Q: grabbing multiple types of tags in one jquery object From http://jqfundamentals.com/chapter/events, "In all of our examples up until now, we've been passing anonymous functions as event handlers. However, you can create a function ahead of time and store it in a variable, then pass that variable as the event handler. This is useful if you want to use the same handler for different events or events on different elements."
$( 'li' ).on( 'click', handleClick );
$( 'h1' ).on( 'click', handleClick );

Is there a jquery to get all li and all h1 elements in one liner? I interpret
$( 'h1 li' ).on( 'click', handleClick );

to mean "all li items inside of h1 items"
Thank you

A: You can try with:
$( 'h1, li' ).on( 'click', handleClick );

Here's the documentation.

A: Separate the selectors with commas.
$( 'h1, li' ).on( 'click', handleClick );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Capistrano 3: Run task only on a single server from a pool of servers assigned a role I have 20 servers that are in the "web" role.  I have a task I need to perform on only one of them as the change affects shared storage.  My current solution is a hack to get around this (below).  Looking for a better way, I don't have a ton of ruby or cap experience.
task :checkout_project_properties do
    num_runs = 0
    on roles(:web), in: :sequence do
        if num_runs > 0
            abort('Only running on one server.  Exiting')
        end
        execute("checkout-project-properties #{uc_stage} #{repo} #{branch}")
        num_runs += 1
    end
end

A: I assume that you are referring to your production configuration, with so many web servers. In this case, your config/deploy/production.rb probably contains many lines like this:
server 'web_1', roles: %w(web)
server 'web_2', roles: %w(web)
server 'web_3', roles: %w(web)
...

Simply make one of these servers primary, so it looks like:
server 'web_1', roles: %w(web), primary: true
server 'web_2', roles: %w(web)
server 'web_3', roles: %w(web)
...

Then change your task so it looks like this:
task :checkout_project_properties do
    on primary(:web) do
        execute("checkout-project-properties #{uc_stage} #{repo} #{branch}")
    end
end


text:
Q: Use of absolutePan() to move background image and elements around on canvas with touch event I am using next code to force content of canvas to follow finger touch movement on screen (drag and drop).
document.addEventListener('touchmove', function(e){

if(e.targetTouches.length ==1) {

          var canavasMovex=e.targetTouches[0].pageX-canvasLeftofset-canvas.width/2;
          var canavasMovey=e.targetTouches[0].pageY-canvasTopofset-canvas.height/2;
          document.getElementById("a").innerHTML=  canavasMovex;
          document.getElementById("b").innerHTML= canavasMovey;

        var delta = new fabric.Point(-canavasMovex,-canavasMovey);
        canvas.absolutePan(delta);
     canvas.renderAll();
  }
}, false);

Note: "-canavasMovex,-canavasMovey" values have the negative sign (I had to use it because otherwise the canvas was moving opposite to finger moment(I think you can ignore this fact and that it has noting to do with offset, which I am trying to solve asking for help here))
I have displacement of position proportional to the distance of touch point from the centre of canvas. If I start the movement pressing from the centre of screen, then displacement is not so notable. But if I start from  top corner (for example) I get centre of canvas there in that touch point. From attached drawing I was trying with taking of consideration of "d" parameter (distance of touching point to the centre of canvas), to find right value for the equation for the canvas.absolutePan() function, but no success. Can you help me with this case,pleas? I was trying to use some solutions from browsing the internet to find the way to move canvas content. But then I had lost some of functions of my app because "new" libraries were not interacting correctly with my existing fabric.min.js library. Image info(external rectangle-web page,internal rectangle-canvas):  a-canvas offset,b-distance to centre of canvas,c- touch point,d-distance from touch point to centre of canvas. So on the end I am trying to get to accomplish this task in this way.
Malfunction:
Bigger than distance "d" is on starting of dragging , bigger is then the offset. (actuary if I start dragging from canvas corner, canvas content transfers its centre there)

A: The solution is to get the finger position, calculate the difference to previous position, add difference to the previous position and then finally do the panning.
 var canvasMovexoold = 0;
 var canvasMoveyoold = 0;

document.addEventListener('touchstart', function(e){
    canvasMovexoold = canvasLeftofset+canvas.width/2-e.targetTouches[0].pageX;
    canvasMoveyoold =canvasTopofset+canvas.height/2- e.targetTouches[0].pageY;
}, false);

document.addEventListener('touchmove', function(e){

 if(e.targetTouches.length ==1) {
      var  canvasMovexo += canvasLeftofset+canvas.width/2-e.targetTouches[0].pageX-canvasMovexoold ;
      var  canvasMoveyo +=canvasTopofset+canvas.height/2- e.targetTouches[0].pageY-canvasMoveyoold ;
      var delta = new fabric.Point(canvasMovexo,canvasMoveyo);
      canvas.absolutePan(delta);
      canvasMovexoold = canvasLeftofset+canvas.width/2-e.targetTouches[0].pageX;
      canvasMoveyoold =canvasTopofset+canvas.height/2- e.targetTouches[0].pageY;
   }
}, false);


text:
Q: Ubuntu on VirtualBox character outputs differently I am using Ubuntu 14.04 Server on Virtual Box + Mac.
When I type [, ], \, {, }, | etc I get the following outputs.

I have UTF on locale.

UPDATE:
I found that I can type | by right option+shift+| on Mac. But how can I set it so that I can type normally without holding right+option key?

A: The problem is not in your locales, it is in your key mappings. The kernel maintains a mapping of keyboard scan codes (the key index values a keyboard outputs) to symbols, which appears to be incorrect. Most likely, Linux thinks that it receives scan codes from a PC keyboard, while in fact it receives Mac-flavoured scan codes.
To choose a key map, reconfigure the keyboard-configuration package:
sudo dpkg-reconfigure keyboard-configuration

Here you can select the correct keyboard layout.


text:
Q: Does the XML specification states that parser need to convert \n\r to \n always, even when \n\r appears in a CDATA section? I've stumbled in a problem handling the \line-feed and \carriage-return characters in xml.
I know that, according to http://www.w3.org/TR/REC-xml/#sec-line-ends, xml processors are required to replace any "\n\r" or lone "\r"  sequences with "\n".
The specification states that this has to be the behaviour for handling any "external parsed entity", does this apply to CDATA sections inside of an element as well?
thank you,
Michele
I'm sure that msxml library for example converts every \n\r" or lone "\r"  sequences  to "\n", regardless of their being in a cdata section or not.

A: I'll quote a sentence from the section you link to (emphasis mine):

To simplify the tasks of applications,
  the XML processor must behave as if it
  normalized all line breaks in external
  parsed entities (including the
  document entity) on input, before
  parsing, by translating both the
  two-character sequence #xD #xA and any #xD
  that is not followed by #xA to a single #xA character.

Because the XML processor does this before parsing, it doesn't know yet which parts of the document are CDATA sections. Therefore, it will do the replacement regardless of the characters being in a CDATA section or not.
To reliably preserve these characters, they have to be written to the XML document as
 and
 entities.

A: Yes - "\n\r" or "\r" in CDATA sections must be replaced with "\n" for a processor to be conforming. Any CDATA sections in your XML document will be part of the document entity, which is 'parsed'. You can find an example of an unparsed entity here.


text:
Q: Jquery if element has class, add class to this element child I want to add a class(active) to a child of an element who has a class (is-active) and does not effect other elements. using jQuery!

Link 1

Link 2

Link 3

Link 4

I'm using this code but it's effect all other elements.
if ($(".nav-item").hasClass("is-active")) {
  $('a', this).addClass('active');
}

I want to be like this:

Link 1

Link 2

Link 3

Link 4

A: You can chain the selector to target the parent then use .find() to get the child.
$(".nav-item.is-active").find('a').addClass('active')

A: if ($(".nav-item").hasClass("is-active")) {
  $(this).find('a').addClass('active');
}

You this code it will work

A: You can combine it's into a single selector(which selects a tag within .nav-item having is-active) and then add class to that.
$('.nav-item.is-active a').addClass('active');

$(".nav-item.is-active a").addClass('active');

console.log($('ul').html())

Link 1

Link 2

Link 3

Link 4

FYI : In your code this does not refer to the element, it may be window object or something else so it won't work. To make it work use each() method.
$(".nav-item").each(function(){
  if($(this).hasClass("is-active")) {
     $('a', this).addClass('active');
  }
})

$(".nav-item").each(function() {
  if ($(this).hasClass("is-active")) {
    $('a', this).addClass('active');
  }
})

console.log($('ul').html())

Link 1

Link 2

Link 3

Link 4

A: You can loop through your element and add class if current element has certain class. Here is working example.

var navlist = $(".nav-item");
$.each(navlist, function() {
  if ($(this).hasClass("is-active")) {
    $(this).find('a').addClass('active');
  }
});

console.log($('ul').html())

Link 1

Link 2

Link 3

Link 4


text:
Q: jQuery how to match two text strings without changing either? Another newbie question...
The script (below) compares selected text in one div with some target text in another, then applies a style to the second div's parent. I need to change the script to be less literal---not "if A is selected, look for A"; but rather, "if Apples is selected, look for A."
So, how do you get jQuery to recognize two different text strings as being the same thing? I tried "var A = 'Apples', B = 'Bravo' [etc] ;", but then the class is added to .embox when I hover over any #menutable div.
The HTML:

      content

A,B,C

      content

B,F

Apples

Bravo

Comp

Ferengi

Current script (doesn't work):
$('#menutable div').hover(function() {
    var that = this, A = "Apples", B = "Bravo", C = "Comp", F = "Ferengi";
    $('#maintable .options').filter(function() {
        return $(this).text().indexOf($(that).text()) === -1;
    }).closest(".embox").addClass("bgtransp");
},
function() {
    $(".embox").removeClass("bgtransp");
});

A: You can try to use jQuery's inArray() method to see if the value is within an array of values that you define.
Example:
$.inArray($(this).html(), ['Apples', 'A', 'Orange']);

In your code, check to see if the function returns something greater than -1. More info can be found in the jQuery docs linked above.

A: Use data attributes
HTML
div id="menutable">

Apples

Bravo

Comp

Ferengi

JS
$('#menutable div').hover(function() {
    var that = this;
    $('#maintable .options').filter(function() {
        return $(this).text().indexOf($(that).data('letter')) === -1;
        //seems to be !== -1
    }).closest(".embox").addClass("bgtransp");
},
function() {
    $(".embox").removeClass("bgtransp");
});

Besides, You can get first letter from string useing stringname[0]

A: if you don't want to use HTML5 data-*, you can use
var myArray = ['Apples', 'A', 'Orange'];
var i=0;
$("#menutable > .option").each(
   function(){
     $(this).data("myOption",myArray[i]);
     i++;
});

and you can get the data using
$('#menutable > .option').click(function() {
   var myOption = $(this).data("myOption");
}

note: its more web standard to set the id like menu-table instead of menutable :)


text:
Q: Sending e-mail with Google App Engine I'm trying to send e-mails from Google App Engine via a servlet with the following code. application.owner@gmail.com is listed in "Email API authorized senders". I don't get any errors and i don't receive any e-mails. I can see the log message in the log, so I'm pretty sure that the code is executed. Any ideas why I don't receive any e-mails?
package com.myapplication;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendMailServlet extends HttpServlet {

    final static Logger logger = Logger.getLogger(SendMailServlet.class.getName());

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        try {

            sendMail();

            logger.log(Level.INFO, "Send mail!");

        } catch (AddressException e) {
            logger.log(Level.WARNING, e.getMessage());
        } catch (MessagingException e) {
            logger.log(Level.WARNING, e.getMessage());
        }
    }

    private void sendMail() throws MessagingException {

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress("application.owner@gmail.com"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress("application.owner@gmail.com"));
        msg.setSubject("The subject");
        msg.setText("The message body");

        Transport.send(msg);
    }
}


text:
Q: Initial Data for D3 Tree are not properly visualize I managed to use d3 to make a bottom up family tree, the adding, deletion works fine as it is, but when i try to load initial data that have nested children to be more than 2 or more than the root, visualization of said data breaks.

*

*How do i get the initialize data to visualize given multiple nested
children? What did i missed in getting it to work?

*How do i calculate and set the separation between nodes when it gets more than 3 levels?
I've done the enter,update and exit as it should i think, resulting it to works in adding,deleting. JSFiddle for only root data, with adding and deleting.

When i initiliaze the data with more than 1 children, the visualization started to breaks, instead of initially showing all the relationships it only shows one relationship. The fiddle of said problem. As such:

What i wanted to achieve when it initially load with nested children data are the visualization of the nested relationships, as situation above it should be:

The data:
{
     patient_name: "Adam Farish",
     reference_id: "199210291",
     relationship: "",
     pc_id: "121292",
     consanguineous_marriage: false,
     children: [{
           patient_name: "Adam Father",
            reference_id: "199210291",
            relationship: "",
            pc_id: "121292",
            consanguineous_marriage: false,
            children: [],
            problems: [{
              id: 0,
              name: "cleft lip",
              impact: "disease",
              remarks: "Need constant monitoring."
            },
            {
              id: 1,
              name: "cleft palate",
              impact: "carrier",
              remarks: "Need constant monitoring."
            }]
        },{
           patient_name: "Adam Mother",
            reference_id: "199210291",
            relationship: "",
            pc_id: "121292",
            consanguineous_marriage: false,
            children: [],
            problems: [{
              id: 0,
              name: "cleft lip",
              impact: "disease",
              remarks: "Need constant monitoring."
            },
            {
              id: 1,
              name: "cleft palate",
              impact: "carrier",
              remarks: "Need constant monitoring."
            }]
        }
 ],
     problems: [{
       id: 0,
     name: "cleft lip",
     impact: "disease",
     remarks: "Need constant monitoring."
     },
     {
       id: 1,
     name: "cleft palate",
     impact: "carrier",
     remarks: "Need constant monitoring."
     }]
    }

The code for the D3 Family Tree:
var margin = {top: 140, right: 10, bottom: 140, left: 10};
    var height = 600;
    var width = 800;
    var rectW =  150;
    var rectH = 130;

    var tree = d3.layout.tree().size([width - 20, height - 60]);

    // var root = {};
    // get the tree layout
    var root = {
     patient_name: "Adam Farish",
     reference_id: "199210291",
     relationship: "",
     pc_id: "121292",
     consanguineous_marriage: false,
     children: [{
           patient_name: "Adam Father",
            reference_id: "199210291",
            relationship: "",
            pc_id: "121292",
            consanguineous_marriage: false,
            children: [],
            problems: [{
              id: 0,
              name: "cleft lip",
              impact: "disease",
              remarks: "Need constant monitoring."
            },
            {
              id: 1,
              name: "cleft palate",
              impact: "carrier",
              remarks: "Need constant monitoring."
            }]
        },{
           patient_name: "Adam Mother",
            reference_id: "199210291",
            relationship: "",
            pc_id: "121292",
            consanguineous_marriage: false,
            children: [],
            problems: [{
              id: 0,
              name: "cleft lip",
              impact: "disease",
              remarks: "Need constant monitoring."
            },
            {
              id: 1,
              name: "cleft palate",
              impact: "carrier",
              remarks: "Need constant monitoring."
            }]
        }
 ],
     problems: [{
       id: 0,
     name: "cleft lip",
     impact: "disease",
     remarks: "Need constant monitoring."
     },
     {
       id: 1,
     name: "cleft palate",
     impact: "carrier",
     remarks: "Need constant monitoring."
     }]
    };
    var nodes = tree(root);
    root.parent = root;
    root.px = root.x;
    root.py = root.y;
    root.id = 0;

    // make the diagonal link connection
    // var diagonal = d3.svg.diagonal();
    var diagonal = d3.svg.diagonal()
        // .source(function(d) { return {"x":d.source.x, "y":height - d.source.y + 12}; })
        .target(function(d) { return {"x":d.target.x, "y": height - d.target.y - 12}; })
        .source(function(d) { return {"x":d.source.x, "y":height - d.source.y + 12}; })
        .projection(function (d) {
            return [d.x + rectW / 2, d.y + rectH /2];
    });

    var svg = d3.select("#viz").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom);

    var node = svg.selectAll(".node");
    var link = svg.selectAll(".link");

    function addNode(val,method,rel){
        if(method === 'add'){
          var n = {id: nodes.length,relationship:rel,problems:[]};
            if(val){
                console.log("got value");
                var p = val;
            }else{
                console.log("no value");
                var p = nodes[Math.random() * nodes.length | 0];
                console.log("First node insert",p);
            }

            if (p.children) p.children.push(n); else p.children = [n];
            nodes.push(n);
        }else{
            if(val){
                val.parent.children.forEach(function(entry,i){
              if(entry.id === val.id){
                  val.parent.children.splice(i,1);
                  }
                });
                nodes.forEach(function(e,n){
                    if(e.id === val.id){
                        nodes.splice(n,1);
                    }
                })
            }
        }
        console.log('ADD NODE RUN!');
    }

    function removeNode(v){
        console.log('remove node',v);
        if("parent" in v){
            for(var i = v.parent.children.length - 1; i >= 0; i--) {
                if(v.parent.children[i].id === v.id) {
                  v.parent.children.splice(i, 1);
                }
            }
            nodes.forEach(function(entry,i){
               if(entry.id === v.id){
                   nodes.splice(i,1);
               }
            });
            console.log('value',v);
            console.log('nodes',nodes);
        }
    }

    var duration = 750
    // var timer = setInterval(update, duration);

    update();

    function update(v,method,rel) {
    //   if (nodes.length >= 2) return clearInterval(timer);
    //   if (nodes.length >= 1){
    //       clearInterval(timer);
    //   }

    console.log("UPDATE RUNS!");

      if(method === 'add'){
        addNode(v,'add',rel);
      }
      if(method=='remove'){
        addNode(v,'remove');
      }

      // Add a new node to a random parent.
      // Recompute the layout and data join.
      node = node.data(tree.nodes(root), function(d) { return d.id; });
      link = link.data(tree.links(nodes), function(d) { return d.source.id + "-" + d.target.id; });

      console.log(tree.nodes(root));

      var nodeEnter = node.enter().append("g");

       var foreignObject = nodeEnter.append("foreignObject")
            .attr("class", "htmlObject")
            .attr("height", rectH)
            .attr("width",rectW)
            .attr("x", function(d) { return d.parent.px; })
            .attr("y", function(d) { return height - d.parent.py + 30;  });

       var familyTreeNode = foreignObject.append("xhtml:div")
            .attr("class","ft-box ft-box-male ft-box-main clearfix");

            familyTreeNode.append("xhtml:div")
            .attr("class","ft-box-btn clearfix")
            .append("xhtml:div")
            .attr("class","ft-btn-menu")
            .append("xhtml:button")
            .attr("class","ft-btn-delete")
            .attr("title","Delete")
            .attr("dropdown-toggle","")
            .attr("aria-haspopup","")
            .attr("aria-expanded","false")
            .on("click",function(d){
                console.log("DELETE THIS NODE!",d);
                update(d,"remove");
            })
            .append("xhtml:em")
            .attr("class","fa fa-close");

    var dropdownButton = familyTreeNode.append("xhtml:div")
            // .attr("class","ft-btn-menu dropdown")
            // .attr("dropdown","dropdown");
            .attr("class","ft-btn-menu dropdown")
            // .attr("dropdown","dropdown");

            dropdownButton.append("xhtml:button")
            // .attr("class","btn btn-default dropdown-toggle")
            .attr("class","ft-btn-add")
            .attr("type","button")
            .attr("data-toggle","dropdown")
            // .attr("dropdown-toggle","")
            .attr("title","Add")
            .attr("aria-haspopup","true")
            .attr("aria-expanded","false")
            // .text("Action")
            .append("xhtml:em")
            .attr("class","fa fa-plus");

    var dropdownMenu = dropdownButton
            .append("xhtml:ul")
            // .attr("class","dropdown-menu");
            // .attr("role","menu")
            .attr("class","dropdown-menu ft-btn add animated fadeInDown");

        dropdownMenu.append("xhtml:div")
            .attr("class","arrow");

    var listDropdownFather = dropdownMenu.append("xhtml:li")
            .append("xhtml:a")
            .on("click",function(d){
               console.log("Add Father",d);
                 update(d,'add','father');
            });

        listDropdownFather.append("xhtml:em")
            .attr("class","fa fa-plus-circle");

        listDropdownFather.append("xhtml:span")
            .attr("class","ft-label-add")
            .text("Add Daddy");

    var listDropdownMother = dropdownMenu
            .append("xhtml:li")
            .append("xhtml:a")
            .on("click",function(d){
               console.log("Add Mommy",d);
               if('children' in d){
                   if(d.children[0].rel !== 'mother' && d.children.length < 2){
                        console.log('has children but not mother',d.children[0]);
                        update(d,'add','mother');
                   }
               }
               else{
                   console.log('no children, add Mother');
                   update(d,'add','mother');
               }
            });

        listDropdownMother.append("xhtml:em")
            .attr("class","fa fa-plus-circle");

        listDropdownMother.append("xhtml:span")
            .attr("class","ft-label-add")
            .text("Add Mother");

    familyTreeNode.append("xhtml:div")
            .attr("class","ft-person-icon clearfix")
            .append("xhtml:div")
            .attr("class","ft-male-icon")
            .attr("title","Info Details")
            .on("click", function(d){
                console.log("Open Modal Box",d);
                $scope.open({d: d});
            });

    var inputText = familyTreeNode.append("xhtml:input")
            .attr("class","ft-person-name ft-name clearfix")
            .attr("style","border:none;background: transparent;")
            .attr("id","patientname")
            .attr("value",function(d){
                return d.patient_name;
            })
            .on("blur",function(d){
                // console.log('Blur!',this);
               d.patient_name = this.value;
               inputText.attr("value",d.patient_name);
               console.log(this.value);
            });

    var footer = familyTreeNode.append("xhtml:div")
            .attr("class","ft-footer clearfix");

        footer.each(function(d, i) {
            var span = d3.select(this)
                  .selectAll('span')
                  .data(d.problems);

            span.enter()
              .append("xhtml:span")
              .attr("class",function(d,i){
                  var myStr = d.name.toLowerCase();
                  var matches = myStr.match(/\b(\w)/g);
                //   console.log('APPEND',matches);
                  return "ft-disease ft-"+matches.join('');
              })
              .text(function(prob){
                  console.log('APPEND',prob);
                  var myStr = prob.name.toUpperCase();
                  var matches = myStr.match(/\b(\w)/g);
                  return matches.join('');
              })

        });

      node.exit().remove();
      link.exit().remove();

      link.enter().insert("path", "g")
            .attr("class", "link")
            .attr("x", rectW / 2)
            .attr("y", rectH / 2)
            .attr("d", function (d) {
            var o = {
                x: d.source.px,
                y: height - d.source.py
            };
            return diagonal({
                source: o,
                target: o
            });
        });

        link.exit().transition()
            .duration(duration)
            .attr("d", function (d) {
            var o = {
                x: d.source.x,
                y: height - d.source.y
            };
            return diagonal({
                source: o,
                target: o
            });
        }).remove();

      var t = svg.transition()
          .duration(duration);

      t.selectAll(".link")
          .attr("d", diagonal);

      t.selectAll(".node")
          .attr("x", function(d) { return d.px = d.x; })
          .attr("y", function(d) { return d.py = height - d.y; });

      t.selectAll(".htmlObject")
          .attr("x", function(d) { return d.px = d.x; })
          .attr("y", function(d) { return d.py = height - d.y; });
  }

A: Okay, it seems that i just failed to initiate the id for each of the members, since the important part of generating the node is highly dependent on id(well u can change it to anything unique really).
node = node.data(tree.nodes(root), function(d) { return d.id; });
link = link.data(tree.links(nodes), function(d) { return d.source.id + "-" + d.target.id; });

The initial data needed to load the visualization must have id as such:
{
           id:2,
           patient_name: "Adam Father",
            reference_id: "199210291",
            relationship: "",
            pc_id: "121292",
            consanguineous_marriage: false,
            children: [],
            problems: [{
              id: 0,
              name: "cleft lip",
              impact: "disease",
              remarks: "Need constant monitoring."
            },
            {
              id: 1,
              name: "cleft palate",
              impact: "carrier",
              remarks: "Need constant monitoring."
            }]
        },{
           id:3,
           patient_name: "Adam Mother",
            reference_id: "199210291",
            relationship: "",
            pc_id: "121292",
            consanguineous_marriage: false,
            children: [],
            problems: [{
              id: 0,
              name: "cleft lip",
              impact: "disease",
              remarks: "Need constant monitoring."
            },
            {
              id: 1,
              name: "cleft palate",
              impact: "carrier",
              remarks: "Need constant monitoring."
            }]
        }

Working jsfiddle


text:
Q: When i try to resume JW Player video it starts at beginning I have a video pause like below:
jwplayer('video').onTime(function(event){
                    if ((event.position >= 19 && event.position < 20) || (event.position >= 29 && event.position < 30)){
                        jwplayer('video').pause();
                        $(".container").fadeOut(300);
                    }
                });

Then my app hides the video's container whilst it does something else.
Later my app will show the container then attempt to resume it.
$(".container").show();
var currentPosition = Math.ceil(jwplayer('video').getPosition());
jwplayer('video').seek(currentPosition);

For some strange reason the video will start from the beginning. Does someone know what i am doing wrong?
If i use console and try:
$(".container").show();

It seems to be restarting. I believe the "show" is causing it to start again.
I have narrowed down the problem a bit. When jquery changes display from none to block (as part of show method) the video restarts.

A: Might be easier to store the resume position in a variable accessible from both places and see if bypassing getPosition resolves your issues
var resume_position = 0;
jwplayer('video').onTime(function(event){
    if ((event.position >= 19 && event.position < 20) || (event.position >= 29 && event.position < 30)){
        resume_position = event.position;
        jwplayer('video').pause();
        $(".container").fadeOut(300);
    }
});

...

$(".container").show();
jwplayer('video').seek(resume_position);

A: I have found a solution which is a combination of a few ideas.
If i set the video's autostart property to false and then manually start the video it seems to fix part of the problem.
jwplayer('quest-video').setup({
            file: $("#quest-video").text(),
            title: 'Quest for the Golden Shield',
            width: '1000',
            height: '535',
            controls: 'false',
            fallback: 'false',
            mute: 'true',
            autostart: 'false'
        });

 jwplayer('quest-video').play();

Then when i hide and show it by setting the visibility to hidden etc it does not restart.
Thanks for the ideas!


text:
Q: Understand finite discretisation with and without eliminating boundary conditions. Exercise: For a given function $f$ we consider the following boundary value problem:
$$-\dfrac{d^2u(x)}{dx^2} + u(x) = f(x) \text{ for }0<x<1,$$
with boundary conditions $$u(x =0) = 0\text{ and } u(x = 1) = 0.$$
A finite difference method is used on a uniform mesh with $N$ intervals and mesh width $h = 1/N$.

*

*Give the finite difference stencil for internal grid points.

*Give the matrix $A^h$ for $N = 3$ where the boundary conditions are eliminated.

What I've tried: I know that $\dfrac{d^2u(x)}{dx^2}(x_i,y_j) = \dfrac{u_{i-1,j}^h - 2u_{i,j}^h + u_{i+1,j}^h}{h^2} + \mathcal{O}(h^2)$, so the stencil for internal points will look like: $1/h^2\begin{bmatrix}-1&2&-1\end{bmatrix} +\begin{bmatrix}0&1&0\end{bmatrix} = 1/h^2\begin{bmatrix}-1 & 2+ h^2 & -1\end{bmatrix}$. I think I was able to figure out $A^h$; the matrix denoted by $A^h$ is of size $2\times 2$ and given by $$A^h = \dfrac{1}{h^2}\begin{bmatrix}2+h^2& -1\\-1 & 2+h^2\end{bmatrix}$$ Question: What would the matrix $A^h$ have looked like without elimination of boundary conditions?


text:
Q: Setting up OpenGL on NetBeans in Window I'm trying to set up OpenGL in Netbeans 8.1. I have installed MinGW as C++ compiler and it works.
I want to use GLEW and GLFW libraries so I have downloaded them and I have created a include folder where I have stored all the .h files and a libs folder where I have stored the glew32.lib and glfw3.lib. I have included in NetBeans the include folder by setting
Project Properties > Build > C ++ Compiler > Include Directories
and I have included in NetBeans the bin folder by setting
Project Properties > Build > Linker > Libraries
Then in my main.cpp file I have inserted the include for GLEW and GLFW, but when I execute mi file this get me this output error
cd 'D:\Documenti\NetBeansProjects\Test'
C:\MinGW\msys\1.0\bin\make.exe -f Makefile CONF=Debug
"/C/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/d/Documenti/NetBeansProjects/Test'
"/C/MinGW/msys/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/test.exe
make.exe[2]: Entering directory `/d/Documenti/NetBeansProjects/Test'
mkdir -p dist/Debug/MinGW-Windows
g++     -o dist/Debug/MinGW-Windows/test build/Debug/MinGW-Windows/main.o -l glew32 -lglfw3
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: cannot find -lglew32
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: cannot find -lglfw3
collect2.exe: error: ld returned 1 exit status
make.exe[2]: *** [dist/Debug/MinGW-Windows/test.exe] Error 1
make.exe[2]: Leaving directory `/d/Documenti/NetBeansProjects/Test'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/d/Documenti/NetBeansProjects/Test'
make.exe": *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 1s)

Does anyone know how to solve this problem?

A: The linker can't find your libraries because you didn't tell NetBeans a directory where they are stored. Please go to:
Project Properties -> Linker -> Additional Library Directories
and add this directory to your NetBeans project. After that you'll see the additional linker option -L<path> when you compile/link.


text:
Q: Optimal unbalanced design for A/B test I want to find the right way to distribute variants (control/test) in A/B-test with the constraint of no more 10 percent of population in test group. The test is t-test for continuous metric.
I can design in 2 different ways:

*

*Split control/test in 90/10 percent proportion, and calculate the evaluation metric on test (10% of population) and full control (90%).

*Expose experiment on 20% of population, 10% on control and 10% on test.  Other 80% will not take part in metric calculation.

Which is the best from the view of statistical power?

A: @DemetriPananos correctly states that, with a 2-sample t test, power for a given
total sample size $(n_1+n_2)$ is maximized when subjects are split with equal numbers in the two groups $(n_1=n_2).$ Consequently, the 'power and sample size' procedures in many statistical software programs give results
only for balanced designs (equal sample sizes).
However, if you have a constraint on the number in the treatment
group and it is not vastly expensive to use a larger control group, then you might consider using a larger control group, which would give you some
increase in power.
I illustrate for the specific case of distinguishing
between a treatment group sampled from $\mathsf{Norm}(\mu = 105,
\sigma = 5)$ and a control group from
$\mathsf{Norm}(\mu = 100, \sigma = 5).$ So we are trying to
design an experiment that can often detect a difference in
population means that is equal to one SD.
The following simulations in R show that the power is reasonably good (about 87%) with
$n = 20$ in each group, but noticeably better (about 98%) with $n_1 = 20$
in the treatment group and $n_2=200$ in the control group.
set.seed(2020)
pv.bal = replicate(10^5, t.test(rnorm(20,105,5), rnorm(20,100,5))$p.val)
mean(pv.bal <= .05)
[1] 0.86832   # aprx power for n1 = n2 = 20

pv.unb = replicate(10^5, t.test(rnorm(20,105,5), rnorm(200,100,5))$p.val)
mean(pv.unb <= .05)
[1] 0.98289   # aprx power for n1 = 20, n2 = 200

Notes: (1) Many 'power and sample size' procedures give results
for pooled 2-sample t tests, rather than the generally preferable Welch 2-sample t tests, which do not assume equal variances in treatment
and control groups.
(2) The simulations shown above are for Welch 2-sample t tests. The power advantage of a larger
control group might be usefully magnified if the control group had a larger variance than the treatment group.
set.seed(609)
pv.bal = replicate(10^5, t.test(rnorm(20,105,4), rnorm(20,100,6))$p.val)  # Trt var 16, Ctrl var 36
mean(pv.bal <= .05)
[1] 0.85287
pv.unb = replicate(10^5, t.test(rnorm(20,105,4), rnorm(200,100,6))$p.val)
mean(pv.unb <= .05)
[1] 0.99812

(3) In the R code vectors such as pv <= .05 are logical
vectors consisting of TRUEs and FALSEs. The mean of
such a vector is its proportion of TRUEs. With 100,000
iterations, power values should be accurate to two or more
decimal places.

A: The power for such a test is roughly (according to the end of chapter 4 of this book) roughly...
$$ \beta = 1-\mathbf{\Phi}^{-1}(z_{1-\alpha/2}-\Delta\sqrt{f(1-f)}\sqrt{n}/\sigma_y) $$
Here, $\Delta$ is the smallest meaningful effect, $f$ is the fraction of people in the test group, $n$ is the sample size, and $\sigma_y$ is the standard deviation of the outcome.  The only thing that differs between your two designs is $f$ and $n$.  We want $\Delta\sqrt{f(1-f)}\sqrt{n}/\sigma_y$ to be as big as possible because that results in the most power.  All else considered equal, we only have to worry about $f$ and $n$.
In the first case $f=0.1$.  In the second, $f=0.5$ but we have a 20% of our sample.  We need to determine, which is larger: $.5  \times \sqrt{0.2 \times n}$, or $0.3 \times \sqrt{ n}$?
Turns out...
$$0.5  \times \sqrt{0.2 \times n} < 0.3 \times \sqrt{ n}$$
So the first design (more controls, smaller exposure) should yield more power. How much more power will depend on other parameters.  The difference could be very big or very small.
Here is some code to double check my arguments
library(tidyverse)

case_a = mean(replicate(1000,{

  Ny = 10
  Nx = 90
  x = rnorm(Nx)
  y = rnorm(Ny, 1)
  t.test(x,y)$p.value<0.05

}))
>>>0.765

case_b = mean(replicate(1000,{

  Ny = 10
  Nx = 10
  x = rnorm(Nx)
  y = rnorm(Ny, 1)
  t.test(x,y)$p.value<0.05

}))
>>>0.58

You could very easily draw power curves by either computing my first equation, or varying the size of the difference between the two samples in these simulations.


text:
Q: Is there a way to select items from an array based on time passed? I am building a day calendar. It has 8 boxes each representing an hour. I would like the the boxes in the past greyed out using moment. What I am thinking so far is this here:
var greyedOut = ["nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
  "fifteen", "sixteen", "seventeen"
]
var selected = [];

greyedOut.forEach(function(check) {
  selected.push(check)
})

console.log(selected);

if (moment().isAfter(moment(check))) {
  $()
};

var check = moment.duration(8, 'hours').asMinutes();
console.log(check);

let divvy = [480 / 8, 60 / 8];
console.log(divvy);

Thank you for any input or advice

A: Your question isn't very clear, but maybe this is close to what you want.

greyedOut.forEach(function(check) {
  if (moment().isAfter(moment(check))) {
    $("#" + check).css("background-color", "grey");
  } else {
    selected.push(check);
  }
});

console.log(selected);

The test of moment(check) needs to be inside the loop.


text:
Q: apache reverse proxy not working with explicit worker I am using my apache container as a reverse-proxy and trying to access one of my VM services.
It is working when I configure like,
ProxyPassMatch "^/(.*)" "https://host1:443/$1"
ProxyPassReverse "^/(.*)" "https://host1:443/$1"

With the above config I am able to access all the urls of https://host1:443/*. But When I want to access via an explicit worker like,
ProxyPassMatch "^/sample/(.*)" "https://host1:443/$1"
ProxyPassReverse "^/sample/(.*)" "https://host1:443/$1

the error says the url is not found.


text:
Q: Execute method in JavascriptInterface after page has finished loading I would like to be able to do some processing on the html and javascript of a page before it is presented to the user of my app. The page uses window.open for all the links and that causes a new browser window, not controlled by my app, to be opened, which destroys to illusion of using an app. This is what I have right now, which I think will work for the most part.
class LinkFixer
{
    static HashMap<String,String>pages = new HashMap<String,String>();//static so multiple pages can access it

    public void processPage(String html)
    {
        html = html.replace("window.open","LinkFixer.openInNewTab");
    }

    public void openInNewTab(String url, String targetName)
    {
        if(!pages.containsKey(targetName))//targetName is unique for every link
        {
            pages.put(targetName,url);
            //add new tab to my TabHost, which will contain a WebView with page from url loaded
        }

        //move user to tab
    }
}
WebView browser = (WebView)findViewById(R.id.browser);
browser.getSettings().setJavaScriptEnabled(true);

browser.addJavascriptInterface(new LinkFixer(), "LinkFixer");
browser.loadUrl("http://serverIP:port/mobilecontrol.html");
//something to make the browser execute LinkFixer.processPage goes here

The problem I'll have with it, is that I'm not sure how I would make the page execute LinkFixer.processPage when the page finishes loading. Other than that, I think the code will work. Any suggestions?

A: I wound up making a new WebChromeClient and overriding the onProgressChanged method to fix the links after newProgress is 100 or greater.
browser.setWebChromeClient(new WebChromeClient()
    {
        public void onProgressChanged(WebView webView, int newProgress)
        {
            super.onProgressChanged(webView,newProgress);
            if(newProgress >= 100)
            {
                System.out.println("Done loading");
                browser.loadUrl("javascript:document.getElementsByTagName(\"html\")[0].innerHTML = window.LinkFixer.processPage((document.getElementsByTagName(\"html\")[0].innerHTML))");
            }
        }
    });

Which works exactly how I want it to


text:
Q: TypeError: undefined is not an object (evaluating '_reactNative.Sentry.captureBreadcrumb') I have upgraded to @sentry/react-native latest version with react-native version 0.62.2.
Already I am using react-native-sentry package with react-native version 0.59.9 it works fine.
After the upgrade, I have changed the import alone and run pod install. After bundle success evaluating '_reactNative.Sentry.captureBreadcrumb'. How to fix this?
My question is while upgrading sentry from react-native-sentry to @sentry/react-native and with the latest version of RN (0.62.2) shall I need to a setup wizard as mentioned here yarn sentry-wizard -i reactNative -p ios android https://docs.sentry.io/platforms/react-native/#linking.

A: That same documentation has a section for upgrading from react-native-sentry to @sentry/react-native:
https://docs.sentry.io/platforms/react-native/#upgrading-from-react-native-sentry
Basically first you react-native unlink react-native-sentry. Then:

After that remove react-native-sentry from your package.json:

npm uninstall react-native-sentry --save
# or
yarn remove react-native-sentry

Once you've done that, just install @sentry/react-native as the documentation describes like if it was a new project.


text:
Q: How can i use Router of BackboneJs in Html As i html with Router link of Angular 4 how can i set Router in that of backboneJS
html is mentioned below

History

Profile

Address Book

Preferences

Wishlist

I am using backboneJs and Handlersbar any suggestions or good approach would be so useful. Thanks in advance.
I have to make footer and header in my application.

A: You can just set the href of  as normal hash like:

History

or if your app supports push state, without the hash like:

History

and set up and instance of Backbone.Router as mentioned in the docs.
This router instance will listen to changes in url and invoke the callbacks you define while instantiating the backbone router.

A: You can do following in your backbone.js View
events: {
    'click a': 'changeRoute'
},
changeRoute: function(e) {
    e.preventDefault();
    var href = $(e.currentTarget).attr("href");
    router.navigate(href, true);
}


text:
Q: Filtering records on date in d3 I am trying to filter records on the basis of date. However, I am unable to do so. Following is the code:
 data2  =       data1.filter(function(row) { console.log(row["wsrweek"],parseDate("05-30-2014"));
            return  row["wsrweek"] == parseDate("05-30-2014");})

log output:
Date 2014-05-29T18:30:00.000Z Date 2014-05-29T18:30:00.000Z utilization.js:122
Date 2014-05-22T18:30:00.000Z Date 2014-05-29T18:30:00.000Z utilization.js:122
Date 2014-05-15T18:30:00.000Z Date 2014-05-29T18:30:00.000Z utilization.js:122
Date 2014-05-08T18:30:00.000Z Date 2014-05-29T18:30:00.000Z utilization.js:122

First row is have equal records. However, its not getting returned as data2 is empty. Kindly suggest


text:
Q: IIS 8.5 500.19 status code with 0x80070038 access share We are experiencing an intermittent issue with websites accessing resources/images over CIFS/SMB shares (running on our storage array).  It comes and goes and we are trying to get to the bottom of it.
The error code in the browser is 500.19 with the error code 0x80070038.
I've come across these two locked threads and is seems like the same issue:
http://forums.iis.net/t/1165964.aspx?500+19+error+NetBios+command+limit
http://forums.iis.net/t/1158781.aspx
Is this still applicable in a Windows 2012r2/IIS 8.5 environment?
I've had a look in the registry for MKLM\Services\CurrentControlSet\lanmanworkstation\MaxCmds but cannot see it.

A: I have seen this post to be helpful such as your case. I hope you find help full too.
Please click this LINK
Thank You


text:
Q: How to add Autosize script to Wordpress? I am still learning Wordpress so forgive me if this is a stupid question but I am trying to add the Autosize script to a page on my website and I am kind of lost. How do you add scripts to Wordpress? And how do I call it on a specific page with the textarea element that I want to autosize?

A: To include the scripts to WordPress you need to use wp_enqueue_script Documentation Since you will need to call the JS to target the textarea, use the function in a custom.js file and include that too.
function autoresize_scripts() {
  wp_enqueue_script( 'auto-resize', get_template_directory_uri() . '/js/autoresize.js', array(), '1.0.0', true );
  wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array(), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'autoresize_scripts' );

The above code will be used in functions.php
If you need to call it on a specific page:
Use is_page function in WordPress:
if( is_page( 2 ) ) // 2 is the page id
{
    // Target textarea with JS
}

And if you want to target many pages with the textarea element, WordPress will automatically take care as it is added to footer.php which is loaded in all the web pages.


text:
Q: Why do we have $X\in \mathcal{L}^1(P(.|A))$? Let $\mathcal{L}^1(\mu)$ be the set of integrable functions with respect to measure $\mu$.
Assuming that $X\in \mathcal{L}^1(P)$, we have $1_{A}X \in \mathcal{L}^1(P)$. But why do we have $X\in \mathcal{L}^1(P(.|A))$?
I'm using the following definition: $P(B|A)= \frac{P(B\cap A)}{P(A)}$ if $P(A)>0$, and zero otherwise.
Edit:
$X\in \mathcal{L}^1(P)$ is equivalent to $\int_{\Omega} |X| dP< \infty$, so $X\in \mathcal{L}^1(P(.|A))$ is equivalent to $\int_{\Omega} |X| dP(.|A)< \infty$.


text:
Q: C# child thread is still working even main thread exit I happened to read Semaphore class sample as below from msdn:
https://msdn.microsoft.com/en-us/library/system.threading.semaphore%28v=vs.110%29.aspx
It's a console app, however something confused me that child threads are able to work even main thread exits.

From my understanding, when main thread/process exits, all child threads will be terminated, that's why usually we signal and wait child threads to finish before main thread stops.
Am I wrong or the behaviour has been changed in .net due to reference?

A: If you want the child thread to abort on the termination of the parent thread, it must be set as a Background thread.
t.IsBackground = true;
t.Start(i);

Otherwise, all foreground threads run to completion before the process exits


text:
Q: Responsive width and height for a group of squares I'm creating a grid of 1:1 squares. The user can keep adding squares and I want the size of the squares to be maintained at their aspect ratio but resize accordingly. The tricky part is I want the square to always be visible on the page - that is to say that there is no scrolling and the webpage would be responsive with width and height.
I have created an example that adds a square every second while testing this. However, I am unable to get it working with the height part. I have been able to get it working with the width.

setInterval(() => {
  //  console.log(document.getElementsByClassName('square-container')[0]);
  document.getElementsByClassName('square-container')[0].innerHTML += ("

");
}, 1000);
.square-container {
  display: flex;
  flex-wrap: wrap;
}

.square {
  position: relative;
  flex-basis: calc(33.333% - 10px);
  margin: 5px;
  box-sizing: border-box;
  background: red;
  transition: background 1s;
}

.square::before {
  content: "";
  display: block;
  padding-top: 100%;
}

I'm not using any ui libraries like bootstrap, just vanilla html, css and javascript.

A: Use Float instead of wrap. set the square-container display block.

#square-container{
  display: block
}
#square{
    float: left;
    height: 100px;
    width: 100px;
    background-color: orangered;
    margin: 1px;
}

A: Might I suggest a pure javascript approach?
Basically  just set a inicial value and let javascript do all the calculating every time a square is added.

// Function to resize the squares
function resizeSquares(){
    // Get the squares
    squares = document.getElementsByClassName('square');
    for (i=0;i<squares.length;i++) {
        // Set the width of the square according to the window width
        squares[i].style.width = document.body.clientWidth / squarePerRow + 'px';
        // Set the height of the square to its width to keep the aspect ratio
        squares[i].style.height = squares[i].style.width;
    }
}

// Set initial square capacity for each row
    squarePerRow = 3;

// Inicialize the size of the squares
resizeSquares();

setInterval(function(){
    // Add a square
    document.getElementById('container').innerHTML += '

';
    // Check if squares exceeds the window
    if(document.body.clientHeight > document.documentElement.clientHeight) {
        // If they do, add one square capacity per row
        squarePerRow = squarePerRow + 1;
    }
    // Resize the squares
    resizeSquares()
}, 1000)
#container {
    display: flex;
    flex-wrap: wrap;
}

.square {
    background: red;
    border: 5px solid white;
    box-sizing: border-box;
    transition: all, 0.5s;
}


text:
Q: Multiple inserts during concatenation? I've a JSONObject that I've converted to a JSON array then parsed it further to its separate strings. I've concatenated these to form one new string. Here is the code that I've used.
            for(int n = 0; n<newtrs_array.length();n++){
                JSONObject object = newtrs_array.getJSONObject(n);
                String newcompanyid = object.getString("companyid");
                String newusername = object.getString("username");
                String newdate = object.getString("date");
                String newClientId = object.getString("clientid");
                String newprojectId = object.getString("projectid");
                String newniv1 = object.getString("niv1");
                String newniv2 = object.getString("niv2");
                String newworktypeid = object.getString("worktypeid");
                String newtimetypeid = object.getString("timetypeid");
                String newhours = object.getString("hours");
                String newcomment = object.getString("comment");
                String newprivatecomment = object.getString("privatecomment");
                String newopen = object.getString("open");
                String newreportid = object.getString("reportid");

                newtrsArray += newcompanyid+"#"+newusername+"#"+newdate+"#"
                               +newClientId+"#"+newprojectId
                               +"#"+newniv1+"#"+newniv2+"#"+newworktypeid
                               +"#"+newtimetypeid+"#"+newhours+"#"+newcomment
                               +"#"+newprivatecomment+"#"+newopen+"#"+newreportid;
                        }
            }

This is the code that is used to split the newtrsarray
        for(int n=0; n<split_frombufferedValue.length; n++){
            if(split_frombufferedValue[n] != null){
            try{
                //Log.i(TAG, "***********%%%%%%%%%"+split_frombufferedValue[1]);
                newtrsArray = split_frombufferedValue[0].toString();
                newschemaArray = split_frombufferedValue[1].toString();
                Log.i(TAG, "************* "+newschemaArray);
                newdeletedtrsArray = split_frombufferedValue[2].toString();
                String newcreatedtrs_array = split_frombufferedValue[3].toString();
                String newsync_reponse = split_frombufferedValue[4].toString();
                String newmodtrs_array = split_frombufferedValue[5].toString();

            } catch(Exception e){
                e.printStackTrace();
            }
        }

        }
            split_newtrsArray = newtrsArray.split("#");
                    split_newdeletedtrsArray = newdeletedtrsArray.split("@@@@");
            split_newschemaArray = newschemaArray.split("%%%%");
            Log.i(TAG, "############# "+split_newtrsArray[0]+" -length "+split_newtrsArray.length);

    }

My PROBLEM is that: newtrsarray is about 4000chars or more in size. This is causing the "#" to be inserted twice or even thrice at times. As shown below
&&--Second activty:HTTPClient--**(824): !!!!!------UTB17#DA#2011-10-10#1000#363636#10##105#30#5###no#30667UTB17#DA#2011-09-12#1000#363636#10##100##6##Not Available#yes#31659UTB17#DA#2011-09-13#1000#363636#10##100##2###yes#31665

How can I work around this problem. The values must be concatenated to one string and then split at an another function. These must be then inserted into a database. Hope I was able to explain my problem clearly.
Cheers !

A: I think your problem comes when you are inserting it again which is when the array has a null element check out an if statement and check if its null or not. Do it as so:
                if(newcompanyid.equals("") || newcompanyid == null || newusername.equals("") || newusername == null
                        || newdate.equals("") || newdate == null || newClientId.equals("") || newClientId == null ||
                        newprojectId.equals("") || newprojectId == null || newniv1.equals("") || newniv1 == null ||
                        newniv2.equals("") || newworktypeid.equals("") || newworktypeid == null ||newtimetypeid.equals("")
                        || newtimetypeid == null || newhours.equals("") ||newhours == null ||newcomment.equals("")
                        ||newcomment == null ||newprivatecomment.equals("") ||newprivatecomment == null||newopen.equals("")
                        ||newopen == null||newreportid.equals("") || newreportid == null)


text:
Q: Java Swing: drawing not centered in separate JPanel I'm Jari and I'm having some trouble with drawing a circle in a separate JPanel:
my circle won't center in the middle of a jpanel called "jPanelOutput" here 's my code:
Graphics2D graphics = (Graphics2D) jPanelOutput.getGraphics().create();

    Insets insets = jPanelOutput.getInsets();
    System.out.println(insets.toString());
    int w = (int)((jPanelOutput.getWidth())/ 2)-insets.left-insets.right;
    int h = (int)(jPanelOutput.getHeight()/ 2)-insets.top-insets.bottom;
    System.out.println(w + "  " + h);
    graphics.translate(w, h);
    graphics.drawRect(0, 0, 1, 1);
    graphics.drawOval(0, 0, 150, 150);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setColor(Color.BLACK);

    graphics.dispose();

But the output is:

don't worry about the spelling, it's in Dutch ("vlakke spiegel" means flat mirror and "cirkel" means circle. the title means fysics mirror laws.
thanks in advance
Jari

A: The problem is the circle is drawn from the top_left corner. The upper left corner of the circle is at perfect center position. All you need to do is to subtract circle's width and height from the center point.  The following code will center the circle.
int cw = 150;
int ch = 150;
graphics.translate(w - cw / 2, h - ch / 2);
graphics.drawRect(0, 0, 1, 1);
graphics.drawOval(0, 0, cw, ch);


text:
Q: Why are attributes of a Process object not kept after run? I have the following subclass of Process:
from multiprocessing import Process

class MyProcess(Process):
    def __init__(self, **kwargs):
        self.my_attribute = "debug0"
        print("my_attribute : ", self.my_attribute)

        super().__init__(**kwargs)

        self.my_attribute = "debug1"
        print("my_attribute : ", self.my_attribute)

    def run(self):
        self.my_attribute = "debug2"
        print("my_attribute : ", self.my_attribute)

my_process = MyProcess()

my_process.start()
my_process.join()

print("my_process.my_attribute : ", my_process.my_attribute)

I get the following logs:
my_attribute :  debug0
my_attribute :  debug1
my_attribute :  debug2
my_process.my_attribute :  debug1

Why does the attribute my_attribute, while being changed during run is not kept as set in the run method? How can I set an attribute in this case that keeps its value when the run function has finished executing?

A: The run function runs in a separate process, with its own memory space and its own copy of the my_process object, so it can't directly affect the my_process object in the parent process.  If you want something to change in the parent process when the run function runs in the child process, you will have to arrange some kind of interprocess communication.  This won't happen automatically as a result of using the Process class.


text:
Q: How to check the text found on an object in OnTriggerEnter I have a question, I created a game where I need to collect a Ballon, and check the number of the text that I attached on it:
Example
  public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Ballon")
        {
       //now I want to check the text//
        }
     }

A: This is very simple to do. As your example you have a TextMeshPro in the child of the other object. Now in this situation there are two way for you to get the child object.
I'll Add reference links at the bottom of the answer.

*

*other.transform.Find();

*other.transform.GetChild();

1. other.transform.Find()
Using transform.find() method it will go through all the Game Objects that are child of the the parent object in your case this method will go through all the children of other object, as ass soon as it finds the object which matches the name it will return that object.
Here is an example:
public void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Ballon")
    {
         TextMeshPro tmp = other.transform.Find("Text (TMP) (1)").GetComponent<TextMeshPro>();
         if(tmp.text == "text of your liking")
         {
             Debug.Log("Do what you want");
         }
    }
 }

2. other.transform.GetChild()
This method will directly return the child from the index that you enter. And this method is quit an efficient one to use.
Here is the example:
public void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Ballon")
    {
         TextMeshPro tmp = other.transform.GetChild(0).GetComponent<TextMeshPro>();
         if(tmp.text == "text of your liking")
         {
             Debug.Log("Do what you want");
         }
    }
 }

References:
1.Transform.Find()
2.Transform.GetChild()


text:
Q: Python find a string with single quote symbol in postgresql table I need to look up for a string that contains multiple single quotes from my psql table. My current solution is replacing the single quotes with double single quotes like this:
sql_query = f"""SELECT exists (SELECT 1 FROM {table_name} WHERE my_column = '{my_string.replace("'","''")}' LIMIT 1);"""
cursor = connection.cursor()
cursor.execute(sql_query)

Is there a nicer solution for this kind of formatting ?

A: I solved this by making the query like this
sql_query = f"""SELECT exists (SELECT 1 FROM {table_name} WHERE my_column = %s LIMIT 1);"""
cursor = connection.cursor()
cursor.execute(sql_query, (mystring,))

In this case it formats mystring in such way that it is not executed as sql query and doesn't cause the problems mentioned in the question


text:
Q: Azure mobile client hangs when pulling data from specific entity I have an entity that looks like:
 public class Category : EntityData
{

    [Index("IX_CategoryName", IsUnique = true), MaxLength(60)]
    public string Name { get; set; }
    public string CreatorId { get; set; }
    [ForeignKey("CreatorId"), JsonIgnore]
    public User Creator { get; set; }
    [JsonIgnore]
    public virtual ICollection<Choice> Choices { get; set; }
    [JsonIgnore]
    public virtual ICollection<UserCategory> Users { get; set; }
    public string Password { get; set; }
    public bool Private { get; set; }
}

I had some problems with Self referencing loop detected for property. I tried both (both alone, and in combination)
 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =      Newtonsoft.Json.ReferenceLoopHandling.Ignore;
 config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

but without luck. So i went with the [JsonIgnore] tag as you can see in my entity. And as far as I'm aware, azure mobile service doesnt even send nested objects anyways, so there is no reason to serialize that. However when i try to pull the data, the process never returns. No timeouts, no exceptions..
The weird part comes now. If I call the service with postman I get a response.
  {
"name": "Food",
"creatorId": "nemtid",
"password": null,
"private": false,
"id": "707cc064-f797-40ee-9ef1-b235e447ff5f",
"version": "AAAAAAAAB9k=",
"createdAt": "2016-11-29T19:58:12.58Z",
"updatedAt": "2016-11-29T19:58:12.58Z",
"deleted": false
}

So i guess it's a client side problem?..
I have no clue about how I should debug on this, so if any of you got any clue, either how to debug this, or another way of fixing the Self referencing loop problem, please let me know.
EDIT:
One side note to make all this even more wierd.
From my client, if i pull all the data there is no problem (neither with the code hangning nor the self reference problem that i fixed with the [JsonIgnore]. So i can pull all data just fine without JsonIgnore) My problem is only occuring with this method request handler on the server:
public async Task<IEnumerable<Category>> GetSubscribedCategories(string userId, string subbedCats)
    {
        var res = _context.Categories.Where(c => c.Users.Select(u => u.UserId).Contains(userId));
        return res;
    }

A: So I fixed the problem by changing my method return value from IEnumerable to IQueryable.
Furthermore this also fixed my reference loop. So i've deleted all [JsonIgnore] and its still working. Don't ask why


text:
Q: Couldn't create HBITMAP from glReadpixels So here's a part of my code, what I'm trying to do is to make a HBITMAP from a OpenGl frame capture.
unsigned char *output = 0;
output = new unsigned char[WINDOW_WIDTH * WINDOW_HEIGHT * 3];

glReadPixels(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE,
    output);

HBITMAP hdm = CreateBitmap(800, 800, 1, 32, output);

But my (HBITMAP)hdm is always NULL. Maybe there's another way to do that or what's wrong? I guess CreateBitmap would allocate memory itself, so the mistake must not be here. The output array seems to be fine though.
I've also tried the code from here: Creating a HBITMAP from glReadPixels but it didn't work as well, still getting NULL.
Would appreciate any help with this!

A: The 4th parameter of CreateBitmap is the number of bits required to identify the color of a single pixel.
Since the format of the pixel data is GL_RGB, the 3rd paramter of CreateBitmap has be 24 instead of 32. Note GL_RGB/GL_UNSIGNED_BYTE means 3 color components with each a byte, which leads to 24 bits:
HBITMAP hdm = CreateBitmap(WINDOW_WIDTH, WINDOW_HEIGHT, 1, 24, output);

Or you have to use the GL_RGBA format:
unsigned char *output = new unsigned char[WINDOW_WIDTH * WINDOW_HEIGHT * 4];
glReadPixels(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, output);

HBITMAP hdm = CreateBitmap(WINDOW_WIDTH, WINDOW_HEIGHT, 1, 32, output);

Note, If you use the GL_RGB format, you have to consider that CreateBitmap requires each scan line be word aligned.
The alignmnet for the glReadPixels operation can be set by glPixelStorei, by setting the parameter GL_PACK_ALIGNMENT, which is by default 4, so this should not be an issue.
But you have to ensure that the dynamically allocated buffer is large enough:
size_t bpl = WINDOW_WIDTH * 3; // bytes per line
size_t r   = bpl % 4;          // rest of division by 4
bpl       += r ? (4-r) : 0;    // bytes per line aligned to 4
unsigned char *output = new unsigned char[bpl * WINDOW_HEIGHT];

or
size_t bpl = (WINDOW_WIDTH * 3 + 3) & ~3;
unsigned char *output = new unsigned char[bpl * WINDOW_HEIGHT];


text:
Q: Error message; Cannot access class 'androidx.compose.ui.Alignment.Horizontal'. Check your module classpath for missing or conflicting dependencies I am making a QR Code Scanner app using Jetpack compose. But when I am trying to use Column, the composable function then the compiler is giving me this error:
Cannot access class 'androidx.compose.ui.Alignment.Horizontal'. Check your module classpath for missing or conflicting dependencies
Here is my app build.gradle module for the app:
    plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.plcoding.qrcodescannercompose"
        minSdk 26
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    // Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
    implementation("androidx.compose.foundation:foundation:1.0.5")
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    // Activity Compose
    implementation "androidx.activity:activity-compose:1.4.0"

    // CameraX
    implementation "androidx.camera:camera-camera2:1.0.2"
    implementation "androidx.camera:camera-lifecycle:1.0.2"
    implementation "androidx.camera:camera-view:1.1.0-beta01"

    // Zxing
    implementation 'com.google.zxing:core:3.3.3'
}

Update: This is the code that is generating the error:

I don't know what this error message is saying and how to resolve this?

A: Make sure to upgrade your version of Compose to the latest stable version which is 1.1.0-rc03
If your project consists of multiple modules, make sure that all of them are using the same version of Compose.


text:
Q: Upload profile image for a user Firebase I am trying to add an image to the user information in the real time database(firebase) for android. I have uploaded the image on the firebase storage but how will I be able to add the image in the database for that user?
Code Below:
//inside onCreate() method

img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(Intent.ACTION_PICK);
            i.setType("image/*");
            startActivityForResult(i,request_code);
        }
    });

Here I am clicking on the imageview, so I will be able to change it and get an image from the gallery.
Here I authenticate the user and send data to the database:
 auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(StudentSignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(StudentSignUpActivity.this, HomeActivity.class));
                                finish();
                            }
                        }
                    });

mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
            DatabaseReference newStudent=mDatabase.push();
            newStudent.child("email").setValue(email);
            newStudent.child("password").setValue(password);
            newStudent.child("name").setValue(name);
            newStudent.child("date").setValue(dates);
            newStudent.child("phone").setValue(number);
            newStudent.child("uid").setValue(mCurrentUser.getUid());

//outside of onCreate()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }
        });
    }
}

In the above code I have uploaded the image to the firebase storage. Now how will i be able to add that image as a child for a specific user.
I think I need to do something like this:
 newStudent.child("image").setValue(uri_here);

But I am unable to figure how to get the uri of the image and how to add that uri in the setValue() since its in another method.

A: You can use the method getDownloadUrl() in the success listener to access the download URL:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                newStudent.child("image").setValue(downloadUrl);
            }
        });
    }
}

As an aside, instead of using push(), I recommend storing the user's data with the uid as the key. This will make your data easier to find.
private DatabaseReference newStudent;

mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
            newStudent=mDatabase.child(mCurrentUser.getUid());
            newStudent.child("email").setValue(email);
            // etc

A: Just to update because I spent sometime to find this answer, getDownloadUrl() is NOT a function of taskSnapshot anymore. So in order to get  the image URL from Firebase Storage you need to add a listener to
taskSnapshot.getMetadata().getReference().getDownloadUrl()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                taskSnapshot.getMetadata().getReference().getDownloadUrl()
                    .addOnSuccessListener(new OnSuccessListener<Uri>() {

                    @Override
                    public void onSuccess(Uri uri) {
                        newStudent.child("image").setValue(uri);

                    }
                });
            }
        });
    }
}

Now it's safe to use uri to whatever you want


text:
Q: Get a Authorized token for O365 Calendar I'm making an app that needs to access the content of a Office 365 Calendar.
That app shouldn't need a direct user action to log in and retreive its data, so I can't use a standard OAuth way to get this token.
I was a bit familiar of google's calendar way to do that, with it's "Service Account" logic, involving a non symetrical RSA key to do it, so I tried to find something like that for O365.
I've found this blog :
https://blogs.msdn.microsoft.com/arsen/2015/09/18/certificate-based-auth-with-azure-service-principals-from-linux-command-line/
that helped me a lot configuring an application and setting up all the keys on both side to allow the connection. In the end, I managed to make it work, got a token and list the resourcegroups.
All was fine and I exepected it to work quite easily with Microsoft graph API.
So :
- I added the Microsft Graph API in my application's Authorizations on Azure Management and added all the read / write permissions on all users' calendars ( in the application's authorizations and in delegated authorization )
- I regenerated the tokens so the new rights can be added to it
- I used this token to get a list of the calendars
And it never worked. I have the token, and the request gives me the good scopes with it. So I know i'm on the right app, and everything. When i give the token to outlook.office.com, I have this message : <>
I've probably missed a step somewhere, but I can't find where. In my requests ? In my Azure account ?
Any help please ?
The requests (didn't blur anything, just a test account anyway).
Get Token Request :
POST /6a23b9c1-04fc-4782-b08c-786d2a16c95d/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: f7b2884d-44e9-c48a-6245-453be490758c

grant_type=client_credentials&client_id=0577ff63-730e-418a-a68f-6cbc590b6874&resource=https%3A%2F%2Foutlook.office.com%2F&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsIng1dCI6ImxhVkMzbEd3K3hKWkpkTUQrbUpmdmRoU1V2bz0ifQ.eyJhdWQiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNmEyM2I5YzEtMDRmYy00NzgyLWIwOGMtNzg2ZDJhMTZjOTVkL29hdXRoMi90b2tlbiIsImlzcyI6IjA1NzdmZjYzLTczMGUtNDE4YS1hNjhmLTZjYmM1OTBiNjg3NCIsInN1YiI6IjA1NzdmZjYzLTczMGUtNDE4YS1hNjhmLTZjYmM1OTBiNjg3NCIsImp0aSI6IjAuMTgyOTg1ODUzNjM2NjM3MzMiLCJuYmYiOiIxNDYxOTQyODU2IiwiZXhwIjoiMTUyMjQyMzg1NiIsImlhdCI6MTQ2MTk0Mzg1Nn0.Czm9ks_jrEVViUDjfMF1uVUlf5sZrCSGtCmisFn3c8119KQ-OczLpWbpU3crJjidiP2y-xcSGjRSCGYJPiwq2Qks45_97-jBe_fBPoJb5lni5QYT_2ep6OyaAnId4VxlF9WScxFfHEtLqOsqOZwB4c6_YXdOiy82SJ0sLqLgZrFlnqYn6uMXGWThEFKPR3qsolgO4Wn5lthFRwF__IuIpg2DnjyNIz2KVhqVLqqZ-pglzE_soaKldiAR4bAZMxlndhMCnoUADgfsR0PAaZ-AyM0me4K7FrGbLpaTdXU6M4v9edLM9J23dg82HOKdf0GDC6pCIxKmIsuTR8IxGfxoTw

Get Token Answer :
{
    "token_type" : "Bearer",
    "scope" : "Calendars.Read Calendars.ReadWrite",
    "expires_in" : "3600",
    "expires_on" : "1461951871",
    "not_before" : "1461947971",
    "resource" : "https://outlook.office.com/",
    "access_token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbS8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82YTIzYjljMS0wNGZjLTQ3ODItYjA4Yy03ODZkMmExNmM5NWQvIiwiaWF0IjoxNDYxOTQ3OTcxLCJuYmYiOjE0NjE5NDc5NzEsImV4cCI6MTQ2MTk1MTg3MSwiYXBwaWQiOiIwNTc3ZmY2My03MzBlLTQxOGEtYTY4Zi02Y2JjNTkwYjY4NzQiLCJhcHBpZGFjciI6IjIiLCJpZHAiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82YTIzYjljMS0wNGZjLTQ3ODItYjA4Yy03ODZkMmExNmM5NWQvIiwib2lkIjoiMGQyODJlMDgtZGZkOC00Y2YwLWJmYzMtYmQ2MDZmMDEyNzVhIiwic3ViIjoiMGQyODJlMDgtZGZkOC00Y2YwLWJmYzMtYmQ2MDZmMDEyNzVhIiwidGlkIjoiNmEyM2I5YzEtMDRmYy00NzgyLWIwOGMtNzg2ZDJhMTZjOTVkIiwidmVyIjoiMS4wIn0.L8mP4t_Zmxfl5vJQwEaOsd-ere81jtz9ltzxk0TA0qA_hwRIYNVmHrydyPTHHQC7Jv3M6hiSnSVyVeXX_uYNFkPRZ3Sy_XOjmOF5xslMrw1niqE6J7OhQ5PEPmOfa0mQoWManChemDV5JCdxNOotBd4xes_jzg9tLMihzpqBcAUo3zGn8q5PT7AG-pydOEaHCWwDSKlHlFkBjZ3y_NTtQadDSR9aE2H6DOtP5-hXCpHqzkZODTZCuSBQRz1vCshcd8kZiuX_ebxItlJ8JU-zUr1YJFy9jww0NtROOB71xJP9IUf2NjMS-rQvR2qL8vfLPTArpgQFRU9cCZ4KpbVs3Q"
}

Calendar List Request :
GET /api/v2.0/me/calendars HTTP/1.1
Host: outlook.office.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbS8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82YTIzYjljMS0wNGZjLTQ3ODItYjA4Yy03ODZkMmExNmM5NWQvIiwiaWF0IjoxNDYxOTQ3OTcxLCJuYmYiOjE0NjE5NDc5NzEsImV4cCI6MTQ2MTk1MTg3MSwiYXBwaWQiOiIwNTc3ZmY2My03MzBlLTQxOGEtYTY4Zi02Y2JjNTkwYjY4NzQiLCJhcHBpZGFjciI6IjIiLCJpZHAiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82YTIzYjljMS0wNGZjLTQ3ODItYjA4Yy03ODZkMmExNmM5NWQvIiwib2lkIjoiMGQyODJlMDgtZGZkOC00Y2YwLWJmYzMtYmQ2MDZmMDEyNzVhIiwic3ViIjoiMGQyODJlMDgtZGZkOC00Y2YwLWJmYzMtYmQ2MDZmMDEyNzVhIiwidGlkIjoiNmEyM2I5YzEtMDRmYy00NzgyLWIwOGMtNzg2ZDJhMTZjOTVkIiwidmVyIjoiMS4wIn0.L8mP4t_Zmxfl5vJQwEaOsd-ere81jtz9ltzxk0TA0qA_hwRIYNVmHrydyPTHHQC7Jv3M6hiSnSVyVeXX_uYNFkPRZ3Sy_XOjmOF5xslMrw1niqE6J7OhQ5PEPmOfa0mQoWManChemDV5JCdxNOotBd4xes_jzg9tLMihzpqBcAUo3zGn8q5PT7AG-pydOEaHCWwDSKlHlFkBjZ3y_NTtQadDSR9aE2H6DOtP5-hXCpHqzkZODTZCuSBQRz1vCshcd8kZiuX_ebxItlJ8JU-zUr1YJFy9jww0NtROOB71xJP9IUf2NjMS-rQvR2qL8vfLPTArpgQFRU9cCZ4KpbVs3Q
Cache-Control: no-cache
Postman-Token: e85ac526-c56a-4d5b-2f74-83f4033decb4

Answer empty, but in the headers :
Content-Length →0
Date →Fri, 29 Apr 2016 16:44:59 GMT
Server →Microsoft-IIS/8.5
WWW-Authenticate →Bearer client_id="00000002-0000-0ff1-ce00-000000000000", trusted_issuers="00000001-0000-0000-c000-000000000000@*", token_types="app_asserted_user_v1 service_asserted_app_v1", authorization_uri="https://login.windows.net/common/oauth2/authorize", error="invalid_token",Basic Realm="",Basic Realm=""
X-BEServer →VI1PR08MB0910
X-BackEndHttpStatus →401
X-CalculatedBETarget →VI1PR08MB0910.eurprd08.prod.outlook.com
X-DiagInfo →VI1PR08MB0910
X-FEServer →AM3PR08CA0034
X-MSEdge-Ref →Ref A: B612166BB1764A45B0F3BCE6DF9CB639 Ref B: A8D71806CB57091B57FD0130AABF9D85 Ref C: Fri Apr 29 09:45:00 2016 PST
X-Powered-By →ASP.NET
request-id →26f132ca-df5e-439f-bd4f-7d655ba7df21
x-ms-diagnostics →2000008;reason="The token contains no permissions, or permissions can not be understood.";error_category="invalid_grant"

A: Take a look at the blog post Building Daemon or Service Apps with Office 365 Mail, Calendar, and Contacts APIs (OAuth2 client credential flow) for instructions on how to use app-only access with REST APIs.  Since the blog post is pretty old, replace outlook.office365.com/api/v1.0 with outlook.office.com/api/v2.0.  You can also follow the same procedures to register your app for app-only access for Microsoft Graph as well.

A: After comparing with the worked access token and yours on https://jwt.io, I found that the "roles" claim was missing in your access token.

I can not reproduce this issue in my test tenant. But here is the client assert comparing result for your reference:

Hope this will help.


text:
Q: Find the reason why a thread starts I have an application for which I can see threads starting and terminating all over again. I'm now wondering where those threads come from, because IMHO they shouldn't be there (or at least the overhead of creating a thread is not worth it).
This is the first time I use sxe ct to be notified about new threads being started. I can inspect the new thread using k, but it's not giving much information at this point:
0:010> k
 # Child-SP          RetAddr               Call Site
00 000000c7`de1ff898 00000000`00000000     ntdll!RtlUserThreadStart

I then used ~*k and had a look for CreateThread() or similar. Sometimes, I can find such a call
   6  Id: 5264.4d68 Suspend: 1 Teb: 000000c7`dd6cb000 Unfrozen
 # Child-SP          RetAddr               Call Site
00 000000c7`dd58ea68 00007ffb`77f3baa2     ntdll!NtCreateThreadEx+0x14
[...]

But in many cases, I don't find such a call. I'm aware that threads could also be injected into the process, like the debugger injects the breakpoint thread.
How do I find out what the origin/reason for a newly created thread is?
Clarifications:
The application is written in .NET, but may have loaded unmanaged DLLs, which in worst case might load other stuff written in interpreted languages. I am not looking for an answer that describes the various reasons a .NET application could create a thread. I am looking for an answer where I have already identified a particular thread (with sxe ct) and I want to know where that thread comes from.

A: The Break for Sxe ct happens when the system calls the LPTHREADROUTINE function
At this point you do not have the information about who Created the thread in first place.
for example you can run  for (i=0;i<x;i++) {CreateThread(....,ThreadRoutine,...);}
and sxe ct wont break until the loop has run x times
You May Need to Set a Breakpoint on one of Create Functions
and look at the Disassembly at the Return Address to know who is Creating the Thread.
a sample code for demo below
the main() creates 10 threads and if you run the binary in windbg with sxe ct
the break will happen only after the printf(...) and before WaitForMultipleObject(...)
#include <stdio.h>
#include <windows.h>
#define THNO 10
CRITICAL_SECTION mycritty;
int counter = 0;
DWORD WINAPI tproc( LPVOID  )
{
    EnterCriticalSection(&mycritty);
    counter++;
    printf("%d\n",counter);
    Sleep(10000);
    LeaveCriticalSection(&mycritty);
    return 0;
}

int main(void)
{
    ULONG htid[THNO] = {0};
    HANDLE hth[THNO] = {NULL};
    InitializeCriticalSection( &mycritty );
    for(int i = 0; i < THNO; i++)
    {
        hth[i] = CreateThread(NULL,0,&tproc,NULL,0,&htid[0]);//Line Number 23
    }
    printf("\n\nAll Threads Created Wait Below  Yields cpu for Scheduling\n");
    printf("tproc() %p will be executed only now\n\n\n", &tproc);
    WaitForMultipleObjects(THNO, hth, TRUE, INFINITE);
    return getchar();
}

executing with sxe -c "r @eax" ct in cdb.exe
you can notice the printf() in main has executed prior to sxe break
so you either need an utility in kernel doing PsCreateThreadNotifyRoutine() Callback
or you may need to set a break in Say ntdll!NtCreateThreadEx() function and look at   callstack for the Module that Does the Thread Creation.
:\>cdb -c ".prompt_allow -reg -sym;sxe -c \"r @eax\" ct;g" critter.exe

Microsoft (R) Windows Debugger Version 10.0.18362.1 X86

ntdll!LdrpDoDebuggerBreak+0x2c:
778c05a6 cc              int     3
0:000> cdb: Reading initial command '.prompt_allow -reg -sym;sxe -c "r @eax" ct;g'

All Threads Created Wait Below  Yields cpu for Scheduling
tproc() 012D1000 will be executed only now

eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0167fccc=00000000
0:001> g
1
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0253f9f4=00000000
0:002> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0235fbec=00000000
0:003> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0211fe68=00000000
0:004> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:01f7fbe4=00000000
0:005> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:01e1fbdc=00000000
0:006> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:01ccfb78=00000000
0:007> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:01b9f9cc=00000000
0:008> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:01a6fa38=00000000
0:009> g
eax=012d1000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0187fa60=00000000
0:010> g
2
3
4
5
6
7
8
9
10
g
778670f4 c3              ret
0:000>
0:000> q
quit:

**
now with a break and sxe ct
notice the Conditional Bp prints the src line number of LPTHREADROUTINE
 **
:\>cdb -c ".lines;.prompt_allow -reg -sym;bp ntdll!NtCreateThreadEx \".frame 3;k1;? poi(@esp+14);gc\";sxe -c \"r @eax\" ct;g" critter.exe

Microsoft (R) Windows Debugger Version 10.0.18362.1 X86

0:000> cdb: Reading initial command '.lines;.prompt_allow -reg -sym;bp ntdll!NtCreateThreadEx ".frame 3;k1;? poi(@esp+14);gc";sxe -c "r @eax" ct;g'

03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000
03 002ef9fc 00091384 critter!main+0x93 [xxx\critter.cpp @ 23]
ChildEBP RetAddr
002ef6ac 75b1b9da ntdll!ZwCreateThreadEx
Evaluate expression: 593920 = 00091000

All Threads Created Wait Below  Yields cpu for Scheduling
tproc() 00091000 will be executed only now

eax=00091000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0160fda4=00000000
0:001> g
1
eax=00091000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:023ef820=00000000
0:002> g
eax=00091000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:0217fea4=00000000
0:003> g
eax=00091000
778670d8 89442404        mov     dword ptr [esp+4],eax ss:0023:01e8fdd0=00000000
0:004>


text:
Q: USB3.0 Shield connection In the below image for Amphenol GSB343K33HR, do the 4 rectangular pads in the center of the image signify Shield connections?

A: Looking at the drawing of the connector, yes, those would be shield connections. Those four pads would require solder paste to improve the mechanical connection of the connector to the PCB beyond that provided by the two soldered posts.


text:
Q: How to compile the current VLC version (2.2.4) on Ubuntu 12.04? I tried to compile the current version of the VLC media player on Ubuntu 12.04 LTS.
Trying to achieve this I attempted the following:

*

*I extracted the .xz with tar xvfJ vlc-2.2.4.tar.xz

*Changed to the vlc-2.2.4 directory

*Executed ./bootstrap

*Executed ./configure

*Executed ./make
This did not work!
I had to install several *-dev packages (dependencies) via sudo apt-get -y install * to proceed further.
Unfortunately even this has not been sufficient to create an executable. I got stuck at this error message in the make process:

video_chroma/swscale.c:39:32: fatal error: libswscale/version.h: File or directory not found

Trying to research this error was not successful.
So my full question is:
What exact steps do I have to take to successfully compile VLC-2.2.4 on Ubuntu 12.04?

A: I had similar problem and this worked for me:
% cd contrib
% mkdir native
% cd native
% ../bootstrap
% make

Everything else you may need is in here: https://wiki.videolan.org/UnixCompile/
If this doesn't work - check your dependencies.


text:
Q: How did Adam Warlock become The Living Tribunal? I had seen in the comics that Adam Warlock is now the Living Tribunal. How and when did this happen?

A: As per Shreedar's comment, this is an alternate universe Adam Warlock who merged with the Adam Warlock of Earth-616. The wiki explains how he became the Living Tribunal in Thanos: The Infinity Finale as follows:

Having accidentally destroyed the entire universe when Pip the Troll awakened him in order to rescue him from Annihilus, a scared Adam Warlock summoned Thanos to his presence in the nothing that was left in his wake to know what he should do next. As he couldn't bring the universe back as it was, Warlock was convinced by Thanos to seek the aid of the Above-All-Others, which was only possible because Warlock had absorbed the essence of the Living Tribunal of his universe, along with everything else, into himself.
Accompanied by the Mad Titan, Warlock had an audition with the Above-All-Others, who was convinced by Thanos to strike a deal with them to allow them to restore the universe as it was before Annihilus' uprising against the Posiverse in exchange for the flavor of an all-new, all-different universe. With the army of the dead by their side, Warlock and Thanos defeated Annihilus' forces and submitted him. Warlock punished Annihilus by devolving him into an early stage of his evolution, which prompted Thanos to kill him by stomping on him, and took away Mephisto's mouth to prevent him from doing any trickery again.
With the universe fully restored and with only the most powerful beings remembering what never happened, Warlock resurrected the original version of himself from that actuality, and proceeded to become the new Living Tribunal as part of the deal he struck with the Above-All-Others.


text:
Q: Mailman sending messages as wrong domain I've got mailman and exim on my server for our mailing lists. When you send a message to it ( testlist@bar.company.com ), the message sender is testlist@foo.company.com.  This server is locally known as foo.company.com, with bar.company.com as an alias. foo.company.com is the servers internal name, while bar.company.com is what outsiders see. How can I get mailman to send from bar.company.com rather than foo?

A: Check, please, in web interface for list what you have in in General section in host_name. You should have bar.company.com here. You can also explicit set reply_to_address in same section.


text:
Q: My Application is shutting down itself and logcat is not showing any error messages I am using my android phone as emulator and current version of android is marshmallow. When I run an application which is having exceptions, the application in my phone is simply closing and it is even not saying application has stopped working. And android studio is not showing anything about the error occurred in application. Previously in eclipse as well as android studio it used say application has stopped working and it used to show all the error in logcat. Now I am using android studio version 2.2.3 and its so much helpless to find error present in the application. So can anyone help me to fix this?

A: private void handleUncaughtExceptions()
{
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
    {
        @Override
        public void uncaughtException (Thread thread, Throwable e)
        {
            handleUncaughtException (thread, e);
            Log.e(TAG, "error: " + e.getMessage());
        }
    });
}

try implementing this method in your main activity and calling it in onCreate() of your main activity and see if you can see the crash logs. You can also try and put a breakpoint there and try to reproduce the crash and see what's going on

A: Turns out there was nothing wrong with android studio. It was my mobile which was not giving proper reply to android studio's logcat. I used the genymotion emulator and its working fine now.


text:
Q: multi line variable does not work for parameters when used in a bash shell script I have a script that is used to set up a couple default widgets on a wordpress site through wp-cli.
script widgets.sh:
read -r -d '' TEXT << EOM
Line1

Address

Phone: 555-x
E-mail: so@you.say
EOM

sudo --user=$USRNAME -s wp widget add text footer-1 999 --title="Widget1" --filter="true" --visual="true" --text="$TEXT"

problem:
My problem lies in that when i call the shell script with these commands in them, such as by running
bash ~/widgets.sh

the variable $TEXT once sent to wp-cli have its linebreaks removed.
If i add
echo "$TEXT"

to the script file, it echoes it with linebreaks preserved properly, which just adds to my confusion.
If i copy and paste the commands into my terminal, it preserves the linebreaks from the HEREDOC properly.
I do not understand why, but there is a lot of things i don't understand about shell scripts and bash in general, so i hope someone can enlighten me :)
Thanks in advance!

A: In the html context, line numbers in the source code are not displayed on the rendered pages. If you add  tags to the end of your lines, your line breaks should show up there again.
May it help you to use nl2br


text:
Q: String not splitting properly using string.split I'm embarrassed to ask this one, it's a real newbie question but it's been kicking my butt all morning. Here goes:
I'm trying to split an IP address up into four seperate strings using the three periods as delimiters. Here's the code I am using:
     Toast.makeText(getBaseContext(),s,Toast.LENGTH_SHORT).show();
     String[] ip = s.split(".",4);
     String ip0ne = ip[0];
     String ipTwo = ip[1];
     String ipThree = ip[2];
     String ipFour = ip[3];

's' is the string containing the ip address '82.163.99.82', this is verified in the toast
The problem is, ipOne, ipTwo and ipThree end up containing nothing, and ipFour ends up containing '163.99.82' The first number of the ip address has disappeared altogether. Help please!

A: String[] ip = s.split("\\.",4);

The string argument is evaluated as a regular expression and so we have to escape the dot (and in java we have to escape the escape-char too - therefore: a double-backslash)

A: The split method takes a regular expression - and . in a regular expression matches any character :( Personally I think it's crazy for any non-regex API to take a regex as a String without having anything in the method name to indicate that, but hey...
You could use "\\." as the split value - but I would personally use Guava and its Splitter type:
private static final Splitter DOT_SPLITTER = Splitter.on('.').limit(4);