text:
Q: Uncaught ReferenceError: myFunction is not defined at HTMLInputElement.onkeyup Basically the same thing as
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onkeyup
But I am getting this error for some reason.
HTML
<nb-card>
  <nb-card-header>
    Enter your name:
  </nb-card-header>
  <nb-card-body>
    <input type="text" id="fname" onkeyup="myFunction()">
  </nb-card-body>
  <script>
    function myFunction() {
      var x = document.getElementById("fname");
      x.value = x.value.toUpperCase();
    }
    </script>
</nb-card>

Same error without the nebular library:
HTML
<html>
<body>
  Enter your name:
  <input type="text" id="fname" onkeyup="myFunction()">

  <script>
    function myFunction() {
      var x = document.getElementById("fname");
      x.value = x.value.toUpperCase();
    }
  </script>
</body>
</html>

Does anyone know why? Thanks.
I have tried many other stack overflow solutions and they do not work. I am hoping to not use JQuery. This should have worked but it doesn't. I follow the other W3 School examples and get the same error.

A: your code seems to work fine here.  What's the problem?

<nb-card>
  <nb-card-header>
    Enter your name:
  </nb-card-header>
  <nb-card-body>
    <input type="text" id="fname" onkeyup="myFunction()">
  </nb-card-body>
  <script>
    function myFunction() {
      var x = document.getElementById("fname");
      x.value = x.value.toUpperCase();
    }
    </script>
</nb-card>

A: This isn't how to code in AngularJS. Make use of the platform's baked-in functionality - like using ng-click,  ng-model and ng-keyup
In this case, I think the solution is as easy as using a CSS class to force the uppercase, but still, I hope this helps.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.fname = "";
    $scope.myFunction = function() {
      console.log($scope.fname)
    }
  }]);
.ucase {
  text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <nb-card>
    <nb-card-header>
      Enter your name:
    </nb-card-header>
    <nb-card-body>
      <input type="text" ng-model="fname" class='ucase' ng-keyup="myFunction()">
    </nb-card-body>
  </nb-card>
</div>


text:
Q: When creating a builder with a superclass, parent cannot return instance of child class If I am using the builder pattern to configure new objects I may have two classes like Game and HockeyGame (shown below). When I want to create a new HockeyGame, I get it's builder and start calling methods to configure the object as needed.
The problem I am running into is shown in the main function. Once I call one method from the super class it returns as an intance of Game.Builder, and I can no longer call any method from the child class.
What is the best way to deal with this?
Main.java
class Main {

    public static void main(String[] args){

        HockeyGame hg = new HockeyGame.Builder()
                .setScore(5)
                .setTimeLimit(3600)
//--------------------------------------------------------------------
                .setIceTemperature(-5) // Error! Cannot call setIceTempurature() on
                                       // an instance of Game.Builder
//--------------------------------------------------------------------
                .build();

    }
}

Game.java
public class Game{

    int score;
    int timeLimit;

    public Game(int score, int timeLimit) {
        this.score = score;
        this.timeLimit = timeLimit;
    }

    public static class Builder {

        int score;
        int timeLimit;

        public Builder setScore(int score) {
            this.score = score;
            return this;
        }

        public Builder setTimeLimit(int timeLimit) {
            this.timeLimit = timeLimit;
            return this;
        }

        public Game build() {
            return new Game(score, timeLimit);
        }
    }
}

HockeyGame.java
public class HockeyGame extends Game {

    float iceTemperature;

    public HockeyGame(int score, int timeLimit, float iceTemperature) {
        super(score, timeLimit);
        this.iceTemperature = iceTemperature;
    }

    public static class Builder extends Game.Builder {

        float iceTemperature;

        public HockeyGame.Buidler setIceTemperature(float iceTemperature) {
            this.iceTemperature = iceTemperature;
            return this;
        }

        public HockeyGame build(){
            return new HockeyGame(score, timeLimit, iceTemperature);
        }
    }
}

Thanks.

A: You need to use the getThis() trick that is prevalent in much fluent API code.
First you need to make your Game.Builder generic in itself:
public static class Builder<B extends Builder<B>>

Then you add a getThis() method:
public B getThis() {
    return (B) this;
}

Now you change your setters to return a B and return getThis() rather than this:
public B setTimeLimit(int timeLimit) {
    //...
    return getThis();
}

Your extension class also needs to be generic, in itself:
public static class Builder<B extends Builder<B>> extends Game.Builder<B>

Now you can use the code, and it will "remember" the intended type:
HockeyGame hockeyGame = new HockeyGame.Builder<>().setScore(10)
        .setTimeLimit(20)
        .setIceTemperature(-1)
        .build();

This final code looks something like:
public class Game {

    private final int score;
    private final int timeLimit;

    private Game(final Builder<?> builder) {
        this.score = builder.score;
        this.timeLimit = builder.timeLimit;
    }

    public static class Builder<B extends Builder<B>> {

        private int score;
        private int timeLimit;

        public B setScore(int score) {
            this.score = score;
            return getThis();
        }

        public B setTimeLimit(int timeLimit) {
            this.timeLimit = timeLimit;
            return getThis();
        }

        protected B getThis() {
            return (B) this;
        }

        public Game build() {
            return new Game(this);
        }
    }
}

public class HockeyGame extends Game {

    private final float iceTemperature;

    private HockeyGame(final Builder<?> builder) {
        super(builder);
        this.iceTemperature = builder.iceTemperature;
    }

    public static class Builder<B extends Builder<B>> extends Game.Builder<B> {

        private float iceTemperature;

        public B setIceTemperature(float iceTemperature) {
            this.iceTemperature = iceTemperature;
            return getThis();
        }

        @Override
        public HockeyGame build() {
            return new HockeyGame(this);
        }
    }
}

N.B: I have made the fields private final and also the main type constructors - this forces people to use the Builder.  Also, the constructor can take a Builder<?> and copy the variable from there - this tidies the code a little.

The actual hack is, as you may have noticed, here:
public B getThis() {
    return (B) this;
}

Here, we force a cast of the Builder to its generic type - this allows us to change the return type of the method dependant upon the specific instance being used.  The issue is, if you declare a new Builder something like the following:
public static class FootballGame extends Game {

    private FootballGame(final Builder<?> builder) {
        super(builder);
    }

    public static class Builder<B extends HockeyGame.Builder<B>> extends Game.Builder<B> {

        float iceTemperature;

        @Override
        public FootballGame build() {
            return new FootballGame(this);
        }
    }
}

This this will blow up at runtime with a ClassCastException. But the setter method will return a HockeyGame.Builder rather than FootballGame.Builder so the issue should be obvious.

A: Try something like this
You explicitely cast it back to a HockeyGame.Builder object and work with its own method(s) on it.
The problem you had is that setTimeLimit returns a Builder object (mother class) and so you can not use the child methods on it.
HockeyGame hg = ((HockeyGame.Builder)(new HockeyGame.Builder().setScore(5)
                                                              .setTimeLimit(3600)))
                                                              .setIceTemperature(-5)
                                                              .build();

Also, setIceTemparature should return a HockeyGame.Builder object to be able to build on it.
public Builder setIceTemperature(float iceTemperature) {
    this.iceTemperature = iceTemperature;
    return this;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sort an object array by two different values I have an object array
var arr= [  {vara:4, varb:0, varc:3}    {vara:1, varb:2, varc:0}    {vara:3, varb:1, varc:5} ..... ]

At first i want to sort the array by vara so i use
arr.sort(function(a, b){return a.vara-b.vara});

If the sorted array have equal values in vara parameter, i want to do a second sorting by varb that will only resort the objects with equal vara values and not all the array.
How is this possible?

A: How about something like:
arr.sort(function(a, b){
    if (a.vara === b.vara) {
        return a.varb - b.varb
    }
    return a.vara-b.vara;
});


text:
Q: Advanced custom field as CSS class I'm using WordPress with ACF, I need to use a custom field as the width of a CSS class.
I created a dynamic style with a variable:
<?php header("Content-type: text/css");
$scala = get_field('scala');
?>

#chart li .bar {
height: 10px;
background: #546a79;
width: <?php echo  $scala  ; ?> }

Unfortunately I can not see the result on the page, But if I put a precise value then it's works:
<?php header("Content-type: text/css");
$scala = '60%';
?>

#chart li .bar {
height: 10px;
background: #546a79;
width: <?php echo  $scala  ; ?> }

Obviously I already have registered the custom value in the post.

A: Can you add a custom class to the container of the content that you want to scale with a custom field on the post. Soemthing like a dropdown that you can set to "sixty" perhaps and then have the following code:
<div class="post-container <?php the_field('sixty'); ?>">

which will make the  div  look like this, when the class is activated:

And then style it like this:
.post-container.sixty {
  width: 60%
}


text:
Q: R and MATLAB returning different eigenvectors I'm missing something obvious, but here goes:
In R,
dput(M)
structure(c(-2.77555756156289e-16, 9.63770703841896e-16, 0, 9.63770703841896e-16,
10.6543192562307, 4.11228781751498e-14, 0, 4.11228781751498e-14,
275.591724761168), .Dim = c(3L, 3L), .Dimnames = list(c("", "",
""), c("", "", "")))

#thus M is

 -2.775558e-16 9.637707e-16 0.000000e+00
  9.637707e-16 1.065432e+01 4.112288e-14
  0.000000e+00 4.112288e-14 2.755917e+02

eig(M)
$values
[1]  2.755917e+02  1.065432e+01 -2.775558e-16

$vectors
             [,1]         [,2] [,3]
[1,] 5.428099e-34 9.045822e-17    1
[2,] 1.552173e-16 1.000000e+00    0
[3,] 1.000000e+00 0.000000e+00    0

But in MATLAB
[vv,ee] = eig(M)
% hand-copied so ignore the precision)
vv =
   1.0    -0.    -0.
   0      0      -1
   0      -1     0

ee =
 %diagonals only
0.0    275.59   10.6543

The eigenvalues match up with the  locations where abs(vv) == 1 ,  but the thing I don't understand is why some eigenvectors are negative one in MATLAB but not in R.
It makes a big difference, as I'm trying to port this MATLAB package, (in particular, parabolafit_direct.m and `parabolafit_directm.m' )  and the subsequent algorithms are sensitive to the sign of the values.  I checked, and the MATLAB package does produce the correct fitted output (parabolic curve to dataset), while my R-port does not, because of these sign differences.
So, why the difference, and what can I do to modify my R code to get the desired signs of the data?
EDIT: I continue to dig into the code to see if these two "negative one" values cancel out in the next set of equations, but haven't seen that yet.

