text:
Q: Want to add top padding on annotation text in bar chart in Google Chart (Visualization) I am using Google Chart's bar graph chart. There are annotation for every bar at the top, inside of the bar and I want create more space (more than default) between bar top line and annotation text. I have not find any way to create top padding (or top margin) around annotation text.
Here is my code:
var data = google.visualization.arrayToDataTable([
                [USER_AVERAGE, 'User Average', { role: 'style' }],
                ['SANDRA COOMBS', 8.6, '#008FBE'],
                ['STEVE ADAMS', 4.3, '#008FBE'],
            ]);

            var view = new google.visualization.DataView(data);
            view.setColumns([0, 1, 2,
                {
                    calc: "stringify",
                    sourceColumn: 1,
                    type: "string",
                    role: "annotation"
                }]);
            var options = {
                legend: {
                    position: 'none'
                },
                chartArea: { width: width, height: height, right: right },
                isStacked: true,
                orientation: orientation.orientation,
                fontSize: '12',
                fontName: 'OpenSans-Regular',
                hAxis: {
                    viewWindowMode: 'maximized',
                },
                vAxis: {
                    viewWindowMode: 'maximized',
                },
                animation: {
                    startup: true,
                    duration: 1500,
                    easing: 'out',
                },
            };
            var chart = new google.visualization.ColumnChart(document.getElementById("averageDaysChart"));
            chart.draw(view.toDataTable(), options);

A: there are no config options for annotation padding, position, or the like...
however, you can move them manually on the chart's 'animationfinish' event
but, a MutationObserver must be used,
because the chart will move them back on interactivity,
such as when you hover the column.
see following working snippet for an example of moving the annotations...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
      ['USER_AVERAGE', 'User Average', { role: 'style' }],
      ['SANDRA COOMBS', 8.6, '#008FBE'],
      ['STEVE ADAMS', 4.3, '#008FBE'],
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, 2,
      {
          calc: "stringify",
          sourceColumn: 1,
          type: "string",
          role: "annotation"
      }]);
  var options = {
      legend: {
          position: 'none'
      },
      //chartArea: { width: width, height: height, right: right },
      isStacked: true,
      //orientation: orientation.orientation,
      fontSize: '12',
      fontName: 'OpenSans-Regular',
      hAxis: {
          viewWindowMode: 'maximized',
      },
      vAxis: {
          viewWindowMode: 'maximized',
      },
      animation: {
          startup: true,
          duration: 1500,
          easing: 'out',
      },
  };

  var container = document.getElementById("averageDaysChart");
  var chart = new google.visualization.ColumnChart(container);

  google.visualization.events.addListener(chart, 'animationfinish', function () {
    moveAnnotations();
    var observer = new MutationObserver(moveAnnotations);
    observer.observe(container, {
      childList: true,
      subtree: true
    });
  });

  var originalY = {};
  function moveAnnotations() {
    var labels = container.getElementsByTagName('text');
    Array.prototype.forEach.call(labels, function(label) {
      if ((!isNaN(parseFloat(label.textContent))) && (label.getAttribute('text-anchor') === 'middle')) {
        if (!originalY.hasOwnProperty(label.textContent)) {
          originalY[label.textContent] = parseFloat(label.getAttribute('y'));
        }
        label.setAttribute('y', originalY[label.textContent] + 20);
      }
    });
  }

  chart.draw(view.toDataTable(), options);
});

A: No need for an animation hook or MutationObserver, just use good old fashioned CSS for this.
With Column and Bar charts, you only want to apply the "padding" to the annotation if it's placed within the bar itself. It's only placed inside the bar if the annotation text fits in the bar. When placed inside, it's given a white text color, so let's target that.
#averageDaysChart text[fill="#ffffff"] {
    transform: translateY(10px);
}


text:
Q: Send a message with a new library (Microsoft.Azure.ServiceBus) that is read by an old library (Microsoft.ServiceBus.Messaging) with BodyType - String I have a client written for some time ago that uses the old library and does call GetBody<string>() to read the body when receiving messages.
Now I have the new client Microsoft.Azure.ServiceBus (sends messages) that as far as I understand always uses Stream.
So the old client just crashes as it expects string body type. I have found a lot of information on the opposite scenario (new reader, old writer), but cannot figure out how to make the new client send the data in required format.
Related links:

*

*A stackoverflow answer

*Interop extension to do the opposite (read an old message in the new client)

