text:
Q: Windows encoding with unicode? I have a package in development cowsay https://github.com/sckott/cowsay
I use unicode characters in some cases. E.g., https://github.com/sckott/cowsay/blob/master/R/animals.r#L167-L175
Those unicode characters are printed just fine in R on mac and linux machines, but on windows they do not print correctly.
Where on my mac \uFF8A gives
"\uFF8A"
[1] "ハ"

On the Windows machine I tried on I get
"\uFF8A"
[1] <U+FF8A>

The github issue is here https://github.com/sckott/cowsay/issues/9#issue-43149822
Since this is a package we hope can work across all major platforms, I'm hoping for a solution to this that just works without Windows users having to take an extra step that *unix users don't have to.
I think this has to do with encoding, but I'm not quite sure how to fix this, and I haven't found a solution googling/searching SO.


text:
Q: Magento 2 - How to return custom json response from API I'm working with Magento 2 API and I'm really struggled with response of it
How can I return some kind of response like this:
{
    "status": 200,
    "error": false,
    "message": "Request processed successfully.",
    "data": {
        "id": "1",
        "email": "us@test.com",
        "first_name": "user1",
        "last_name": "user01"
    }
}

It's simple with other framework like Laravel or Express. But it seems really hard to achieve this with Magento 2 API.
Anyone has idea?
Thank you.

A: First you need to define the interface/class of the result type.
The interface will look like this.
namespace Vnecoms\SampleAPI\Api;

interface Result
{
    /**
     * @return int
     */
    public function getStatus();

    /**
     * @return bool
     */
    public function getError();

    /**
     * @return string
     */
    public function getMessage();

    /**
     * @return \Vnecoms\SampleAPI\Api\ResultData
     */
    public function getData();
}

Next is the ResultData interface
namespace Vnecoms\SampleAPI\Api;

interface ResultData
{
    /**
     * @return int
     */
    public function getId();

    /**
     * @return string
     */
    public function getEmail();

    /**
     * @return string
     */
    public function getFirstName();

    /**
     * @return string
     */
    public function getLastName();
}

Now in your API just return an object of \Vnecoms\SampleAPI\Api\Result

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use binary operators "<" and ">" for comparing objects in Java? Consider having this class in Java:
public class Foo implements Comparable<Foo> {
    private int someValue;

    @Override
    public int compareTo(Foo o) {
        if (this.someValue < o.someValue) {
            return -1;
        } else if (this.someValue == o.someValue) {
            return 0;
        } else {
            return 1;
        }
    }
}

I tried to do this:
Foo foo1 = new Foo(someValue);
Foo foo2 = new Foo(someAnotherValue);
if (foo1 < foo2) {
   // do something
}

But the IDE is giving me an error which is: "Bad operand types for binary operation '<' first type: Foo, second type: Foo"
May you please tell me what is wrong?
Thanks in advance for your help,