A: Most of the important info is in the comments by Andras Deak.  To summarize: as we all (should) know,  eigenvalues and eigenvectors are only unique up to a multiplicative constant.  While in this particular case R and MATLAB happened to end up with differing signs,  all subsequent matrix operations on the eigenvectors will yield the same result (again,to within sign or constant value).
In my particular case, the final result essentially was:  one answer was a*x -b =0 and the other was -a*x + b = 0 .


text:
Q: Jitsi in Ionic? How to use jitsi in Ionic?
I have tried following code to integrate jitsi in Ionic, but it gives me the following error when I build the Android app.
Also, I have tried using capacitor-jitsi-meet but couldn't succeed.
    import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
    import { Plugins } from '@capacitor/core';
    import 'capacitor-jitsi-meet';
    const { Jitsi } = Plugins;

    @Component({
      selector: "app-jitsi-poc",
      templateUrl: "./jitsi-poc.page.html",
      styleUrls: ["./jitsi-poc.page.scss"],
    })
    export class JitsiPocPage implements OnInit {
      @ViewChild("videoConatiner") videoContainer: ElementRef;
      jitsi: any;
      options = {
        roomName: "my room ",
        configOverwrite: { startWithAudioMuted: true },
        interfaceConfigOverwrite: {
          SHOW_CHROME_EXTENSION_BANNER: false,
          SHOW_DEEP_LINKING_IMAGE: false,
          SHOW_JITSI_WATERMARK: false,
          SHOW_POWERED_BY: false,
          SHOW_PROMOTIONAL_CLOSE_PAGE: false,
          SHOW_BRAND_WATERMARK: false,
          JITSI_WATERMARK_LINK: "",
          SHOW_WATERMARK_FOR_GUESTS: false,
        },
      };

      constructor() { }

      ngOnInit() { }

      startMeeting() {
        this.options["parentNode"] = document.querySelector("#meet");
        // Setting parentNode option on init after the DOM has rendered
        this.jitsi = new (window as any).JitsiMeetExternalAPI("meet.jit.si", {
          ...this.options,
        }); // Jitsi running in local docker container
      }

    }

error
    Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
    Could not find org.jitsi.react:jitsi-meet-sdk:3.5.0.
    Searched in the following locations:

A: Have you followed the instructions to install Capacitor? https://capacitorjs.com/docs/getting-started
Next, I noticed you tried to activate the Jitsi web implementation, which won't work for native app implementation. The proper way of initiating a jitsi call on Android app is via the capacitor-jitsi-meet plugin, which is called using this syntax:
// On Capacitor 3
import { Jitsi } from 'capacitor-jitsi-meet';

// On Capacitor 1 and 2
import { Plugins } from '@capacitor/core';
import 'capacitor-jitsi-meet';

const { Jitsi } = Plugins;

const result = await Jitsi.joinConference({
   roomName: 'room1', // room identifier for the conference
   url: 'https://meet.jit.si' // endpoint of the Jitsi Meet video bridge
});

Please see the readme for the full installation instructions: https://github.com/calvinckho/capacitor-jitsi-meet


text:
Q: На объект сущности не могут ссылаться несколько экземпляров интерфейса IEntityChangeTracker, проблема в asp.net mvc 5 Есть модель книги
public class Book
{
    // id книги
    public int Id { get; set; }
    // название книги
    public string Name { get; set; }
    // автор книги
    public string Author { get; set; }
    // описаниек книги
    public string Description { get; set; }
    // жанр книги
    public string Genre { get; set; }
    // забронирована/не забронирована
    public BookState BookState { get; set; }
    // обложка книги
    public byte[] Picture { get; set; }
    // клиент
    public string Client { get; set; }
}

Модель состояния книги
    public enum BookState
{
    // книга свободна
    Free = 0,
    // книга забронирована
    Booked = 1,
    // книга выдана
    Issued = 2
}

И модель бронирования книги, для ведения учета книг в "библиотеке"
public class Booking
{
    public int BookingId { get; set; }
    public ApplicationUser User { get; set; }
    public Book Book { get; set; }
    public DateTime ReserveAt { get; set; }
    public DateTime? AcceptedAt { get; set; }
}

Использую систему Identity.
Проблема такова, что есть некий Task который отвечает за бронирование книги:
        public async Task<ActionResult> Reservation(int id)
    {
        var user = await UserManager.FindByNameAsync(User.Identity.Name);
        var book = db.Books.Find(id);

        if(book.BookState == BookState.Free)
        {
            book.BookState = BookState.Booked;

            db.Bookings.Add(new Booking
            {
                Book = book,
                User = user,
                ReserveAt = DateTime.Now
            });
               db.SaveChanges();
        }

        return RedirectToAction("Catalog");
    }

Как видно,он находит юзура по имени, книгу по id и проверяет состояние книги, после чего книга меняет свое состояние (BookState) и делает запись в таблицу Booking. Но при попытке сделать запись, выходит ошибка  - На объект сущности не могут ссылаться несколько экземпляров интерфейса IEntityChangeTracker из-за которой дальнейшая работа просто невозможно. Подскажите, что делать в данной ситцуации? Знаю, есть похожие вопросы на ruStackOverflow однако они мне никак не помогли. В проекте использовался подход CodeFirst.

A: Изменил модель Booking
    public class Booking
    {
        public int BookingId { get; set; }
        public string User { get; set; }
        public Book Book { get; set; }
        public DateTime ReserveAt { get; set; }
        public DateTime? AcceptedAt { get; set; }
    }

т.е. заменил public ApplicationUser User { get; set; } на public string User { get; set; }, так же заменил в контроллере значение user, получилось в итоге так:
    public ActionResult Reservation(int id)
    {
        var user = User.Identity.Name;
        var book = db.Books.Find(id);

        if (book.BookState == BookState.Free)
        {
            book.BookState = BookState.Booked;

            db.Bookings.Add(new Booking
            {
                Book = book,
                User = user,
                ReserveAt = DateTime.Now
            });

            db.SaveChanges();
        }

        return RedirectToAction("Catalog");
    }


text:
Q: Two different SQL Server with same collation show same decimal field in two different ways I have 2 different SQL Server installations with the same collation, "Latin1_General_CI_AS".
The 2 instances have same database, with same tables and same fields.
One of the field is a Decimal(18,4), and if in Sql Server Managment I show the records of the table, I see 2 different values.
In one instance I see a "comma" for the decimal separator, in the other one I see "dot" for the decimal separator.
Something like this:
124.4500
124,4500

The command:
SELECT @@Language

is the same for both instances ("us_english").
I do not know why I get 2 different values for the same field of the same table.

A: Likely the account you are using to connect is not defined at same way on both the instances.
I had similar issue with the same server by connecting with two different accounts. In my case the default language was set to "default" instead than "Italian" for one of the two accounts so only one of them was using the value from the global @@Language .
I also noticed that this kind of setting, in case you are working with ODBC, can be overridden at DNS level, in the same windows where you can specify the Database.


text: Q: How to Access Android/data folder in Android11 without using MANAGE_EXTERNAL_STORAGE permission IS there anyone who can help in accessing other Application directory/folder Under Android/data/. I want to put some .bin files in other Application folder. Please help. As in Android11 due to some restrictions 3rd party apps are not allowed to access other folder.


text:
Q: Mobile Angular Ui toggle not working I am trying to use mobile angular ui toggle and toggleable to make a side navigation.
my navigation div looks like this:

BLA BLA

I tried using a simple a tag to make it appear / disappear:
Side Menu

I have included mobile angular ui file and in my app configuration. still, it does not work.
my app initialization:
var myApp = angular.module('myApp', ['myApp.controllers','myApp.directives', 'mobile-angular-ui', 'luegg.directives', 'ngRoute', 'ngTouch', 'ngAnimate','wu.masonry']);

any suggestions what's the problem?

A: seems like the manuals were not up to date.
solved :)


text:
Q: How to split compound word in pandas? I have and document that consist of many compounds (or sometimes combined) word as:
document.csv
index  text
 0    my first java code was helloworld
 1    my cardoor is totally broken
 2    I will buy a screwdriver to fix my bike

As seen above some words are combined or compound and I am using compound word splitter from here to fix this issue, however, I have trouble to apply it in each row of my document (like pandas series) and convert the document into a clean form of:
cleanDocument.csv
index  text
 0    my first java code was hello world
 1    my car door is totally broken
 2    I will buy a screw driver to fix my bike

(I am aware of word such as screwdriver should be together, but my goal is cleaning the document). If you have a better idea for splitting only combined words, please let me know.
splitter code may works as:
import pandas as pd
import splitter ## This use enchant dict (pip install enchant requires)
data = pd.read_csv('document.csv.csv')

then, it should use:
splitter.split(data) ## ???

I already looked into something like this but this not work in my case. thanks

A: You use apply wit axis =1  :  Can you try the following
 data.apply(lambda x: splitter.split(j) for j in (x.split()), axis = 1)

I do not have splitter installed on my system. By looking at the link you have provided, I have this following code. Can you try:
def handle_list(m):
    ret_lst = []
    L = m['text'].split()
    for wrd in L:
        g = splitter.split(wrd)
        if g :
            ret_lst.extend(g)
        else:
            ret_lst.append(wrd)

    return ret_lst

dft.apply(handle_list, axis = 1)


text:
Q: Best practice for developing app extensions in iOS 8 beta I'm wondering what the best practices are when it comes to developing app extensions now during the beta of iOS 8. What I mean is that since XCode 5 doesn't support the entitlements and the targets required for an app extension (App groups, widget target etc) and XCode 6 doesn't support submitting to the appstore, is there a good way to make sure that we can both develop and deploy to the App Store, compile the old project etc?
Of course there is the SCM approach with just creating a branch but I'm wondering if there is any way to solve this in XCode?

A: It would seem that creating a duplicate target is the best way, thereby keeping the old target for old Xcode and using the new target for debugging the extension.


text:
Q: Git commits not ordered by commit date We have a build process set up to create product builds ordered by commit date, but it turns out that is not always the correct order?
Two recent commits:
Commit A
Author date:    22 hours ago (7/22/2019 16:56:46)
Commit date:    22 hours ago (7/22/2019 16:57:50)

Commit B
Author date:    22 hours ago (7/22/2019 16:57:22)
Commit date:    22 hours ago (7/22/2019 16:57:44)