A: The scenario is described here.
You will need to serialize the message following this approach:
 var serializer = DataContractBinarySerializer<string>.Instance;
 using (MemoryStream stream = new MemoryStream())
 {
     serializer.WriteObject(stream, some_string);
     var msg = new Message(stream.ToArray());
     var client = new Microsoft.Azure.ServiceBus.QueueClient(ConnectionString, Queue);
     await client.SendAsync(msg);
     await client.CloseAsync();
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Php OpenID fault in google accounts I'm use"PHP OpenID" for login with Google accounts into my site(forum and wiki) but when i send my profile address and i signed in bellow error are shown:
OpenID authentication failed: Nonce already used or out of range
1.where is the problem and how can i fix it?
2.how can get picture and another information's from a Google profile?
3.how can i get the following list and other information about followers and ... from it?
my test page is:
http://www.osdev.ir/openid/

A: The 'nonce already used or out of range' means that the nonce returned by the OpenID provider has expired -- this is checked against to prevent replay attacks.
This could be because your system time is out of whack (at least, that's when I got the error).


text:
Q: Dialogflow v2 android sdk - Add QueryParameters to QueryInput i'm actually trying to use Dialogflow v2 with java sdk in android.
I can already make queries to dialogflow but I wanted to send some payload with my query.
Because of this, I discovered the QueryParameters object and I already set it with my desired payload.
The problem is, I have both QueryInput and QueryParameters defined but there is no documentation (or code references in the source code) about how to apply the parameters to the input before trying to detect the intent.
SessionsClient.create().use { sessionsClient ->
            // Set the session name using the sessionId (UUID) and projectID
            val session = SessionName.of(PROJECT_ID, UUID)

            System.out.println("Session Path: $session")

            // Set the text (input) and language code (en) for the query
            val textInput = TextInput.newBuilder().setText(text).setLanguageCode(LANGUAGE_CODE)

            // Build the query with the TextInput
            val queryInput = QueryInput.newBuilder().setText(textInput).build()

            // Set payload
            val payload = "{someid: $someid}"
            val queryParameters = QueryParameters.newBuilder().setPayload(Struct.parseFrom(payload.toByteArray())).build()

            // (HERE I NEED TO ADD THE PARAMETERS TO INPUT)

            // Performs the detect intent request
            val response = sessionsClient.detectIntent(session, queryInput)

            // returns the query result
            return response.queryResult
        }

A: After hours of deep searching, I managed to find the DetectIntentRequest class.
            //Build the request
            val request = DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .setQueryParams(queryParameters)
                .build()

            // Performs the detect intent request
            val response = sessionsClient.detectIntent(request)

Note: if you are using other languages probably you 'll have a third
  parameter in detectIntent function to place your queryParameters

A: For Kotlin ,
val queryInput1211 = QueryInput.newBuilder()
            .setText(TextInput.newBuilder().setText(msg).setLanguageCode("en-US"))
            .setEvent(com.google.cloud.dialogflow.v2beta1.EventInput.newBuilder()
                    .setName("Welcome")
                    .setLanguageCode("en-US")
                    .setParameters(
                            Struct.newBuilder().putFields("user_id",
                                    Value.newBuilder().setStringValue("1234").build())
                                    .build())
                    .build())
            .build()

For java
QueryInput queryInput1211 = QueryInput.newBuilder()
                    .setText(TextInput.newBuilder().setText(msg).setLanguageCode("en-US"))
                    .setEvent(com.google.cloud.dialogflow.v2beta1.EventInput.newBuilder()
                            .setName("Welcome")
                            .setLanguageCode("en-US")
                            .setParameters(
                                    Struct.newBuilder().putFields("user_id",
                                            Value.newBuilder().setStringValue("1234").build())
                                            .build())
                            .build())
                    .build();

Where Welcome is intent event name and user_id as parameter name


text:
Q: SAML OAuth Integration - toggle SAML We are implementing the flexibility to configure OAuth or SAML or both OAuth and SAML. Configured the following in the saml security context:
<security:http pattern="/oauth/authorize/**" entry-point-ref="samlEntryPoint" use-expressions="true">
<security:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter" />
 ........
 ........

<bean id="samlFilter" class="org.springframework.security.web.FilterChainProxy">
        <security:filter-chain pattern="/saml/login/**" filters="samlEntryPoint" />
        <security:filter-chain pattern="/saml/metadata/**" filters="metadataDisplayFilter" />
        <security:filter-chain pattern="/saml/SSO/**" filters="samlWebSSOProcessingFilter" />
        <security:filter-chain pattern="/saml/SingleLogout/**" filters="samlLogoutProcessingFilter" />
        <security:filter-chain pattern="/oauth/authorize/**" filters="samlEntryPoint" />
    </security:filter-chain-map>
</bean>

There is a configurable property which determines whether SAML is enabled or disabled. How can I skip the samlEntryPoint from getting invoked when SAML is disabled? Application is always restarted when toggling SAML, I don't have to consider the use case of switching it on/off when the application is running.
Any help is appreciated.

A:
How can I skip the samlEntryPoint from getting invoked when SAML is disabled?

To have various authentication schemes, you can use Spring profiles and write separate security contexts files. This is how you do it :
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Spring Security configuration for SAML only authentication -->
    <beans profile="auth-saml">
        <import resource="security/applicationContext-security-saml.xml" />
    </beans>

    <!-- Spring Security configuration for OAUTH only authentication -->
    <beans profile="auth-oauth">
        <import resource="security/applicationContext-security-oauth.xml" />
    </beans>

    <!-- Spring Security configuration for SAML+OAUTH authentication -->
    <beans profile="auth-saml-oauth">
        <import resource="security/applicationContext-security-saml-oauth.xml" />
    </beans>

</beans>

Then you choose the active Spring profile with the environment variable spring.profiles.active with value corresponding to the profile attribute value (either auth-saml, auth-oauth or auth-saml-oauth).

A: In addition to Gregoire's response, you can also create a class such as multiAuthenticationEntryPoint -which takes those entrypoints as property- where you can implement
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    // TODO Auto-generated method stub
    if(sth)
        {
        customAuthenticationEntryPoint.commence(request, response, authException);
        return;
        }
    else {
        samlEntryPoint.commence(request, response, authException);
        return;
    }

}


text:
Q: How do I get off the island in The Cave? I am on the island and I got the boat to the big door which blocks its path, but I don't know what to do next.
Although I found the explosives and I got the steam balloon working, I don't know how to get past the half way mark and where to put the FEMUR to distract Spanky the dog.

A: There is a variety of things to do.  (Not giving too much away here, just how to deal with the issues you are having).
First you need to drain some water, to allow the boat to progress to the right.  See spoiler for how.

 You have 3 explosive barrels.  Drag one to the bottom of the ramp to the right, one near the pile of rocks, and one near the grate.  Then drag the right-most barrel up the ramp until it ignites from the heat and push it back down the ramp (just let go and it will roll into position, causing a chain explosion.)

When you get the boat to the other shore, there will be another obvious problem you need to solve.  See spoiler for how.

 As for Spanky, you need the parrot first.  Find the crackers, go get the parrot, and then visit Spanky.  wave the bone in front of Spanky, and the parrot will pick up his bark.  Then take the parrot to the hermit (you will know when to do this, because you need to distract the hermit).


text:
Q: Hidden @Font-face ? font-weight 700 resorts to local Arial instead of custom font I can't seem to use the custom font I want on my server nor on my gulp browsersync demo.
For an h4 element, I have the @font-face rules in place in chrome, I can see it.
I have Raleway-Regular.woff2 for font-weight 700 and Raleway-Black.woff2 for font-weight: 900
If you put this you can see the same.
<link href="https://fonts.googleapis.com/css?family=Raleway:400,700,900" rel="stylesheet">

.h4,
.h5,
.h6 {
  font-family: "Raleway", Arial, sans-serif;
  font-weight: 700; /* changing to 800 works for Raleway */
  line-height: 1.1;
  color: inherit;
}

For some reason using localhost or remotely, when I inspect element on an H4, look at "computed" tab. You can see rendered font: Arial.
If I modify font-weight of h4 to "900", then it goes to Raleway-Black. If I change it to 800 it goes to "Raleway-Bold". But if I go to "700" suddenly, it doesn't render Raleway-Regular.woff2... it goes back to "Arial".
Why is Arial being displayed instead of Raleway-Regular.woff2 ?
In my code I am using Bootstrap & gulp with wiredep etc. But I do not see any font-face anywhere in my html being rendered other than Font-Awesome and Glyphicons. Which work fine.
I only have one custom CSS for bootstrap. I have disabled any other bootstrap plugins.
Sass is available too, but my sass file being rendered has no "font-face" or "import".


text:
Q: Converting .ps1 to .bat doesn't cause cmd.exe to hit max character length - but why? Based on a related question and some Googling/testing, it is pretty clear that the maximum length of a command line in cmd.exe is 8,191 characters. However...my script seems to successfully exceed that length, and I can't figure out why it works.
So I have:

*

*A script written/saved as a .ps1

*I'm converting it to a .bat using the method from Converting PowerShell to Batch

*If I run the .bat - there don't seem to be any issues

*If I try to echo the $encoded command or just remove @echo off before running the .bat - it is easy to see that the length/content of $encoded has been truncated...yet it works as expected

I realize this is a bit of a strange question since I'm trying to ascertain some kind of hidden truth about something that works vs. something that is broken, but I'd like to understand why it is working!
Note:
The primary reason I'm creating a .bat for my script is because I have a number of small 'programs' that I need to run on my work computer and share with others. Our company's execution policies don't allow running scripts, and it is much easier for others to use something I've written if it is a .bat since they won't need to understand/use PowerShell. They can just place the .bat in the right place, give it two clicks, and then sit back and relax until something happens.
EDIT: Here's the truncated command in the cmd.exe window. If I convert from Base64 back to readable text, it is clearly missing about half of the script. Yet - I'm not noticing any problems

A: *

*The 8191-character limit applies to the interactive command line and calls to cmd.exe's CLI (via cmd /c)

*It does not apply to commands invoked from batch files - there the limit is close to[1] 32KiB (32,768) characters.

*

*However, it still seems to apply selectively to cmd.exe's internal commands, such as echo; by contrast, a call to an external program such as powershell.exe is not affected (though it is possible for specific external programs to have their own, lower limits).

As an aside:
As clever as the linked method of converting PowerShell scripts to batch files is, the resulting batch files lack support for arguments to be passed through to the PowerShell code, and adding support for that would be impractical (it would require Base64-encoding the arguments too, at invocation time, which isn't possible from a batch file except with the help of non-built-in utilities).

*

*If your script / batch file is written to either require no arguments on invocation or to prompt for them interactively (as in your case), this limitation is not a concern.

*However, you may want argument support for any of the following reasons:

*

*To allow calling the batch file from cmd.exe (Command Prompt) with arguments.

*To allow calling with arguments from other environments that support passing arguments, notably Task Scheduler and the Windows Run dialog (WinKey-R).

*To make the batch file support drag-and-drop (which implicitly passes the dropped files' paths as arguments).

As for the overall reason to wrap PowerShell code in batch files:

*

*Batch files (.cmd, .bat) can be launched directly, as if they were executables, system-wide.

*By contrast, this is not supported for PowerShell scripts (.ps1), which from outside PowerShell must be invoked via an explicit call to the PowerShell CLI; note that systems may be configured to categorically prevent execution of .ps1 scripts - see next section.

If you do need argument support in your batch file, the best - but inconvenient - solution is to distribute two files:

*

*the original *.ps1 file...

*and a companion batch file, with the same base file name, to be placed in the same directory - which can be invoked from outside PowerShell - whose sole purpose is to invoke the *.ps1 file via powershell.exe with pass-through arguments.

E.g. foo.cmd would accompany foo.ps1, with the following - invariant - content:
@powershell.exe -NoProfile -File "%~dpn0.ps1" %*

Note:

*

*Important: The above assumes that the effective PowerShell execution policy allows execution of script files (.ps1).

*

*If you cannot make this assumption, place -ExecutionPolicy RemoteSigned before -NoProfile above (or, to deactivate all checks, -ExecutionPolicy Bypass), but note that an execution policy based on  GPO (Group Policy Objects) may still prevent script execution.

*To call PowerShell (Core) 7+ instead, use pwsh.exe instead of powershell.exe.

*%~dpn0 expands to the full path of the enclosing batch file itself without its filename extension; appending .ps1 therefore targets the companion PowerShell script in the same directory; run cmd /c call /? for an explanation of the syntax.

*%* passes any and all arguments received by the batch file on.

[1] In practice, the limits appear to be: 32,767 characters in batch files, and - lower by 3 chars. - 32,764 for Powershell (both on the command line / via the CLI and in *.ps1 scripts). In PowerShell, the limit may in practice be even lower than that, because PowerShell expands the names of executables it locates via $env:PATH to their full paths in the command lines constructed behind the scenes, which cmd.exe doesn't do.


text:
Q: how to position my customized carousel widget section that should be responsive I have made the customized carousel in html using java script, in which the size of  the, scroll-able small pictures underneath the current display picture, changes on run time based upon the number of pictures. The anchors should be stuck to the first and last images, to do so i have float:right the right anchor and the position of the left anchor is changed upon run time based upon number of pictures in java script. Now the issue is that I have to align this whole thing (small images) in the middle with respect to the display image on top. Is there any way to do so without positioning through java script but by using css. Any suggestion will be very helpful. Everything should be responsive for all types of screens.
Note: The page is RTL
Link to the Fiddle

var totalLandMarks = 2;
   var landMarkCount =  0;
   var landMarkId =0;
   var currentIndex = 1;
   //var scrollindex = 1;
   var flag=0;
   /* uncomment when need to scroll automatically
   var screenWidth = $('#country-selected').width();
   if (window.matchMedia("(min-width: 1000px)").matches) {
   /* the viewport is at max 360 pixels wide
   screenWidth = 900;
 }*/
    //   $sortableList.on("sortchange", sortEventHandler);

 $( document ).ready(function() {
     console.log( "ready!" );

     for(var i=0;i<totalLandMarks;i++) {
      landMarkCount++;
      landMarkId++;

      $('#sortable').css({
    'width': ''+(((landMarkCount)*100)+((landMarkCount)*10))+'px',
    'height': '35px',
    'padding': '0em'
   });
   if($(".demo").width() > ((((landMarkCount)*100)-20)+((landMarkCount-1)*10))){
    $(".anchor-left").css({
     "right": ""+((((landMarkCount)*100)-20)+((landMarkCount-1)*10))+"px",
    })
   }
   else{
    $(".anchor-left").css({
     "right": "auto",
     "left": "0px",
     "position": "absolute",
     "top": "23px",
    })
   }

      if(landMarkCount%2 == 0){
       $("#sortable").append('

');
      }
      else
      {
       $("#sortable").append('

');
      }

    }
    updateImages();
 });

 function scrollRight(){

  var leftPos = $('.demo').scrollLeft();
   $(".demo").animate({scrollLeft: leftPos + 111}, 200);
 }
 function scrollLeft(){

  var leftPos = $('.demo').scrollLeft();
    $(".demo").animate({scrollLeft: leftPos - 111}, 200);
 }

 $(document).on("click",".anchor-right",function(){
  //$('.demo').scrollLeft(200);
  scrollRight();

  if(currentIndex > 1){
   currentIndex-=2;
  }

  updateImages();

 });
 $(document).on("click",".anchor-left",function(){
  //alert("Clicked Left");
  //$('.demo').scrollLeft(-5);
  scrollLeft();
  updateImages();

 });
 function updateImages(){

  if(currentIndex > totalLandMarks){ // when the highlighted pic needs to move from last to first
   currentIndex=1;
    $(".demo").animate({scrollLeft: $("#landMark"+currentIndex).offset().left}, 200);

    flag=0;
  }
  var imgSource = document.getElementById("landMark"+currentIndex).src;
  $("div").removeClass("overlay");
  $('[data-id=' + currentIndex + ']').addClass("overlay"); // its the purple color shown on the highlighted pics
  /*$("#landMark"+currentIndex).css({
   'opacity': '0.5'

  });*/
  $(".bottom-border").hide();

  $('#landMarkBottom'+currentIndex).show(); // showing the div at the bottom

  //console.log((scrollindex*(document.getElementById('landMarkBottom'+currentIndex).clientWidth)));
  //console.log(screenWidth+" maxWidth");
  /* un comment when you need to scroll
  if((scrollindex*(document.getElementById('landMarkBottom'+currentIndex).clientWidth)) > screenWidth){
   flag=1;
  }
  else{
   scrollindex++;
  }

  if(flag == 1){
   //$('#landMarkBottom'+currentIndex).focus();
   scrollLeft();
  }
  */

  console.log(imgSource);
  $(".display-image").html('');
  // document.getElementByClassName(".display-image").innerHTML = imgSource;
  currentIndex++;

 }
 setInterval(function() {
   // method to be executed;
   //updateImages();

 }, 5000);

 $(document).on("click",".draggable",function(){

  $('#landMarkBottom'+(currentIndex-1)).hide();
  currentIndex = $(this).attr('data-id');
  updateImages();
 });
.country-content{
   width: 100%;
      height: 150px;
      position: relative;
      padding: 0px 20px;
  }
  .draggable {
      width: 100px;
      height: 90px;
      margin-left: 10px;
      position: relative;
  }
  .overlay:before{
   position: absolute;
   content:" ";
   top:0;
   left:0;
   width:100%;
   height:100%;
   display: block;
   z-index:10;
   background-color: rgba(140, 116, 158, 0.4);
   border-radius: 10px;
  }

  #sortable {
   width: 10%; /* width of scorllable needs to be cahnged upon runtime */
   height: 35px;
   padding: 3em;
   padding-right: 0px;
  }
  .country-image {
      width: 100px;
      height: 90px;
      border-radius: 10px;
      right: 0px;
  }

  #sortable > div {
   float: right;
  }
  .demo {
      width: 100%;
      overflow: hidden;
      margin: 0px 0px;
      min-height: 100px;
  }
  .current-image {
         width: 100%;
   height: 100%;
   border-radius: 20px;
  }
  .display-image{
   width: 100%;
      height: 400px;
      padding: 10px 20px;
  }

  /* Styling the scrollbar */
  .demo::-webkit-scrollbar {
      width: 0px;
      height: 0px;

  }

  .anchor-right {
      float: right;
      top: 26px;
      padding-right: 12px;
      position: absolute;
      right: 0px;
      font-size: 30px;
      box-shadow: inset 0 0 5px grey;
      width: 42px;
      border-radius: 33px;
      background-color: white;
      z-index: 1000;
  }
  .anchor-left {
      font-size: 30px;
      padding-right: 14px;
      position: relative;
      box-shadow: inset 0 0 5px grey;
      top: -74px;
      /* left: 0px; */
      right: 83px;
      z-index: 20;
      width: 42px;
      border-radius: 30px;
      background-color: white;
  }
  .anchor-left a{
   text-decoration: none;
   color:grey;
  }
  .anchor-right a{
   text-decoration: none;
   color:grey;
  }
  .bottom-border{
   margin-top: 3px;
      margin-right: 5px;
      margin-left: 5px;
      border: 2px solid #8C749E;
      display: none;
      border-radius: 16%;
  }
  @media only screen and (min-width: 100px) and (max-width: 376px) {
   .display-image{
    width: 100%;
       height: 250px;
       padding: 10px 20px;
   }

  }

@media only screen and (min-width: 377px) and (max-width: 824px) {
   .display-image{
    width: 100%;
       height: 300px;
       padding: 10px 20px;
   }

  }
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>44 HTML</title>

  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" type="text/css" rel="stylesheet"">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

A: Give your div with class demo margin 0 auto
.demo
{
 width: 50%;
 overflow: hidden;
 margin: 0 auto;
 min-height: 100px;
}

and for anchor-right
right:126px;

for anchor-left add inline style
style="right: 308px;"


text:
Q: Angular8 cdk , How to load components inside for loop in Drag and Drop functionality.? Drag and Drop in angular8 cdk only, i have one doubt. can i load my widgets/card inside for loop ?  i have 40+ widgets need to be displayed in dashboard and all cards are of different sizes and each card drag among each other and drop.
how i call my all 40+ components of different width and height inside cards array given below???
please help me ...
<mat-grid-list cols="12" rowHeight="1:1" gutterSize="15px">
          <mat-grid-tile *ngFor="let card of cards; let i = index;"
                         [colspan]="card.cols" [rowspan]="card.rows">
            <cdk-drop-list [cdkDropListConnectedTo]="drops" [cdkDropListData]="i" >
              <mat-card cdkDrag (cdkDragEntered)="entered($event)" [cdkDragData]="i"
                        class="dashboard-card"  [style.backgroundColor]="card.color">

                <mat-card-content class="dashboard-card-content">
/// how to load components here-------------------------------------------->>

{{card.title}}

                </mat-card-content>
              </mat-card>
            </cdk-drop-list>
          </mat-grid-tile>
    </mat-grid-list>```

```
 cards = [
    { title: 'Card 1', cols: 3, rows: 2},
    { title: 'Card 2', cols: 3, rows: 2 },
    { title: 'Card 3', cols: 3, rows: 2 },
    { title: 'Card 4', cols: 6, rows: 2},
    { title: 'Card 5', cols: 9, rows: 2},
    { title: 'Card 6', cols: 3, rows: 2},
    { title: 'Card 7', cols: 6, rows: 2 },
    { title: 'Card 8', cols: 3, rows: 2 },
   ];
```

A: You can use Dragula module for Angular : npm install ng2-dragula

    {{ vamp.name }} likes {{ vamp.favouriteColor }}

In componet.ts file
   constructor(private dragulaService: DragulaService) {
}

ngOnInit() {
    this.dragulaService.createGroup("DRAGULA_EVENTS", {
        direction: 'horizontal',
        moves: (el, source, handle) => handle.className === "group-handle"
    });
    // You can also get all events, not limited to a particular group
    this.subs.add(this.dragulaService.drop()
        .subscribe(({name, el, target, source, sibling}) => {
            console.log(name, el, target, sibling)
        })
    );
}

https://github.com/valor-software/ng2-dragula/
DEMO: you can see demo click here


text:
Q: ID3 tags with Swift I'm looking for a way to modify ID3 tags with Swift. More specifically, I want to write the Album Art image to an mp3/m4a file.
A Swift library would be the best, but I'll take anything that can be done natively in Swift. I don't want to rely on another language's library.
I had a quick look at AVFoundation, but it looks like it's only for audio/video playback and conversion. This is about the closest I found from ID3 tags: https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVAsset_Class/
Any suggestion?

A: I was faced with this same problem over and over so I decided to make a swift framework for it. You can find it here: https://github.com/philiphardy/ID3Edit
Add it into your Xcode project and then make sure to embed it by going to your project settings > General > Embedded Binaries
Here is how to implement it in your code:
import ID3Edit
...
do
{
   // Open the file
   let mp3File = try MP3File(path: "/Users/Example/Music/example.mp3")
   // Use MP3File(data: data) data being an NSData object
   // to load an MP3 file from memory
   // NOTE: If you use the MP3File(data: NSData?) initializer make
   //       sure to set the path before calling writeTag() or an
   //       exception will be thrown

   // Get song information
   print("Title:\t\(mp3File.getTitle())")
   print("Artist:\t\(mp3File.getArtist())")
   print("Album:\t\(mp3File.getAlbum())")
   print("Lyrics:\n\(mp3File.getLyrics())")

   let artwork = mp3File.getArtwork()

   // Write song information
   mp3File.setTitle("The new song title")
   mp3File.setArtist("The new artist")
   mp3File.setAlbum("The new album")
   mp3File.setLyrics("Yeah Yeah new lyrics")

   if let newArt = NSImage(contentsOfFile: "/Users/Example/Pictures/example.png")
   {
          mp3File.setArtwork(newArt, isPNG: true)
   }
   else
   {
          print("The artwork referenced does not exist.")
   }

   // Save the information to the mp3 file
   mp3File.writeTag() // or mp3.getMP3Data() returns the NSData
                      // of the mp3 file
}
catch ID3EditErrors.FileDoesNotExist
{
   print("The file does not exist.")
}
catch ID3EditErrors.NotAnMP3
{
   print("The file you attempted to open was not an mp3 file.")
}
catch {}


text:
Q: Using imageJ plugin from jython : how to call it in the script? I want to use Jython to analyse images on ImageJ, but I don't know how to call existing plugins and run it from the script. Do you have an idea ?
Thanks.

A: Use the syntax from packagename import namespace
An example:
from ij import IJ, ImagePlus
from ij.plugin.filter import RankFilters

imp = IJ.getImage()
ip = imp.getProcessor().convertToFloat()

radius = 2
RankFilters().rank(ip, radius, RankFilters.MEDIAN)

imp2 = ImagePlus(imp.title + " median filtered", ip)
imp2.show()

You can find the name of specific plugins by searching the command finder.


text:
Q: Access Update Statement And Calling Said Statement Within .NET I am working with an Access database which I really do not enjoy by the way, and am trying to perform an update on a record with a "contacts" table. The statement is written like so...
UPDATE contacts SET FirstName = [c_FirstName], LastName = [c_LastName], Title = [c_Title], Email = [c_Email], IncludeSection4 = [c_IncludeSection4] WHERE (((ContactID)=[c_ContactID]));

Now the .NET part goes like this...
Public Shared Function Update(ByVal contact As IContact) As Boolean
        Dim parameterList As New List(Of DataParameter)
        parameterList.Add(New DataParameter("c_ContactID", contact.ContactID, ParameterDirection.Input, OleDbType.Integer))
        parameterList.Add(New DataParameter("c_FirstName", contact.FirstName, ParameterDirection.Input, OleDbType.VarChar))
        parameterList.Add(New DataParameter("c_LastName", contact.LastName, ParameterDirection.Input, OleDbType.VarChar))
        parameterList.Add(New DataParameter("c_Title", contact.Title, ParameterDirection.Input, OleDbType.VarChar))
        parameterList.Add(New DataParameter("c_Email", contact.Email, ParameterDirection.Input, OleDbType.VarChar))
        parameterList.Add(New DataParameter("c_IncludeSection4", contact.IncludeSection4, ParameterDirection.Input, OleDbType.Boolean))
        If DAL.SendData("UpdateContact", parameterList) Then
            Return True
        End If
        Return False
End Function

For some reason, this does not update and always returns false. cmd.ExecuteNonQuery always returns 0.... I'm thinking that the Access part of it is not correct, is there anything obvious here?

A: OleDb with Access ignores the parameter names.  Supply the parameters in the same order as they appear in the UPDATE statement.
    parameterList.Add(New DataParameter("c_FirstName", contact.FirstName, ParameterDirection.Input, OleDbType.VarChar))
    parameterList.Add(New DataParameter("c_LastName", contact.LastName, ParameterDirection.Input, OleDbType.VarChar))
    parameterList.Add(New DataParameter("c_Title", contact.Title, ParameterDirection.Input, OleDbType.VarChar))
    parameterList.Add(New DataParameter("c_Email", contact.Email, ParameterDirection.Input, OleDbType.VarChar))
    parameterList.Add(New DataParameter("c_IncludeSection4", contact.IncludeSection4, ParameterDirection.Input, OleDbType.Boolean))
    parameterList.Add(New DataParameter("c_ContactID", contact.ContactID, ParameterDirection.Input, OleDbType.Integer))

A: Your update statement looks odd.  It's been a long time since I've done access, but it should look more like this:
UPDATE [contacts] SET [FirstName] = @c_FirstName, [LastName] = @c_LastName, ...

Also, you Access doesn't really care about the parameter names, just make sure they're in the same order.


text:
Q: Rails: Auto-fill reference on nested resource I have a resource "Project" nested inside a resource "Group". On my show group page, I list all the projects the group has. I also have added a "New Project" link leading to
new_group_project_path(@group)

But in the following new project form, the user still needs to enter the id of the group, even though he just clicked the New Project link on a specific group's page. I tried doing
<%= f.text_field :group_id, :value => @group.id %>

But @group seems to be nil, even though I passed it in the link.
How can I auto-fill this field with the group_id, or even hide the whole thing from the user, since it's already predetermined and he shouldn't have to think about that?
Thanks,
MrB
[edit]
Here's more of my code to clarify:
  1 class ProjectController < ApplicationController
  2   def new
  3     @group = Group.find(params[:group_id])
  4     @project = @group.projects.build
  5     respond_with(@project)
  6   end
  7
  8   def create
  9     @group = Group.find(params[:group_id])
 10     @project = @group.projects.build(params[:projects])
 11   end
 12 end

And in the _form.html.erb
 26   <% if @group.nil? %>
 25

 26       <%= f.label :group_id %>

 27       <%= f.text_field :group_id %>
 28

 29   <% end %>

Routes.rb:
  5   resources :groups do
  4     resources :projects
  5   end
  6
  7   resources :projects

Hope this helps. Thank you.

A: If you have nested the controllers in your routes.rb then you should not need to do anything extra in the form. So if your routes.rb looks something like this:
resources :groups do
  resources :projects
end

which it looks like from your path_helper, then you will always have the group_id available from the routing. So when the user submits the form to your create action in ProjectsController, you could handle it something like this:
@group = Group.find(params[:group_id])
@project = @group.projects.build(params[:project])

Edit:
If @group is nil in your form (I'm guessing it is called in the new action) then you have the either add the @group = Group.find(params[:group_id]) in your new action as well (which would go against the DRY principal of Rails) or do what Ryan suggested and add it in a before_filter which could look like this:
class ProjectsController < ApplicationController
  before_filter :find_group

  ...

private
  def find_group
    @group = Group.find(params[:group_id])
  end
end

That will make the @group variable available in all actions in this controller. The declaration of private only makes sure that nothing outside the Controller can make the call to find_group.


text:
Q: Is it legal to make Android app Paid of Monetize Ads if it contains YouTube videos I am planning to develop an Android App for Kids Leaning.
In the initial screen, i will have list of topics like below. These topics will be loaded from a Database and each  link contains a href.

Now, once the kid click on any link, in the next activity, i am loading a WebView and the video is played in the WebView.
String frameVideo = "";

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.loadData(frameVideo, "text/html", "utf-8");

Following is the screenshot how it looks like:

So is it legal to reference video as above?
In the above scenario, can i monetize the App. I dont want to show any Ads on the videoplayer activity, but wanted to place Ads on all other activities. Is it Legal? Please suggest.


text:
Q: SFTP using JSch and GlobalScape I'm trying to establish a SFTP connection using Java secure chanel (JSCh).
My software stack is Red Hat Enterprise Server 5.0, JRE 6.0 and JSch v0.1.44.
The primarily server software stack (to which I'm trying to connect) is Windows Server 2008 and the latest version of GlobalScape.
When trying to connect to it I get a
com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:529)
    at com.jcraft.jsch.Session.connect(Session.java:291)

Enabling JSch logging I get the following for this same connection:
0000001d SystemErr     R INFO: Connecting to xxx.xxx.xxx.157 port 22
0000001d SystemErr     R INFO: Connection established
0000001d SystemErr     R INFO: Remote version string: SSH-2.0-1.36_sshlib GlobalSCAPE
0000001d SystemErr     R INFO: Local version string: SSH-2.0-JSCH-0.1.44
0000001d SystemErr     R INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-    cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
0000001d SystemErr     R INFO: aes256-ctr is not available.
0000001d SystemErr     R INFO: aes192-ctr is not available.
0000001d SystemErr     R INFO: aes256-cbc is not available.
0000001d SystemErr     R INFO: aes192-cbc is not available.
0000001d SystemErr     R INFO: arcfour256 is not available.
0000001d SystemErr     R INFO: SSH_MSG_KEXINIT sent
0000001d SystemErr     R INFO: SSH_MSG_KEXINIT received
0000001d SystemErr     R INFO: Disconnecting from xxx.xxx.xxx.157 port 22

So from the looks of it I'm connecting to the server and I actually can send and receive a msg, but when the client tries to match the server msg proposal and the client msg proposal it throws an exception.
Now comparing it with the JSch logs of a successful connection to a Server with a previous GlobalScape software and Windows Server 2003:
0000001e SystemErr     R INFO: Connecting to xxx.xxx.xxx.156 port 22
0000001e SystemErr     R INFO: Connection established
0000001e SystemErr     R INFO: Remote version string: SSH-2.0-1.36 sshlib: GlobalScape
0000001e SystemErr     R INFO: Local version string: SSH-2.0-JSCH-0.1.44
0000001e SystemErr     R INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
0000001e SystemErr     R INFO: aes256-ctr is not available.
0000001e SystemErr     R INFO: aes192-ctr is not available.
0000001e SystemErr     R INFO: aes256-cbc is not available.
0000001e SystemErr     R INFO: aes192-cbc is not available.
0000001e SystemErr     R INFO: arcfour256 is not available.
0000001e SystemErr     R INFO: SSH_MSG_KEXINIT sent
0000001e SystemErr     R INFO: SSH_MSG_KEXINIT received
0000001e SystemErr     R INFO: kex: server->client aes128-cbc hmac-md5 none
0000001e SystemErr     R INFO: kex: client->server aes128-cbc hmac-md5 none
0000001e SystemErr     R INFO: SSH_MSG_KEXDH_INIT sent
0000001e SystemErr     R INFO: expecting SSH_MSG_KEXDH_REPLY
0000001e SystemErr     R INFO: ssh_dss_verify: signature true
0000001e SystemErr     R WARN: Permanently added 'xxx.xxx.xxx.156' (DSA) to the list of known hosts.
0000001e SystemErr     R INFO: SSH_MSG_NEWKEYS sent
0000001e SystemErr     R INFO: SSH_MSG_NEWKEYS received
0000001e SystemErr     R INFO: SSH_MSG_SERVICE_REQUEST sent
0000001e SystemErr     R INFO: SSH_MSG_SERVICE_ACCEPT received
0000001e SystemErr     R INFO: Authentications that can continue: publickey,keyboard-inteactive,password
0000001e SystemErr     R INFO: Next authentication method: publickey
0000001e SystemErr     R INFO: Authentications that can continue: password
0000001e SystemErr     R INFO: Next authentication method: password
0000001e SystemErr     R INFO: Authentication succeeded (password).

So once again it's able to connect and able to exchange SSH_MSG_KEXINIT, but here the client and server proposals match and no exception is thrown
The sftp security is using a public/private key and username/password.
I can connect to it using WinSCP, Filezilla and linux command line (from the same server the java application runs).
I spoke with one system administrator of the SFTP server and we tried using username/password and I get the same exception and logs.
The system administrator told me that the difference between both servers is the GlobalScape version and now being a Microsoft 2008 Server.
So anyone has any ideas on how to tackle this one?
Many thanks in advance!

A: The problem you are having is nothing to do with globalscape its all about all enabled cipher algorithms SFTP server.
Every sftp server has some cipher algorithms  that they agree over so if you don't have those encodings and algorithms for cipher it doesnot work
cipher algorithms
All other SFTP softwares have inbuilt cipher algorithms which they use according to sftp server configuration chnage to latest 256 bit cipher algorithm and you are all set
https://enterprisedt.com/products/edtftpjssl/doc/manual/html/howtousesftpchoosingalgorithms.html
Public key algorithms
Either DSA or RSA or both can be set for the preferred public key algorithms for server authentication. If, for example, RSA is set, the server will present an RSA public key to the client (if the server supports RSA keys of course - some servers do not). The code below illustrates how to set RSA only. It first disables all keypair algorithms, then enables RSA:
ftp.disableAllAlgorithms(SSHFTPAlgorithm.KEY_PAIR);
ftp.setAlgorithmEnabled(SSHFTPAlgorithm.KEY_RSA, true);
The default is both DSA and RSA enabled.
Cipher algorithms
The cipher algorithms are the symmetric algorithms used to perform the encryption of the SFTP data and commands. The code below illustrates how to set triple DES as the cipher algorithm (disabling all others):
ftp.disableAllAlgorithms(SSHFTPAlgorithm.CIPHER);
ftp.setAlgorithmEnabled(SSHFTPAlgorithm.CIPHER_3DES_CBC, true);
The default is all cipher algorithms enabled.


text:
Q: How to throw exceptions from Handler I'm building a RESTful endpoint that should throw an error if there is invalid data. Here's a simplified (and slightly silly) version:
getEventsR :: Handler Value
getEventsR = do
    mpage   <- lookupGetParam "page"
    let filters = case hasPage mpage of
                      Right val -> val
                      Left val  -> error $ T.unpack val -- Throw an error

     -- The rest...

hasPage :: Maybe Text -> Either Text Text
hasPage =
    Left "This should error out"

*

*Is this the correct way - a function should return an Either that will later be expanded to an error?

*I probably shouldn't use error, right? What instead?

As a side note, I'd be happy if my thrown error would be sent also in JSON format.
Update:
The reason I've used the term "throw exception", is because my code looks something like this (simplified):
let selectOpt = case addPager [] of
                    Right val -> val
                    Left val  -> error $ T.unpack val

let filters = case addFilter [] of
                    Right val -> val
                    Left val  -> error $ T.unpack val

events <- runDB $ selectList filters selectOpt :: Handler [Entity Event]

So if it errors out on selectOpt I'd like it to short-circuit, and not continue with the rest of the handler.

A: You can use the sendResponseStatus to directly specify the response:
getEventsR = do
  mpage   <- lookupGetParam "page"
  case hasPage mpage of
    Left message -> sendResponseStatus status400 message
    Right val    -> ...continue processing with val...

The second argument to sendResponseStatus can be any type which has a ToTypedContent instance. This includes Text, Value and other common types. See this page for types which have this instance defined by default.
Update
In response to your comments...
get404 is defined as:
get404 key = do
    mres <- get key
    case mres of
        Nothing -> notFound'
        Just res -> return res

notFound' :: MonadIO m => m a
notFound' = liftIO $ throwIO $ HCError NotFound

HCError is a constructor of the HandlerContents type:
http://hackage.haskell.org/package/yesod-core-1.4.0/docs/Yesod-Core-Types.html#t:HandlerContents
data HandlerContents:
    HCContent Status !TypedContent
    HCError ErrorResponse
    HCSendFile ContentType FilePath (Maybe FilePart)
    HCRedirect Status Text
    HCCreated Text
    HCWai Response
    HCWaiApp Application

An ErrorResponse has the following constructors:
data ErrorResponse:
    NotFound
    InternalError Text
    InvalidArgs [Text]
    NotAuthenticated
    PermissionDenied Text
    BadMethod Method

So you can throwIO a limited number of errors, and the error messages are limited to Text.


text:
Q: Find the sum of this series $\sum_{k=1}^{\infty} \frac{(2-x)^k}{2^k*k}$ How to find the integration $C$? Hello I have the following series :
$$\sum_{k=1}^{\infty} \frac{(2-x)^k}{2^k*k}$$
I found that the series convergents for $0<x \leq 4$
I managed to reach that
$$f(x)=-ln(x)+C$$
But for some reason the answer is that $$f(x)=ln(\frac{2}{x})$$
I don't understand how they found $C$?
Any ideas, how $C$ could be found?
Thank you!

A: If you insert $x=2$ you get that the series equals zero, since all terms equal zero. That gives you
$$
0=f(2)=-\ln 2+C
$$
and hence
$$
C=\ln 2.
$$


text:
Q: gevent queue does not raise Empty when queue.get invoked inside greenlets (other than the main greenlet)? I am very new to gevent and my question might even be very naive, but the when I run following code I get queue empty exception.
case 1 makes sense
import gevent
from gevent import monkey
monkey.patch_all()

q = gevent.queue.Queue(maxsize=10)

try:
    q.get(timeout=1)
except gevent.queue.Empty:
    print("main greenlet queue empty")

but if I run following code I do not get any timeout and code just never invokes any exceptions and I never enter the exception handeling block, in fact code doesn't even wait for 1 sec to fetch data from queue. I just executes immediately with the shown output.
case 2
import gevent
from gevent import monkey
monkey.patch_all()

q = gevent.queue.Queue(maxsize=10)

def worker(idx):
    print("worker", idx)
    try:
        q.get(timeout=1)
    except gevent.queue.Empty:
        print("worker", idx, "queue empty")

workers = [gevent.spawn(worker, i) for i in range(1)]

this outputs:
worker 0

However, if I call get in the main greenlet with a call to queue.get in both child and main greenlet like following, the behaviour now changes back to normal.
case 3
import gevent
from gevent import monkey
monkey.patch_all()

q = gevent.queue.Queue(maxsize=10)

def worker(idx):
    print("worker", idx)
    try:
        q.get(timeout=1)
    except gevent.queue.Empty:
        print("worker", idx, "queue empty")

workers = [gevent.spawn(worker, i) for i in range(1)]

try:
    q.get(timeout=1)
except gevent.queue.Empty:
    print("main greenlet queue empty")

I get following output.
worker 0
main greenlet queue empty
worker 0 queue empty

I fail to understand that why does case 2 not raise an exception, can some one please explain to me what am I doing wrong?
I am using python 3.7 and gevent '21.1.2'

A: In your second case, you are starting greenlets (the interpreter exits after). Adding joinall() makes your code wait for the spawned greenlets to return:
q = gevent.queue.Queue(maxsize=10)

def worker(idx):
    print("worker", idx)
    try:
        q.get(timeout=1)
    except gevent.queue.Empty:
        print("worker", idx, "queue empty")

print(q.empty())
workers = [gevent.spawn(worker, i) for i in range(1)]
# waiting for them to finish, works as expected!
gevent.joinall(workers)

Out:
True
worker 0
worker 0 queue empty


text:
Q: Cannot find module './accelerometer' I'm getting the below error when trying to run johnny-five on my tessel 2:
Error: Cannot find module './accelerometer'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/tmp/remote-script/node_modules/johnny-five/lib/johnny-five.js:1:152)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

I've tried installing the module but the error still appears.
Any pointers please would be greatly appreciated.

A: Try installing Node version 8.11.1.
It worked for me. Took two days to figure it out.
If it doesn't work, check the version the package.json is on tessel-io and johnny-five. If the node version in the package.json is different from the node version you're using, update it or downgrade it to that package.json node version.


text:
Q: React: useEffect setInterval имею довольно так стандартный useEffect
useEffect(() => {
    setInterval(() => {
       //fetch API
    },2000)
},[])

для определенного компонента обновляю данные с интервалом, понимаю, что, нужно уходить в другую сторону чтобы избавляться от подобного,
возник как вопрос, как лучше сделать, чтобы интервал запускался только когда перешли на страницу с данным компонентом и соответственно останавливать когда ушли с нее, была идея отслеживать по url, возможно можно как то иначе?

A: Жизненный цикл компонента
// вызывается после рендеринга компонента.
componentDidMount() {
  this.timer()
}

// Сам таймер
timer(){
    this.timerID = setInterval(
      () => //fetch API,
      2000
    );
}

// вызывается перед удалением компонента из DOM
componentWillUnmount() {
    clearInterval(this.timerID);//удаляем таймер
}


text:
Q: else condition won't display on bash scripting Can someone help me on this.
This script being use to monitor multple servers and display its error status from the logs, the same logic I have used on other server but it is working and there is one would not work even though they are identically coded.
What happen here is when status of alarm being extract but the alarm didn't satisfy all the if's condition it won't display the last part which is the No Alarm status under else condition. it display blank. Thanks in advance for helping
for ((i=0;i<${#arrPNMIP[@]};++i)); do

ssh -o ConnectTimeout=30 ${arrPNMIP[i]} cat /logs/notificationmanager.log |
    grep -i ALARM | grep ${_date}T${_hour} |
    tail -1 > ${_dir}overload_${arrPNMHOST[i]}.txt
ssh -o ConnectTimeout=30 ${arrPNMIP[i]} cat /logs/notificationmanager.log |
    grep 'disconnectUnsafe disconnected host' | grep ${_date}T${_hour} |
    tail -1 > ${_dir}DCHU_${arrPNMHOST[i]}.txt

_count=$(wc -l ${_dir}overload_${arrPNMHOST[i]}.txt | awk '{print $1}')
_timestamp=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | awk '{print $1}' |
    tail -1 | cut -c 10-13)
_typeR=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep RAISED | wc -l)
_typeC=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep CEASED | wc -l)
_overload=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep -i overload | wc -l)
_sftp=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep -i sftp | wc -l)
_linkbus=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep -i linkbus | wc -l)
_dbconn=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep -i dbconn | wc -l)
_hbmgr=$(cat ${_dir}overload_${arrPNMHOST[i]}.txt | grep -i hbmgr | wc -l)

_DChostUnsafeCount=$(cat ${_dir}DCHU_${arrPNMHOST[i]}.txt |
    grep 'disconnectUnsafe disconnected host' | wc -l)
_dcIPhostUnsafe=$(cat ${_dir}DCHU_${arrPNMHOST[i]}.txt |
    grep 'disconnectUnsafe disconnected host' | awk -F " " '{print $8}' |
    cut -c 2-14 )

#echo ""

if (( ${_count[@]} >= 1)) || (( ${_DChostUnsafeCount[@]} >= 1));
then
  if (( ${_typeR[@]} >= 1)) && (( ${_overload[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_RED}${F_BLACK}RAISED ALARM "\
"OVERLOAD at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeR[@]} >= 1)) && (( ${_sftp[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_RED}${F_BLACK}RAISED ALARM "\
"SFTP at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeR[@]} >= 1)) && (( ${_linkbus[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_RED}${F_BLACK}RAISED ALARM "\
"LINKBUS at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeR[@]} >= 1)) && (( ${_dbconn[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_RED}${F_BLACK}RAISED ALARM "\
"DBCONN at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeR[@]} >= 1)) && (( ${_hbmgr[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_RED}${F_BLACK}RAISED ALARM "\
"HBMGR at ${_timestamp}${BG_NC}"
  fi
  if (( ${_DChostUnsafeCount[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_RED}${F_BLACK}Disconnected "\
"Host with IP:${_dcIPhostUnsafe} at ${_timestamp}${BG_NC}"
  fi

  if (( ${_typeC[@]} >= 1)) && (( ${_overload[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_YELLOW}${F_BLACK}CEASED ALARM "\
"OVERLOAD at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeC[@]} >= 1)) && (( ${_sftp[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_YELLOW}${F_BLACK}CEASED ALARM "\
"SFTP at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeC[@]} >= 1)) && (( ${_linkbus[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_YELLOW}${F_BLACK}CEASED ALARM "\
"LINKBUS at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeC[@]} >= 1)) && (( ${_dbconn[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_YELLOW}${F_BLACK}CEASED ALARM "\
"DBCONN at ${_timestamp}${BG_NC}"
  fi
  if (( ${_typeC[@]} >= 1)) && (( ${_hbmgr[@]} >= 1 ));
  then
    echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_YELLOW}${F_BLACK}CEASED ALARM "\"
"HBMGR at ${_timestamp}${BG_NC}"
  fi

else
  echo -e "${arrPNMHOST[i]} ${arrPNM[i]}:${BG_GREEN}${F_BLACK}NO ALARM${BG_NC}"
fi
done

=================================================================
sample result display of the script

Event Detection Trigger
VMRVNAPD07 EDT07:NO ALARM
VMRVNAPD08 EDT08:NO ALARM
VMRVNAPD09 EDT09:NO ALARM
VMRVNAPD10 EDT10:NO ALARM
VMRVNAPD11 EDT11:NO ALARM
VMRVNAPD12 EDT12:NO ALARM
VMRVNAPD13 EDT13:NO ALARM
VMRVNAPD14 EDT14:NO ALARM
VMRVNAPD15 EDT15:NO ALARM
VMRVNAPD16 EDT16:NO ALARM
VMRVNAPD28 EDT28:NO ALARM

Personal Notification Manager

Access Manager
VMRVNAPD17 AM01: NO ALARM
VMRVNAPD18 AM02: RAISED ALARM SFTP at 0332

Messaging Server
VMRVNAPD30 MSVM01: NO ALARM
VMRVNAPD31 MSVM02: NO ALARM
VMRVNAPD37 MSVM03: NO ALARM
VMRVNAPD40 MSVM04: NO ALARM


text:
Q: Exponential decay Fourier transform

I managed to get part a) but when I try to use the fact that $$\cos(t\omega)=\frac{e^{it\omega}+e^{-it\omega}}{2}$$ and $$\sin(t\omega)=\frac{e^{it\omega}-e^{-it\omega}}{2i}$$
for part b), then I get a result of 0 and not ${\pi}e^{-t\lambda}$

A: notice how we have:
$$g(\omega,\lambda,t)=\frac{\lambda\cos\omega t+\omega\sin\omega t}{\lambda^2+\omega^2}$$
we know that:
$$e^{ix}=\cos x+i\sin x$$
lets break it down and see what we have:
$$e^{i\omega t}=\cos\omega t+i\sin\omega t$$
now notice if we take:
$$(\lambda-i\omega)e^{i\omega t}=(\lambda-i\omega)\cos\omega t+(\lambda-i\omega)i\sin\omega t$$
$$=(\lambda\cos\omega t+\omega\sin\omega t)+i(\lambda\sin\omega t-\omega\cos\omega t)$$
and that is where the hint @md2perpe came from.
Obviously we now need to deal with the integral:
now we can notice that our integral is just equal to:
$$\sqrt{2\pi}\int_0^\infty\bar{f}(t)e^{i\omega t}d\omega$$
and you still need to account for it being the real part but it shouldnt be too hard


text:
Q: on hover Action buttons on magento product grid not showing after adding infinite ajax scroll I am using ultimo theme in my Magento instances, and installed rapidcommerce infinite ajax scroll extension. after installing page scroll work perfectly but, action buttons on hover are not coming on next page products.
<script type="text/javascript">
<?php if ($useIas): ?>
jQuery.ias({
delay:600,
container : '.product-columns-3',
<?php if ($productListMode == 'grid'): ?>
    item: '.products-grid',
<?php else: ?>
    item: '.products-list',
<?php endif; ?>
pagination: '.toolbar .pager',
next: '.next',
loader: '<img src="<?php echo($this->getSkinUrl('images/ajaxscroll/loader.gif')); ?>" /> <?php echo __('Loading more products, please be patient...'); ?>',
<?php if($this->getGoogleAnalyticsEnabled()): ?>
onPageChange: function(pageNum, pageUrl, scrollOffset) {
    // This will track a pageview every time the user scrolls up or down the screen to a different page.
    path = jQuery('<a/>').attr('href',pageUrl)[0].pathname.replace(/^[^\/]/,'/');
    _gaq.push(['_trackPageview', path]);
},
<?php endif; ?>
triggerPageThreshold: <?php echo $this->getIasTriggerpagethreshold(); ?>,
thresholdMargin: <?php echo $this->getIasThresholdmargin(); ?>,
trigger: '<?php echo __('Load more items'); ?>',
history: <?php echo ($this->getIasHistory()) ? 'true' : 'false'; ?>
});
<?php endif; ?>
<?php if ($useUitotop): ?>
jQuery(document).ready(function() {
jQuery().UItoTop({ easingType: 'easeOutQuart' });
});
<?php endif; ?>
</script>

Please help guys.
I have tried copying templete files into theme folder, but no luck :(


text:
Q: How to use psycopg2 to insert data into a postgres Database I have created an app using flask, it takes an input from a user and saves the input into the Postgres Database here's the code:
    from flask import Flask, request, render_template, jsonify
    import psycopg2 as pg2
    import exquixdb

    app = Flask(__name__)

    @app.route('/questions', methods=["POST"])
    def post_question():
        request_data = request.json

        table = ("INSERT INTO question(id, question) VALUES(%s,%s)", (1003, str(request_data['question'])))
        exquixdb.db.create(table)
        app.logger.info("adding questions")

        return "question saved"

    if __name__ == '__main__':
        app.run(debug=True, port=8989)

I've created a database Module the code is:
# Module exquizdb.py
import psycopg2 as pg2

class Database():
    def db_connect(self, db="exquizdb", user="jim", pas="password", port=5433):
        global conn
        self.conn = pg2.connect(database=db, user=user, password=pas, port=port)
        global cur
        self.cur = self.conn.cursor()

    def close(self):
        self.cur.close()
        self.conn.close()

    def query(self, query):
        self.cur.execute(query)
        self.close()

    def create(self, table):
        self.cur.execute(table)
        self.conn.commit()
        self.close()

db = Database()

table = ("INSERT INTO question(id, question) VALUES(%s,%s)", (1003, 'Test'))

db.create(table)

so when I run the code I get (AttributeError: 'Database' object has no attribute 'cur') I am new database and python. So i don't know how to fix it. How do I fix the problem. thank you.

A: The error is as a result of not making proper use of Class. The global is not needed as the variables could have been initiated in the class constructor.
Also, the create and query method can be defined as one. Closing the connection after every query means you will have to create a new connection before running a new query.
NOTE: I refactored the query and create method as execute_query. Also the methods can still be improved on for proper error handling. Adding a try and catch block can suffice.
# Module exquizdb.py
import psycopg2 as pg2

class Database:
  def __init__(self, db, username, password, port):
    self.db = db
    self.username = username
    self.password = password
    self.port = port
    self.cur = None
    self.conn = None

  def connect(self):
    self.conn = pg2.connect(database=self.db, user=self.user, password=self.password, port=self.port)
    self.cur = self.conn.cursor()

  def execute_query(self, query):
    self.cur.execute(query)
    self.conn.commit()

  def close(self):
    self.cur.close()
    self.conn.close()

db = Database(db="exquizdb", user="jim", pas="password", port=5433)

db.connect()

    from flask import Flask, request, render_template, jsonify
    import psycopg2 as pg2
    from exquixdb import db

    app = Flask(__name__)

    @app.route('/questions', methods=["POST"])
    def post_question():
        request_data = request.json

        table = ("INSERT INTO question(id, question) VALUES(%s,%s)", (1003, str(request_data['question'])))
        db.execute_query(table)
        app.logger.info("adding questions")

        return "question saved"

    if __name__ == '__main__':
        app.run(debug=True, port=8989)


text:
Q: Slice pandas' MultiIndex DataFrame To keep track of all simulation-results in a parametric run, i create a MultIndex DataFrame named dfParRun in pandas as follows:
import pandas as pd
import numpy as np
import itertools
limOpt = [0.1,1,10]
reimbOpt = ['Cash','Time']
xOpt = [0.1, .02, .03, .04, .05, .06, .07, .08]
zOpt = [1,5n10]
arrays = [limOpt, reimbOpt, xOpt, zOpt]
parameters = list(itertools.product(*arrays))
nPar = len(parameters)

variables = ['X', 'Y', 'Z']
nVar = len(variables)
index = pd.MultiIndex.from_tuples(parameters, names=['lim', 'reimb', 'xMax', 'zMax'])

dfParRun = pd.DataFrame(np.random.rand((nPar, nVar)), index=index, columns=variables)

To analyse my parametric run, i want to slice this dataframe but this seems a burden. For example, i want to have all results for xMax above 0.5 and lim equal to 10. At this moment, the only working method i find is:
df = dfParRun.reset_index()
df.loc[(df.xMax>0.5) & (df.lim==10)]

and i wonder if there is a method without resetting the index of the DataFrame ?

A: option 1
use pd.IndexSlice
caveat: requires sort_index
dfParRun.sort_index().loc[pd.IndexSlice[10, :, .0500001:, :]]

option 2
use your df after having reset_index
df.query('xMax > 0.05 & lim == 10')

setup
import pandas as pd
import numpy as np
import itertools
limOpt = [0.1,1,10]
reimbOpt = ['Cash','Time']
xOpt = [0.1, .02, .03, .04, .05, .06, .07, .08]
zOpt = [1, 5, 10]
arrays = [limOpt, reimbOpt, xOpt, zOpt]
parameters = list(itertools.product(*arrays))
nPar = len(parameters)

variables = ['X', 'Y', 'Z']
nVar = len(variables)
index = pd.MultiIndex.from_tuples(parameters, names=['lim', 'reimb', 'xMax', 'zMax'])

dfParRun = pd.DataFrame(np.random.rand(*(nPar, nVar)), index=index, columns=variables)
df = dfParRun.reset_index()


text:
Q: Copying code from PDF changes apostrophes and quotations, which breaks the code Trying to copy PHP code out of the PDF textbook in Adobe Acrobat Reader, however whenever I copy some code it always changes the ' apostrophes into those weird italicized apostrophes, which then completely breaks the code.
How do I get it to copy and paste from the PDF into PhpStorm without changing the apostrophes? It also does the same thing to quotations.

A: Have you tried Control + Shift + V into a text editor and then copy+paste to PHPStorm?


text:
Q: global vairable did not initialize correctly between running multiple test cases in c++ I am still actively learning c++ with a strong background in python3, the point of this question is not seeking any help with solving the problem Decode Variations on leetcode or pramp, but to understand the compilation or syntax related issue in c++.
The following code using dfs runs well if I run it case by case, however on pramp, it failed in RUN TESTS! Very surprising! It seems like in test case #2  int n=0; was not initialized and used the output of n in test case #1 as its value rather than 0, see the console in the attached screenshot at the end.
#include <iostream>
#include <string>

using namespace std;

int n=0;

void dfs(const string& s, int i){
  if (i==s.size()){
    n++;
    return;
  }
  if ( 0<s[i]-'0' && s[i]-'0'<10)
    dfs(s, i+1);
  if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
    dfs(s, i+2);
}

int decodeVariations(const string& s)
{

  dfs(s,0);
  cout<<n<<endl;
  return n;
}

int main()
{

    return 0;
}

Here is the code to run test case #2:
int main()
{
  const string s = "26";
  dfs(s,0);
  cout<<n<<endl;
    return 0;
}

If I added another initialization of n=0; to int decodeVariations(const string& s), then everything works fine. I try to become a programmer with a clear mind, please educate me.

A: Yes, non-const global variable is evil. Even though I don't know how leetcode and pramp (especially, the main function is empty) run a number of test cases, but I get a hunch it runs test case in the main function, which only compile and run the code once. Thus the global did not get reinitialized.

#include <iostream>
#include <string>

using namespace std;

int n=0;

void dfs(const string& s, int i){
    if (i==s.size()){
        n++;
        return;
    }
    if ( 0<s[i]-'0' && s[i]-'0'<10)
        dfs(s, i+1);
    if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
        dfs(s, i+2);
}

int decodeVariations(const string& s)
{

    dfs(s,0);
    return n;
}

int main(int argc, char **argv){
    for (int i=1;i<argc;i++)
        cout<<decodeVariations(argv[i])<<endl;
}

run with ./test 26 26 26
output:
2

4

6

Quick fix is to get rid of global variable
#include <iostream>
#include <string>

using namespace std;

//int n=0;
int dfs(const string& s, int i){
  int ans = 0;
  if (i==s.size()){
    return 1;
  }
  if ( 0<s[i]-'0' && s[i]-'0'<10)
     ans += dfs(s, i+1);
  if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
     ans += dfs(s, i+2);
  return ans;
}

int decodeVariations(const string& s)
{
    // your code goes here
  int n;
  n = dfs(s,0);
  cout<<n<<endl;
  return n;
}


text:
Q: Error when installing axios and redux thunk
I keep getting this error when trying to install axios and redux thunk, and I am not sure how to read this. Can anyone help me out? Thank you!
Here is the error I get after running the command "npm install axios redux-thunk"


text:
Q: Verification of a Geometry proof I chanced across the following problem recently while working on some geometry problems. I did not expect to solve it so easily; hence I am asking for help to verify if my proof is valid, or if any logical gaps are present.
Below is the problem, copied verbatim -
Let $\Gamma$ be the circumcircle of an acute scalene triangle $ABC$. Reflect $A$ in $BC$ to obtain $A'$, and let $A'C$ intersect $\Gamma$ a second time at $P$. Denote by $E$ the altitude from $B$ to $AC$ and denote by $N$ the altitude from $P$ to $BC$. Prove that the intersection of $BE$ and $PN$ lies on $\Gamma$.
For convenience's sake, I have attached a Geogebra-generated diagram below for easy reference.
Anyways, my proof proceeds as follows:
Proof:
Since $B, P$ and  $C$ all lie on $\Gamma$, it suffices for us to prove that the points $B, P, C$ and $M$ are concyclic. By the Power of a Point Theorem, this is equivalent to showing that $BN \cdot CN = PN \cdot MN $.
We define points $Q, R, S$ as in the diagram, where $Q$ is the point of intersection of $\overline{BE}$ and $\overline{AA'}$, $R$ is the point of intersection of $\overline{AC}$ and $\overline{PM}$, and $S$ is the altitude from $A$ to $\overline{BC}$. We note that $R$ is also the point of reflection of $P$ over $\overline{BC}$ onto $\overline{AC}$; hence $\triangle CNR \equiv \triangle CNP$.
Now, we proceed by simple angle chasing. Since $\overline{AA'} \perp \overline{BC}$ and $\overline{PM} \perp \overline{BC}$, it is easy to see that $\overline{AA'} \parallel \overline{PM}$. We then have the following:
Let $\angle AQE = \theta  \Rightarrow \angle QAE = 90^{\circ} - \theta$. Additionally, we have that $\angle RME =\theta$ and $\angle MRE = \angle NRC= \angle NPC= 90^{\circ} - \theta \Rightarrow \angle NCR = \angle NCP = \theta$. Now, $\angle RME = \angle NMB = \theta \Rightarrow NBM = 90^{\circ} - \theta $.
From the above, we essentially have that $\triangle BNM \sim \triangle PNC$. Thus, $\frac{BN}{NM}=\frac{PN}{NC} \Rightarrow BN \cdot NC = PN \cdot NM$, and we are done.
On a side note, why is the scalene triangle condition even necessary?

A: Another proof:
Notice $ENCM$ cyclic.
SO, $\angle BMP=\angle EMN=\angle ECN=\angle ACB=\angle BCA'$(reflection property)$=\angle BCP$
So,$BCMP$ cyclic.Hence the claim follows.


text:
Q: Compute the Cartesian Distance between points in high-dimensional space optimally Summary:
My class SquareDistance computes the square of the Cartesian distance in four ways using methods with these names:

*

*Signed

*UnsignedBranching

*UnsignedDistribute

*CastToSignedLong

The first one is fastest and uses signed integers, but my data must be unsigned (for reasons given below). The other three methods start with unsigned numbers. My goal is to write a method like those in SquareDistance that takes unsigned data and performs better than the three I already wrote, as close as possible in performance to #1. Code with benchmark results follows.  (unsafe code is permitted, if you think it will help.)
Details:
I am developing an algorithm to solve K-nearest neighbor problems using an index derived from the Hilbert curve. The execution time for the naive, linear scan algorithm grows in time quadratically with the number of points and linearly with the number of dimensions, and it spends all its time computing and comparing Cartesian distances.
The motivation behind the special Hilbert index is to reduce the number of times that the distance function is called. However, it must still be called millions of times, so I must make it as fast as possible. (It is the most frequently called function in the program. A recent failed attempt to optimize the distance function doubled the program execution time from seven minutes to fifteen minutes, so no, this is not a premature or superfluous optimization.)
Dimensions: The points may have anywhere from ten to five thousand dimensions.
Constraints. I have two annoying constraints:

*

*The Hilbert transformation logic requires that the points be expressed as uint (unsigned integer) arrays. (The code was written by another, is magic and uses shifts, ANDs, ORs, and the like and can't be changed.) Storing my points as signed integers and incessantly casting them to uint arrays produced wretched performance, so I must at the very least store a uint array copy of each point.

*To improve efficiency, I made a signed integer copy of each point to speed up the distance calculations. This worked very well, but once I get to about 3,000 dimensions, I run out of memory!
To save on memory, I removed the memoized signed integer arrays and tried to write an unsigned version of the distance calculation. My best results are 2.25 times worse than the signed integer version.
The benchmarks create 1000 random points of 1000 dimensions each and perform distance calculations between every point and every other point, for 1,000,000 comparisons. Since I only care about the relative distance, I save time by not performing the square root.
In debug mode:

SignedBenchmark                  Ratio: 1.000 Seconds: 3.739
UnsignedBranchingBenchmark       Ratio: 2.731 Seconds: 10.212
UnsignedDistributeBenchmark      Ratio: 3.294 Seconds: 12.320
CastToSignedLongBenchmark        Ratio: 3.265 Seconds: 12.211

In release mode:
 SignedBenchmark                  Ratio: 1.000 Seconds: 3.494
 UnsignedBranchingBenchmark       Ratio: 2.672 Seconds: 9.334
 UnsignedDistributeBenchmark      Ratio: 3.336 Seconds: 11.657
 CastToSignedLongBenchmark        Ratio: 3.471 Seconds: 12.127

The above benchmarks were run on a Dell with an Intel Core i7-4800MQ CPU @ 2.70GHz with 16 GB memory. My larger algorithm already uses the Task Parallel library for larger tasks, so it is fruitless to parallelize this inner loop.
Question: Can anyone think of a faster algorithm than UnsignedBranching?
Below is my benchmark code.
UPDATE
This uses loop unrolling (thanks to @dasblinkenlight) and is 2.7 times faster:
public static long UnsignedLoopUnrolledBranching(uint[] x, uint[] y)
{
    var distance = 0UL;
    var leftovers = x.Length % 4;
    var dimensions = x.Length;
    var roundDimensions = dimensions - leftovers;

    for (var i = 0; i < roundDimensions; i += 4)
    {
        var x1 = x[i];
        var y1 = y[i];
        var x2 = x[i+1];
        var y2 = y[i+1];
        var x3 = x[i+2];
        var y3 = y[i+2];
        var x4 = x[i+3];
        var y4 = y[i+3];
        var delta1 = x1 > y1 ? x1 - y1 : y1 - x1;
        var delta2 = x2 > y2 ? x2 - y2 : y2 - x2;
        var delta3 = x3 > y3 ? x3 - y3 : y3 - x3;
        var delta4 = x4 > y4 ? x4 - y4 : y4 - x4;
        distance += delta1 * delta1 + delta2 * delta2 + delta3 * delta3 + delta4 * delta4;
    }
    for (var i = roundDimensions; i < dimensions; i++)
    {
        var xi = x[i];
        var yi = y[i];
        var delta = xi > yi ? xi - yi : yi - xi;
        distance += delta * delta;
    }
    return (long)distance;
}

SquareDistance.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DistanceBenchmark
{
    /// <summary>
    /// Provide several alternate methods for computing the square of the Cartesian distance
    /// to allow study of their relative performance.
    /// </summary>
    public static class SquareDistance
    {
        /// <summary>
        /// Compute the square of the Cartesian distance between two N-dimensional points
        /// with calculations done on signed numbers using signed arithmetic,
        /// a single multiplication and no branching.
        /// </summary>
        /// <param name="x">First point.</param>
        /// <param name="y">Second point.</param>
        /// <returns>Square of the distance.</returns>
        public static long Signed(int[] x, int[] y)
        {
            var distance = 0L;
            var dimensions = x.Length;
            for (var i = 0; i < dimensions; i++)
            {
                var delta = x[i] - y[i];
                distance += delta * delta;
            }
            return distance;
        }

        /// <summary>
        /// Compute the square of the Cartesian distance between two N-dimensional points
        /// with calculations done on unsigned numbers using unsigned arithmetic, a single multiplication
        /// and a branching instruction (the ternary operator).
        /// </summary>
        /// <param name="x">First point.</param>
        /// <param name="y">Second point.</param>
        /// <returns>Square of the distance.</returns>
        public static long UnsignedBranching(uint[] x, uint[] y)
        {
            var distance = 0UL;
            var dimensions = x.Length;
            for (var i = 0; i < dimensions; i++)
            {
                var xi = x[i];
                var yi = y[i];
                var delta = xi > yi ? xi - yi : yi - xi;
                distance += delta * delta;
            }
            return (long)distance;
        }

        /// <summary>
        /// Compute the square of the Cartesian distance between two N-dimensional points
        /// with calculations done on unsigned numbers using unsigned arithmetic and the distributive law,
        /// which requires four multiplications and no branching.
        ///
        /// To prevent overflow, the coordinates are cast to ulongs.
        /// </summary>
        /// <param name="x">First point.</param>
        /// <param name="y">Second point.</param>
        /// <returns>Square of the distance.</returns>
        public static long UnsignedDistribute(uint[] x, uint[] y)
        {
            var distance = 0UL;
            var dimensions = x.Length;
            for (var i = 0; i < dimensions; i++)
            {
                ulong xi = x[i];
                ulong yi = y[i];
                distance += xi * xi + yi * yi - 2 * xi * yi;
            }
            return (long)distance;
        }

        /// <summary>
        /// Compute the square of the Cartesian distance between two N-dimensional points
        /// with calculations done on unsigned numbers using signed arithmetic,
        /// by first casting the values into longs.
        /// </summary>
        /// <param name="x">First point.</param>
        /// <param name="y">Second point.</param>
        /// <returns>Square of the distance.</returns>
        public static long CastToSignedLong(uint[] x, uint[] y)
        {
            var distance = 0L;
            var dimensions = x.Length;
            for (var i = 0; i < dimensions; i++)
            {
                var delta = (long)x[i] - (long)y[i];
                distance += delta * delta;
            }
            return distance;
        }

    }
}

RandomPointFactory.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DistanceBenchmark
{
    public static class RandomPointFactory
    {
        /// <summary>
        /// Get a random list of signed integer points with the given number of dimensions to use as test data.
        /// </summary>
        /// <param name="recordCount">Number of points to get.</param>
        /// <param name="dimensions">Number of dimensions per point.</param>
        /// <returns>Signed integer test data.</returns>
        public static IList<int[]> GetSignedTestPoints(int recordCount, int dimensions)
        {
            var testData = new List<int[]>();
            var random = new Random(DateTime.Now.Millisecond);

            for (var iRecord = 0; iRecord < recordCount; iRecord++)
            {
                int[] point;
                testData.Add(point = new int[dimensions]);
                for (var d = 0; d < dimensions; d++)
                    point[d] = random.Next(100000);
            }
            return testData;
        }

        /// <summary>
        /// Get a random list of unsigned integer points with the given number of dimensions to use as test data.
        /// </summary>
        /// <param name="recordCount">Number of points to get.</param>
        /// <param name="dimensions">Number of dimensions per point.</param>
        /// <returns>Unsigned integer test data.</returns>
        public static IList<uint[]> GetUnsignedTestPoints(int recordCount, int dimensions)
        {
            var testData = new List<uint[]>();
            var random = new Random(DateTime.Now.Millisecond);

            for (var iRecord = 0; iRecord < recordCount; iRecord++)
            {
                uint[] point;
                testData.Add(point = new uint[dimensions]);
                for (var d = 0; d < dimensions; d++)
                    point[d] = (uint)random.Next(100000);
            }
            return testData;
        }
    }
}

Program.cs:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DistanceBenchmark
{
    public class Program
    {
        private static IList<int[]> SignedTestData = RandomPointFactory.GetSignedTestPoints(1000, 1000);
        private static IList<uint[]> UnsignedTestData = RandomPointFactory.GetUnsignedTestPoints(1000, 1000);

        static void Main(string[] args)
        {
            var baseline = TimeIt("SignedBenchmark", SignedBenchmark);
            TimeIt("UnsignedBranchingBenchmark", UnsignedBranchingBenchmark, baseline);
            TimeIt("UnsignedDistributeBenchmark", UnsignedDistributeBenchmark, baseline);
            TimeIt("CastToSignedLongBenchmark", CastToSignedLongBenchmark, baseline);
            TimeIt("SignedBenchmark", SignedBenchmark, baseline);
            Console.WriteLine("Done. Type any key to exit.");
            Console.ReadLine();
        }

        public static void SignedBenchmark()
        {
            foreach(var p1 in SignedTestData)
                foreach (var p2 in SignedTestData)
                    SquareDistance.Signed(p1, p2);
        }

        public static void UnsignedBranchingBenchmark()
        {
            foreach (var p1 in UnsignedTestData)
                foreach (var p2 in UnsignedTestData)
                    SquareDistance.UnsignedBranching(p1, p2);
        }

        public static void UnsignedDistributeBenchmark()
        {
            foreach (var p1 in UnsignedTestData)
                foreach (var p2 in UnsignedTestData)
                    SquareDistance.UnsignedDistribute(p1, p2);
        }

        public static void CastToSignedLongBenchmark()
        {
            foreach (var p1 in UnsignedTestData)
                foreach (var p2 in UnsignedTestData)
                    SquareDistance.CastToSignedLong(p1, p2);
        }

        public static double TimeIt(String testName, Action benchmark, double baseline = 0.0)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            benchmark();
            stopwatch.Stop();
            var seconds = stopwatch.Elapsed.TotalSeconds;
            var ratio = baseline <= 0 ? 1.0 : seconds/baseline;
            Console.WriteLine(String.Format("{0,-32} Ratio: {1:0.000} Seconds: {2:0.000}", testName, ratio, seconds));
            return seconds;
        }
    }
}

A: You should be able to shave off a lot of execution time by unrolling your loops:
public static long Signed(int[] x, int[] y)
{
    var distance = 0L;
    var dimensions = x.Length;
    var stop = dimensions - (dimensions % 4);
    for (var i = 0; i < stop; i+=4)
    {
        var delta0 = x[i] - y[i];
        var delta1 = x[i+1] - y[i+1];
        var delta2 = x[i+2] - y[i+2];
        var delta3 = x[i+3] - y[i+3];
        distance += (delta0 * delta0)
                  + (delta1 * delta1)
                  + (delta2 * delta2)
                  + (delta3 * delta3);
    }
    for (var i = stop; i < dimensions; i++)
    {
        var delta = x[i] - y[i];
        distance += delta * delta;
    }
    return distance;
}

This change alone reduced the execution time from 8.325s to 4.745s on my local system - a 43% improvement!
The idea is to do four points at a time while you can, and then finish off the remaining points in a separate loop.

A: If you cannot change the hilbert curve you can try a z curve, i.e. a morton curve. Translate the dimensions to a binary and interleave it. Then sort it. You can verify the upper bounds with the mostsignificat bits. Hilbert curve in n-dimension uses a gray code maybe you can search the internet for a faster version. You can find some fast implementation in the hackers cookbook. A morton curve should be similar to a h-tree. When you need the precision you can try copies of the hilbert curves, i.e. a moore curve. For example in 2d you can interleave 4 hilbert curves:
"
,

A: Best possible improvement I can see isn't going to be a low hanging fruit. This kind of problem is not well suited for the current version of the .net framework (or a CPU in general).
The class of problem you have is called SIMD. You may have heard of Intel Pentium MMX. The MMX instruction set is the marketing term for SIMD instruction set.
There are three pretty good ways to get SIMD to run with your program. In order of slowest to fastest, and in order of easiest to hardest.

*

*RyuJIT (the preview version of the next .net Compiler) to take advantage of CPU SIMD

*P/Invoke into C++ AMP onto your GPU

*Interop onto a FPGA with a core designed for this calculation.

I would highly recommend trying to take advantage of your GPU with C++ AMP, especially since uint[] should be easily passed to C++ AMP.

A: In the shower this morning, I came up with a way to improve this further using the dot product, shaving another fifty percent off the time when the data is stored as uint[] arrays. I had investigated this idea before, but failed to recognize a loop invariant that I could optimize by precomputing. The basis of the idea is to distribute the operations:
    (x-y)(x-y) = x*x + y*y - 2xy

If I sum this over all coordinates, the result is:
        2         2       2
       D    =  |x|  +  |y|  -  2(x·y)

Since I will be performing lots of distance computations, I can store the square length of each vector. Then finding the distance between two vectors amounts to summing their square distances (outside the loop) and computing the dot-product, which has no negative values, so needs no branching!
Why is the branching a problem? It is because with uint vectors you can't subtract values in the Cartesian formula without using a branch operation to test which value is larger. Thus if I want (x-y)*(x-y) I needed to do this in my loop:
var delta = x[i] > y[i] ? x[i] - y[i] : y[i] - x[i];
distance += delta * delta;

In addition, to prevent overflow from uint to ulong, I needed to cast numbers to ulong a lot, which really killed performance. Since most of my coordinates are smallish, I was able to create a test. I also store the max value for each vector. Since I am unrolling my loops by four iterations at a time, if 4*xMax*yMax does not overflow uint, I can dispense with most of my casting operations. If the test fails, I do the more costly version that casts more.
In the end, I had several implementations: naive with casting, with branching, distributed with casting and loop invariants not removed, and dot product with less casting and invariants removed.
The naive approach has a subtraction, a multiplication and an addition in each loop iteration. The dot product distribution with loop invariants removed uses only a multiplication and an addition.
Here are the benchmarks:
For 100000 iterations and 2000 dimensions.
    Naive time        = 2.505 sec.
    Branch time       = 0.628 sec.
    Distributed time  = 6.371 sec.
    Dot Product time  = 0.288 sec.
    Improve vs Naive  = 88.5%.
    Improve vs Branch = 54.14%.

Here is the code as an NUnit test:
using System;
using System.Diagnostics;
using NUnit.Framework;
using System.Linq;

namespace HilbertTransformationTests
{
    [TestFixture]
    public class CartesianDistanceTests
    {

        [Test]
        public void SquareDistanceBenchmark()
        {
            var dims = 2000;
            var x = new uint[dims];
            var y = new uint[dims];
            var xMag2 = 0L;
            var yMag2 = 0L;

            for (var i = 0; i < dims; i++)
            {
                x[i] = (uint)i;
                xMag2 += x[i] * (long)x[i];
                y[i] = (uint)(10000 - i);
                yMag2 += y[i] * (long)y[i];
            }
            var xMax = (long)x.Max();
            var yMax = (long)y.Max();
            var repetitions = 100000;
            var naiveTime = Time(() => SquareDistanceNaive(x, y), repetitions);
            var distributeTime = Time(() => SquareDistanceDistributed(x, y), repetitions);
var branchTime = Time(() => SquareDistanceBranching(x, y), repetitions);
            var dotProductTime = Time(() => SquareDistanceDotProduct(x, y, xMag2, yMag2, xMax, yMax), repetitions);

            Console.Write($@"
For {repetitions} iterations and {dims} dimensions.
    Naive time        = {naiveTime} sec.
    Branch time       = {branchTime} sec.
    Distributed time  = {distributeTime} sec.
    Dot Product time  = {dotProductTime} sec.
    Improve vs Naive  = {((int)(10000 * (naiveTime - dotProductTime) / naiveTime)) / 100.0}%.
    Improve vs Branch = {((int)(10000 * (branchTime - dotProductTime) / branchTime)) / 100.0}%.
");
            Assert.Less(dotProductTime, branchTime, "Dot product time should have been less than branch time");
        }

        private static double Time(Action action, int repeatCount)
        {
            var timer = new Stopwatch();
            timer.Start();
            for (var j = 0; j < repeatCount; j++)
                action();
            timer.Stop();
            return timer.ElapsedMilliseconds / 1000.0;
        }

        private static long SquareDistanceNaive(uint[] x, uint[] y)
        {
            var squareDistance = 0L;
            for (var i = 0; i < x.Length; i++)
            {
                var delta = (long)x[i] - (long)y[i];
                squareDistance += delta * delta;
            }
            return squareDistance;
        }

        /// <summary>
        /// Compute the square distance, using ternary operators for branching to keep subtraction operations from going negative,
        /// which is inappropriate for unsigned numbers.
        /// </summary>
        /// <returns>The distance branching.</returns>
        /// <param name="x">The x coordinate.</param>
        /// <param name="y">The y coordinate.</param>
        private static long SquareDistanceBranching(uint[] x, uint[] y)
        {
            long squareDistanceLoopUnrolled;

            // Unroll the loop partially to improve speed. (2.7x improvement!)
            var distance = 0UL;
            var leftovers = x.Length % 4;
            var dimensions = x.Length;
            var roundDimensions = dimensions - leftovers;

            for (var i = 0; i < roundDimensions; i += 4)
            {
                var x1 = x[i];
                var y1 = y[i];
                var x2 = x[i + 1];
                var y2 = y[i + 1];
                var x3 = x[i + 2];
                var y3 = y[i + 2];
                var x4 = x[i + 3];
                var y4 = y[i + 3];
                var delta1 = x1 > y1 ? x1 - y1 : y1 - x1;
                var delta2 = x2 > y2 ? x2 - y2 : y2 - x2;
                var delta3 = x3 > y3 ? x3 - y3 : y3 - x3;
                var delta4 = x4 > y4 ? x4 - y4 : y4 - x4;
                distance += delta1 * delta1 + delta2 * delta2 + delta3 * delta3 + delta4 * delta4;
            }
            for (var i = roundDimensions; i < dimensions; i++)
            {
                var xi = x[i];
                var yi = y[i];
                var delta = xi > yi ? xi - yi : yi - xi;
                distance += delta * delta;
            }
            squareDistanceLoopUnrolled = (long)distance;

            return squareDistanceLoopUnrolled;
        }

        private static long SquareDistanceDistributed(uint[] x, uint[] y)
        {
            long squareDistanceLoopUnrolled;

            // Unroll the loop partially to improve speed. (2.7x improvement!)
            var distance = 0UL;
            var dSubtract = 0UL;
            var leftovers = x.Length % 4;
            var dimensions = x.Length;
            var roundDimensions = dimensions - leftovers;

            for (var i = 0; i < roundDimensions; i += 4)
            {
                ulong x1 = x[i];
                ulong y1 = y[i];
                ulong x2 = x[i + 1];
                ulong y2 = y[i + 1];
                ulong x3 = x[i + 2];
                ulong y3 = y[i + 2];
                ulong x4 = x[i + 3];
                ulong y4 = y[i + 3];

                distance += x1 * x1 + y1 * y1
                          + x2 * x2 + y2 * y2
                          + x3 * x3 + y3 * y3
                          + x4 * x4 + y4 * y4;
                dSubtract += x1 * y1 + x2 * y2 + x3 * y3 + x4 * y4;
            }
            distance = distance - 2UL * dSubtract;
            for (var i = roundDimensions; i < dimensions; i++)
            {
                var xi = x[i];
                var yi = y[i];
                var delta = xi > yi ? xi - yi : yi - xi;
                distance += delta * delta;
            }
            squareDistanceLoopUnrolled = (long)distance;

            return squareDistanceLoopUnrolled;
        }

        private static long SquareDistanceDotProduct(uint[] x, uint[] y, long xMag2, long yMag2, long xMax, long yMax)
        {
            const int unroll = 4;
            if (xMax * yMax * unroll < (long) uint.MaxValue)
                return SquareDistanceDotProductNoOverflow(x, y, xMag2, yMag2);

            // Unroll the loop partially to improve speed. (2.7x improvement!)
            var dotProduct = 0UL;
            var leftovers = x.Length % unroll;
            var dimensions = x.Length;
            var roundDimensions = dimensions - leftovers;

            for (var i = 0; i < roundDimensions; i += unroll)
            {
                var x1 = x[i];
                ulong y1 = y[i];
                var x2 = x[i + 1];
                ulong y2 = y[i + 1];
                var x3 = x[i + 2];
                ulong y3 = y[i + 2];
                var x4 = x[i + 3];
                ulong y4 = y[i + 3];
                dotProduct += x1 * y1 + x2 * y2 + x3 * y3 + x4 * y4;
            }
            for (var i = roundDimensions; i < dimensions; i++)
                dotProduct += x[i] * (ulong)y[i];
            return xMag2 + yMag2 - 2L * (long)dotProduct;
        }

        /// <summary>
        /// Compute the square of the Cartesian distance using the dotproduct method,
        /// assuming that calculations wont overflow uint.
        ///
        /// This permits us to skip some widening conversions to ulong, making the computation faster.
        ///
        /// Algorithm:
        ///
        ///    2         2       2
        ///   D    =  |x|  +  |y|  -  2(x·y)
        ///
        /// Using the dot product of x and y and precomputed values for the square magnitudes of x and y
        /// permits us to use two operations (multiply and add) instead of three (subtract, multiply and add)
        /// in the main loop, saving one third of the time.
        /// </summary>
        /// <returns>The square distance.</returns>
        /// <param name="x">First point.</param>
        /// <param name="y">Second point.</param>
        /// <param name="xMag2">Distance from x to the origin, squared.</param>
        /// <param name="yMag2">Distance from y to the origin, squared.</param>
        private static long SquareDistanceDotProductNoOverflow(uint[] x, uint[] y, long xMag2, long yMag2)
        {
            // Unroll the loop partially to improve speed. (2.7x improvement!)
            const int unroll = 4;
            var dotProduct = 0UL;
            var leftovers = x.Length % unroll;
            var dimensions = x.Length;
            var roundDimensions = dimensions - leftovers;
            for (var i = 0; i < roundDimensions; i += unroll)
                dotProduct += (x[i] * y[i] + x[i+1] * y[i+1] + x[i+2] * y[i+2] + x[i+3] * y[i+3]);
            for (var i = roundDimensions; i < dimensions; i++)
                dotProduct += x[i] * y[i];
            return xMag2 + yMag2 - 2L * (long)dotProduct;
        }

    }

}