A: Implementing the Comparable interface is a good first step to being able to compare your objects properly.  However, that doesn't allow you to use the < and > comparison operators as if the operators were overloaded.  You just need to call your compareTo method.
if (foo1.compareTo(foo2) < 0) {


text:
Q: How to redirect to home.php after facebook oAuth login? I tried to put  header( 'Location: home.php' ) ; into the function login with facebook but after I successfully login, the page still doesn't redirect to homepage.
Anyone can help me out? Thanks!
function login(response, info){
            if (response.authResponse) {

               var accessToken =   response.authResponse.accessToken;

                userInfo.innerHTML = '' + info.name
                                                                 + "
 Your Access Token: " + accessToken;
                button.innerHTML                               = 'Logout';
                showLoader(false);
                document.getElementById('other').style.display = "block";
                header( 'Location: home.php' ) ;
            }
        }

A: You seem to be mixing up your PHP and JavaScript. Header is a PHP function. You can't use it with JavaScript.
You might want to try a JavaScript redirect method -
var homeUrl = 'home.php';
top.location.href = homeUrl;


text:
Q: bash script complains about file name too long So I have a script that does this (jq is a command line JSON processor):
echo "Getting LB Node IDs"
echo $LB_STATUS | jq '.loadBalancer.nodes[] .id'

The output of the last line is:
1
2
3

But when I try and assign it to an array:
echo "Creating an Array"
nodeIdArray=($($LB_STATUS | jq '.loadBalancer.nodes[] .id'))

I get this error:
./myShellScript.sh: line 53: {"loadBalancer":{"name":"lbName","id":1,"protocol":"HTTP","port":80,"algorithm":"WEIGHTED_LEAST_CONNECTIONS","status":"ACTIVE","cluster":{"name":"ztm-n22.dfw1.lbaas.rackspace.net"},"nodes":[{"address":"1.2.3.4","id":1,"type":"PRIMARY","port":80,"status":"ONLINE","condition":"ENABLED","weight":1},{"address":"1.2.3.4","id":2,"type":"PRIMARY","port":80,"status":"ONLINE","condition":"ENABLED","weight":1},{"address":"1.2.3.4","id":3,"type":"PRIMARY","port":80,"status":"ONLINE","condition":"ENABLED","weight":1}],"timeout":30,"created":{"time":"2016-06-28T22:14:24Z"},"healthMonitor":{"type":"CONNECT","delay":10,"timeout":5,"attemptsBeforeDeactivation":2},"sslTermination":...<A BOAT LOAD MORE JSON I CUT OUT FOR BREVITY'S SAKE>: File name too long

SO $LB_STATUS | jq '.loadBalancer.nodes[] .id' produces a few numbers while trying to assign those numbers to an array doesn't work

A: You left out the echo.
Change
nodeIdArray=($($LB_STATUS | jq '.loadBalancer.nodes[] .id'))

to
nodeIdArray=($( echo $LB_STATUS | jq '.loadBalancer.nodes[] .id' ))

A: What Went Wrong
$variable | something doesn't pass the text in variable as input to something -- instead, it runs the contents of $variable as a command. Presumably you wanted echo "$variable" | something instead (but see below!)
Even if that were fixed, the array=( $(some-command) ) idiom is itself buggy. See BashPitfalls #50 describing why it shouldn't be used, and the various alternatives.
What To Do Instead
When feeding content from a variable as an input to a command, it's idiomatic to use a herestring: somecommand <<<"$variable". These aren't free (as they create temporary files), but they're cheaper than pipelines (which fork off subshells).
If you have bash 4.x or newer, you have readarray:
readarray -t nodeIdArray < <(jq -r '.loadBalancer.nodes[].id' <<<"$LB_STATUS")

If you need compatibility with bash 3.x, read -a can do the job:
IFS=$'\n' read -r -d '' -a nodeIdArray \
  < <(jq -r '.loadBalancer.nodes[].id' <<<"$LB_STATUS" && printf '\0')

...which also has the advantage of causing read to return a nonzero exit status if the jq command fails.


text:
Q: Display separately available object properties on click, not only the last defined one I have some countries on the map that are displaying some links when clicked. They are stored as objects in an array of objects like you can see below.
let groupData = [
      {
        "color": chart.colors.getIndex(0),
        "data": [
          {
            "country": "Austria",
            "id": "AT", // With MapPolygonSeries.useGeodata = true, it will try and match this id, then apply the other properties as custom data
            "link": ["https://www.example1.com"]
          }, {
            "country": "France",
            "id": "FR",
            "link": ["https://www.example2.com", "https://www.example3.com", "https://www.example4.com"]
          }
        ]
      }
    ];

Currently, when I click on the countries, I am getting the links from the last object (country) defined in the array of objects. In this case, France.
"country": "France",
            "id": "FR",
            "link": ["https://www.example2.com", "https://www.example3.com", "https://www.example4.com"]

How can I make each country to display only the links defined for it? 1 link for AT and 3 links for FR?
For better understanding, please check the snippet.
Many thanks!

am4core.ready(function() {

    // Themes begin
    am4core.useTheme(am4themes_animated);
    // Themes end

    // Create map instance
    let chart = am4core.create("map", am4maps.MapChart);

    // Responsiveness enabled
    chart.responsive.enabled = true;

    // Set map definition
    chart.geodata = am4geodata_worldHigh;

    // Set projection
    chart.projection = new am4maps.projections.Miller();

    // Zoom control
    chart.zoomControl = new am4maps.ZoomControl();

    let homeButton = new am4core.Button();
    homeButton.events.on("hit", function() {
      chart.goHome();
    });

    homeButton.icon = new am4core.Sprite();
    homeButton.padding(7, 5, 7, 5);
    homeButton.width = 30;
    homeButton.icon.path = "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8";
    homeButton.marginBottom = 10;
    homeButton.parent = chart.zoomControl;
    homeButton.insertBefore(chart.zoomControl.plusButton);

    // Center on the groups by default
    chart.homeZoomLevel = 3.5;
    chart.homeGeoPoint = { longitude: 10, latitude: 54 };

    let groupData = [
      {
        "color": chart.colors.getIndex(0),
        "data": [
          {
            "country": "Austria",
            "id": "AT",
            "link": ["https://www.example1.com"]
          }, {
            "country": "France",
            "id": "FR",
            "link": ["https://www.example2.com", "https://www.example3.com", "https://www.example4.com"]
          }
        ]
      }
    ];

    // This array will be populated with country IDs to exclude from the world series
    let excludedCountries = ["AQ"];

    // Create a series for each group, and populate the above array
    groupData.forEach(function(group) {
      let series = chart.series.push(new am4maps.MapPolygonSeries());
      series.name = group.name;
      series.useGeodata = true;
      let includedCountries = [];

      group.data.forEach(function(country) {
        includedCountries.push(country.id);
        excludedCountries.push(country.id);

        let polygonTemplate = series.mapPolygons.template;
        polygonTemplate.tooltipHTML = '{country}';

          polygonTemplate.events.on("hit", function(ev) {
            chart.closeAllPopups();

            // Display country specific links

            chart.openPopup("" + ev.target.dataItem.dataContext.country + "" + country.link.map(url =>
              '
Country specific links ' + '').join(""));

              console.log(country);
              console.log(country.link);
          });
      });

      series.include = includedCountries;

      series.fill = am4core.color(group.color);
      series.setStateOnChildren = true;
      series.calculateVisualCenter = true;
      series.tooltip.label.interactionsEnabled = false; //disable tooltip click
      series.tooltip.keepTargetHover = true;

      // Country shape properties & behaviors
      let mapPolygonTemplate = series.mapPolygons.template;
      mapPolygonTemplate.fill = am4core.color("orange");
      mapPolygonTemplate.fillOpacity = 0.8;
      mapPolygonTemplate.nonScalingStroke = true;
      mapPolygonTemplate.tooltipPosition = "fixed";

      mapPolygonTemplate.events.on("over", function(event) {
        series.mapPolygons.each(function(mapPolygon) {
          mapPolygon.isHover = false;
        })
        event.target.isHover = false;
        event.target.isHover = true;
      })

      mapPolygonTemplate.events.on("out", function(event) {
        series.mapPolygons.each(function(mapPolygon) {
          mapPolygon.isHover = false;
        })

      })

      // States
      let hoverState = mapPolygonTemplate.states.create("hover");
      hoverState.properties.fill = am4core.color("#FFCC00");

      series.data = JSON.parse(JSON.stringify(group.data));

    });

    // The rest of the world.
    let worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
    let worldSeriesName = "world";
    worldSeries.name = worldSeriesName;
    worldSeries.useGeodata = true;
    worldSeries.exclude = excludedCountries;
    worldSeries.fillOpacity = 0.5;
    worldSeries.hiddenInLegend = true;
    worldSeries.mapPolygons.template.nonScalingStroke = true;

});
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  }

  #map {
    width: 100%;
    height: 600px;
    overflow: hidden;
  }

  #map a,
  b {
    cursor: pointer;
    color:  #003399;
    text-align: center;
  }

  #map a:hover {
    color: #023432;
  }

  .ampopup-content {
    /* width: 40%; */
    text-align: center;
  }

  .ampopup-header {
    background-color: #003399 !important;
  }

  .ampopup-close {
    filter: invert(1);
  }

  .ampopup-inside {
    background-color: rgb(255, 255, 255);
  }

  .ampopup-inside a {
    color: #28a86c !important;
  }

  .ampopup-inside a:hover {
    color: #023432 !important;
  }

  .ampopup-curtain {
    display: block !important;
    background-color: rgba(7, 22, 51, 0.7) !important;
  }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EU agencies map</title>
    <link rel="stylesheet" href="css/site.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

A: The problem was in the loop. I had to take out the following lines out of the loop:
group.data.forEach(function(country) {
        includedCountries.push(country.id);
        excludedCountries.push(country.id);
});

let polygonTemplate = series.mapPolygons.template;
        polygonTemplate.tooltipHTML = '{country}';

          polygonTemplate.events.on("hit", function(ev) {
            chart.closeAllPopups();

            chart.openPopup("" + ev.target.dataItem.dataContext.country + "" + country.link.map(url => '
Country specific links ' + '').join(""));

          });


text:
Q: How can I modify the registration form on the website Odoo 12? I need to add other fields to the registration form that brings the web site module by default, I imagine that I can inherit from somewhere to add it to my own module, the inheritance does not know if it should be in the python or in the xml.
Thanks

A: You will have to find XML template for that registration and using xpath and doing controller inherit to pass values you can able to do that.


text:
Q: Is R looking for a function that is not there? I'm having a weird issue with R.
Basically, I am following this analysis pipeline in order to understand how it works. At some point (right after the first introductory paragraph, the last few lines of the history) I find this piece of code:
#--- clustering ---#
for (n in names(all.sce)) {
    g <- buildSNNGraph(all.sce[[n]], k=10, use.dimred='PCA')
    clust <- igraph::cluster_walktrap(g)$membership
    colLabels(all.sce[[n]])  <- factor(clust)
}

that calls this function colLabels which throws a very weird error:
Error in colLabels(allEnsembl[[n]]) <- factor(clust) :    cant find the
function "colLabels<-"

Now, since I am working with a specific kind of data, i.e. single cell data (bioinformatics here), I've looked into this function and it seems to be part of this package called SingleCellExperiment, which I can load successfully before launching the above piece of code.
Once I encountered the error I looked into the R help which can't actually find anything:
> help(colLabels)

No documentation for 'colLabels' in specified packages and libraries: you could try '??colLabels'

> ??colLabels

No vignettes or demos or help files found with alias or concept or title matching 'colLabels' using fuzzy matching.

Problem is...why does the error point to a function (apparently) called colLabels<-?
EDIT: other functions from the mentioned package, i.e. SingleCellExperiment, work and help pages are available.
EDIT 2: I've imported the required library. I also looked into the version I've installed and it seems to be an issue related to the versions. Using sessionInfo() R tells me I've version 1.8.0 which fits with what stated in the Bioconductor website. The packages version available and also the pdf documentation refers to 1.8.0. BUT I've noticed that in the previous link I've attached I was referring to a development version...probably I need to install it (?)
EDIT 3: ok, I have other issues now. The one in the question was an issue related to the package version since the official SingleCellExperiment was 1.8.0 while the doc I found was related to 1.9.3 which was a development version. Once installed, the help for the function works, but the function itself do not.
sessionInfo() now states that I have the version 1.9.3 but other functions do not work anymore so, I dont know.

A: This is the default R behaviour.
If you call a not imported or non-existing function, the error message looks like:
> non_existing_function(x)
Error in non_existing_function(x) :
  could not find function "non_existing_function"

If you call a not imported or non-existing function together with an assignment operator, the error message looks like:
> non_existing_function(x) <- y
Error in non_existing_function(x) <- y :
  could not find function "non_existing_function<-"

You have to import the SingleCellExperiment package to be able to use colLabels:
library(SingleCellExperiment)

Update: You definitely have to use the dev version (1.9.3). If you check the manual for the current stable (1.8.0), there is no function colLables there, but there is in the manual for dev version (1.9.3).

A: The colLabels function was only added in version 1.9.3.
This will come out with the next Bioconductor release at the end of this month, see here. In the meantime, you can either:
Install R 4.0.0 and start using BioC-devel to get access to 1.9.3, or
Just get and set values from sce$label, which does the same thing.
These are quotes from Aaron Lun's (SingleCellExperiment package developper) Git Memory.


text:
Q: Angular Reactive Form Select dropdown has an empty option I'm having a reactive form with dropdowns. I'm showing user's selected dropdown items in the form. Values are getting from API. There are several drop-downs are generating and in every dropdown there's an empty option(blank item). But from the API side ,there are no blank items are coming. This is what I tried. Can someone help to solve this issue
View.
<form [formGroup]="feedbackForm" (ngSubmit)="onSubmit()">

                    Category
                    Option

                    <ng-container [formGroupName]="j">
                        {{item.value.categories}}

                            <select name="apivalues" formControlName="option">
                                <option  [ngValue]="item.value.categories">{{item.value.categories}}
                                <option>
                            </select>

                    </ng-container>

This is how items are getting and added to reactive form
 getOptionsFromAPI() {
    this.apiService.getOptions()
      .subscribe(res=> {

        this.arr = this.feedbackForm.get('arr') as FormArray;

        if (res['data'].length > 0) {
          for (let i = 0; i < res['data'].length; i++) {
            this.category = "";
            this.getOptions= response['data'][i].options;
            this.category = response['data'][i].categories

            this.arr.push(this.createItems());
          }
        }
      },

      error => {

      });
  }

  createItem() {
    return this.fb.group({
      category: [this.category],
      options: [this.getOptions],
    })
  }

A: I think you can solve it with 2 options:
a. Use Reactive Forms Validations to make sure the control is not
    empty.
b. Add a selected attribute to a default value, let say, the first one:
<option *ngFor="let option of options; let i = index" [value]="option.key" [selected]="i === 0">{{option.value}}</option>

A: If you want to generate <option> items within an <select> dropdown, you will have to loop over the options. Passing an array to [ngValue] will most likely not work.
Maybe you can fork this stackblitz so that it shows your problem better.
Example of generating options for a dropdown without an empty option:

<form [formGroup]="form">
  <select name="cars" formControlName="cars">

    <option *ngFor="let option of options" [value]="option.value">
      {{option.label}}
    </option>
  </select>
</form>

export class AppComponent  {
  carControl = new FormControl(1);

  form = new FormGroup({
    cars: this.carControl
  });

  name = 'Angular';

  options = [
    {
      label: 'Car BMW',
      value: 1
    },
    {
      label: 'Car Audi',
      value: 2
    },
    {
      label: 'Car VW',
      value: 3
    }
  ];
}


text:
Q: JsPlump Custom Connector's events I created new simple Connector using jsPlumb.
And I want to handle event in this Connector, when I stop drag my Item (a click of the mouse after dragging).
I need handle it only in Connector in depends on new position of the Item.
How can I do it?
It is my simple connector
    var CustomConnector = function(params) {
    var _super = jsPlumb.Connectors.AbstractConnector.apply(this, params);
    this.type = "CustomConnector";

    this._compute = function(paintInfo, paintParams) {
    //my code
    };
    };

   jsPlumbUtil.extend(CustomConnector , jsPlumb.Connectors.AbstractConnector);
   jsPlumb.registerConnectorType(CustomConnector , "CustomConnector ");


text:
Q: Trouble calling a function This is my first time posting after looking through for a while and I am new to javascript, but I am having trouble figuring this out.
I am trying to call a function I have created, and everytime I attempt to call it...i am told I am not calling the function.
What am I missing?
//Simple greeting function
var greeting = function (name) {
console.log("Great to see you," + " " + name);
};

//Calling function
var greeting = function(name) {
console.log("Hello" + "" + name);
} // this was missing in the original question

or if I try
functionName = function(name)

I'll get a syntax error

A: What?! Try this:
var greeting = function(name) {
   console.log('Hello ' + name);
}

greeting('ktm');

So there are two ways to define functions.
(1) Function Expression
var greeting = function(name) { ... }
(2) Function Declaration
function greeting(name) { ... }
There is a simple way to call functions.
greeting('hello');
You can actually pass it any number of arguments, but if the function expects an argument, and you pass it none, it will treat it as undefined.

A: You're not calling your function at all.
A call to your function would look like this:
greeting( "Mike" );

A: Try:
//Simple greeting function
var greeting = function (name) {
    console.log("Great to see you," + " " + name);
};

greeting('foo bar');

A: Here is how to define your function:
function greeting(name) {

    console.log("Great to see you," + " " + name);

}

and call it:
greeting("Tomas");

A: or you can do...
/*here i am declaring my function*/
function greeting(name) {
console.log(name);
}

/*here i am calling it*/
greeting('ktm');

function greeting(){} is a function declaration.  Function declarations are probably easier to pick up and learn before you go diving-in, into storing functions into variables. Especially if you're learning this stuff for the first time.


text:
Q: ng-repeat in ng-repeat, scope not change Question Link Plnkr
http://plnkr.co/edit/iWTkPrDDvrDdc4LRQjTN?p=preview
code is like:
<!doctype html>

{{action.content}}

but why the result is:
11
13
11
13
11
13
I expect it is
11
13
21
23
31
33
why the line not change?

A:

    {{line[0]}} {{line[2]}}

I think for your case you don't even need the actions. Just do it like this.

A: Formatting is the job of a filter, not directive. Try:

{{line | format:action.content }}
 //Change this line to use filter to format output

DEMO


text:
Q: How to show at most 5 numbers in a pagination? I have a pagination and I want to achieve and limit it to 5 page numbers,
See below:
Examples:
 PREVIOUS 1 2 3 4 5 NEXT
 PREVIOUS 20 21 22 23 ... 39 NEXT
 PREVIOUS 59 ... 81 82 83 84 NEXT

Just five page number that they should be display.
Which part of the code should I alter and modify?
I am having trouble with the combination.
 <?php
 /* Setup page vars for display. */
if ($page == 0) $page = 1;                  //if no page var is given, default to 1.
$prev = $page - 1;                          //previous page is page - 1
$next = $page + 1;                          //next page is page + 1
$lastpage = ceil($total_pages/$limit);      //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1;                      //last page minus 1

/*
    Now we apply our rules and draw the pagination object.
    We're actually saving the code to a variable in case we want to draw it more than once.
*/
    $pagination = "";
    if($lastpage > 1)
    {
        $pagination .= "
";
    //previous buttons
        if ($page > 1)
            $pagination.= "previous";
        else
            $pagination.= "<buttons disabled>previous</buttons>";

    //pages
    if ($lastpage < 7 + ($adjacents * 2))   //not enough pages to bother breaking it up
    {
        for ($counter = 1; $counter <= $lastpage; $counter++)
        {
            if ($counter == $page)
                $pagination.= "<buttons style='background-color:#CEF6F5'>$counter</buttons>";
            else
                $pagination.= "$counter";
        }
    }
    elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
    {
        //close to beginning; only hide later pages
        if($page < 1 + ($adjacents * 2))
        {
            for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<buttons style='background-color:#CEF6F5'>$counter</buttons>";
                else
                    $pagination.= "$counter";
            }
            $pagination.= "...";
            $pagination.= "$lpm1";
            $pagination.= "$lastpage";
        }
        //in middle; hide some front and some back
        elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
        {
            $pagination.= " 1 ";
            $pagination.= " 2 ";
            $pagination.= "...";
            for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<buttons style='background-color:#CEF6F5'>$counter</buttons>";
                else
                    $pagination.= "$counter";
            }
            $pagination.= "...";
            $pagination.= "$lpm1";
            $pagination.= "$lastpage";
        }
        //close to end; only hide early pages
        else
        {
            $pagination.= "1";
            $pagination.= "2";
            $pagination.= "...";
            for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<buttons style='background-color:#CEF6F5'>$counter</buttons>";
                else
                    $pagination.= "$counter";
            }
        }
    }

    //next buttons
    if ($page < $counter - 1)
        $pagination.= "next";
    else
        $pagination.= "next";
    $pagination.= "
\n";
}
?>

I am having problem tracing the limit for displaying page number.

A: This worked for me.
You have to pass your current page number and total number of pages to the function.
function pageRange(page,pageCount){

var start = page-2,
    end = page+2;

if(end>pageCount){
    start-=(end-pageCount);
    end=pageCount;
}
if(start<=0){
    end+=((start-1)*(-1));
    start=1;
}

end = end>pageCount?pageCount:end;

return {start:start, end:end};
}

EDIT: check out this fiddle i made https://jsfiddle.net/qsLp6ajL/2/

A: I used below code for my wordpress plugin to display pagination and display data in table. You can use this according to your mysql query.
<?php echo '
'; ?>
    <col width="10%" />
    <col width="25%" />
    <col width="25%" />
    <col width="30%" />
    <col width="10%" />

<?php
        echo '
';
        echo ' ID	';
        echo ' Name	';
        echo ' Phone	';
        echo 'Address	';
        echo 'Details	';
        echo '
';
        global $wpdb;
        $num_rec_per_page=4;

        if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
        $start_from = ($page-1) * $num_rec_per_page;
        $sql = "SELECT * FROM {$wpdb->prefix}addressbook LIMIT $start_from, $num_rec_per_page";

        $result = $wpdb->get_results($sql);

        foreach($result as $row)
        {
            echo '
';
                echo '' . $row->id. '	';
                echo '' . $row->f_name, ' ', $row->m_name, ' ', $row->l_name . '	';
                echo '' . $row->phone . '	';
                echo '' . $row->address . '	';
                //echo '' . $row->address . '	';

                $pages2 = get_pages(array(
                    'meta_key' => '_wp_page_template',
                    'meta_value' => 'user_list_page.php'
                ));
                foreach($pages2 as $page2){
                    //echo $page->ID.'
';

                }
                if ( is_user_logged_in() ) {
                 $user_ID = get_current_user_id();
                }
                if ($user_ID==$row->id) {
                    # code...

                    echo '';
                        //echo 'ID).'&id=' . $row->id . '"> Edit|';
                         if ( get_option('permalink_structure') ) {
                        echo 'ID).'?id=' . $row->id . '"> Details';
                        //echo 'permalinks enabled';
                    } else {
                        echo 'ID).'&id=' . $row->id . '"> Details';
                    }
                 echo'	';
                }
                if ($user_ID!=$row->id) {
                     echo 'ID).'&id=' . $row->id . '"> Details	';
                }

            echo '
';
 }
 echo '
';
 $sql = "SELECT * FROM " . $wpdb->prefix."addressbook";
 $rs_result = mysql_query($sql); //run the query
 $total_records = mysql_num_rows($rs_result);  //count number of records
 $total_pages = ceil($total_records / $num_rec_per_page);
 $aaa = get_permalink( $page2->ID);?>

 <?php echo "".'|<'." "; // Goto 1st page
    for ($i=1; $i<=$total_pages; $i++) {
         if ( get_option('permalink_structure') ) {
                        echo "".$i." ";
                        //echo 'permalinks enabled';
                    } else {
                        echo "".$i." ";
                    }

    };
     if ( get_option('permalink_structure') ) {
                        echo "".'>|'." "; // Goto last page

                    } else {
                        echo "".'>|'." "; // Goto last page
                    }

    echo '
';?>


text:
Q: How to auto backup set directories to ext hard disk upon docking computer? I have a slight problem, my computers hard disk is quite small so it get's filled up quite fast.
Luckily I have 2TB external hard disc, however copying files to it constantly is a pain. I was wondering if there is any script that I could use that will back up directories that I have chosen from my computers hard disc onto the external drive upon connecting to the dock?


text:
Q: Finding the mean of two columns with two different classes/labels right now I'm trying to create a data frame that contains the mean of two columns for two separate labels/categories.
But, I don't know how to calculate the mean for two columns, it just returns the same mean for both winner and opponent/loser.
Currently, I'm using the tidyverse library.
Here is the original data frame:
winner_hand winner_ht   winner_ioc  winner_age  opponent_hand   opponent_ht opponent_ioc    opponent_age    result  name
<chr>   <dbl>   <chr>   <dbl>   <chr>   <dbl>   <chr>   <dbl>   <fct>   <chr>
R   178 JPN 29.00479    R   NA  RUS 22.88569    winner  Kei Nishikori
R   NA  RUS 22.88569    R   188 FRA 33.70568    winner  Daniil Medvedev
R   178 JPN 29.00479    R   188 FRA 31.88227    winner  Kei Nishikori
R   188 FRA 33.70568    R   NA  AUS 19.86858    winner  Jo Wilfried Tsonga
R   NA  RUS 22.88569    R   196 CAN 28.01095    winner  Daniil Medvedev
R   188 FRA 31.88227    R   NA  JPN 26.40383    winner  Jeremy Chardy

My code:
age_summary <- game_data %>%
                group_by(result) %>%
                summarize(mean_age = mean(winner_age))
age_summary

Resulting Data frame:
result  mean_age
<fct>   <dbl>
winner  27.68495
loser   27.68495

A: If you want summaries from two columns, you need expressions for each column in the call to summarize().
Example with fake data, since your excerpt only has one value for the 'result' column:
library(tidyverse)
dat <- read_csv(
"result, winner_age, opponent_age
A, 5, 10
A, 6, 11,
B, 12, 2
B, 13, 1")

dat %>%
  group_by(result) %>%
  # note: two expressions here:
  summarise(mean_winner_age = mean(winner_age),
            mean_opponent_age = mean(opponent_age))

output:
# A tibble: 2 x 3
  result mean_winner_age mean_opponent_age
  <chr>            <dbl>             <dbl>
1 A                  5.5              10.5
2 B                 12.5               1.5


text:
Q: IBM MobileFirst Platform v8.0 - Operational Analytics multi-tenancy From an existing WL v6.2 infrastructure I used to send analytics data from different runtimes to a single Operational Analytics server, adding a tenant parameter in order to treat them separately.
I'm trying to configure in the same way a new MFP v8.0 infrastructure, but I can't get it to work.
Searching the InfoCenter I find documentation about multi-tenancy only up to MFP v7.1, but can't see anything on latest MFP v8.0.
Is multi-tenancy still supported in MFP v8 ?
I think yes, because I see that the analytics server still has an analytics/DEFAULT_Tenant jndi entry.
However I don't know how to compose the mfp.analytics.url jndi entry in the MFP runtime server in order to correctly pass the tenant info to the target analytics server.
I tried something like
http://<opan-host>:<opan-port>/analytics-service/rest?tenant=MFPSVIL

but it doesn't seem to work.
When I restart the runtime war, in the access log of the analytics web server I see an invalid request coming in e producing an http405 error:
[03/Oct/2017:09:59:42 +0200] "POST /analytics-service/rest?tenant=MFPSVIL/v3 HTTP/1.1" 405 -

What am I doing wrong ?
What is the correct syntax for the mfp.analytics.url entry ?
If there is also any doc/wiki/tutorial that I have missed, please let me know.
Any help would be really appreciated.
Many thanks in advance.
Ciao, Stefano.

A: Unfortunately, Multi-tenancy is not supported with MFP Analytics 8.0.
Documentation needs to be updated. That is the reason no where in the documentation support was claimed or the steps for enabling Multi-Tenancy exists in 8.0


text:
Q: Prueba unitaria en C# para rellenar un formulario Tengo que hacer una prueba unitaria para rellenar un formulario de modo automático 200 veces con el fin de que de esta forma se pueda descubrir algún bug o algo por el estilo,  lo que tengo hecho hasta ahora son simples clases que generan datos personales aleatorios los cuales se pondrán en el formulario, simplemente son métodos que devuelven texto todos los métodos funcionan, sin embargo mas que un problema con mi código he llegado a un punto en donde no se como hacer lo que sigue, es decir pasar los datos que tengo guardado al formulario, pensaba hacer un método llamado robot el cual sera quien coloque los datos (el método no existe) aunque igual quizá se pueda hacer de otra forma.
Básicamente mi duda es como podría mandar los  datos a un formulario y como podría interactuar con campos como por ejemplo estado civil que en el caso de que estos sea una lista desplegable de donde se seleccione. Realmente no tengo idea de como hacer eso
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Rellenador_de_formulario
{
    [TestClass]
    public class FormularioTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Datos datos = new Datos();
            Numero numeros = new Numero();
            Robot llenar = new Robot();

        String name, dadLastname, momLastname, nId, curp, rfc, phoneOne, phoneTwo, direction ;

        for (int i = 0; i<200; i++)
        {
            name = datos.Nombre();
            dadLastname = datos.Apellido();
            momLastname = datos.Apellido();
            nId = numeros.NId();
            curp = numeros.Curp();
            rfc = numeros.RFC();
            phoneOne = numeros.Telefono();
            phoneTwo = numeros.Telefono();
            direction = datos.Direcion();

            Robot.Bot(name, dadLastname, momLastname, nId, curp, rfc, phoneOne, phoneTwo, direction);

        }

    }
}

}