That is the order they appear in the repository - commit B is last, and contains changes from commit A. Yet the first commit has a date 6 seconds later than the second one. As a result, the build system assigned build numbers in the wrong order.
Does this mean the commit date is not a reliable way to order commits?

A: There are several different points to be addressed here.
First, as you show, every commit has two date-and-time-stamps embedded in it.  One is the author date and the other is the committer date.  You can view both dates with git log using --pretty=fuller, for instance (there are other ways but this is simple and easy).
Next, commits can have parent / child relationships, as you mention in your second comment.  More precisely:

*

*Each commit has a unique hash ID.  The hash ID is, in effect, the "true name" of the commit.  git log generally prints these hash IDs, so that git log --pretty=fuller starts with commit <hash>.

*Each commit also records some number of parent hash IDs.  Most commits store one parent hash ID.  What this means is that each child commit knows who its parent is, even though the parent commits don't know who their children are.  In other words, the linkage goes only one way: from child, to parent.
The reason for the latter is that commits—in fact, all stored Git objects—are permanently frozen from the time they are created.  This is because a hash ID, which is what Git uses to name and find each object, is actually just a checksum of the contents of the object as stored in the Git object database.  If you take an object out of the database, fiddle with its contents in any way, and write that back, you get a new and different checksum.  The original object remains unchanged.  Anyone using the original hash ID gets the original object.
The way the git log command works is a little bit complicated, but it starts out pretty simple.  A branch name like master or develop or release simply holds one hash ID.  This hash ID locates one particular commit.  That one particular commit is the tip commit of the branch.  That is the definition of how branch names work in Git: whatever hash ID is stored in the branch name, that commit is the tip commit of that branch.  Git changes the stored hash ID so as to change which commit is the branch-tip:
... <-F <-G <-H   <--master

Here, the uppercase letters stand in for real hash IDs.  The name master holds the raw hash ID of the last commit in the branch.  Git uses that to find the commit itself: the hash ID in master is the key that Git looks up in its big database of "all objects in the repository", and commit H is the result.  Git reads commit H and finds that H's parent is the hash ID of commit G, so now git log can fish commit G out of the repository.  Commit G has its usual information—including the two date-and-time stamps, and as G's parent, the hash ID of commit F.
To add a new commit to the master branch, Git writes out a new commit—which gets some random-looking hash ID, but we'll just call it I—that has its two date-and-time stamps, and that has the hash ID of commit H as its parent.  Git gets the hash ID for H from the name master.  The writing-out of the new commit is what assigns it its unique hash ID.  Now that commit I exists in the repository, Git simply overwrites master with the new hash ID:
... <-F <-G <-H <-I   <--master

Hence, what git log does—at least for simple cases like this—is:

*

*Extract the hash ID for the current branch.

*Show that commit (with its date-and-time stamps).

*Follow that commit to its parent.  Show that commit.

*Follow that commit to its parent.  Show that commit.

*Repeat until you run out of commits.
The result is that the output of git log is in graph order, starting with the tip of the branch and working backwards.  The date-and-time-stamps stored in these commits don't matter.  There are more complicated cases for git log where they do matter, but let's start with this.  Fundamentally, git log works backwards, commit-by-commit, through the graph formed by the links that connect a child commit to its parent.
Who puts the date-and-time stamps into the commits?
By default, git commit creates a new commit with both timestamps set to "now".  But "now" is determined by your computer's clock.  If your computer's clock is wrong, the timestamps will be wrong.
You can override the author timestamp pretty easily: many Git commands, including git commit itself, take a flag, such as --date=date, to set whatever author timestamp you want.  Overriding the committer timestamp is a bit harder as there is no flag, but not actually hard because git commit reads environment variables.  The environment variable GIT_COMMITTER_DATE can be set to the same kinds of string values that the --date option accepts; setting this forces the committer timestamp to whatever value you like (within the range of dates Git can represent, that is).
When does git log sort by date?
There are two ways that git log gets into situations in which it "wants" to show more than one commit at a time.  One is when you tell git log which commits to show:
git log master develop

says, for instance, to show the tip commit of branch master and the tip commit of branch develop:
             I--J   <-- develop
            /
...--F--G--H   <-- master

Which one should git log show first?  Ideally, it might be J, since J goes back to I and then to H.  In practice, git log chooses whichever commit has the greater committer timestamp, unless you set various other git log options to override it.  In most cases, that is commit J and everything works nicely.
Another case occurs when your commit graph has merge commits in it.  A merge commit is simply any commit with two or more parents.  ("More" is rare, and not really special, nor especially useful; it suffices to consider the case of two parents.)  That is, suppose we have, at some point, this graph:
       I--J   <-- master
      /
...--H
      \
       K--L   <-- feature

While things are like this, in this repository, we git checkout master and then git merge feature.  If all goes well, the result is:
       I--J
      /    \
...--H      M   <-- master
      \    /
       K--L   <-- feature

Commit M here is a merge commit, which means it has more than one parent.  Its two parents are commit J—the old tip of master, before Git overwrote the name master with hash ID M—and commit L, which is still the tip of feature.  We can now safely delete the name feature because we can find commit L by starting at commit M and working backwards.
If we do delete the name feature, and maybe add another commit to master, we end up with:
       I--J
      /    \
...--H      M--N   <-- master
      \    /
       K--L

Now git log will start by showing us commit N.  Then it will move to N's parent M, and show us M.  Then it will ... well, now what?
The trick git log uses here—and with our git log master develop example too, actually—is that git log actually uses a priority queue.  This priority queue is, initially, totally empty.  You run:
git log ...

and give it a list of starting points.  If you don't give it any, git log picks the current branch's tip commit as the (single) starting point.  Git turns the branch name(s), if any, into their hash IDs, and stuffs all the hash IDs into this priority queue.
Now that the queue has some entries, Git takes the highest priority commit out of the queue.  By default, that's the one with the highest committer timestamp.  But if the queue only has one commit in it, Git just takes the one commit.  There's nothing to compare: there's just the one commit in the queue!  Note that this takes the only commit that's in the queue, out of the queue, so that now the queue is empty.
That's the commit that git log will show now.1  Git fetches the actual commit out of the all-objects database and shows it.  Fetching the commit also gives git log the hash IDs of the parent commit(s).  Git puts those into the queue.2  If there's just the one parent, and the queue got emptied by pulling out its one entry, now there's just one entry in the queue again.
So, for a simple chain that starts at some branch tip and works backwards without any merges, this queue algorithm just shows each commit, one at a time, in the backwards order that Git uses.  The last commit comes out first, and the first one comes out last.
But when Git hits a merge commit like M, Git puts both parents into the queue.  Now the queue has two entries, so now its priority sorting takes effect.  Again, the default priority is that newer commits—those with higher committer timestamps—go to the front of the queue.  Git will show the later (by committer date) commit next, and put its parent(s) into the queue.  If this commit's parents have higher priority than any other commits in the queue, those parents get shown next.
In other words, the actual git log loop is not just show commit, show parent, show parent, ... but rather:

*

*Put all command-line commits into the queue.

*While the queue is not empty:

*

*Pick the next commit from the queue.

*Show it (or not, with details depending on git log options).

*Put its parent(s) into the queue (with details depending on git log options).

The queue itself determines the order in which commits get shown, but the parent linkage determines the ability for commits to get into the queue.  You prime the queue with your command-line git log command.  After that, the parent linkages and queue mechanics take over.

1Depending on options to git log, maybe it won't actually show the commit.  Let's leave that for other questions, though.
2Again, there can be complications here, but let's stick with the simple model.  Just remember that git log can do what Git calls History Simplification, which can omit some legs of branches, as well as not bother to show some commits.  Also, Git won't show the same commit twice in one git log, so if this would put an already-shown commit into the queue, it doesn't put it in now.

Conclusion
While git log does default to using committer timestamps to sort commits, that happens only if/when there are multiple entries in the "to be shown" queue.  Each commit's parent hash IDs get put into the queue at the time the commit gets shown.  So for simple linear chains, git log just walks those chains in their internal, backwards order.  It's mainly at merges where the sort order becomes important (or, of course, if you use more than one branch name, or use --all to look at all branches).
The date-and-time-stamps can be wrong (because the computer's clock was wrong) or spoofed (on purpose, for good or bad reasons).  So even if there's nothing malicious going on, you cannot rely on these.
The --graph option to git log, which draws crude ASCII representations of the parent/child relationships, also forces --topo-order, which changes the priorities in the priority queue.  Under --topo-order, a parent commit only gets shown after all of its children that will get shown, have been shown.


text:
Q: Chrome extension that can open URLs There are some extensions for Google Chrome browser - History 2, Better History Manager, etc. I need this one, but with feature of open URLs of founded via search masks. For example, I open my history with this extension and type 'youtube.com/watch'. So I see Youtube URLs from my history. Now, by default, I must open each of them by hands. Is there such an extension, with 'Open these URLs in tabs' or something like this?
Thanks.


text:
Q: Can Scrum and Project Management live together? Can Scrum and Project Management live together?
Can you take the best of both worlds or will combining these two methods?

A: A few things to consider:

*

*Scrum is about empowering the team as opposed to command and control management style.

*There is no manager in Scrum, there is a ScrumMaster which is a servant leader.

*The ScrumMaster is responsible for the Scrum process, making sure it is used correctly and maximizes its benefits.

*The ScrumMaster has to remove impediments so that the team can do his job in a productive way.

*Scrum implements transparency with a minimal set of practices/roles/ceremonies and there is no real paperwork.

*There is no real PMO type work in Scrum, most of PMO work is (considered as) waste.

So please, keep your PM habits away :)
And during an adoption, I'd recommend to do it as in the book (Shu), don't try to adapt it for now (Ri) (see Alistair Cockburn on Shu Ha Ri). I wouldn't even consider things like Scrumban (a modified version of Scrum using Kaban for continuous flow, no more iterations) at the start.
PS: Agile methods have all been influenced by the Lean movement (most, if not all, Agile manifesto signatories had The Machine That Changed The World in their shelves). Some could say Agile methods are a transposition of lean concepts (for new product development) to software development; others would say Agile and Lean share the same theory (see for example Jeff Sutherland's article The First Scrum: Was it Scrum or Lean?). To me, there are obvious similarities (it would be easy to map the whole Toyota Production System "House" on Agile practices) and I find Lean useful to understand how Agile works and how to implement an Agile process efficiently. So I use Lean as an as an additional toolbox. But to me, Scrum has already everything to make your development process lean, if well implemented. So there is no need to mix it. Just apply it (Shu).

A: Yes, Scrum and the PMO can live together. They're concerned with different things though, so the edges where the two meet are going to have to give a little. There will be some conflict at the intersection. Traditional PMBOK approaches are a poor fit to product development domains like software development, but there's quite a bit of smart statistical controls in the PMBOK, and skilled project managers who can be taught to manage flow rather than schedule are precious.
Neither Scrum nor Lean nor the Toyota organization suggest that either hierarchy or directed authority are off-limits. The definition of "Self-Organization" has been significantly stretched by software developers over the years until it has become largely indistinguishable from "Self-Determination", which was never the intention.
Toyota, for example, is a very hierarchical organization that depends very much on command and control. The difference is that it's a Learning Organization and managers at Toyota are required to have mastery of the work done in their purview, and have a duty to teach that work to workers. Team members at Toyota who envision possible improvements to their work and to the process are coached by their managers through the scientific process to prove their ideas. It helps that the process isn't shaped to fit the organization, but that the organization shifts to fit a process that is continually improved.
There is always an element of command and control in any organization. Even Scrum teams are subject to it. Even if a work team itself is perfectly flat, a Product Owner can still call the ball. Software teams have seniors and juniors, and their opinions are not perfectly equal. On Lean teams, managers are expected to be masters of the work, or have, as Toyota calls it, "towering technical competence". If management isn't skilled or is too far from the work, then they'll likely make bad decisions about the work. This is the real problem, and Self-Directed Work Teams (SDWT) are a predictable result of workers seeking to insulate themselves from poor management. SDWT is not the best answer, but it might be the limit of what an organization might achieve.
And finally, Scrum is not a project management methodology - at least not from the perspective of the rigor of the PMBOK or of Lean. But then, the application of the PMBOK to software development without significant modification to account for the nature of product development is often a fool's errand, so efforts to displace the PMBOK on software teams is understandable.
At best, Scrum is a timebox planning methodology. That's still valuable if it's the thing you need, but there's nothing inherent in software work management that suggests you need timeboxes like sprints and iterations. In fact, the upwelling of interest in iteration-less approaches like Kanban and Flow-Based management are a testament to this.
In the end, there a heck of a lot of orthodoxy built up around Scrum now that wasn't introduced by Scrum's founders and leaders, and often isn't supported by them. The same can be said about how PMOs operate. Focus on the principles of flow and learning cultures and you might be able to avoid the blind alleys and myths that gather around methodologies once they've been in the mainstream for five years or so.

A: Has anyone tried to incorporate different ideas (scrum, six sigma, pmp, lean?)
Essentially all of the above derive from the Japanese Quality Movement in the early 1980's.
It's all about increasing quality by reducing waste, called Muda in Japan
Lean was Toyota's implementation of the Quality Philosophies
and Six Sigma was General Electric's attempt to Americanize Lean based on corporate culture of the day.
Fast forward 20 years and the IT industry have realized that all this 'lean' thinking is a great idea for building better quality software, faster.  In what has been labelled Agile.
XP (extreme programming) and SCRUM are just two different implementations of Agile techniques.
Traditional management and software management is coming up against these new ways of thinking.
You can't have it all. Either your focus is on command and hierarchy (DO AS YOUR TOLD, traditional approach) vs Collaboration and working together to reduce wastes and deliver amazing things to customers (LETS DO IT TOGETHER, new model).
If you want to go deeper on this, the best approach is to read back on the original LEAN philosophies and then see how you think they can best be applied to project management. Many of best project management ideas were already considered as part of the original Lean movement, read the book 'The Toyota Way' and look into Lean that is where you can find your own answers.
Google: the seven types of muda for a start.

A: Your question doesn't make sense since scrum is a project management framework but here are some things to consider:

*

*Quality is the sole responsibility of the Team; not any PM.

*Not sure what you mean by "artifacts", but the few scrum has (backlog, burndown) are maintained by the PO and Team under the guidance of the ScrumMaster.

*There were no "best parts" to waterfall to want to consider continuing to use once you embrace Agile.

*There is no "paperwork" in scrum; its considered waste.

*People try to combine things all the time.  But most of the time they get the WORST of all worlds; not the best.  Most mistakes teams make in implementing scrum is to make excuses for why they can't do it the right way.  Then they claim it would be better to combine in something else and just make a mess of the whole thing.

A: I think you are going it from the wrong side.
First you need to know what kind of team you have. Then start from that knowledge and use the appropriate methodology for your team. Rather than trying to use some methodology for your team. Do a methodology for your team. That means see what they are comfortable doing and what they think would benefit all of them.
For example: Usually when a team failed using RUP, it wasn't because they didn't follow the guidelines, but because they tried to follow all of them.
Generally I think it's better if developers don't have to do paperwork and logistics. Either they are bad at it or they would be more productive doing development.

A: Found this useful link today, regarding The software industry has an appaling record for project delivery. Which address your exact question.
Suggest you browse around this site to get more of an idea:
http://behaviour-driven.org/SoftwareIndustryRecordOfFailure
The above the wiki for the very excellent Dan North who proposed the idea of Behaviour Driven Design (Premise: The way we think depends on the language we use and this can be applied to software also).

A: Well, first of all, Scrum is a project management process, so asking if Scrum and project management can coexist is like asking if water and H2O can coexist.
Second, the PMBOK defines the project manager role as having responsibility for the success of a project. Similarly, in Scrum the Product Owner is responsible for ROI, so the responsibilities of these roles are similar even if their duties are different. Scrum eschews a command-and-control management structure, emphasizing the need for self-managed and self-empowered teams that collectively make commitments and own delivering on those commitments under the principle that the people who do the work make and own the commitment... no responsibility without authority. In Scrum, the Product Owner provides guidance to the team via the product backlog prioritization and by the defined acceptance criteria for each backlog item ("Here's what I need done and here's the functionality that must exist for me to be happy"). The Product Owner also has the final say as to whether something is done or not; if the team doesn't complete a backlog item to the Product Owner's satisfaction for any reason then the Product Owner can reject the work. I'd say that makes the Product Owner a very powerful and important role in Scrum... IMO the most important role in terms of project success.
You might want to read this blogpost on selecting the Product Owner for more information on the Product Owner role.

A: I think the way I read your post is that the PM does 2 things:
1) Creates artifacts necessary for the business (like compliance)
2) Manage the project
As far as #2 goes, that job becomes encompassed in the PO and SM roles. The PM continuing to do it will add confusion and hurt the process.
As for #1, that is a vital role. If the business needs this, why not add the creation of these artifacts as part of the definition of "done" and add them to the team as a member who performs this specialized task. Alternatively, you could do this outside Scrum with no one even aware that it's happening, then perhaps providing those artifacts to the PO.

A: Scrum is project management, just not the way project managers do it, but as Scrum does it. In short, Scrum does the compelte opposite of what people think of and are tought about project management. So, from that angle, I would say no.
On the other hand, project managers can be very efficient Product Owners.

A: The answer is an absolute YES.
Great question by the way.
More detailed information on this can be found here: http://www.blog.pmmetrics.com/#!SCRUM-Traditional-Project-Management-Chaos-in-IT-Industry/uiho7/577428320cf2e26a9986aa33


text:
Q: How do i get values of elements in slice of interface? I have the following struct
type response struct {
        Symbols    []struct {
                Status                     string   `json:"status"`
                Symbol                     string   `json:"symbol"`
                BaseAssetPrecision      int64  `json:"baseAssetPrecision"`
                BaseCommissionPrecision int64  `json:"baseCommissionPrecision"`
                Filters                 []struct {
                        FilterType string  `json:"filterType"`
                        MaxPrice   float64 `json:"maxPrice,string"`
                        MinPrice   float64 `json:"minPrice,string"`
                        TickSize   float64 `json:"tickSize,string"`
                } `json:"filters"`
        } `json:"symbols"`
        Timezone string `json:"timezone"`
}

I will like to iterate over response to get the values of certain elements deep into the struct

*

*How do i get the value of Symbols => Symbol?

*How do i get the value of Symbols => Filters => MaxPrice?

I know timezone works fine but not sure how to get symbol and maxPrice
var data []response

for _, r := range data {
    fmt.Println("timezone: ", r.Timezone)
    fmt.Println("symbol: ", r.Symbols.Symbol) // how???
    fmt.Println("maxPrice: ", r.Symbols.Filters.MaxPrice) // how???
}

and looks something like this
{
    "timezone": "UTC",
    "symbols": [{
            "symbol": "TESLA",
            "status": "TRADING",
            "baseAssetPrecision": 8,
            "baseCommissionPrecision": 8,
            "filters": [{
                    "filterType": "PRICE_FILTER",
                    "minPrice": "0.00000100",
                    "maxPrice": "922327.00000000",
                    "tickSize": "0.00000100"
                },
                {
                    "filterType": "PERCENT_PRICE",
                    "multiplierUp": "5",
                    "multiplierDown": "0.2",
                    "avgPriceMins": 5
                },
                {
                    "filterType": "LOT_SIZE",
                    "minQty": "0.00010000",
                    "maxQty": "100000.00000000",
                    "stepSize": "0.00010000"
                },
                {
                    "filterType": "MIN_NOTIONAL",
                    "minNotional": "0.00010000",
                    "applyToMarket": true,
                    "avgPriceMins": 5
                },
                {
                    "filterType": "ICEBERG_PARTS",
                    "limit": 10
                },
                {
                    "filterType": "MARKET_LOT_SIZE",
                    "minQty": "0.00000000",
                    "maxQty": "891.04020423",
                    "stepSize": "0.00000000"
                },
                {
                    "filterType": "MAX_NUM_ORDERS",
                    "maxNumOrders": 200
                },
                {
                    "filterType": "MAX_NUM_ALGO_ORDERS",
                    "maxNumAlgoOrders": 5
                }
            ]
        },
        {
            "symbol": "AAPL",
            "status": "TRADING",
            "baseAssetPrecision": 8,
            "baseCommissionPrecision": 8,
            "filters": [{
                    "filterType": "PRICE_FILTER",
                    "minPrice": "0.00000100",
                    "maxPrice": "922327.00000000",
                    "tickSize": "0.00000100"
                },
                {
                    "filterType": "PERCENT_PRICE",
                    "multiplierUp": "5",
                    "multiplierDown": "0.2",
                    "avgPriceMins": 5
                },
                {
                    "filterType": "LOT_SIZE",
                    "minQty": "0.00010000",
                    "maxQty": "100000.00000000",
                    "stepSize": "0.00010000"
                },
                {
                    "filterType": "MIN_NOTIONAL",
                    "minNotional": "0.00010000",
                    "applyToMarket": true,
                    "avgPriceMins": 5
                },
                {
                    "filterType": "ICEBERG_PARTS",
                    "limit": 10
                },
                {
                    "filterType": "MARKET_LOT_SIZE",
                    "minQty": "0.00000000",
                    "maxQty": "891.04020423",
                    "stepSize": "0.00000000"
                },
                {
                    "filterType": "MAX_NUM_ORDERS",
                    "maxNumOrders": 200
                },
                {
                    "filterType": "MAX_NUM_ALGO_ORDERS",
                    "maxNumAlgoOrders": 5
                }
            ]
        }
    ]
}