text:
Q: Strictly invariant sets of the rotation transformation on a discrete space. Fix an integer $n>0$. Consider the space $X=\{a_0,a_1,...,a_{n-1}\}$ with transformation $T:X\to X$ defined by $T(a_i)=a_{i+1(\text{ mod n})}$.
What are the strictly invariant sets of this space? (i.e the $A\subset X$ with $T^{-1}A=A$.)
I think the only strictly invariant sets are $X$ and $\emptyset$, but I am having some trouble proving this claim.

A: Let $A$ be a non-empty invariant set. If $a_j\in A$, then $a_j\in T^{-1}(A)\cap T(A)$, hence $a_{j+1\mod n}$ and $a_{j-1\mod n}$ also are in $A$. This proves that $A=X$.


text:
Q: Authetication from 3rd Party Application to Host iFrames I have an application that hosts a series of iFrames within a 3rd party application. How can I assure only the 3rd party application will have access to my application and prevent any outside parties from accessing my application?
Thanks for the help, in advance.


text:
Q: SQL Sever parent, child, child relationships within table I have the following table of items with contain a list of name with map back to a parent field within the table -
id  nameVal parentId
1   A   NULL
2   B   NULL
3   C   NULL
4   D   NULL
5   E   NULL
6   A1  1
7   A2  6
8   A3  1
9   A4  7
10  B1  2
11  B2  2