How do i iterate over the

A: Your target structure for un-marshalling your JSON is incorrectly defined. If you take a look at your JSON structure, its an object type with a symbols being an array type. The equivalent Go representation would be a type struct with a slice of symbol records.
Your function should be written as
var data response
if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
    panic(err)
}
for _, rec := range data.Symbols {
    fmt.Println(rec.Symbol)
    for _, filter := range rec.Filters {
        fmt.Printf("%f\n", filter.MaxPrice)
    }
}

https://go.dev/play/p/5oxJfYx_61M


text:
Q: C++ (function) template that return its unique argument without copying it for certain types I have a function value(x) which is overloaded for many types such that:
double value(double x) { return x; }
double value(MyType x) { return x.value(); }
SomeContainer<double> value(SomeContainer<double> x) { return x; }
SomeContainer<double> value(SomeContainer<MyType> x) { ... }

where MyType is actually a number with a gradient vector with respect to a set of parameters.
for use in generic (template) programs.
I want to define:
Matrix<double> value(Matrix<double>)
Matrix<double> value(Matrix<MyType>)

I am using Eigen matrices and this is my current implementation of the first function:
template < typename Derived,
    typename std::enable_if< std::is_floating_point< typename Derived::Scalar >::value, int >::type = 0 >
Derived value( const Eigen::MatrixBase< Derived >& matrix )
{
    return matrix;
}

The problem is that this seems inefficient unless in possible cases where the compiler can figure out that the result/argument are not being modified and elude the copy. I also cannot return a reference to the argument since it is a local/temporary.
Basically what I would like is for value(x) to be compiled as the argument expression itself if the argument is a Matrix of double/float. I don't see how I can achieve this with a function template and a macro would not allow for specialization.
What could be done to avoid the copy?
EDIT March 22, 2019:
If I replace the return type by
const Derived &

I get the following GCC warning:
warning: returning reference to temporary [-Wreturn-local-addr]

in the following code:
Matrix33 m;
m << 1, 2, 3,
     4, 5, 6,
     7, 8, 9;
std::cout << m << std::endl;
std::cout << value(m) << std::endl;

and the value(m) printout is garbage.
Also I am now thinking more and more this would be a bad idea to "return the object itself" because it is going to be used in generic code:
 auto m = value(Mx)

where Mx is a Matrix of X (template parameter) and m is a double matrix.
Having different semantics (stealing the object in case X is double and creating a separate object in other cases) could lead to many programming mistakes.
Another possibility would be to return proxy objects.
The best however would be for the compiler to see when a copy is not needed because nothing is being changed. However this does not seem to be the case: my benchmark to compare
  Matrix<double,3,3> M = ...
  norm(M)

and
  Matrix<double,3,3> M = ...
  norm(value(M))

shows that the second is a bit slower in a release (optimised) build.

A: You need to return matrix.derived() if you want to have a reference to the encapsulated type:
template < typename Derived,
    typename std::enable_if< std::is_floating_point< typename Derived::Scalar >::value, int >::type = 0 >
const Derived& value( const Eigen::MatrixBase< Derived >& matrix )
{
    return matrix.derived();
}

Regarding value(Matrix<MyType> const&), you can implement that in a way that it returns just a view, essentially like this (requires C++14, or some more implementation work):
template < typename Derived,
    typename std::enable_if< std::is_same< typename Derived::Scalar, MyType >::value, int >::type = 0 >
auto value( const Eigen::MatrixBase< Derived >& matrix )
{
    // If `x.value()` returns by value, better use `unaryExpr` instead of `unaryViewExpr`:
    return matrix.unaryViewExpr([](const MyType& x){ return x.value();} );
}

Godbolt-Link: https://godbolt.org/z/qcYKnw
No warnings are generated and both foo1 and foo2 just tail-call the norm function. foo3 has some small overhead, which likely would get optimized away if norm was inlined.


text:
Q: R counting instances of a specific value I have a data.frame as below
df <- read.table(header = T, text = "Item.Nbr supply demand
1   82078-002          1  1
2   82078-007           2 0
3   82078-007          4 0
4   82078-007           0 0
5   82078-007           0 7")
> df
   Item.Nbr supply demand
1 82078-002      1      1
2 82078-007      2      0
3 82078-007      4      0
4 82078-007      0      0
5 82078-007      0      7

I want to count how many times 0 supply and demand occurs by Item.Nbr, I also want to know how many times both the supply and the demand are 0 by Item.Nbr
   Item.Nbr 0_supply 0_demand 0_both
1 82078-002      0      0       0
2 82078-007      2      3       1

A: Using base R aggregate:
aggregate(. ~ Item.Nbr, data=transform(df, both=supply+demand), FUN=function(x) sum(x==0) )
#or
aggregate(
  cbind(supply,demand,both=supply+demand) ~ Item.Nbr, data=df, FUN=function(x) sum(x==0)
)

#   Item.Nbr supply demand both
#1 82078-002      0      0    0
#2 82078-007      2      3    1

Or in dplyr if that's your bag (with a nod to @akrun):
df %>%
  mutate(both= supply+demand) %>%
  group_by(Item.Nbr) %>%
  summarise_each(funs(sum(!.)))

#Source: local data frame [2 x 4]
#
#   Item.Nbr supply demand both
#1 82078-002      0      0    0
#2 82078-007      2      3    1


text:
Q: Cognito confirmation code timeout I'm registering my user on AngularJS with Cognito from Amazon WebService.
I have a very strange bug :
If users directly try to confirm them account with the verification code received by email they always have this error message : "ExpiredCodeException: Invalid code provided, please request a code again" eventhough them account is well confirmed in the user pool...
But If they register themselves and they wait few minutes to try to confirm them account its works perfectly !
This is how I confirm the verification code :
confirmRegistration: function(verificationCode, username, _poolData) {
    var deferred = $q.defer();
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(_poolData);
    var userData = {
            Username : username,
            Pool : userPool
        };
    cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.confirmRegistration(verificationCode, true, function(err, result) {
            if (err) {
                    alert(err);
                    deferred.reject('confirmation failled.');
            }
            deferred.resolve('successfully confirmed.')
    });
    return deferred.promise;
},

How could I fixe it ?
Where is from this problem ?
Do there is a timeout to set somewhere ?


text:
Q: Perl: how do i get creation date and time of a few folders? I'm actually new in perl.
I would like to know how do I get the creation date and time of a folder(or maybe more than 1)?
I have searched online and only modification time appears.
Is there anyway to do it?
thanks in advance!!!

A: It depends on the specific file system type.  On POSIX systems, creation date is not generally available - all you can get is content modification, metadata modification, and access times. Some systems, such as the HFS+ file system on Mac OS X systems, do provide a creation date, but since it's not a standard feature, there's no standard API to get it, and you will likely have to take advantage of filesystem-specific, or at least platform-specific, code.


text:
Q: Keep MathKernel Running In Background - Speed Up Execution Time Background: I'm running Debian on a remote server with Mathematica installed.  I have several dozen small mathematica files that are run in cron jobs at unpredictable intervals and updated based on a web interface.  I'm trying to get  faster response times when I run the smaller files.
Question: For Example I have file.m which contains(This is just an example)
Export["/home/rob/Desktop/eq.png",Sum[1/2,{x,i}]]

If I setup a cron job to run the following
time MathKernel -noprompt -script /home/rob/Desktop/file.m

I get a real response time of 6.31.
But now if I ssh into the server and run MathKernel and the following
AbsoluteTiming[Export["/home/rob/Desktop/eq.png",HoldForm[Sum[1/2,{x,i}]]]

the script returns 1.13.
The start up time definitely appears to be the issue 6.31 vs 1.13.
So what is the best way to keep MathKernel running it the background so it can periodically run file.m?
I would like to avoid using CreateScheduledTask because of the extensive rewrite that would be needed.
EDIT:This and this are clunky but should work.

A: Spawn1701D's idea to use $IgnoreEOF is interesting, but unfortunately this flag doesn't work at all in version 9, and it doesn't work when reading from files in version 8.
Instead we can use the tail Unix utility to prevent Mathematica from stopping to read input.

*

*Create a pipe: mkfifo mmpipe

*Execute tail -f mmpipe | math.  tail will keep feeding Mathematica from whatever is written to mmpipe.

*Pipe input to mmpipe, e.g. echo 1+1 > mmpipe.  Mathematica will execute it.  You can do this as many times as needed.
Just make sure that every input you give Mathematica is complete and correct.  An unclosed bracket could make this approach fail.

A more robust solution would use MathLink to feed expressions to Mathematica (this is what the Front End does).  This would take more work to implement.

EDIT: You'll find some more information about this method and its shortcomings in this thread.

A: You have to set the variable $IgnoreEOF to True. Actually as the first job you can give the command
MathKernel -noprompt -script /home/rob/Desktop/init.m

where in init.m you have the command
$IgnoreEOF = True


text:
Q: Trouble installing mssql extensions for PHP We're using a MSSQL db at work and I want to be able to write PHP scripts that fetches data directly from the db to my local MAMP environment. I've tried installing pdo_sqlsrv and sqlsrv using Homebrew and I've tried compiling the extensions on my own using PECL commands, but in both cases it has ended unsuccessfully with the error message:
fatal error: 'sql.h' file not found
I've been googling this problem all day and can't seem to find a solution that I can get to work/understand. I'd be grateful for any help or hints.
Computer: Macbook Pro 2018 (macOS 10.13.6)
Local environment: MAMP PRO 4.5 (PHP version: 7.2.1)

A: I found the solution here: https://github.com/Microsoft/msphpsql/issues/198
I was missing tools provided by unixodbc, so:
brew install unixodbc

...provided the .h file(s) I was missing. The PECL installer was then able to locate the required libraries. In case it wouldn't have worked, I would have tried:
sudo CXXFLAGS="-I/usr/local/opt/unixodbc/include" LDFLAGS="-L/usr/local/lib" pecl install pdo_sqlsrv
sudo CXXFLAGS="-I/usr/local/opt/unixodbc/include" LDFLAGS="-L/usr/local/lib" pecl install sqlsrv

...as suggested in the link.


text:
Q: Caron accent in the bibliography causes a microtype error I'm getting the microtype-related error ! Argument of \MT@res@a has an extra }. when trying to compile a BibLaTeX bibliography that contains a caracter with a caron accent (\v{a}, i.e., ǎ).
Here's a minimal example (file microtype.tex):
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{microtype}
\usepackage{biblatex}
\usepackage{filecontents}
\begin{filecontents}{microtype.bib}
@Article{         ref,
  author        = {Name, \v{a}},
}
\end{filecontents}
\bibliography{microtype.bib}
\begin{document}
\cite{ref}
\printbibliography
\end{document}

When compiling this file as follows:
pdflatex microtype
biber microtype
pdflatex microtype

I get the following error:
(/usr/share/texlive/texmf-dist/tex/latex/biblatex/lbx/english.lbx)
(./microtype.aux) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-cmr.cfg
) (./microtype.bbl)
! Argument of \MT@res@a has an extra }.
<inserted text>
                \par