it can be more that one step away from the parent record - A, A1, A4 are all related etc. as below...
A1 => A
A2 => A1 => A
A3 => A
A4 => A2 => A1 => A

So what I'm trying to do is pull through all records where a relationship exists, ie, A4 would bring back all the A's as there is a link to the original A records.
Is this possible?

A: You can do this with a recursive CTE.  The key is to get the parent.  Here is one method:
with cte as (
      select id, nameval, id as orig
      from t
      where parentid is null
      union all
      select t.nameval, cte.orig
      from cte join
           t
           on t.parentid = cte.id
    )
select cte.*
from cte
where cte.orig = (select cte2.orig from cte cte2 where ct2.nameval = 'A4');

A: Perhaps a little more than necessary, but consider the following:
You can set the top node (null will default to the entire hierachy)
You also can set a filter.  This can be empty for no filter, a single ID, or a delimited string of IDs.
Declare @T table (id int,nameVal varchar(50),parentId int)
Insert into @T values
(1   ,'A',   NULL),
(2   ,'B',   NULL),
(3   ,'C',   NULL),
(4   ,'D',   NULL),
(5   ,'E',   NULL),
(6   ,'A1',  1),
(7   ,'A2',  6),
(8   ,'A3',  1),
(9   ,'A4',  7),
(10  ,'B1',  2),
(11  ,'B2',  2)

Declare @Top    int         = null      --<<  Sets top of Hier Try 6
Declare @Nest   varchar(25) = '|-----'  --<<  Optional: Added for readability
Declare @Filter varchar(25) = '7'       --<<  Empty for All or try '7,10'

;with cteP as (
      Select Seq  = cast(10000+Row_Number() over (Order by nameVal) as varchar(500))
            ,ID
            ,parentId
            ,Lvl=1
            ,nameVal
      From   @T
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(parentId,-1) else ID end
      Union  All
      Select Seq  = cast(concat(p.Seq,'.',10000+Row_Number() over (Order by r.nameVal)) as varchar(500))
            ,r.ID
            ,r.parentId
            ,p.Lvl+1
            ,r.nameVal
      From   @T r
      Join   cteP p on r.parentId = p.ID)
     ,cteR1 as (Select *,R1=Row_Number() over (Order By Seq) From cteP)
     ,cteR2 as (Select A.Seq,A.ID,R2=Max(B.R1) From cteR1 A Join cteR1 B on (B.Seq like A.Seq+'%') Group By A.Seq,A.ID )
     ,cte   as (
                Select A.R1
                      ,B.R2
                      ,A.ID
                      ,A.parentId
                      ,A.Lvl
                      ,nameVal = Replicate(@Nest,A.Lvl-1) + A.nameVal
                 From cteR1 A
                 Join cteR2 B on A.ID=B.ID
               )
Select Distinct A.*
 From  cte A
 Join (
        Select A.R1,A.R2
         From  cte A
         Join (Select R1 from cte Where IIF(@Filter='',1,0)+CharIndex(concat(',',ID,','),concat(',',@Filter+','))>0) B
           on B.R1 between A.R1 and A.R2
      ) B on A.R1 between B.R1 and B.R2
 Order By A.R1

Returns

Now, if you set @Filter = '7,10', you'll get

If you set @Filter = '', you'll get

A: You can use a recursive query to fetch all of the related rows.  Whether the data will be in the form you want, I don't know, as the question seems a bit unclear about that.  But for example
Fetch a record and all descendants:
with r as (
     select *
       from my_table t
      where id = 7
     union all
     select t1.*
       from            my_table t1
            inner join r
                    on t1.parent_id = r.id
)
select * from r;

Fetch a record and all ancestors:
with r as (
     select *
       from my_table t
      where id = 7
     union all
     select t1.*
       from            my_table t1
            inner join r
                    on t1.id = r.parent_id
)
select * from r;

Now maybe you want both children and ancestors.  This can get a little trickier; recursion works best in a straight line so there can be no infinite loops.  One way is to union together the two above queries.  If your real query has complex logic that you don't want to write twice, then you could use this to get a list of ID's and then run the real query over a select ... where id in (my_list) type query.
Another consideration is whether a record can have multiple children.  If we have
A
A1 => A
A10 => A1
A11 => A1
A2 => A
A20 => A2
A21 => A2

you could say these are all related (through A; some are "cousins").  So if you search from A1 and union the first two example queries, you'd get A, A1, A10, A11... but would you also want the other children of A?  If so you could take a slightly different approach:
First, find the eldest ancestor:
with r as (
     select *
       from my_table t
      where id = 7
     union all
     select t1.*
       from            my_table t1
            inner join r
                    on t1.id = r.parent_id
)
select id from r where parent_id is null;