l.16 \end
         {document}
?

Any ideas about how to fix this problem? Thanks a lot in advance!
The problem still occurs if I run biber --output-safechars microtype. Oddly enough, the problem does not happen with other accents, i.e., the document compiles fine with \'{a} instead of \v{a}. The error I'm having was also mentioned in another question but there are no specific insights there.

A: The error seems to be similar to the one described in Biber 2.4, microtype, and special characters
The workaround seems to consist in fixing the definition of \ifempty:
\begin{filecontents}{\jobname.bib}
@Article{ref,
  author = {Name, \v{a}},
}
\end{filecontents}

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{microtype}
\usepackage{biblatex}
\addbibresource{\jobname.bib}

% fix the bad definition of \ifempty
\makeatletter
\def\ifempty#1{%
  \protected@edef\z{#1}\expandafter\ifblank\expandafter{\z}%
}
\makeatother

\begin{document}

\cite{ref}

\printbibliography

\end{document}


text:
Q: ffmpeg unable to open mipi camera I am trying to use ffmpeg to open mipi camera but it gives the following error
video4linux2,v4l2 @ 0x55a6df3790] Not a video capture device.
/dev/video0: No such device
However, when I use VLC it works fine.
I am not sure what is wrong with the ffmpeg here. Error while opening camera

A: Are you sure the device type is "Video Capture"?
I have same issue but My device type is "Video Capture Multiplanar".


text:
Q: PHP ini sessions.save neither lifetime are not working Original issue
session override in .htaccess, and even php ini_set not working - I made and changed .php INI settings file , I changed the lifetime to 60 seconds and changed the session.gc_divisor 1 1 to 1 , along with session.gc_probability 1 1 (which worked as I  chcked doing phpinfo() ) - After 60-ish seconds I refreshed the browser and was logged out....I put then put 3600000 seconds - I was logged out as usual.... approx 10 minutes of being idle after logging in.
session.cookie_lifetime 0 0
session.cookie_path / /
session.cookie_secure Off Off
session.entropy_file /dev/urandom /dev/urandom
session.entropy_length 32 32
session.gc_divisor 1 1
session.gc_maxlifetime 3600000 3600000
session.gc_probability 1 1
session.save.path /tmp

I attempted to change the save path to a local hard disk (in .htaccess)... as suggested by a user.

Unknown: session_start():
  open(D:\sessions/sess_1l1en5ku2n57aeoo6mvsso9oh6, O_RDWR) failed: No
  such file or directory

also second error

Failed to write session data (files).

All I am wanting to achieve is be able to stay logged in for a long long period of time - even if idle - of of course if the browser is closed...then I will be logged out
echo $_SERVER['DOCUMENT_ROOT']; outputs:

/websites/123reg/LinuxPackage24/fo/cu/s_/focus.uk.com/public_html

A: You need to create a folder within your FTP space of your hoster. According to your comments this should be located at /websites/123reg/LinuxPackage24/fo/cu/s_/focus.uk.com. If you cannot write to that home folder, you need to create a folder within the document root folder /websites/123reg/LinuxPackage24/fo/cu/s_/focus.uk.com/public_html and ensure you deny web access via .htaccess.
Configure the session.save_path setting to your own created folder. Within the PHP scripts it would be e.g.:
session_save_path(realpath($_SERVER['DOCUMENT_ROOT'] . '../sessions'));

or
ini_set('session.save_path', realpath($_SERVER['DOCUMENT_ROOT'] . '../sessions'));

or, if within the public folder, just
session_save_path($_SERVER['DOCUMENT_ROOT'] . '/sessions');

or
ini_set('session.save_path', $_SERVER['DOCUMENT_ROOT'] . '/sessions');

Ensure as well that PHP has write permissions to that folder. In the worst case you need to make it world-writable on shared hosting.


text:
Q: Gradle, SonarQube plugin and project names with illegal characters We have a multi-project gradle build, which organizes the projects into directories. Example:
root
+--Libraries
   +-- Project1
   +-- Project2
+--Tools
   +-- Project3
   +-- Project4

Since the SonarRunner plugin is deprecated, we have attempted to use the official SonarQube plugin for gradle. The gradle version used is 2.10.
Due to our project structure, there are problems with the project names: SonarQube plugin receives projects names "Libraries\Project1". "\" is an illegal character for a project name.
Previously, for SonarRunner, the problem was fixed by overriding the ProjectKey property:
// project specific sonar configuration
gradle.projectsEvaluated {
  subprojects {
    sonarRunner {
      sonarProperties {
        def projectKey = "$project.group:$project.name".replaceAll('/', '-')
        property 'sonar.projectKey', projectKey
      }
    }
  }
}

The equivalent tried for SonarQube is
// project specific sonar configuration
gradle.projectsEvaluated {
  subprojects {
    sonarqube{
      properties {
        def projectKey = "$project.group:$project.name".replaceAll('/', '-')
        property 'sonar.projectKey', projectKey
      }
    }
  }
}

However, this doesn't work with SonarQube. Has anyone encountered a similar problem?
Thanks for your help!

A: What worked for me, on a Linux environment, was to replace a '/' with ':', and to override the moduleKey. Add this part in your root build.gradle file:
subprojects {
sonarqube {
    String regex = "(.*)/(.*)"
    String projectKey = project.name.replaceAll(regex, "\$1:\$2")
    String sonarModuleKey = rootProject.group + ':' + rootProject.name + ':' + projectKey

    properties {
        property "sonar.moduleKey", sonarModuleKey
    }
}

}


text:
Q: Is it possible to get a floating power supply to power multiple MOSFETs Hey guys this is my first post on stack exchange so please go easy on me!
I have a hobby project where I was trying to make a few batteries go in series using a micro controller and a floating power supply (in this case an isolated DC-DC converter), the arduino is powered separately.
I've attached a schematic of the rough problem.

simulate this circuit – Schematic created using CircuitLab
The arduino needs to be isolated from the rest of the higher powered battery stuff which is why I have used an isolated DC-DC converter and an opto-isolated mosfet driver
The output of the opto-isolated driver is hooked to the gate of the mosfet and the COM terminal of the dual output converter is hooked to the sources of both mosfets. This lets the mosfets see a +15V and the -15V drive signal. (please dont pay attention to the irf530 i just used the default on circuit labs and have some mosfets that can handle +/-30V for gate to source voltage)
My issue is that instead of buying more DC-DC converters and opto-isolated drivers to drive each next pair of mosfets, is there a way to power the next set using the same DC-DC converter and isolated driver? I need to add six more pairs of mosfets and batteries and thought that someone might know a cheaper way than buying more converters and drivers. Perhaps someone knows how you could use caps, resistors or diodes etc to do it.
Another issue that I have had is that if I were to connect the output of the isolated driver to the gate of the next pair of mosfets that would be okay but if i go to connect the COM terminal to sources of the next pair aswell it would create a short that bypasses the next battery.
Specifics:

*

*DC-DC converter is the DPU01M-15

*Driver is the FOD3150

*Switching frequency range from 1Hz - 3kHz

I hope that makes sense
Thanks for any help in advance!
EDIT:
The switches will turn on and off simultaneously

A: Sharing the one converter is "hard" but there is a low cost and easy and simple alternative (choose any 3).
It is common to use a "bootstrap" supply to high side gates using the switching action to provide the reuaisite "AC pump" - BUT that needs the gates to be switched more often than the decay time of the voltage which is produced in one switching cycle.  So ...
Have a look at the simple but useful concept used in this SE Q&A .
An AC square wave (can have asymmetric mark/space) is capacitor coupled to the floating node. A +ve half cycle conducting diode provides charge voltage and a negative half cycle diode to local "FLOATING GROUND'/ source" maintains the capacitor voltage at 0V-floating on average.
As seen here it is used to directly drive the gate BUT the same method could be used to provide a floating voltage which is then used by an appropriately coupled floating driver.  Do read the answers and comments as they address several relevant issues.
Here are two conceptual circuit diagrams.
Design is required.
The upper circuit provides both drive and drive-power by applying a square wave to "AC signal drive".
The lower circuit uses the diode pump to provide a floating DC voltage and a separate signal line - derived by whatever means suits - perhaps an optocoupler, or ... .

simulate this circuit – Schematic created using CircuitLab
This circuit can be used to provide floating voltage for other applications.
In this application and (probably) yours the gate is driven relative to a steadyish source voltage which is DC referenced to the local ground. If the circuit is fully floating then a capacitor can connect floating ground to local ground or an 180 degree out of phase drive input can be provided by two capacitors. Some low cost panel meter circuits use this arrangement to 'float' the meter supply. Note that when you have multiple driven FETs "standing on top of each other" the switching of one stage may affect others - this needs to be accounted for in  the design detail.
_____________________________________
Also see SE questions gate driver and   [floating gate driver](https://electronics.stackexchange.com/search?q=floating + gate+driver)
This graph and circuit are copied from Selvek's excellent answer to the above reference question.
It can be seen that the gate voltage acquires it's full value within a few cycles of the AC drive waveform. If you wish to use simple high/low drive signals from the microcontroller you could AND these with an appropriate AC waveform - or the uC can provide the AC signal. Do read the cited Q&A as voltage drive levels, gate turn on voltages and more are discussed.

A: You don't need DC/DC converters at all.
Instead you can use the positive side of the battery to provide the voltage you need to turn on the FETs.
You can use solid state relays (like the CPC1002N optical relay for instance) between the positive of the upper battery and the combined gates of the FETs. You will also need a shunt resistor between the gates and the drains of the FETs to prevent the leakage current of the relay from turning the FETs on.
This assumes the batteries will never fully discharge and their voltages will be always higher than the threshold voltage of the FETs you use.
If you use optical relays you can wire their LEDs to your micro controller the same way you were originally planning on connecting the FOD3150 driver. In fact, the only reason why you can't use the FOD3150 itself as the relay is that it requires the battery voltage to be 13.5V or greater, what is a little too high in your case.


text:
Q: Matlab error Dimensions of matrices being concatenated are not consistent I have error when trying to create classifier_pattern as seen below.
classifier_pattern = [25,'no','fine','no';200,'no','hot','yes';100,'no','rainy','no';125,'yes','rainy','no';030,'yes','rainy','no';300,'yes','fine','yes';055,'yes','hot','no';140,'no','hot','no';020,'yes','fine','no';175,'yes','fine','yes';110,'no','hot','yes'];

Matlab error Dimensions of matrices being concatenated are not consistent.

I'm not sure why this is happening. Later I try and also use vertcat with another similar matrix, which also fails.

A: Your issue is that you are trying to use character arrays (e.g. 'no') within a matrix. You should be using a cell array for mixed data types.
Look at a simple example
m = [1, 2, 'no'];
% >> m = '  no' because you have attempted character array concatenation,
%               and the 1 and 2 are assumed to be ASCII whitespaces

m = [1, 2, 'no';
     3, 4, 'ya;]
% >> m = ['  no'; '  ya'] same story, now it's a 2*4 character array

m = [1, 2, 'no';
     3, 4, 'yes']
% ERROR: Dimensions not consistent
% This is because you're trying vertical concatenation of 4 and 5 element character arrays.

Fix this by using cell arrays:
m = {1, 2, 'no';
     3, 4, 'yes'};
% >> m = 2*3 cell, as expected.


text:
Q: Create aggregate jar for distribution from supplied jars including javadocs we are provided lots of jars from a vendor (his own SDK + jar-dependencies as files) plus an accompanied javadoc/ directory for his own SDK containing javadoc html files.
we bundle/package these up into a proper maven artifact that we publish into our corporate nexus using mvn deploy. this is already working fine and uses the maven assembly plugin with an assembly.xml and pom.xml
What is missing though is to publish an additional javadoc-dedicated jar like vendor-tool-1.0-javadoc.jar that allows to integrate/use javadocs properly from the IDE.
I experimented with maven-javadoc-plugin, maven-source-plugin and the maven-assembly-plugin but failed to include the javadoc directory into a separate ...-javadoc.jar for mvn deploy. does not need to be a separate jar anyways, anything that is working out of the box with IntelliJ is greatly appreciated.


text:
Q: Alignment of label to the left of material UI select not working as expected I was trying to left align a label for a select built using Material UI
This causes the label to go outside the formControl so as to get it aligned to the left.
Is there a better way to get it done so that label remains within formControl? I do not see an option like labelPLacement for InputLabel and FormControlLabel does not seem to work with Select.
https://codesandbox.io/s/material-demo-forked-kbyxf?file=/demo.js
const useStyles = makeStyles((theme) => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  },
  divcontrol: {
    display: "inline-block"
  },
  label: {
    display: "inline-block",
    marginTop: "24px"
  }
}));

export default function SimpleSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <div className={classes.divcontrol}>
      <InputLabel className={classes.label} id="demo-simple-select-label">
        Age
      </InputLabel>
      <FormControl className={classes.formControl}>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}

A: You can use flex to align label:
const useStyles = makeStyles((theme) => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  },
  divcontrol: {
    display: "flex",
    flexDirection: "row",
    alignItems: "center"
  },
  label: {
    display: "flex",
  }
}));

Here is a live example:


text:
Q: Have frontend javascript access text file that is private to users I'm having trouble putting into words what I want, but I'll try to explain better. What I want to do is have the javascript (or another solution, if there is one) be able to access a text file on a static site and use data from the text file (in whatever way). The catch is I don't want users browsing to the website to be able to access the text file itself, but only be able to see the output of however I use the file and display results. Is there a way to do this?

A: Like AVAVT et al. said, you can't do this. But you could transfer/obfuscate text data in your Javascript code text (though you can't prevent a user from viewing your script, so this isn't going to stop aggressive attempts at getting your raw data, if that's what you want).


text:
Q: What functional/performance testing approach should I take during data ingestion testing using JMeter? Project overview:
We are building a data ingestion backend platform. 3 major components of the backend system are: Listener (will ingest vehicle GPS tracker data and store in message queue) >> Adapter (will process the ingested data by Listener and store processed data in message queue) >> Datarouter (will route the processed data by Adapter to any 3rd party platform)
My Task:
In the above scenario, my task is to do the functional testing and performance testing of data ingestion backend platform using JMeter open source tool. We are using JMeter as a load generator tool, which is basically simulating the sending of vehicle GPS tracker data to the listener. In JMeter, we are using TCP sampler to send the data in the following format:
$$${data_identifier},${imei},AAA,35,${lat},${long},${__dateTimeConvert(${__time()},,yyMMddhhmmss)},
A,8,15,60,274,0.9,25,34900,211818,404|30|7033|0BBF5744,0000,0000|0000|0000|0190|04B7,00000001,,1,0000*80

From functional point of view, we need to check the data ingested by listener and finally routed by datarouter after processing is all consistent.
From performance point of view, we need to check that the backend system can handle load of say for ex. 100 vehicles sending data packets every 10 sec for continuous period of time lets say 15-20 days.
Currently I am testing all the functions locally. After testing is done, deployment will happen to dev env.
Note: Please note that we are not using any big data tool like HDFS, Apache Spark etc. As a message broker, we are considering Redis/Kafka.
My question:
Please let me know what kind of functional and performance test scenarios to execute?
Any option to publish test results in statistical format/pictorial form directly from JMeter?
How can I ensure performance bottleneck & other performance aspects while testing in local environment setup?

A: *

*Please let me know what kind of functional and performance test scenarios to execute?

*

*it's your job to define the scenarios, you can start from normal Load Testing to see whether the system performance is acceptable given the anticipated load and them go for Stress Testing to identify the saturation point, the first bottleneck and first breaking point

*Any option to publish test results in statistical format/pictorial form directly from JMeter?

*

*JMeter provides possibility to generate HTML Reporting Dashboard

*Individual charts can be generated using i.e. JMeter Plugins Command Line Tool

*How can I ensure performance bottleneck & other performance aspects while testing in local environment setup?

*

*performance testing on local environment doesn't make a lot of sense because there are not too many things you can check there and the results you will get won't properly extrapolate to the larger system. You can still test several aspects against a scaled down environment like:

*

*run functional tests

*run soak tests

*test components integration


text:
Q: MPI_Send double pointer I have following code:
double * myX;
double * myY;
double * myZ;
int amount;
int count;      // number of process