Then run the original "all descendants" query against that ID.  If you want to get it all into a single statement, the following *should * work I think (but I'm not where I can test it):
with ancestors as (
     select *
       from my_table t
      where id = 7
     union all
     select t1.*
       from            my_table t1
            inner join ancestors
                    on t1.id = ancestors.parent_id
) , related as (
     select *
       from ancestors
      where parent_id is null
     union all
     select t1.*
       from            my_table t1
            inner join related
                    on t1.parent_id = related.id
)
select * from related;


text:
Q: AttributeError: 'Line2D' object has no property 'max_sr' I am getting
AttributeError: 'Line2D' object has no property 'max_sr'

in the following code
from matplotlib import pyplot as plt
plt.figure(figsize=(15,2))
librosa.display.waveshow(y=y, sr=sr, max_sr=1000, alpha=0.25, color='blue')


text:
Q: in Web Api Validate field is exactly 15 characters but the field in not required Is there a way in data attributes to say if the field is not null then it must be a certain length?
I have
 <StringLength(15, MinimumLength:=15, ErrorMessage:="RequisitonNumber must be exactly 15 characters. ")>
    Public Property RequisitonNumber() As String
        Get
            Return m_RequisitonNumber
        End Get
        Set(value As String)
            m_RequisitonNumber = value
        End Set
    End Property
    Private m_RequisitonNumber As String

this works fine when a value is submitted but this is not a required field so when it is left empty the validation error is being thrown.


text:
Q: PHP constant string square bracket indexing I'm trying to get a constant string and index it as if it was an array of characters (square bracket syntax).  When I try this code it fails on the last line.
define( 'CONSTANT_STRING','0123456789abcdef');
echo CONSTANT_STRING; // Works by itself :)
$string = CONSTANT_STRING;
echo $string[9]; // Also works by itself.
echo strlen(CONSTANT_STRING); // Also works by itself.

echo substr(CONSTANT_STRING, 9, 1); // Ok, yes this works, but not as clean.

echo CONSTANT_STRING[9]; // Fails as a syntax (parse) error.

I am using a constant string like this in a function.  Since it could be called multiple times on one page it really should be a constant.  What is the best option if there is no way to do this like I originally intended.

A: PHP Constants can only be scalar values, so the engine doesn't try to properly parse a constant that's used as something more than a scalar, like an array or an object.
This is a problem in your case because the brackets are used to point at an array index and can be used as a shortcut to grab a character at a specific location in the string.
You'll just have to do it the "hard" way and use substr().


text:
Q: Payara server not starting I'm trying out some Java EE and I can get my code to run on Glassfish 5.0.1 no problem. I want to run it on Payara but I can only get Payara Micro to work, the full and web-profile both crash and give the following errors that I cant find any info about. The closest related problem I could find told me to try changing my path to Java 8 instead, but that had no effect. Thanks!
[2020-09-14T18:59:27.963+0200] [Payara 5.2020.4] [INFO] [NCLS-LOGGING-00009] [javax.enterprise.logging] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102767963] [levelValue: 800] [[
  Running Payara Version: Payara Server  5.2020.4 #badassfish (build 817)]]

[2020-09-14T18:59:27.968+0200] [Payara 5.2020.4] [INFO] [NCLS-LOGGING-00010] [javax.enterprise.logging] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102767968] [levelValue: 800] [[
  Server log file is using Formatter class: com.sun.enterprise.server.logging.ODLLogFormatter]]

[2020-09-14T18:59:28.508+0200] [Payara 5.2020.4] [INFO] [] [org.glassfish.ha.store.spi.BackingStoreFactoryRegistry] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102768508] [levelValue: 800] [[
  Registered fish.payara.ha.hazelcast.store.HazelcastBackingStoreFactoryProxy for persistence-type = hazelcast in BackingStoreFactoryRegistry]]

[2020-09-14T18:59:28.544+0200] [Payara 5.2020.4] [INFO] [] [org.hibernate.validator.internal.util.Version] [tid: _ThreadID=24 _ThreadName=RunLevelControllerThread-1600102767870] [timeMillis: 1600102768544] [levelValue: 800] [[
  HV000001: Hibernate Validator 6.1.2.Final]]

[2020-09-14T18:59:33.272+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=23 _ThreadName=RunLevelControllerThread-1600102767870] [timeMillis: 1600102773272] [levelValue: 800] [[
  Hazelcast Instance Bound to JNDI at payara/Hazelcast]]

[2020-09-14T18:59:33.272+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=23 _ThreadName=RunLevelControllerThread-1600102767870] [timeMillis: 1600102773272] [levelValue: 800] [[
  JSR107 Caching Provider Bound to JNDI at payara/CachingProvider]]

[2020-09-14T18:59:33.272+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=23 _ThreadName=RunLevelControllerThread-1600102767870] [timeMillis: 1600102773272] [levelValue: 800] [[
  JSR107 Default Cache Manager Bound to JNDI at payara/CacheManager]]

[2020-09-14T18:59:33.474+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00015] [javax.enterprise.system.core] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102773474] [levelValue: 800] [[
  Shutdown requested
MultiException stack 1 of 2
java.lang.RuntimeException: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:169)
    at fish.payara.nucleus.microprofile.config.source.PasswordAliasConfigSource.getValue(PasswordAliasConfigSource.java:100)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getSourceValue(PayaraConfig.java:183)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValueConverted(PayaraConfig.java:166)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.lambda$getValue$1(PayaraConfig.java:161)
    at java.util.concurrent.ConcurrentHashMap.compute(ConcurrentHashMap.java:1853)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValue(PayaraConfig.java:157)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValueInternal(PayaraConfig.java:127)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getOptionalValue(PayaraConfig.java:123)
    at fish.payara.microprofile.healthcheck.HealthCheckService.postConstruct(HealthCheckService.java:139)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1268)
    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:309)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:351)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:103)
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:167)
    ... 27 more
Caused by: java.security.KeyStoreException: JCEKS not found
    at java.security.KeyStore.getInstance(KeyStore.java:851)
    at com.sun.enterprise.security.store.PasswordAdapter.loadKeyStore(PasswordAdapter.java:131)
    at com.sun.enterprise.security.store.PasswordAdapter.<init>(PasswordAdapter.java:110)
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:101)
    ... 28 more
Caused by: java.security.NoSuchAlgorithmException: JCEKS KeyStore not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
    at java.security.Security.getImpl(Security.java:697)
    at java.security.KeyStore.getInstance(KeyStore.java:848)
    ... 31 more
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: post construct on fish.payara.microprofile.healthcheck.HealthCheckService
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:369)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
]]

[2020-09-14T18:59:33.477+0200] [Payara 5.2020.4] [ALLVARLIG] [NCLS-CORE-00016] [javax.enterprise.system.core] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102773477] [levelValue: 1000] [[
  Startup service failed to start
MultiException stack 1 of 2
java.lang.RuntimeException: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:169)
    at fish.payara.nucleus.microprofile.config.source.PasswordAliasConfigSource.getValue(PasswordAliasConfigSource.java:100)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getSourceValue(PayaraConfig.java:183)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValueConverted(PayaraConfig.java:166)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.lambda$getValue$1(PayaraConfig.java:161)
    at java.util.concurrent.ConcurrentHashMap.compute(ConcurrentHashMap.java:1853)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValue(PayaraConfig.java:157)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValueInternal(PayaraConfig.java:127)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getOptionalValue(PayaraConfig.java:123)
    at fish.payara.microprofile.healthcheck.HealthCheckService.postConstruct(HealthCheckService.java:139)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1268)
    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:309)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:351)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:103)
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:167)
    ... 27 more
Caused by: java.security.KeyStoreException: JCEKS not found
    at java.security.KeyStore.getInstance(KeyStore.java:851)
    at com.sun.enterprise.security.store.PasswordAdapter.loadKeyStore(PasswordAdapter.java:131)
    at com.sun.enterprise.security.store.PasswordAdapter.<init>(PasswordAdapter.java:110)
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:101)
    ... 28 more
Caused by: java.security.NoSuchAlgorithmException: JCEKS KeyStore not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
    at java.security.Security.getImpl(Security.java:697)
    at java.security.KeyStore.getInstance(KeyStore.java:848)
    ... 31 more
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: post construct on fish.payara.microprofile.healthcheck.HealthCheckService
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:369)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
]]

[2020-09-14T18:59:33.476+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=21 _ThreadName=RunLevelControllerThread-1600102767863] [timeMillis: 1600102773476] [levelValue: 800] [[
  Network Listener http-listener-1 started in: 21ms - bound to [/0.0.0.0:8080]]]

[2020-09-14T18:59:33.513+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=21 _ThreadName=RunLevelControllerThread-1600102767863] [timeMillis: 1600102773513] [levelValue: 800] [[
  Network Listener http-listener-2 started in: 17ms - bound to [/0.0.0.0:8181]]]

[2020-09-14T18:59:33.525+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=21 _ThreadName=RunLevelControllerThread-1600102767863] [timeMillis: 1600102773525] [levelValue: 800] [[
  Network Listener admin-listener started in: 6ms - bound to [/0.0.0.0:4848]]]

[2020-09-14T18:59:33.526+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00087] [javax.enterprise.system.core] [tid: _ThreadID=21 _ThreadName=RunLevelControllerThread-1600102767863] [timeMillis: 1600102773526] [levelValue: 800] [[
  Grizzly 2.4.4 started in: 5,133ms - bound to [http-listener-1:8080, http-listener-2:8181, admin-listener:4848]]]

[2020-09-14T18:59:33.563+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=23 _ThreadName=RunLevelControllerThread-1600102767870] [timeMillis: 1600102773563] [levelValue: 800] [[
  Network Listener iiop-service started in: 6ms - bound to [/0.0.0.0:3700]]]

[2020-09-14T18:59:33.590+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102773590] [levelValue: 800] [[
  Hazelcast Instance Unbound from JNDI at payara/Hazelcast]]

[2020-09-14T18:59:33.595+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102773595] [levelValue: 800] [[
  JSR107 Caching Provider Unbound from JNDI at payara/CachingProvider]]

[2020-09-14T18:59:33.595+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102773595] [levelValue: 800] [[
  JSR107 Cache Manager Unbound from JNDI at payara/CacheManager]]

[2020-09-14T18:59:33.611+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=87 _ThreadName=Executor-Service-10] [timeMillis: 1600102773611] [levelValue: 800] [[
  Network Listener http-listener-1 started in: 4ms - bound to [/0.0.0.0:8080]]]

[2020-09-14T18:59:33.700+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=87 _ThreadName=Executor-Service-10] [timeMillis: 1600102773700] [levelValue: 800] [[
  Network Listener http-listener-2 started in: 82ms - bound to [/0.0.0.0:8181]]]

[2020-09-14T18:59:33.711+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00101] [javax.enterprise.system.core] [tid: _ThreadID=87 _ThreadName=Executor-Service-10] [timeMillis: 1600102773711] [levelValue: 800] [[
  Network Listener admin-listener started in: 5ms - bound to [/0.0.0.0:4848]]]

[2020-09-14T18:59:33.711+0200] [Payara 5.2020.4] [INFO] [NCLS-CORE-00087] [javax.enterprise.system.core] [tid: _ThreadID=87 _ThreadName=Executor-Service-10] [timeMillis: 1600102773711] [levelValue: 800] [[
  Grizzly 2.4.4 started in: 114ms - bound to [http-listener-1:8080, http-listener-2:8181, admin-listener:4848]]]

[2020-09-14T18:59:34.162+0200] [Payara 5.2020.4] [INFO] [] [fish.payara.nucleus.hazelcast.HazelcastCore] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1600102767864] [timeMillis: 1600102774162] [levelValue: 800] [[
  Shutdown Hazelcast]]