void SomeClass::someMethod(double *x, double *y, double *z, int amount) {

    if (myId == 0) {
        myX = x;
        myY = y;
        myZ = z;
        amount = amount;
        for(int i = 1; i < count; ++i) {
            MPI_Send(&amount, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
            MPI_Send(myX, amount, MPI_DOUBLE, i, 0, MPI_COMM_WORLD);
            MPI_Send(myY, amount, MPI_DOUBLE, i, 0, MPI_COMM_WORLD);
            MPI_Send(myX, amount, MPI_DOUBLE, i, 0, MPI_COMM_WORLD);
        }
    }
}

void SomeClass::anotherMethod(void) {

    if(myId != 0) {
        MPI_Recv(&amount, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(myX, amount, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(myY, amount, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(myZ, amount, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    }

    // rest of code
    MPI_Reduce(args);
}

But I have problem because I get Null buffer pointer when I run this code or Segmentation fault when I change something, for example set & before var name and then run.
MPI_init and other required function are called in other class, where I also create this class objects.
Can someone help me?

A: MPI_Recv will copy the data it receives to the buffer specified by the first parameter (myX in the case below):
MPI_Recv(myX, amount, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

The problem is that you haven't created a buffer to store this.
You could do:
myX = new double[amount];

For example to create the buffer, not forgetting to free the memory again afterwards with:
delete[] myX;


text:
Q: Dependency Loading & File System Mocking So I have a dependency:
dep = require('dep')

If I mock out the file system prior to calling a function of dep, the file the dep is exported from is not found.
mockFs({})
dep.bar() #file where dep exported from not found

If I call a function prior to mocking out the file the dep is exported from is found.
dep.foo()
mockFs({})
dep.bar() #works

Any thoughts as to what would account for this behavior?

A: Your require() call is cached, so dep is using the real file system because it likely called require('fs'), which is not mocked yet.
Mocking fs later means that any new calls to require('fs') will use the mock, but anything that is loaded already is not affected.


text:
Q: Widget z-index modification I am having issue in displaying a widget inside a modal on ASP.NET MVC platform. Currently, the widget is showing at the back of my modal.
@Html.TextBoxFor(Function(model) model.Clinic, New With {.Style = "width:300px", .id = "txtClinic"})

Widget
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
    _create: function () {
        this._super();
        this.widget().menu("option", "items", "> :not(.ui-widget-header)");
    },
    _renderMenu: function (ul, items) {
        var self = this,
            thead;
        if (this.options.showHeader) {
            table = $('

');
            $.each(this.options.columns, function (index, item) {
                table.append('' + item.name + '');
            });
            table.append('

');
            ul.append(table);
        }
        $.each(items, function (index, item) {
            self._renderItem(ul, item);
        });
    },
    _renderItem: function (ul, item) {
        var t = '',
            result = '';
        var term = this.term;
        $.each(this.options.columns, function (index, column) {
            var value = item[column.valueField ? column.valueField : index];
            t += '' + value + ''
        });

        var $a = '' + t + '

';

        result = $('

')
            .data('ui-autocomplete-item', item)
            .append($a)
            .appendTo(ul);

        return result;
    }
});

Ajax
$("#txtClinic").mcautocomplete({

    showHeader: true,
    columns: [{
        name: 'Code',
        width: '120px',
        valueField: 'ClinicCode'
    }, {
        name: 'Clinic Name',
        width: '370px',
        valueField: 'Clinic'
    }
    ],

    minLength: 3,
    source: function (request, response) {
        $.ajax({
            cache: false,
            url: '/User/GetClinicAllDetails',
            type: "POST",
            dataType: "json",
            data: { query: request.term },
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        ClinicCode: item.ClinicCode,
                        Clinic: item.Clinic
                    }
                }));
            },
            error: function (response) {
                swal("", response.message, "error");
            }
        });
    }
});

All the codes are listed in my Modal View, any ideas what could went wrong?

A: For anyone who is having the same issue as me.
Simply add the following line to the widget portion:
$(".ui-autocomplete.ui-front.ui-menu.ui-widget.ui-widget-content").addClass("zindex9999");

In your style:
.zindex9999{z-index:9999 !important;}

The reason of doing so is because when a modal is opened, the position is set to absolute and it neglect all the existing div, by setting z-index to 9999, it actually overwrites the absolute index as the absolute index is around 9998 (I'm not sure)


text:
Q: Docker Postgres - error while creating a database and user I use the official Postgres image from the Docker Hub
docker pull postgres

I start my container in my machine on local:
docker run --name some-postgres -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -e POSTGRES_DB=test postgres

The container would have to create my test base with my user on port 542
I have this error when I want to connect on my db
$ sudo docker run -it postgres /bin/bash
root@ef4407c26a96:/# su postgres
postgres@ef4407c26a96:/$ psql
psql: error: could not connect to server: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
postgres@ef4407c26a96:/$

A: Please provide the database that you want to connect to. As you've provided POSTGRES_DB=test, use it when you wish to connect to psql:
psql -d test -U user

Also, I was able to connect with psql both as root and postgres user.


text:
Q: what is the significance of specifying the keystore name and alias with Java keytool import? A Tomcat server will be run on /programs/x64/java/jdk1.8.
Therefore, we would need to run keytool to import certs from services that the apps running on the Tomcat server need encrypted access.
What is the significance in the keystore name and cert alias? Do they affect how the Tomcat is able to access the stored certs?
What is a good upgrade-proof strategy, such that certs/keystore imported/created by current JDK version are visible to a new JDK version installed?

A:
Therefore, we would need to run keytool to import certs from services that the apps running on the Tomcat server need encrypted access.

Only if those applications run on servers that have self-signed certificates. NB the result of this process is called a truststore, not a keystore. A keystore is for your own private key and certificate.

What is the significance in the keystore name

The keystore name is the name of a file.

and cert alias?

The cert alias is the name of the certificate.

Do they affect how the Tomcat is able to access the stored keys?

There are no stored keys. Only certificates. Tomcat doesn't care what their aliases are.

What is a good upgrade-proof strategy, such that certs/keystore imported/created by current JDK version are visible to a new JDK version installed?

Avoid the whole problem, by insisting that the application servers use CA-signed certificates. Self-signed certificates aren't worth the paper they're printed on.


text:
Q: Most Pythonic way to do input validation What is the most "correct", Pythonic way to do user input validation in Python?
I've been using the following:
while True:
    stuff = input("Please enter foo: ")
    try:
        some_test(stuff)
        print("Thanks.")
        break
    except SomeException:
        print("Invalid input.")

Which is nice and readable, I suppose, but I can't help wondering if there isn't some built-in function or something I should be using instead.

A: The most Pythonic way to do this kind of validation of "User INput" is to catch an appropriate exception.
Example:
def get_user_input():
    while True:
        try:
            return int(input("Please enter a number: "))
        except ValueError:
            print("Invalid input. Please try again!")

n = get_user_input()
print("Thanks! You entered: {0:d}".format(n))

It's also good practice to allow exceptions occur where they lie and allow them to bubble up rather than hide them so you can clearly see what's going wrong in a Python Traceback.
In this case Validating User Input -- Use Python's Duck Typing and catch the error. i.e: If it acts like a duct, it must be a duck. (If it acts like an int, it must be an int).

A: I like decorators to separate the checking from the rest of the input handling.
#!/usr/bin/env python

def repeatOnError(*exceptions):
  def checking(function):
    def checked(*args, **kwargs):
      while True:
        try:
          result = function(*args, **kwargs)
        except exceptions as problem:
          print "There was a problem with the input:"
          print problem.__class__.__name__
          print problem
          print "Please repeat!"
        else:
          return result
    return checked
  return checking

@repeatOnError(ValueError)
def getNumberOfIterations():
  return int(raw_input("Please enter the number of iterations: "))

iterationCounter = getNumberOfIterations()
print "You have chosen", iterationCounter, "iterations."

EDIT:
A decorator is more or less a wrapper for an existing function (or method).  It takes the existing function (denoted below its @decorator directive) and returns a "replacement" for it.  This replacement in our case calls the original function in a loop and catches any exception happening while doing so.  If no exception happens, it just returns the result of the original function.

A: A bit complicated, but may be interesting:
import re
from sys import exc_info,excepthook
from traceback import format_exc

def condition1(stuff):
    '''
    stuff must be the string of an integer'''
    try:
        i = int(stuff)
        return True
    except:
        return False

def condition2(stuff):
    '''
    stuff is the string of an integer
    but the integer must be in the range(10,30)'''
    return int(stuff) in xrange(10,30)

regx = re.compile('assert *\( *([_a-z\d]+)')

while True:
    try:
        stuff = raw_input("Please enter foo: ")
        assert(condition1(stuff))
        assert (  condition2(stuff))
        print("Thanks.")
        break
    except AssertionError:
        tbs = format_exc(exc_info()[0])
        funky = globals()[regx.search(tbs).group(1)]
        excepthook(exc_info()[0], funky.func_doc, None)

result
Please enter foo: g
AssertionError:
    stuff must be the string of an integer
Please enter foo: 170
AssertionError:
    stuff is the string of an integer
    but the integer must be in the range(10,30)
Please enter foo: 15
Thanks.

.
EDIT
I found a way to simplify:
from sys import excepthook

def condition1(stuff):
    '''
    stuff must be the string of an integer'''
    try:
        int(stuff)
        return True
    except:
        return False

def another2(stuff):
    '''
    stuff is the string of an integer
    but the integer must be in the range(10,30)'''
    return int(stuff) in xrange(10,30)

tup = (condition1,another2)

while True:
    try:
        stuff = raw_input("Please enter foo: ")
        for condition in tup:
            assert(condition(stuff))
        print("Thanks.")
        break
    except AssertionError:
        excepthook('AssertionError', condition.func_doc, None)


text:
Q: Can not deserialize empty content within tags when newline met Have following 2 classes:
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Structure {
    @JacksonXmlProperty
    private Info info;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
@AllArgsConstructor
public class Info{
    private Subinfo subinfo;
}

doing deserialization like:
 private static final XmlMapper XML_MAPPER = new XmlMapper();
 Structure structure = XML_MAPPER.readValue(input, Structure.class);

where input is my XML(see below)
got exception:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.test.models.Info` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('

    ')

this Jackson feature did not help:
XML_MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

my XML that failed:
<?xml version='1.0' encoding='UTF-8' ?>
  <Structure>
    <Info>

    </Info>
  </Structure>

for this XML deserialization works OK:
<?xml version='1.0' encoding='UTF-8' ?>
  <Structure>
    <Info/>
  </Structure>

The problem is with tag closing approach:
<Info/> VS <Info></Info>
<Info/> works OK
while
<Info>

 </Info>

causes Exception when line terminators occurred

A: As others already mentioned in their comments, DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT converts only empty strings to null, but you have spaces and line separators within your Info element.
Others cannot reproduce your problem since you either missed to mention that you also use XML_MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) in your code or Info in your example XML should actually be info, otherwise the element is ignored.
To handle empty strings and strings that only contain spaces and/or line separators you can add the following code before you parse the XML:
XML_MAPPER.addHandler(new DeserializationProblemHandler() {

    @Override
    public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass,
            ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {

      String value = p.getValueAsString();

      // ignore "empty" Info elements
      if (instClass.isAssignableFrom(Info.class) && (value.isEmpty() || value.matches("[\n\s]+"))) {
        return null;
      }
      return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
    }

});

If you want to do this for all elements you can simply ignore instClass


text:
Q: Asp.Net MVC 3 : Client IP addres Using Javascript
Possible Duplicate:
Get Client IP using just Javascript?

I am working on .net mvc 3 application. i just want to get the ip address of the client.
How can i get client ip using JavaScript. If any body knows please share .

A: You can't do that with javascript. You could use javascript to send an AJAX request to a controller action that will return the IP of the client reading it from Request.UserHostAddress:
public ActionResult GetIP()
{
    return Json(new { ip = Request.UserHostAddress }, JsonRequestBehavior.AllowGet);
}

and then:
var url = '@Url.Action("GetIP", "SomeController")';
$.getJSON(url, function(result) {
    alert(result.ip);
});

A:

              <title></title>

                  <form>

                  </form>

A:

a working Example


text:
Q: Checkbox input in python urllib How can I check checkbox if HTML code looks like:
<input type="checkbox" name="tos_understood" style="background:none; border:none" />

So, my python code is:
import urllib
import urllib2
import cookielib

authentication_url = 'http://test.com'

# Input parameters we are going to send
payload = {
  'user': 'newuser',
  'pass': '12345'
  'tos_understood': ??????????
  }

# Use urllib to encode the payload
data = urllib.urlencode(payload)

# Build our Request object
req = urllib2.Request(authentication_url, data)
print req

# Make the request and read the response
resp = urllib2.urlopen(req)
contents = resp.read()
print contents

What should I write in tos_understood section? There is no way to login without checked checkbox.

A: did you try something like :
"tos_understood": "1"

 "tos_understood": "checked"

or
"tos_understood": "on"

I looked around for an answer to this but couldnt really find much
If those dont work maybe try something like selenium that actually drives a browser with a window it is waaaayyy easier and you can also run it headless so that the window doesn't pop up

A: This should work:
payload = {
  'user': 'newuser',
  'pass': '12345',
  'tos_understood': 'on',
  }


text:
Q: Replace wildcard string inside double quote I have this string
var newtypegraph=newtypegraph.replace(' "type":"bar3d" ',' "type":"area" ');

I want to make bar3d as wildcard.

A: This looks like JavaScript, so you can use regex:
var newtypegraph = newtypegraph.replace(/"type":".*?"/g, '"type":"area"');

This looks like the properties of a JSON object. Is this JSON?