[2020-09-14T18:59:34.164+0200] [Payara 5.2020.4] [ALLVARLIG] [NCLS-CORE-00014] [javax.enterprise.system.core] [tid: _ThreadID=1 _ThreadName=main] [timeMillis: 1600102774164] [levelValue: 1000] [[
  Shutdown required
MultiException stack 1 of 1
MultiException stack 1 of 2
java.lang.RuntimeException: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:169)
    at fish.payara.nucleus.microprofile.config.source.PasswordAliasConfigSource.getValue(PasswordAliasConfigSource.java:100)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getSourceValue(PayaraConfig.java:183)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValueConverted(PayaraConfig.java:166)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.lambda$getValue$1(PayaraConfig.java:161)
    at java.util.concurrent.ConcurrentHashMap.compute(ConcurrentHashMap.java:1853)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValue(PayaraConfig.java:157)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValueInternal(PayaraConfig.java:127)
    at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getOptionalValue(PayaraConfig.java:123)
    at fish.payara.microprofile.healthcheck.HealthCheckService.postConstruct(HealthCheckService.java:139)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1268)
    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:309)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:351)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:103)
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:167)
    ... 27 more
Caused by: java.security.KeyStoreException: JCEKS not found
    at java.security.KeyStore.getInstance(KeyStore.java:851)
    at com.sun.enterprise.security.store.PasswordAdapter.loadKeyStore(PasswordAdapter.java:131)
    at com.sun.enterprise.security.store.PasswordAdapter.<init>(PasswordAdapter.java:110)
    at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:101)
    ... 28 more
Caused by: java.security.NoSuchAlgorithmException: JCEKS KeyStore not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
    at java.security.Security.getImpl(Security.java:697)
    at java.security.KeyStore.getInstance(KeyStore.java:848)
    ... 31 more
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: post construct on fish.payara.microprofile.healthcheck.HealthCheckService
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:369)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
]]

[2020-09-14T18:59:34.166+0200] [Payara 5.2020.4] [ALLVARLIG] [] [javax.enterprise.system.core] [tid: _ThreadID=1 _ThreadName=main] [timeMillis: 1600102774166] [levelValue: 1000] [[
  Failed to start, exiting]]

[2020-09-14T18:59:34.166+0200] [Payara 5.2020.4] [INFO] [] [] [tid: _ThreadID=1 _ThreadName=main] [timeMillis: 1600102774166] [levelValue: 800] [[
  FileMonitoring shutdown]]

EDIT*
I also created a brand new Java EE project with only the following class and I still get the same output from Payara
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("api")
public class CdiConfig extends Application {
}

A: This happens because your security provider doesn't support the JCEKS algorithm to open the Payara keystore. Try using a different distribution of Java, e.g. AdoptOpenJDK (https://adoptopenjdk.net/). It's possible that your Java doesn't support that algorithm.
The reason why Payara Server fails and GlassFish doesn't is that Payara Server attempts to find configuration values in password aliases, which are protected by the keystore. This results in an exception because it can't open the keystore. I bet that GlassFish would also fail to open the keystore if it needed it at some point later. GlassFish just doesn't have the functionality of reading the configuration from password aliases and thus doesn't attempt to open the keystore at startup.
Anyway, it's definitely a bug that this exception brings down the whole server. Payara Server should just ignore the configuration and go on. Raise this as a bug in Payara bug tracker: https://github.com/payara/Payara/issues.


text:
Q: How can we Replace date in a text file using Windows Powershell scripting? I'm writing a windows powershell script to open/edit a text file.
It has many records and each record is sorted of comma-separated values (csv):
Steps I want to achieve:

*

*Open the text files in a directory on Server A.

*Edit the "Date" field with "Current Date" or other.

*Save the same text file at the same location(folder).

*Copying all the files to a new folder in different Server B.

I've just written this code snippet:
$path = "C:\PSFiles\Rec_File_001.txt"
$Filedata = Get-Content $path
$Record01 = $Filedata[0].split(",")
$Record01Date = $Record01[3]
$Record01CurrentDate = Get-Date -format yyMMdd
$Record01 -replace $Record01Date, $Record01CurrentDate
Set-Content $path

Please, any help on this?

A: You are having multiple questions here.  I'll address the one that is presented in the title - replacing text in a text file.
The script:
# current date in a new format
$CurrentDate = Get-Date -format yyMMdd

#replace old format
Get-Content -ReadCount 500 -Path C:\PSFiles\Rec_File_001.txt | % {$_ -replace "(0[1-9]|1[012])\d{1,2}(0[1-9]|[12][0-9]|3[01])", "$CurrentDate"} | Set-Content -Path C:\PSFiles_output\Rec_File_001.txt

This takes regexp for date format Date(mmYYdd) and exchanges it for a new one.  An option -ReadCount limits the number of lines that go via pipe at one time.

A: Import-CSV $Path -header text1, text2, text3, date, text5 |
Select text1, text2, text3, @{Name="Date"; Expression={Get-Date -format yyMMdd}}, text5 |
ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1 |
Set-Content $Path

Or:
$data = Import-CSV $Path -header text1, text2, text3, date, text5
$data | ForEach {"Date" = Get-Date -format yyMMdd}
$data | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content $Path

A: Hopefully this helps. Run the following commands in powershell:
$(Get-Item ath/filename.extensionfilename).creationtime=$(get-date "2019-10-15T15:45:12.2723844+01:00")

$(Get-Item C:\temp\log\txt.log).creationtime=$(get-date "2019-10-15T15:45:12.2723844+01:00")

Here is an article from Microsoft that explains how to modify the timestamps of a file https://devblogs.microsoft.com/scripting/use-powershell-to-modify-file-access-time-stamps/
Below is a table from that article showing the attributes that involve time that you can modify.
+----------------+----------+-----------------+---------------------------+
|      Name      |  Member  |      Type       |        Definition         |
+----------------+----------+-----------------+---------------------------+
| CreationTime   | Property | System.DateTime | CreationTime {get;set;}   |
| LastAccessTime | Property | System.DateTime | LastAccessTime {get;set;} |
| LastWriteTime  | Property | System.DateTime | LastWriteTime {get;set;}  |
+----------------+----------+-----------------+---------------------------+


text:
Q: How to create and modify copy of data frame in Shiny R I am writing a quality control application in Shiny where I'd like to be able to keep an "original" or raw data file, and create another file with extra columns.  I'm running into a problem where I can't figure out how to do this without overwriting the original data frame.  My current code looks like this, which works fine, but again, destroys the original data frame.
        ##########################################################################################
    reactiveData <- reactiveValues(df = NULL)

    #This function is responsible for loading in the selected file
    observe({
            req(input$file_selector)
            rv$df <- read.csv(paste0(parseDirPath(c(home = 'C:\\Users\\Ruben\\Desktop\\Test_QC_Program\\FiveMin'), file_dir()),'\\',input$file_selector),skip=1,na.strings='Null') # Simplified for testing
    })

    # This previews the CSV data file
    output$filetable <- renderDataTable({
            rv$df
    })

    observeEvent(input$qc_final_cols, {
            if (input$qc_final_cols){
                    utc <- ymd_hms(rv$df$TmStamp,tz='UTC')
                    ldt <- with_tz(utc,tzone='America/Chicago')
                    bv0 <- which(hour(ldt) == 0 & minute(ldt) == 0 & second(ldt) == 0)
                    if (length(bv0) > 0){
                            ldt[bv0] <- ldt[bv0] - 1}

                    rv$df <- rv$df %>%
                            add_column(LDT = as.character(ldt), .after = 'TmStamp')

                    for (v in 1:length(var_names)){
                            ind <- which(colnames(rv$df) == var_names[v])
                            rv$df <- rv$df %>%
                                    add_column(z = NA,.after = ind)
                            colnames(rv$df)[ind+1] <- paste0(var_names[v],'_QC')
                            rv$df <- rv$df %>%
                                    add_column(y = NA,.after = ind+1)
                            colnames(rv$df)[ind+2] <- paste0(var_names[v],'_Final')
                    }
            }
    })
    #######################################################################################

Is there a way to refer to the original data frame that I read in, as I try in the code below so I can create a new, separate data frame?  I want the new data frame to be reactive, not the original output$rawdata.
        output$rawdata <- renderDataTable({
            req(input$station_file)
            rawdata <- read.csv(input$station_file$datapath,
                                header = input$header,
                                skip = input$skip,
                                na.strings = input$nastrings)
    })

    qcdata <- reactiveValues(df = "rawdata")  ##RIGHT HERE I AM TRYING TO
REFER TO THE ORIGINALLY READ IN DATA, BUT UNSUCCESSFULLY

    observeEvent(input$station_file, {
                    utc <- ymd_hms(qcdata$df$TmStamp,tz='UTC')
                    ldt <- with_tz(utc,tzone='America/Chicago')
                    bv0 <- which(hour(ldt) == 0 & minute(ldt) == 0 & second(ldt) == 0)
                    if (length(bv0) > 0){
                            ldt[bv0] <- ldt[bv0] - 1}

                    qcdata$df <- qcdata$df %>%
                            add_column(LDT = as.character(ldt), .after = 'TmStamp')

                    for (v in 1:length(var_names)){
                            ind <- which(colnames(qcdata$df) == var_names[v])
                            qcdata$df <- qcdata$df %>%
                                    add_column(z = NA,.after = ind)
                            colnames(qcdata$df)[ind+1] <- paste0(var_names[v],'_QC')
                            qcdata$df <- qcdata$df %>%
                                    add_column(y = NA,.after = ind+1)
                            colnames(qcdata$df)[ind+2] <- paste0(var_names[v],'_Final')
                    }
    })

    # This previews the CSV data file
    output$qcdata <- renderDataTable({
            qcdata$df

A: When you read in your data, you can make a copy of it. It's not defined in your code above, but I assume that rv is also a reactiveValues object. Then you can do:
rv <- reactiveValues()
observe({
            req(input$file_selector)
            rv$original_data <- read.csv(paste0(parseDirPath(c(home = 'C:\\Users\\Ruben\\Desktop\\Test_QC_Program\\FiveMin'), file_dir()),'\\',input$file_selector),skip=1,na.strings='Null') # Simplified for testing
            rv$df <- rv$original_data
    })

Afterwards, you can do your calculations with rv$df but still have the original data.


text:
Q: How to create numpy array from dataframe? I am working with a Pandas DataFrame that contains 4 columns: 'TV', 'Radio', 'Newspaper' and 'Sales'. I need to create two NumPy arrays: X that contains the first 3 columns and y that contains the 'Sales' column.
I figured out there are two ways to create a NumPy array from a Pandas DataFrame:
import numpy as np
X = np.array(adver_data.iloc[:,0:3].values)
y = np.array(adver_data["Sales"].values)

and:
import numpy as np
X = adver_data[['TV', 'Radio', 'Newspaper']].values
y = adver_data[['Sales']].values

The problem is that even though these two ways actually create a NumPy array later my code gives different results for these two ways and I don't know why as I don't see how the arrays of the two ways are different.
What is the difference?

A: Let's say you have 'n' rows of data.
The code:
y = np.array(adver_data["Sales"].values)

gives shape of y as (n,) i.e. 1D array
whereas the code:
y = adver_data[['Sales']].values

gives shape of y as (n, 1) i.e. 2D array
So, you are getting different results.


text:
Q: How to add text on countdown timer I have the following code and am looking to give my Countdown timer a title. Inside the bar, right above the boxes that give the time remaining. Would like it to be easy to edit font, size and spacing across. Having trouble doing so.
It also seems like when publishing this code, the padding for the variables: days, hours, mins, and secs get pushed down. Not centered under the boxes and the edge of the bottom of the countdown timer.

var target_date = new Date("Aug 30, 2018 20:30:00").getTime(); // set the countdown date
var days, hours, minutes, seconds; // variables for time units

var countdown = document.getElementById("tiles"); // get tag element

getCountdown();

setInterval(function() {
  getCountdown();
}, 1000);

function getCountdown() {

  // find the amount of "seconds" between now and target
  var current_date = new Date().getTime();
  var seconds_left = (target_date - current_date) / 1000;

  days = pad(parseInt(seconds_left / 86400));
  seconds_left = seconds_left % 86400;

  hours = pad(parseInt(seconds_left / 3600));
  seconds_left = seconds_left % 3600;

  minutes = pad(parseInt(seconds_left / 60));
  seconds = pad(parseInt(seconds_left % 60));

  // format countdown string + set tag value
  countdown.innerHTML = "" + days + "" + hours + "" + minutes + "" + seconds + "";
}

function pad(n) {
  return (n < 10 ? '0' : '') + n;
}
body {
  font: normal 13px/20px Arial, Helvetica, sans-serif;
  word-wrap: break-word;
  color: #eee;
}

#countdown {
  /*bar*/
  width: 232.5px;
  /*changed*/
  height: 56px;
  /*changed*/
  text-align: center;
  background: #222;
  background-image: -webkit-linear-gradient(top, #264033, #feb330, #feb330, #264033);
  background-image: -moz-linear-gradient(top, #222, #333, #333, #222);
  background-image: -ms-linear-gradient(top, #222, #333, #333, #222);
  background-image: -o-linear-gradient(top, #222, #333, #333, #222);
  border: 1px solid #111;
  border-radius: 5px;
  box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.6);
  margin: auto;
  padding: 12px 0;
  /*changed*/
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

#countdown:before {
  /*handles*/
  content: "";
  width: 4px;
  /*changed*/
  height: 32.5px;
  /*changed*/
  background: #444;
  background-image: -webkit-linear-gradient(top, #264033, #264033, #264033, #264033);
  /*changed*/
  background-image: -moz-linear-gradient(top, #555, #444, #444, #555);
  background-image: -ms-linear-gradient(top, #555, #444, #444, #555);
  background-image: -o-linear-gradient(top, #555, #444, #444, #555);
  border: 1px solid #111;
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
  display: block;
  position: absolute;
  top: 24px;
  /*changed*/
  left: -5px;
  /*changed*/
}

#countdown:after {
  /*handles*/
  content: "";
  width: 4px;
  /*changed*/
  height: 32.5px;
  /*changed*/
  background: #444;
  background-image: -webkit-linear-gradient(top, #264033, #264033, #264033, #264033);
  /*changed*/
  background-image: -moz-linear-gradient(top, #555, #444, #444, #555);
  background-image: -ms-linear-gradient(top, #555, #444, #444, #555);
  background-image: -o-linear-gradient(top, #555, #444, #444, #555);
  border: 1px solid #111;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
  display: block;
  position: absolute;
  top: 24px;
  /*changed*/
  right: -5px;
}

#countdown #tiles {
  position: relative;
  z-index: 1;
}

#countdown #tiles>span {
  /*box*/
  width: 46px;
  /*changed*/
  max-width: 46px;
  /*changed*/
  font: bold 24px 'Droid Sans', Arial, sans-serif;
  /*changed*/
  text-align: center;
  color: #000000;
  /*color of numbers*/
  /*changed*/
  background-color: #ddd;
  background-image: -webkit-linear-gradient(top, #111, #eee);
  /*color of box*/
  /*changed*/
  background-image: -moz-linear-gradient(top, #bbb, #eee);
  background-image: -ms-linear-gradient(top, #bbb, #eee);
  background-image: -o-linear-gradient(top, #bbb, #eee);
  border-top: 1px solid #fff;
  /*top border of box*/
  /*changed*/
  border-left: 1px solid #fff;
  /*left border of box*/
  /*changed*/
  border-right: 1px solid #fff;
  /*right border of box*/
  /*changed*/
  border-bottom: 1px solid #fff;
  /*bottom border of box*/
  /*changed*/
  border-radius: 3px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.7);
  margin: 0 3.5px;
  /*changed*/
  padding: 9px 0;
  /*changed*/
  display: inline-block;
  position: relative;
}

#countdown #tiles>span:before {
  /*mini-handles*/
  content: "";
  width: 100%;
  height: 13px;
  background: #000000;
  /*changed*/
  display: block;
  padding: 0 3px;
  position: absolute;
  top: 41%;
  left: -3px;
  z-index: -1;
}

/* #countdown #tiles>span:after {
  content: "";
  width: 100%;
  height: 1px;
  background: #eee;
  border-top: 1px solid #333;
  display: block;
  position: absolute;
  top: 48%;
  left: 0;
} /*line through middle*/

#countdown .labels {
  /*words*/
  width: 100%;
  height: 12.5px;
  /*changed*/
  text-align: center;
  position: absolute;
  bottom: 8px;
}

#countdown .labels li {
  /*words*/
  width: 51px;
  /*changed*/
  font: bold 10px 'Droid Sans', Arial, sans-serif;
  color: #ffffff;
  /*changed*/
  text-shadow: 1px 1px 0px #000;
  text-align: center;
  text-transform: uppercase;
  display: inline-block;
}

Days

Hours

Mins

Secs

A: I was able to just add a new div above the #tiles div and tweak the CSS to get a title to display where you wanted. Needed to change the padding of #countdown to get it to display properly.

Title

Days

Hours

Mins

Secs

#countdown {
  /*bar*/
  width: 232.5px;
  /*changed*/
  height: 56px;
  /*changed*/
  text-align: center;
  background: #222;
  background-image: -webkit-linear-gradient(top, #264033, #feb330, #feb330, #264033);
  background-image: -moz-linear-gradient(top, #222, #333, #333, #222);
  background-image: -ms-linear-gradient(top, #222, #333, #333, #222);
  background-image: -o-linear-gradient(top, #222, #333, #333, #222);
  border: 1px solid #111;
  border-radius: 5px;
  box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.6);
  margin: auto;
  padding: 0px 0px 32px 0;
  /*changed*/
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Here is a fiddle.


text:
Q: Use repeat function in map alongside lambda function I have a function named tmp that only returns two strings. In addition, I have 2 iterables that I want to pass to the tmp function, one of them has 88000 lengths and another one has 50 lengths. I want to change the second one on every 200 iterates, but the problem is I can not iterate over the second iterable. Here is what I've done so far.
Code:
from itertools import repeat

url_list = [] # contains over 80000 urls
files = [] # contains 50 files

def tmp(url, file):
    return url, file

# I want to use the file for only 200 URLs and then change it and use the next one in the list(files) provided
list(map(tmp, url_list, map(lambda x: repeat(x, 200), files)))

Expected output:
url1, file1
url2, file1
url3, file1
.
.
url201, file2
url202, file2
.
.
.
url401 file3
url402 file3
.
.

Any help would be highly appreciated.

A: Rather than repeating files 200 times, split url_list into chunks of 200. See How do I split a list into equally-sized chunks? for various ways to code this.
Use itertools.cycle() to go back to the beginning of files when you reach the end.
result = []

for url_chunk, file in zip(chunks(url_list, 200), itertools.cycle(files)):
    result.extend([url, file for url in url_chunk])

A: You can try for example this:
import pprint

url_list = ["url" + str(i+1) for i in range(20)]
file_list = ["file" + str(i+1) for i in range(5)]
every_n = 3

result = [ (url_list[i], file_list[min(i // every_n, len(file_list)-1)])
           for i in range(len(url_list)) ]

pprint.pprint(result)

The output of above script:
[('url1', 'file1'),
 ('url2', 'file1'),
 ('url3', 'file1'),
 ('url4', 'file2'),
 ('url5', 'file2'),
 ('url6', 'file2'),
 ('url7', 'file3'),
 ('url8', 'file3'),
 ('url9', 'file3'),
 ('url10', 'file4'),
 ('url11', 'file4'),
 ('url12', 'file4'),
 ('url13', 'file5'),
 ('url14', 'file5'),
 ('url15', 'file5'),
 ('url16', 'file5'),
 ('url17', 'file5'),
 ('url18', 'file5'),
 ('url19', 'file5'),
 ('url20', 'file5')]

Remark:

*

*// integer division 5 // 2 = 2


text:
Q: OnMouseEnter в Lazarus Суть такова: я создаю примитивное приложение на форме, где есть три объекта: Label1, Label2, Label3.
Хочу сделать, чтобы когда я наводил мышь на Label1 то была видна только Label2.
Когда навожу на Label2, то видна Label3, а когда на Label3, то Label1.
так вот. захожу в события объекта. выбираю OnMouseEnter прописываю ей имя. нажимаю Enter, перехожу в функцию, там пишу

 Label1.Visible := False;
    Label2.Visible := True;
    Lavel3.Visible := False;

Когда захожу в свойства объекта Label2 то там это имя функции уже прописано и когда я нажимаю Enter то перехожу в ту же самую процедуру, пытаюсь поменять ее имя, а оно меняется и в двух других объектах(а мне нужны схожие процедуры).
Что мне делать?
A: Все просто.
Надо было присвоить имя процедуре автоматически.(вкладка "События", процедура OnMouseEnter и кнопка справа со значком "...")


text:
Q: getting EnvironmentError when running Pip Install beautifulsoup4 on Win10 while installing a python packet on the win10 machine i get fancy messages from the system!?
note - wanted to install bs4 (beautifulSoup) a python packet via pip
C:\Users\Kasper>pip -V
pip 10.0.1 from c:\program files\python37\lib\site-packages\pip (python 3.7)

C:\Users\Kasper>pip -V
pip 10.0.1 from c:\program files\python37\lib\site-packages\pip (python 3.7)

C:\Users\Kasper>pip install beautifulsoup4
Collecting beautifulsoup4
  Downloading https://files.pythonhosted.org/packages/cb/a1/c698cf319e9cfed6b17376281bd0efc6bfc8465698f54170ef60a485ab5d/beautifulsoup4-4.8.2-py3-none-any.whl (106kB)
    100% |████████████████████████████████| 112kB 2.1MB/s
Collecting soupsieve>=1.2 (from beautifulsoup4)
  Downloading https://files.pythonhosted.org/packages/05/cf/ea245e52f55823f19992447b008bcbb7f78efc5960d77f6c34b5b45b36dd/soupsieve-2.0-py2.py3-none-any.whl
Installing collected packages: soupsieve, beautifulsoup4
Could not install packages due to an EnvironmentError: [WinError 5] Zugriff verweigert: 'c:\\program files\\python37\\Lib\\site-packages\\soupsieve'
Consider using the `--user` option or check the permissions.

You are using pip version 10.0.1, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\Kasper>

Is there some thing wrong with the permissions!?
I thought that i have full admin-rights on this machine (wich runs in my office)
any ideas - look forward for any and all help.

A: I would suggest that you open your command prompt as Administrator and run it again.
If you want to install the package just for the current user, try using --user flag
pip install beautifulsoup4 --user


text:
Q: XL VBA Macro for inserting blank cells right based on criteria i.e. Column B contains a $ I need a macro to insert 2 cells moving existing data right. Sounds easy but been at it all day.
The issue is that the column B contains text and currency. If the cell contains currency, say $4661.52, I need to insert 2 cells, moving existing currency data right.
The length varies as does where the currency cells are. Late in the day
and confused.
Tried this and many variations :
Public Sub insertcells()
Const CLIENT As String = "B"
Dim Lastrow As Long
Dim i As Long
     Application.ScreenUpdating = False
      With ActiveSheet
         Lastrow = .Cells(.Rows.Count, CLIENT).End(xlUp).Row
         For i = Lastrow To 1 Step -1
             If Cells(i, CLIENT).Value2 Like "$*" Then
                 .Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
             End If
         Next i
     End With
Application.ScreenUpdating = True
End Sub

A: Check out this code.
Public Sub insertcells()
Const CLIENT As String = "B"
Dim Lastrow As Long
Dim i As Long
     Application.ScreenUpdating = False
      With ActiveSheet
         Lastrow = .Cells(.Rows.Count, CLIENT).End(xlUp).Row
         For i = Lastrow To 1 Step -1
             If Cells(i, CLIENT).Value2 Like "$*" Or IsNumeric(Cells(i, CLIENT).Value) Then
                 .Cells(i, CLIENT).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
                 .Cells(i, CLIENT).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
             End If
         Next i
     End With
Application.ScreenUpdating = True
End Sub


text:
Q: Kivy - Bad visual quality when using screen manager I want to use the screen manager inside a BoxLayout but my labels and buttons don't come out sharp when I do it this way. Anyone else have this problem?

Here is the .kv file I used:
<Root>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        id: main
        BoxLayout:
            id: menu
            orientation: 'vertical'
            Label:
                text: 'Placeholder'
        BoxLayout:
            id: menu_choice
            ScreenManager:
                Screen:
                    Label:
                        text: 'Placeholder'

    BoxLayout:
        orientation: 'vertical'
        size_hint: (1, 0.05)
        Label:
            id: status_message
            text: 'Test message'
            font_size: sp(11)

Where Root inherits from BoxLayout. I'm on OS X using kivy 1.8.0 and python 2.7.8
I'm actually getting the same quality when using a TabbedPanel:

I have a second monitor connected to my MacBook. And on the page for installation instructions on Kivy.org it does say that "there can be a limitation on some OS X with more than one monitor. The application will crash when you try to start it on the second monitor." But I get the same output when I disconnect the monitor and Kivy never actually crashes.


text:
Q: How to check presence of a URL parameter compared to an Array? Given these two sample urls and code.  How can I use the Array as a reference to check if the values are in the UTM parameter? (There will ONLY be one utm parameter at any given time).
example.com?utm=test
example.com?utm=test2
var partnerArray = ["test", 'test2'];
function findPartner() {
    if window.location.href.indexOf('?utm='(partnerArray)' !== -1) {
        //do something fun here
    }

I know my code is wrong - I haven't found example of using an Array to check for values in the URL.
Thank you.

A: Let's split this into two problems. First, getting the value of the utm parameter:
function getUTM() {
  return new URLSearchParams(window.location.search).get("utm");
}

Then, figuring out whether it's one of the known partners, and returning the one it might be.
const partnerArray = ["test", 'test2'];
function getPartner() {
  const utm = getUTM();
  return partnerArray.find(partner => partner === utm);
}

getPartner() will return undefined if the query string's utm parameter doesn't match either known partner.

A: Thanks all those that gave input.  Here's my solution for future readers with parts from the comments.
1st: Establish an Array:
var partnerArray1 = ["test1", 'test2'];
var partnerArray2 = ["test3", 'test4'];

2nd: Check what is in the URL's UTM parameter value
var urlParams = new URLSearchParams(window.location.search).get("utm");
3rd: Make a function to check the value against the Array:
function checkUTM() {
    if (partnerArray1.indexOf(urlParams) !== -1){
    //do some cool stuff here
    }

    if (partnerArray2.indexOf(urlParams) !== -1){
     //do some more cool stuff here
    }
}

Short of figuring out how to pass values into the function and check that, I went with the slightly more messy way, but it accomplished my goal.  If there are improvements to the above, please feel free to provide clear updated samples.


text:
Q: How to catch an error that is being reported on information stream? I am using Weird-Cmd that has been written by someone else. This command searches the database for things and accepts certain parameters for its -Filter.
If I pass a bogus filter parameter, it returns a message telling me there's no such filter parameter.
That message is reported on Information stream (6). How do I invoke this cmdlet inside a try/catch and catch this error that is being reported on Information stream.
I tried redirecting the stream but it turned out PowerShell doesn't redirect except to Output/Success.
I do not have access to Weird-Cmd so I can't change it. I am limited to PowerShell 5.1.
Here is the message I get:
System.Management.Automation.ParentContainsErrorRecordException: Cannot bind parameter 'Filter' to the target. Exception setting "Filter": ""BogusProp" is not a recognized filterable property. Valid property names are: Prop1, Prop2,...."

A: Assuming that Weird-Cmd is a cmdlet or an advanced function or script, use the common -InformationVariable parameter to capture the information stream's output:
try {
  Weird-Cmd -InformationVariable inf # Note: NO "$" before "inf"
  if ($inf) { throw $inf }
} catch {
  # ... handle the exception.
}

Otherwise - which includes invoking the Weird-Cmd via a script block ({ ... }), use redirection 6> to redirect the information stream to a temporary file:
try {
  Weird-Cmd 6>($tempFile = New-TemporaryFile)
  $inf = (Get-Content -ErrorAction Ignore -Raw $tempFile)
  $tempFile | Remove-Item -ErrorAction Ignore
  if ($inf) { throw $inf }
} catch {
  # ... handle the exception.
}

Note: If you simply want to relay the information-stream content as a  non-terminating error, use the Write-Error cmdlet, either instead of throw with try / catch or from inside the catch block:
Write-Error $inf

zett42 points out that there's an in-memory alternative to 6>$someFile, namely to merge the information stream (6) into the success output stream (1) with 6>&1, and to filter out information-stream output objects by their type, System.Management.Automation.InformationRecord - this assumes that Weird-Cmd does not report a terminating error:
$inf = Weird-Cmd 6>&1 |
       Where-Object { $_ -is [System.Management.Automation.InformationRecord] }

That said, it would be nice to have a way to directly capture a specific stream's output in a variable rather than having to use a file, along the lines of: 6>variable:inf
This potential future enhancement is the subject of GitHub issue #4332.


text:
Q: How to automate OpenID login with a google apps domain using DotNetOpenAuth I am trying to implement OpenId for an internal web app.  Our college is on Google Apps for Edu, so we have the suite of Google OpenID and OAuth exposed to us.
I would like my login page to have the standard username and password, and additionally a button on the side that will authenticate internal users to our app domain.
I have followed the example here http://www.dotnetopenauth.net/developers/code-snippets/programmatic-openid-relying-party/ but it seems that the rules are different for the google apps id than a general google id.
Any help or further documentation would be helpful.

A: I have the same problem as you.
For your Google Apps login, your relying party URL is  https://www.google.com/accounts/o8/site-xrds?hd=example.comsite-xrds?hd=example.com
Where you replace example.com with your URL.
However, As far as I can tell, dotnetopenauth does not handle the protocol extensions google uses when it returns.
However, using https://www.google.com/accounts/o8/id works perfectly fine.
Using this url, you pass off users to Google to login. Google will check for cookies and prompt for a login if required. if not it'll just confirm with the user that they want to associate their authentication with this site and pass you back.
Still trying to get dotnetopenauth to accept the new url: https://www.google.com/accounts/o8/site-xrds?hd=example.com