问:
Use the result of a function call in next function
I want to combine the result of two asynchronouse function calls. I tried to get that as seperate functions.

```<code>$scope.showPage = function () {
    var base ="";
    var menu= "";
    service.getGUI('menu', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               menu = reply.data;
            }
        });

    service.getGUI('base', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               base=reply.data;
        });

console.log("base:"+ base);
console.log("menu:"+ menu);
}
</code>```

But the console output is not updating as expected. How can I execute is one by one and use the result of the first one in second function.

答:
Convert the callback-based API to a promise-based API:

```<code>function getGUIpromise(item) {
    var deferredItem = $q.defer();
    service.getGUI(item, function (reply) {
        if (reply.status === 200 && reply.data !== null) {
            deferredItem.resolve(reply.data);
        } else {
            deferredItem.reject("Error with getGUI "+item);
        };
    });
    return deferredItem.promise;
}
</code>```

Then use $q.all to wait for the promises:

```<code>$scope.showPage = function () {
    var basePromise = getGUIpromise("base");
    var menuPromise = getGUIpromise("menu");

    $q.all({base: basePromise, menu: menuPromise})
    .then(function(result) {
        console.log("base:"+ result.base);
        console.log("menu:"+ result.menu);
    }).catch(function(error) {
        console.log(error);
    });
};
</code>```

Alternately if under-the-hood, the service.getGUI method uses a promise-based API, the original under-the-hood promise should be returned and used.

Body:
I want to combine the result of two asynchronouse function calls. I tried to get that as seperate functions.

$scope.showPage = function () {
    var base ="";
    var menu= "";
    service.getGUI('menu', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               menu = reply.data;
            }
        });

    service.getGUI('base', function (reply) {
            if (reply.status === 200 && reply.data !== null) {
               base=reply.data;
        });

console.log("base:"+ base);
console.log("menu:"+ menu);
}

But the console output is not updating as expected. How can I execute is one by one and use the result of the first one in second function.

Body:
Convert the callback-based API to a promise-based API:

function getGUIpromise(item) {
    var deferredItem = $q.defer();
    service.getGUI(item, function (reply) {
        if (reply.status === 200 && reply.data !== null) {
            deferredItem.resolve(reply.data);
        } else {
            deferredItem.reject("Error with getGUI "+item);
        };
    });
    return deferredItem.promise;
}

Then use $q.all to wait for the promises:

$scope.showPage = function () {
    var basePromise = getGUIpromise("base");
    var menuPromise = getGUIpromise("menu");

    $q.all({base: basePromise, menu: menuPromise})
    .then(function(result) {
        console.log("base:"+ result.base);
        console.log("menu:"+ result.menu);
    }).catch(function(error) {
        console.log(error);
    });
};

Alternately if under-the-hood, the service.getGUI method uses a promise-based API, the original under-the-hood promise should be returned and used.


来源: stackexchange

问:
Where should i put my Admin control panel?
I'm building a community site using PHP/MySQL, I was thinking of just letting admins login where normal users log in, and then present them with a "Admin Control Panel" link. So that the control panel platform is hosted on the same site. Is this secure? Should there be a different "gateway" for admins instead i.e. http://admin.example.com? Or should i host the Control Panel on an entirely different domain?

Thanks for your time.

答:
I would prefer to use a directory with limited access using .htaccess.

If the user-account of an admin will be hacked, his access to the ACP is still secure.

ContentLicense: CC BY-SA 2.5


问:
Can't close mail view controller when clicking Cancel, Save Draft or Delete Draft
I'm implementing a mail controller in my app but I can't figure out why it won't close when clicking save draft or delete draft. The window gets stuck on the email screen and I can't click "Cancel" a second time either.</p>

```<code>@IBAction func emailButtonTapped(_ sender: UIButton) {
    guard MFMailComposeViewController.canSendMail() else {
        if !MFMailComposeViewController.canSendMail() {
            print("Can not send email")
            return
        }
        return
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }

    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["example@example.com"])
    mailComposer.setSubject("Look at this")
    mailComposer.setMessageBody("Hello, this is an email from the app I made.", isHTML: false)

    present(mailComposer, animated: true, completion: nil)
}
</code>```

答:
I successfully fixed the issue, and it was a pretty stupid one!
Some code was outside the emailButtonTapped func:</p>

```<code>@IBAction func emailButtonTapped(_ sender: UIButton) {
    //guard MFMailComposeViewController.canSendMail() else {
        if !MFMailComposeViewController.canSendMail() {
            print("Can not send email")
            return
        }
    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["example@example.com"])
    mailComposer.setSubject("Look at this")
    mailComposer.setMessageBody("Hello, this is an email from the app I made.", isHTML: false)

    present(mailComposer, animated: true, completion: nil)
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    dismiss(animated: true, completion: nil)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm implementing a mail controller in my app but I can't figure out why it won't close when clicking save draft or delete draft. The window gets stuck on the email screen and I can't click "Cancel" a second time either.

@IBAction func emailButtonTapped(_ sender: UIButton) {
    guard MFMailComposeViewController.canSendMail() else {
        if !MFMailComposeViewController.canSendMail() {
            print("Can not send email")
            return
        }
        return
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }

    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["example@example.com"])
    mailComposer.setSubject("Look at this")
    mailComposer.setMessageBody("Hello, this is an email from the app I made.", isHTML: false)

    present(mailComposer, animated: true, completion: nil)
}

Body:
I successfully fixed the issue, and it was a pretty stupid one!
Some code was outside the emailButtonTapped func:

@IBAction func emailButtonTapped(_ sender: UIButton) {
    //guard MFMailComposeViewController.canSendMail() else {
        if !MFMailComposeViewController.canSendMail() {
            print("Can not send email")
            return
        }
    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["example@example.com"])
    mailComposer.setSubject("Look at this")
    mailComposer.setMessageBody("Hello, this is an email from the app I made.", isHTML: false)

    present(mailComposer, animated: true, completion: nil)
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    dismiss(animated: true, completion: nil)
}


问:
Applying expression functions
I need to implement filter function with expression parameter.
So i can't apply filtered query to entity.

Entity :

```<code>[XmlRoot(ElementName = "Zip")]
public class Zip
{
    [XmlAttribute(AttributeName = "code")]
    public string Code { get; set; }
}

[XmlRoot(ElementName = "District")]
public class District
{
    [XmlElement(ElementName = "Zip")]
    public List<Zip> Zip { get; set; }
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "City")]
public class City
{
    [XmlElement(ElementName = "District")]
    public List<District> District { get; set; }
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "code")]
    public string Code { get; set; }
}

[XmlRoot(ElementName = "AddressInfo")]
public class AddressInfo
{
    [XmlElement(ElementName = "City")]
    public List<City> City { get; set; }
}
</code>```

Test case filtered by City name "Berlin". How can apply predicate with function.

```<code>public IConverter<T> Filter(Expression<Func<T, bool>> predicate)
{
    // ???
    return this;
}
</code>```

答:
I presume you need to filter a collection with a given predicate.

You can define a Filter extension method that takes a predicate as an argument (or simply rely on the already existing collection.Where extension method)

```<code>public static class Extensions
{
    public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
    {
        return collection.Where(predicate);
    }
}
</code>```

define predicates based on your needs

```<code>// Filter by city Berlin
Func<City, bool> berlin = city => city.Name == "Berlin";

// Filter by district Spandau
Func<City, bool> spandau = city => city.Districts.Any(d => d.Name == "Spandau");

// Filter by zip 10115
Func<City, bool> zipcode = city =>
{
    var predicate = from district in city.Districts
                    from zip in district.Zips
                    where zip.Code == "10115"
                    select zip;

    return predicate.Any();
};
</code>```

filter the data based on given predicate

```<code>var query = from address in addresses
            from city in address.Cities.Filter(berlin)
            select city;
</code>```

Title: Applying expression functions

Body:
I need to implement filter function with expression parameter.
So i can't apply filtered query to entity.

Entity :

[XmlRoot(ElementName = "Zip")]
public class Zip
{
    [XmlAttribute(AttributeName = "code")]
    public string Code { get; set; }
}

[XmlRoot(ElementName = "District")]
public class District
{
    [XmlElement(ElementName = "Zip")]
    public List<Zip> Zip { get; set; }
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "City")]
public class City
{
    [XmlElement(ElementName = "District")]
    public List<District> District { get; set; }
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "code")]
    public string Code { get; set; }
}

[XmlRoot(ElementName = "AddressInfo")]
public class AddressInfo
{
    [XmlElement(ElementName = "City")]
    public List<City> City { get; set; }
}

Test case filtered by City name "Berlin". How can apply predicate with function.

public IConverter<T> Filter(Expression<Func<T, bool>> predicate)
{
    // ???
    return this;
}

Body:
I presume you need to filter a collection with a given predicate.

You can define a Filter extension method that takes a predicate as an argument (or simply rely on the already existing collection.Where extension method)

public static class Extensions
{
    public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
    {
        return collection.Where(predicate);
    }
}

define predicates based on your needs

// Filter by city Berlin
Func<City, bool> berlin = city => city.Name == "Berlin";

// Filter by district Spandau
Func<City, bool> spandau = city => city.Districts.Any(d => d.Name == "Spandau");

// Filter by zip 10115
Func<City, bool> zipcode = city =>
{
    var predicate = from district in city.Districts
                    from zip in district.Zips
                    where zip.Code == "10115"
                    select zip;

    return predicate.Any();
};

filter the data based on given predicate

var query = from address in addresses
            from city in address.Cities.Filter(berlin)
            select city;


问:
PowerShell passing function as parameter
I have two PS scripts (1 main script and 1 as a module).

Main script uses code like:

```<code>Write-Host "Press Y to continue"
Execute (ConstructSshSessions)
</code>```

Where Execute is a function that asks the question to continue and execute the script in the function ConstructSshSessions. If the users does not type a Y then the main scripts skips the function ConstructSshSessions.

Module uses code like:

```<code>Function Execute($function)
{
    $response = read-host
    Write-Host "You typed: $response"
    if ($response -eq "Y")
    {
        $function
    }
    Remove-Variable response
}
</code>```

When I execute the code Excecute (ConstructSshSession) it first runs the script that creates the SSH sessions and then asks the user to continue. So that is clearly not my intention but I do not see the error.

I would like that it asks the users if it may continue and then execute the script that is beeing send as a parameter to the function Execute.

答:
I wouldn't recommend separating prompting for a response from actually reading the response. I wouldn't recommend passing a function name to some Exec-like invocation routine either.

Wrap the confirmation routine in a function that returns a boolean value and invoke the function as the condition of an if statement.

function ConfirmStep($msg) {
    $title = 'Confirm Step'

    $yes = New-Object Management.Automation.Host.ChoiceDescription '&Yes'
    $no  = New-Object Management.Automation.Host.ChoiceDescription '&No'
    $options = [Management.Automation.Host.ChoiceDescription[]]($no, $yes)
    $default = 1  # $yes

    [bool]$Host.UI.PromptForChoice($title, $msg, $options, $default)
}

if (ConfirmStep "Construct SSH sessions?") {
    ConstructSshSessions
}
```

Body:
I have two PS scripts (1 main script and 1 as a module).

Main script uses code like:

Write-Host "Press Y to continue"
Execute (ConstructSshSessions)

Where Execute is a function that asks the question to continue and execute the script in the function ConstructSshSessions. If the users does not type a Y then the main scripts skips the function ConstructSshSessions.

Module uses code like:

Function Execute($function)
{
    $response = read-host
    Write-Host "You typed: $response"
    if ($response -eq "Y")
    {
        $function
    }
    Remove-Variable response
}

When I execute the code Excecute (ConstructSshSession) it first runs the script that creates the SSH sessions and then asks the user to continue. So that is clearly not my intention but I do not see the error.

I would like that it asks the users if it may continue and then execute the script that is beeing send as a parameter to the function Execute.


问:
How to create an insert view
I have two SQL Server instances on the same PC, a default and a named instance. I have to perform primary horizontal fragmentation. My database has 4 tables I have to fragment the tables on the basis of some conditions. I create a linked server and created a view that takes data from table from both instances and combines them into one view (database and tables on both instances are same/schema is same).

Query in view

I want to write an insert view that inserts values in my first view, as first view returns data from two tables

I want to create a trigger for insert view when value is added in insert view trigger condition is checked and processed data in different tables as accordingly the condition let's say I want the data where Semester > 5 in instance 1 (default instance) and where Semester <= 5 must be stored in instance 2 (named instance).

答: I believe you should use INSTEAD OF triggers in your view. Given the fact that you want to process the data inserted to the view and given certain conditions, finally insert them in different tables INSTEAD OF triggers in views should do it.

Title: How to create an insert view


问:
Error while Accessing Private Func. from Public Func. inside a Class
I have the following class structure. When run the post() function, I receive an error Uncaught Error: Call to undefined function curl_post().

```<code>class POST {

    private function encode($data) {
    }

    private function curl_post($data) {
        encode($data);
    }

    public function post($data) {
        $post = curl_post($data);
        print_r($post);
    }
}
</code>```

What is causing this error? Do I have to use something like $this-> to access the private function?

答:
To call sibling object methods, prefix the call with $this->:

```<code>class POST {

    private function encode($data) {
    }

    private function curl_post($data) {
        $this->encode($data);
    }

    public function post($data) {
        $post = $this->curl_post($data);
        print_r($post);
    }
}
</code>```

From the documentation:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs...

Body:
I have the following class structure. When run the post() function, I receive an error Uncaught Error: Call to undefined function curl_post().

class POST {

    private function encode($data) {
    }

    private function curl_post($data) {
        encode($data);
    }

    public function post($data) {
        $post = curl_post($data);
        print_r($post);
    }
}

What is causing this error? Do I have to use something like $this-> to access the private function?

Body:
To call sibling object methods, prefix the call with $this->:

class POST {

    private function encode($data) {
    }

    private function curl_post($data) {
        $this->encode($data);
    }

    public function post($data) {
        $post = $this->curl_post($data);
        print_r($post);
    }
}

From the documentation:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs...


问:
Object sql is not a member of package org.apache.spark
I am trying to work with spark-sql but while I importing

```<code>import org.apache.spark.sql.{Row, SparkSession}
</code>```

getting following error:

```<code>object sql is not a member of package org.apache.spark
</code>```

Here are my details:

Spark version: 1.6.2
Scala version: 2.11.8
sbt version: 0.13.16

Here is my build.sbt file:

```<code>name := "sbt_demo"
version := "1.0"
scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.2"

libraryDependencies += "org.apache.spark" %% "spark-sql" % "1.6.2"
</code>```

Note: there is another question with the same problem in Stack Overflow, but that accepted answer didn't help me. That is the reason why I am asking again.

答:
You need maven central in your Resolver of sbt. And if behind proxy, set your proxy properly for SBT.

Also, in spark 1.6.2, there's no SparkSession... You should use SQLContext, or move to 2.x

ContentLicense: CC BY-SA 4.0

Body:
I am trying to work with spark-sql but while I importing

import org.apache.spark.sql.{Row, SparkSession}

getting following error:

object sql is not a member of package org.apache.spark

Here are my details:

Spark version: 1.6.2
Scala version: 2.11.8
sbt version: 0.13.16

Here is my build.sbt file:

name := "sbt_demo"
version := "1.0"
scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.2"

libraryDependencies += "org.apache.spark" %% "spark-sql" % "1.6.2"

Note: there is another question with the same problem in Stack Overflow, but that accepted answer didn't help me. That is the reason why I am asking again.


问:
Usage of SUMIF in Excel
I have list of customers and their corresponding revenues in 3 services. These list of customer belongs to various regions- North, East, South, West.

In above excel, I wish to find sum total region wise. Kindly help to use SUMIF or any other useful function.

答:
Try this formula in C13 copied down and across if required

=SUMPRODUCT(SUMIF($B$3:$B$11,$G$3:$G$11,C$3:C$11)*($H$3:$H$11=$B13))

SUMIF creates a total for all customers but the additional check $H$3:$H$11=$B13 ensures that it only adds those for the relevant zone

Title: Usage of SUMIF in Excel


问:
Android move slide down to slide up view
I'm using this library to use slide down menu, the problem is when I want to move the handle from top to bottom and want to change from slide down to slide up, I try to change the variable but can't make it right

This is the original code

```<code>/* User tapped down on screen. */
                    case MotionEvent.ACTION_DOWN:
                        // User has tapped the screen
                        yStart = event.getRawY();
                        lastY = event.getRawY();
                        currentHeight = slideDownView.getHeight();
                        break;

                    /* User is dragging finger. */
                    case MotionEvent.ACTION_MOVE:

                        // Calculate the total height change thus far.
                        float totalHeightDiff = event.getRawY() - yStart;

                        // Adjust the slide down height immediately with touch movements.
                        LayoutParams params = slideDownView.getLayoutParams();
                        params.height = (int)(currentHeight + totalHeightDiff);
                        slideDownView.setLayoutParams(params);

                        // Check and set which direction drag is moving.
                        if (event.getRawY() > lastY) {
                            directionDown = true;
                        } else {
                            directionDown = false;
                        }

                        // Set the lastY for comparison in the next ACTION_MOVE event.
                        lastY = event.getRawY();
                        break;

                    /* User lifted up finger. */
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:

                        /*
                         * Need to snap either up or down. Using ValueAnimator to "finish" the action.
                         * HeightEvaluator is a custom class.
                         *
                         * NOTE: I'm using the nineoldandroids library for
                         */
                        if (directionDown) {

                            // Open the sliding view.
                            int startHeight = slideDownView.getHeight();

                            ValueAnimator animation = ValueAnimator.ofObject(
                                    new HeightEvaluator(slideDownView),
                                    startHeight,
                                    (int) openHeight).setDuration(300);

                            // See Table 3 for other interpolator options
                            // - http://developer.android.com/guide/topics/graphics/prop-animation.html
                            animation.setInterpolator(new OvershootInterpolator(1));
                            animation.start();

                        } else {

                            // Close the sliding view.
                            int startHeight = slideDownView.getHeight();
                            ValueAnimator animation = ValueAnimator.ofObject(
                                    new HeightEvaluator(slideDownView),
                                    startHeight,
                                    (int) closedHeight).setDuration(300);
                            animation.setInterpolator(new OvershootInterpolator(1));
                            animation.start();
                        }
                        break;
</code>```

How to make it reverse ? so I can slide up from bottom to top ? is it have to change also in HeightEvaluator.java ?

答: At the end I use BottomSheet and set PeekHeight to make a slideUp with button at the bottom that still visible to trigger the slideView</p>

Body:
I'm using this library to use slide down menu, the problem is when I want to move the handle from top to bottom and want to change from slide down to slide up, I try to change the variable but can't make it right

This is the original code

/* User tapped down on screen. */
                    case MotionEvent.ACTION_DOWN:
                        // User has tapped the screen
                        yStart = event.getRawY();
                        lastY = event.getRawY();
                        currentHeight = slideDownView.getHeight();
                        break;

                    /* User is dragging finger. */
                    case MotionEvent.ACTION_MOVE:

                        // Calculate the total height change thus far.
                        float totalHeightDiff = event.getRawY() - yStart;

                        // Adjust the slide down height immediately with touch movements.
                        LayoutParams params = slideDownView.getLayoutParams();
                        params.height = (int)(currentHeight + totalHeightDiff);
                        slideDownView.setLayoutParams(params);

                        // Check and set which direction drag is moving.
                        if (event.getRawY() > lastY) {
                            directionDown = true;
                        } else {
                            directionDown = false;
                        }

                        // Set the lastY for comparison in the next ACTION_MOVE event.
                        lastY = event.getRawY();
                        break;

                    /* User lifted up finger. */
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:

                        /*
                         * Need to snap either up or down. Using ValueAnimator to "finish" the action.
                         * HeightEvaluator is a custom class.
                         *
                         * NOTE: I'm using the nineoldandroids library for
                         */
                        if (directionDown) {

                            // Open the sliding view.
                            int startHeight = slideDownView.getHeight();

                            ValueAnimator animation = ValueAnimator.ofObject(
                                    new HeightEvaluator(slideDownView),
                                    startHeight,
                                    (int) openHeight).setDuration(300);

                            // See Table 3 for other interpolator options
                            // - http://developer.android.com/guide/topics/graphics/prop-animation.html
                            animation.setInterpolator(new OvershootInterpolator(1));
                            animation.start();

                        } else {

                            // Close the sliding view.
                            int startHeight = slideDownView.getHeight();
                            ValueAnimator animation = ValueAnimator.ofObject(
                                    new HeightEvaluator(slideDownView),
                                    startHeight,
                                    (int) closedHeight).setDuration(300);
                            animation.setInterpolator(new OvershootInterpolator(1));
                            animation.start();
                        }
                        break;

How to make it reverse ? so I can slide up from bottom to top ? is it have to change also in HeightEvaluator.java ?


问:
FB login window on mobile
How to enable Facebook login window on modal?
Something like that on the image.

but mobile equivalent.

答:
You can do it using the Facebook JavaScript SDK, Note: this runs in frontend not on Backend.

```<code>    function getScript(u, c) {
        var h = document.getElementsByTagName('head')[0], s = document.createElement('script')
      s.async = true
        s.src = u
      s.onload = s.onreadystatechange = function () {
        if (!s.readyState || /loaded|complete/.test(s.readyState)) {
          s.onload = s.onreadystatechange = null; if (h && s.parentNode) { h.removeChild(s) } s = undefined
          if (c) { c() }
        }
      }
      h.insertBefore(s, h.firstChild)
    }
</code>```

Now Fetch the FB JS SDK and Initialise FB API like this:

```<code>getScript('//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.10&appId=yourappidhere', () => {
  if(typeof window.fbAsyncInit === 'undefined') {
    FB.init({
      appId: 'you app id',
      version: 'your app version',
      status: true,
      cookie: true,
      xfbml: true,
      frictionlessRequests: true,
      useCachedDialogs: true,
      oauth: true
    })
  }
})
</code>```

Now, when add an event listener to your login button:

```<code>document.querySelector('your-btn').addEventListener('click', (e) => {
  e.preventDefault()
  FB.login((response) => {
    // your callback
  })
})
</code>```

Title: FB login window on mobile

Body:
You can do it using the Facebook JavaScript SDK, Note: this runs in frontend not on Backend.

    function getScript(u, c) {
        var h = document.getElementsByTagName('head')[0], s = document.createElement('script')
      s.async = true
        s.src = u
      s.onload = s.onreadystatechange = function () {
        if (!s.readyState || /loaded|complete/.test(s.readyState)) {
          s.onload = s.onreadystatechange = null; if (h && s.parentNode) { h.removeChild(s) } s = undefined
          if (c) { c() }
        }
      }
      h.insertBefore(s, h.firstChild)
    }

Now Fetch the FB JS SDK and Initialise FB API like this:

getScript('//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.10&appId=yourappidhere', () => {
  if(typeof window.fbAsyncInit === 'undefined') {
    FB.init({
      appId: 'you app id',
      version: 'your app version',
      status: true,
      cookie: true,
      xfbml: true,
      frictionlessRequests: true,
      useCachedDialogs: true,
      oauth: true
    })
  }
})

Now, when add an event listener to your login button:

document.querySelector('your-btn').addEventListener('click', (e) => {
  e.preventDefault()
  FB.login((response) => {
    // your callback
  })
})


问:
How to add http link as Url Schemes in iOS Swift3
I need to set a web url (http://xxxx.com/project/test) in Url scheme, so if the app is not installed then I have to redirect to the Safari Web page or else need to open app directly. As this Web Url is relate to my App website.

I tried setting scheme without http/https and can open the app successfully from browser. Is it possible to add Host in Url scheme like Android?

This can be possible using Universal Links, but I want to know is there any other way to achieve this to support iOS 8? Please suggest me. Thank you!

答: You should be able to set a Javascript redirect once the page loads in Safari and attempt to open the app. See this post</p>


问:
String "array" to real array
Now I got the string of an array, like this :

```<code>$str = "array('a'=>1, 'b'=>2)";
</code>```

How can I convert this string into real array ? Is there any "smart way" to do that, other that use explode() ? Because the "string" array could be very complicated some time.

Thanks !

答:
Don't use eval() in any case
just call strtoarray($str, 'keys') for array with keys and strtoarray($str) for array which have no keys.

```<code>function strtoarray($a, $t = ''){
    $arr = [];
    $a = ltrim($a, '[');
    $a = ltrim($a, 'array(');
    $a = rtrim($a, ']');
    $a = rtrim($a, ')');
    $tmpArr = explode(",", $a);
    foreach ($tmpArr as $v) {
        if($t == 'keys'){
            $tmp = explode("=>", $v);
            $k = $tmp[0]; $nv = $tmp[1];
            $k = trim(trim($k), "'");
            $k = trim(trim($k), '"');
            $nv = trim(trim($nv), "'");
            $nv = trim(trim($nv), '"');
            $arr[$k] = $nv;
        } else {
            $v = trim(trim($v), "'");
            $v = trim(trim($v), '"');
            $arr[] = $v;
        }
    }
    return $arr;
}
</code>```

Title: String "array" to real array

Body:
Now I got the string of an array, like this :

$str = "array('a'=>1, 'b'=>2)";

How can I convert this string into real array ? Is there any "smart way" to do that, other that use explode() ? Because the "string" array could be very complicated some time.

Thanks !

Body:
Don't use eval() in any case
just call strtoarray($str, 'keys') for array with keys and strtoarray($str) for array which have no keys.

function strtoarray($a, $t = ''){
    $arr = [];
    $a = ltrim($a, '[');
    $a = ltrim($a, 'array(');
    $a = rtrim($a, ']');
    $a = rtrim($a, ')');
    $tmpArr = explode(",", $a);
    foreach ($tmpArr as $v) {
        if($t == 'keys'){
            $tmp = explode("=>", $v);
            $k = $tmp[0]; $nv = $tmp[1];
            $k = trim(trim($k), "'");
            $k = trim(trim($k), '"');
            $nv = trim(trim($nv), "'");
            $nv = trim(trim($nv), '"');
            $arr[$k] = $nv;
        } else {
            $v = trim(trim($v), "'");
            $v = trim(trim($v), '"');
            $arr[] = $v;
        }
    }
    return $arr;
}


问:
How to create a new relational realmResults?
I created a realm object(VolleyballPlayer) according to other realm objects. Female object includes all Volleyball objects but Male object has some Volleyball objects.

I want to create VolleyballPlayer object that group Female and Male objects for gender. But I couldn't find how to do it according to RealmResults.

My realm objects:

```<code>public class Volleyball extends RealmObject {
    private int round;
    // ... Generated getters and setters ...
}

//...All  females play volleyball.
public class Female extends RealmObject {
    private Volleyball volleyball;
    private int clasp;
    // ... Generated getters and setters ...
}

public class Male extends RealmObject {
    private Volleyball volleyball;
    private int belt;
    // ... Generated getters and setters ...
}
</code>```

New object:

```<code>public class VolleyballPlayer extends RealmObject {
    private Volleyball volleyball;
    private String gender;

    // ... Generated getters and setters ...
}
</code>```

I have allFemale and allMale realmResults but I haven't take allPlayer realmResults.

```<code>RealmResults<Female> allFemales = mRealm.where(Female.class).findAll();
RealmResults<Male> allMales = mRealm.where(Male.class).findAll();
</code>```

All female students play volleyball and how can I extract male players from through all the players(in females) who play volleyball?
Is there a way in the realm that I write below code:

```<code> public void setAllVolleyballPlayers(Realm mRealm) {
        Realm mRealm = getRealm();

        mRealm.beginTransaction();
        addAllMalePlayers(mRealm);
        addAllFemalePlayers(mRealm);
        mRealm.commitTransaction();
    }

    private void addAllMalePlayers(Realm mRealm) {
        RealmResults<Male> allMalePlayers = new MalePlayersQueries().getAllMales(mRealm);

        mRealm.beginTransaction();

        if (allMalePlayers != null && allMalePlayers.size() > 0) {

           VolleyballPlayer volleyballPlayer = mRealm.createObject(VolleyballPlayer.class);
           volleyballPlayer.setGender(getString(R.string.male));

           for (Male male : allMales) {

           VolleyballPlayer volleyballPlayer =
           mRealm.createObject(VolleyballPlayer.class);
           volleyballPlayer.setVolleyball(male.getVolleyball());
           }
        }
    }

   private void addAllFemalePlayers(Realm mRealm) {
           RealmResults<Female> allFemales = new FemaleQueries().getAllPlayers(mRealm);

           VolleyballPlayer volleyballPlayer = mRealm.createObject(VolleyballPlayer.class);
           volleyballPlayer.setGender(getString(R.string.female));

           ////// All female students play volleyball and how can I extract male players from all the players(in females) who play this volleyball and get females
}
</code>```

And I want to show at the end of table:

```<code>  **Volleyball Players**

  **Female**
    Emma
    Olivia
    Sophia

  **Male**
    John
    Jame
</code>```

答:
Personally I'd leverage the power of "single-table-inheritance using discriminator field" for this.

```<code>public class Volleyball extends RealmObject {
    private int round;

    @LinkingObjects("volleyball")
    private final RealmResults<VolleyBallPlayer> playedBy = null;
    // ... Generated getters and setters ...
}

public class VolleyBallPlayer extends RealmObject {
    private Volleyball volleyball;
    @Index
    private String gender;
    private int femaleClasp; // 0, or with Integer `null` if male
    private int maleBelt; // 0, or with Integer `null` if female
    // ... Generated getters and setters ...
}
</code>```

Now you can do

```<code>RealmResults<VolleyBallPlayer> femalePlayers = realm.where(VolleyBallPlayer.class)
     .equalTo("gender", Gender.FEMALE.name()).findAll();
RealmResults<VolleyBallPlayer> malePlayers = realm.where(VolleyBallPlayer.class)
     .equalTo("gender", Gender.MALE.name()).findAll();
</code>```

And even

```<code>RealmResults<Volleyball> maleVolleyballs = realm.where(Volleyball.class)
     .equalTo("playedBy.gender", Gender.MALE.name()).findAll();
</code>```

Body:
I created a realm object(VolleyballPlayer) according to other realm objects. Female object includes all Volleyball objects but Male object has some Volleyball objects.

I want to create VolleyballPlayer object that group Female and Male objects for gender. But I couldn't find how to do it according to RealmResults.

My realm objects:

public class Volleyball extends RealmObject {
    private int round;
    // ... Generated getters and setters ...
}

//...All  females play volleyball.
public class Female extends RealmObject {
    private Volleyball volleyball;
    private int clasp;
    // ... Generated getters and setters ...
}

public class Male extends RealmObject {
    private Volleyball volleyball;
    private int belt;
    // ... Generated getters and setters ...
}

New object:

public class VolleyballPlayer extends RealmObject {
    private Volleyball volleyball;
    private String gender;

    // ... Generated getters and setters ...
}

I have allFemale and allMale realmResults but I haven't take allPlayer realmResults.

RealmResults<Female> allFemales = mRealm.where(Female.class).findAll();
RealmResults<Male> allMales = mRealm.where(Male.class).findAll();

All female students play volleyball and how can I extract male players from through all the players(in females) who play volleyball?
Is there a way in the realm that I write below code:

 public void setAllVolleyballPlayers(Realm mRealm) {
        Realm mRealm = getRealm();

        mRealm.beginTransaction();
        addAllMalePlayers(mRealm);
        addAllFemalePlayers(mRealm);
        mRealm.commitTransaction();
    }

    private void addAllMalePlayers(Realm mRealm) {
        RealmResults<Male> allMalePlayers = new MalePlayersQueries().getAllMales(mRealm);

        mRealm.beginTransaction();

        if (allMalePlayers != null && allMalePlayers.size() > 0) {

           VolleyballPlayer volleyballPlayer = mRealm.createObject(VolleyballPlayer.class);
           volleyballPlayer.setGender(getString(R.string.male));

           for (Male male : allMales) {

           VolleyballPlayer volleyballPlayer =
           mRealm.createObject(VolleyballPlayer.class);
           volleyballPlayer.setVolleyball(male.getVolleyball());
           }
        }
    }

   private void addAllFemalePlayers(Realm mRealm) {
           RealmResults<Female> allFemales = new FemaleQueries().getAllPlayers(mRealm);

           VolleyballPlayer volleyballPlayer = mRealm.createObject(VolleyballPlayer.class);
           volleyballPlayer.setGender(getString(R.string.female));

           ////// All female students play volleyball and how can I extract male players from all the players(in females) who play this volleyball and get females
}

And I want to show at the end of table:

  **Volleyball Players**

  **Female**
    Emma
    Olivia
    Sophia

  **Male**
    John
    Jame

Body:
Personally I'd leverage the power of "single-table-inheritance using discriminator field" for this.

public class Volleyball extends RealmObject {
    private int round;

    @LinkingObjects("volleyball")
    private final RealmResults<VolleyBallPlayer> playedBy = null;
    // ... Generated getters and setters ...
}

public class VolleyBallPlayer extends RealmObject {
    private Volleyball volleyball;
    @Index
    private String gender;
    private int femaleClasp; // 0, or with Integer `null` if male
    private int maleBelt; // 0, or with Integer `null` if female
    // ... Generated getters and setters ...
}

Now you can do

RealmResults<VolleyBallPlayer> femalePlayers = realm.where(VolleyBallPlayer.class)
     .equalTo("gender", Gender.FEMALE.name()).findAll();
RealmResults<VolleyBallPlayer> malePlayers = realm.where(VolleyBallPlayer.class)
     .equalTo("gender", Gender.MALE.name()).findAll();

And even

RealmResults<Volleyball> maleVolleyballs = realm.where(Volleyball.class)
     .equalTo("playedBy.gender", Gender.MALE.name()).findAll();


问:
Ember get filtered data from the store/mirage
I am trying to build an app for smarthome devices with ember. I already have installed mirage and declare an array which is called data. It holds arrays like households, users and devices. Now I am stuck with get filtered data from the store and i am really confused by the behaviour of the store. For this reason I already read some equal topics like this Filtering store data in ember but this doesn´t work in my case.

Actually this is my router.js

```<code>Router.map(function() {
  this.route('about');
  this.route('users', function() {
  });
  this.route('households', function() {
    this.route('index', { path: '/:user_id' })
    this.route('rooms',{ path: '/:household_id' });
    this.route('devices');
  });
});
</code>```

If I am going to households.index I want to see all households which have the user-id in his member-array. The following code snipped shows an example of my data-structure.

```<code>  "users": [
      {
          "id":101,
          "forename":"Peter",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      },
      {
          "id":102,
          "forename":"Anna",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      }
]

  "households":[
      {
          "id":501,
          "name":"Zuhause",
          "admin":131000,
          "member":[
              101,
              102
          ]
}
</code>```

I am calling the route household.index like this {{#link-to "households.index" user.id}} and my route in household.index looks like this

```<code>model(params) {
    //holt alle Haushalte und gibt dann nur die Haushalte weiter, die auch den aktuellen Benutzer als Member haben.
   return this.get('store').findAll('household').then(results => results.filter((site) => {
       return site.get('member').filter(x => x == params.user_id).length > 0;
   }));
  }
</code>```

And my config.js part at mirage like this:

```<code>  this.get('/households', function(db, request) {
    return { households: data.households };
});
</code>```

This works fine!
But in my opinion the server is responsible for giving me the data I am requesting for. So all I want is that I send a specific request and just get the households that I need.

My attempt:
index.js:

```<code>export default Route.extend({
    model(params) {
        return this.get('store').find('household', params.user_id);
      }
});
</code>```

config js part:

```<code>  this.get('/households/:id', function(db, request) {
      console.log('household get');
      console.log(data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0));
    return  { households: data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0) };
});
</code>```

Debug Error:

Error while processing route: households.index payload.data is null

I cant understand why this error occurs. The log gives me the array i want to return.

答:
By default Ember Data ships with the JSONAPISerializer and this assumes a few things about the way your server (in this case mirage) is formatting data. In this case the document that mirage is returning is expected to generally conform to the JSON API Spec and have a top-level member data where the response's primary data resides.

If you're looking to stick to your custom formatted responses you may want to check out the Ember Data's JSONSerializer. Otherwise, returning the following should get you closer:

```<code>return  { data: db.households.filter(x => x.member.filter(x => x == request.params.id).length > 0) };
</code>```

or you could leverage the JSONAPISerializer that ships with Mirage

See more here Ember Guides | Serializers

Body:
I am trying to build an app for smarthome devices with ember. I already have installed mirage and declare an array which is called data. It holds arrays like households, users and devices. Now I am stuck with get filtered data from the store and i am really confused by the behaviour of the store. For this reason I already read some equal topics like this Filtering store data in ember but this doesn´t work in my case.

Actually this is my router.js

Router.map(function() {
  this.route('about');
  this.route('users', function() {
  });
  this.route('households', function() {
    this.route('index', { path: '/:user_id' })
    this.route('rooms',{ path: '/:household_id' });
    this.route('devices');
  });
});

If I am going to households.index I want to see all households which have the user-id in his member-array. The following code snipped shows an example of my data-structure.

  "users": [
      {
          "id":101,
          "forename":"Peter",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      },
      {
          "id":102,
          "forename":"Anna",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      }
]

  "households":[
      {
          "id":501,
          "name":"Zuhause",
          "admin":131000,
          "member":[
              101,
              102
          ]
}

I am calling the route household.index like this {{#link-to "households.index" user.id}} and my route in household.index looks like this

model(params) {
    //holt alle Haushalte und gibt dann nur die Haushalte weiter, die auch den aktuellen Benutzer als Member haben.
   return this.get('store').findAll('household').then(results => results.filter((site) => {
       return site.get('member').filter(x => x == params.user_id).length > 0;
   }));
  }

And my config.js part at mirage like this:

  this.get('/households', function(db, request) {
    return { households: data.households };
});

This works fine!
But in my opinion the server is responsible for giving me the data I am requesting for. So all I want is that I send a specific request and just get the households that I need.

My attempt:
index.js:

export default Route.extend({
    model(params) {
        return this.get('store').find('household', params.user_id);
      }
});

config js part:

  this.get('/households/:id', function(db, request) {
      console.log('household get');
      console.log(data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0));
    return  { households: data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0) };
});

Debug Error:

Error while processing route: households.index payload.data is null

I cant understand why this error occurs. The log gives me the array i want to return.

Body:
By default Ember Data ships with the JSONAPISerializer and this assumes a few things about the way your server (in this case mirage) is formatting data. In this case the document that mirage is returning is expected to generally conform to the JSON API Spec and have a top-level member data where the response's primary data resides.

If you're looking to stick to your custom formatted responses you may want to check out the Ember Data's JSONSerializer. Otherwise, returning the following should get you closer:

return  { data: db.households.filter(x => x.member.filter(x => x == request.params.id).length > 0) };

or you could leverage the JSONAPISerializer that ships with Mirage

See more here Ember Guides | Serializers


问:
find a value in a block matrix
I wrote a sparse matrix class, based on Block compressed storage, I wrote almost all the method, but I have not idea to how to write the method findValue(i,j) that give 2 indexes of the original matrix ! the storage consists in four vectors :

`ba_': stored the non zero block (rectangular block in which almost one element is different from zero) of the matrix in top-down left-right order

an_ is the vector of index that points to the first element of the block in the vector ba

aj_ stored the index of the block columns in the blocked matrix.

ai_ stored the first block of each row in the blocked matrix.

the picture clarify anything :

here the following class in which I use two methods to achieve the result, findBlockIndex and findValue(i,j,Brows,Bcols) but I need to get the value of the original i,j index using findValue(i,j) in which i,j are the index in the sparse complete matrix

```<code> # include <iosfwd>
    # include <vector>
    # include <string>
    # include <initializer_list>
    # include "MatrixException.H"
    # include <sstream>
    # include <fstream>
    # include <algorithm>
    # include <iomanip>

    // forward declarations
    template <typename T, std::size_t R, std::size_t C>
    class BCRSmatrix ;

    template <typename T, std::size_t R, std::size_t C>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

    template <typename T, std::size_t Br, std::size_t Bc >
    std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

    template <typename data_type, std::size_t BR , std::size_t BC>
    class BCRSmatrix {

          template <typename T, std::size_t R, std::size_t C>
          friend std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

          template <typename T, std::size_t Br,std::size_t Bc>
          friend std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

       public:

         constexpr BCRSmatrix(std::initializer_list<std::vector<data_type>> dense );

         constexpr BCRSmatrix(const std::string& );

         virtual ~BCRSmatrix() = default ;

         auto constexpr print_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr validate_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr insert_block(const std::vector<std::vector<data_type>>& dense,
                                                           std::size_t i, std::size_t j) noexcept ;

         auto constexpr printBCRS() const noexcept ;

         auto constexpr printBlockMatrix() const noexcept  ;

         auto constexpr size1() const noexcept { return denseRows ;}

         auto constexpr size2() const noexcept { return denseCols ;}

         auto constexpr printBlock(std::size_t i) const noexcept ;

         auto constexpr print() const noexcept ;

       private:

        std::size_t bn  ;
        std::size_t bBR ;
        std::size_t nnz ;
        std::size_t denseRows ;
        std::size_t denseCols ;

        std::vector<data_type>    ba_ ;
        std::vector<std::size_t>  an_ ;
        std::vector<std::size_t>  ai_ ;
        std::vector<std::size_t>  aj_ ;

        std::size_t index =0 ;

        auto constexpr findBlockIndex(const std::size_t r, const std::size_t c) const noexcept ;

        auto constexpr recomposeMatrix() const noexcept ;

        auto constexpr findValue(
                                  const std::size_t i, const std::size_t j,
                                  const std::size_t rBlock, const std::size_t cBlock
                                ) const noexcept ;

    };

    //---------------------------      IMPLEMENTATION
    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(std::initializer_list<std::vector<T>> dense_ )
    {
          this->denseRows = dense_.size();
          auto it         = *(dense_.begin());
          this->denseCols = it.size();

          if( (denseRows*denseCols) % BR != 0 )
          {
                throw InvalidSizeException("Error block size is not multiple of dense matrix size");
          }

         std::vector<std::vector<T>> dense(dense_);
         bBR = BR*BC ;
         bn  = denseRows*denseCols/(BR*BC) ;

        ai_.resize(denseRows/BR +1);
        ai_[0] = 1;

        for(std::size_t i = 0; i < dense.size() / BR ; i++)
        {
            auto rowCount =0;
            for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
            {
                if(validate_block(dense,i,j))
                {
                      aj_.push_back(j+1);
                      insert_block(dense, i, j);
                      rowCount ++ ;
                }

            }
            ai_[i+1] = ai_[i] + rowCount ;
         }
         printBCRS();
    }

    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(const std::string& fname)
    {
        std::ifstream f(fname , std::ios::in);
        if(!f)
        {
           throw OpeningFileException("error opening file in constructor !");
        }
        else
        {
           std::vector<std::vector<T>> dense;
           std::string line, tmp;
           T elem = 0 ;
           std::vector<T> row;
           std::size_t i=0, j=0 ;

           while(getline(f, line))
           {
              row.clear();
              std::istringstream ss(line);
              if(i==0)
              {
                while(ss >> elem)
                {
                  row.push_back(elem);
                  j++;
                }
              }
              else
              {
                while(ss >> elem)
                  row.push_back(elem);
              }
              dense.push_back(row);
              i++;
           }

           this->denseRows = i;
           this->denseCols = j;

           bBR = BR*BR ;
           bn  = denseRows*denseCols/(BR*BC) ;

           ai_.resize(denseRows/BR +1);
           ai_[0] = 1;

           for(std::size_t i = 0; i < dense.size() / BR ; i++)
           {
              auto rowCount =0;
              for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
              {
                  if(validate_block(dense,i,j))
                  {
                        aj_.push_back(j+1);
                        insert_block(dense, i, j);
                        rowCount ++ ;
                  }

              }
              ai_[i+1] = ai_[i] + rowCount ;
           }

        }
        printBCRS();

    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlockMatrix() const noexcept
    {

          for(auto i=0 ; i < denseRows / BR ; i++)
          {
            for(auto j=1 ; j <= denseCols / BC  ; j++)
            {
                std::cout << findBlockIndex(i,j) << ' ' ;
            }
             std::cout << std::endl;
          }
    }

    template <typename T,std::size_t BR,std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlock(std::size_t i) const noexcept
    {
       auto w = i-1 ;
       auto k = 0;
       for(std::size_t i = 0 ; i < BR ; ++i)
       {
          for(std::size_t j=0 ; j < BC ; ++j )
          {
              std::cout << std::setw(8) << ba_.at(an_.at(w)-1+k) << ' ';
              k++;
          }
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::print_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
                      std::cout << dense[m][n] << ' ';
          std::cout << '\n';
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::validate_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       bool nonzero = false ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(dense[m][n] != 0) nonzero = true;
          }
       }
       return nonzero ;
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::insert_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) noexcept
    {

       bool firstElem = true ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(firstElem)
                {
                      an_.push_back(index+1);
                      firstElem = false ;
                }
                ba_.push_back(dense[m][n]);
                index ++ ;
          }
       }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findBlockIndex(const std::size_t r, const std::size_t c) const noexcept
    {
          for(auto j= ai_.at(r) ; j < ai_.at(r+1) ; j++ )
          {
             if( aj_.at(j-1) == c  )
             {
                return j ;
             }
          }
    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::printBCRS() const noexcept
    {

      std::cout << "ba_ :   " ;
      for(auto &x : ba_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

      std::cout << "an_ :   " ;
      for(auto &x : an_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

      std::cout << "aj_ :   " ;
      for(auto &x : aj_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

       std::cout << "ai_ :   " ;
       for(auto &x : ai_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::print() const noexcept
    {
        //for each BCRS row
        for(auto i=0 ; i < denseRows / BR ; i++){
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++){
                //for each BCSR col.
                for(auto j = 1; j <= denseCols / BC; j++){
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        std::cout<< findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                std::cout << std::endl;
            }
        }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::recomposeMatrix() const noexcept
    {

        std::vector<std::vector<T>> sparseMat(denseRows, std::vector<T>(denseCols, 0));
        auto BA_i = 0, AJ_i = 0;
        //for each BCSR row
        for(auto r = 0; r < denseRows/BR; r++){
            //for each Block in row
            for(auto nBlock = 0; nBlock < ai_.at(r+1)-ai_.at(r); nBlock++){
                //for each subMatrix (Block)
                for(auto rBlock = 0; rBlock < BR; rBlock++){
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        //insert value
                        sparseMat.at(rBlock + r*BR).at(cBlock + (aj_.at(AJ_i)-1)*BC) = ba_.at(BA_i);
                        ++BA_i;
                    }
                }
            ++AJ_i;
            }
        }
        return sparseMat;
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findValue(
                                               const std::size_t i, const std::size_t j,
                                               const std::size_t rBlock, const std::size_t cBlock
                                              ) const noexcept
    {
        auto index = findBlockIndex(i,j);
        if(index != 0)
            return ba_.at(an_.at(index-1)-1 + cBlock + rBlock*BC);
        else
          return T(0);
    }

    template <typename T, std::size_t BR,std::size_t BC>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,BR,BC>& m )
    {
        for(auto i=0 ; i < m.denseRows / BR ; i++)
        {
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++)
            {
                //for each BCSR col.
                for(auto j = 1; j <= m.denseCols / BC; j++)
                {
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++)
                    {
                        os << m.findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                os << std::endl;
            }
        }
        return os;
    }

    template <typename T, std::size_t BR, std::size_t BC>
    std::vector<T> operator*(const BCRSmatrix<T,BR,BC>& m, const std::vector<T>& x )
    {
          std::vector<T> y(x.size());
          if(m.size1() != x.size())
          {
           std::string to = "x" ;
           std::string mess = "Error occured in operator* attempt to perfor productor between op1: "
                            + std::to_string(m.size1()) + to + std::to_string(m.size2()) +
                                     " and op2: " + std::to_string(x.size());
                throw InvalidSizeException(mess.c_str());
          }
          else
          {
                auto brows = m.denseRows/BR ;
                auto bnze  = m.an_.size()   ;

                auto z=0;

                for(auto b=0 ; b < brows ; b++)
                {
                   for(auto j= m.ai_.at(b) ; j <= m.ai_.at(b+1)-1; j++ )
                   {
                      for(auto k=0 ; k < BR ; k++ )
                      {
                         for(auto t=0 ; t < BC ; t++)
                         {
                             y.at(BC*b+k) += m.ba_.at(z) * x.at(BC*(m.aj_.at(j-1)-1)+t) ;
                             z++ ;
                         }
                      }
                   }
                }

          }
          return y;

    }
</code>```

and this is the main

```<code># include "BCSmatrix.H"

using namespace std;

int main(){

  BCRSmatrix<int,2,2> bbcsr1 =  {{11,12,13,14,0,0},{0,22,23,0,0,0},{0,0,33,34,35,36},{0,0,0,44,45,0},
                           {0,0,0,0,0,56},{0,0,0,0,0,66}};

  BCRSmatrix<int,2,2> bbcsr2 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  BCRSmatrix<int,2,4> bbcsr3 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  bbcsr3.printBlockMatrix();

  bbcsr3.print();

  BCRSmatrix<int,2,2> bbcsr4("input17.dat");

  bbcsr4.printBlockMatrix();

  BCRSmatrix<int,2,4> bbcsr5("input18.dat");

  bbcsr5.printBlockMatrix();
  cout << bbcsr5 ;

  BCRSmatrix<int,4,4> bbcsr6("input18.dat");

  bbcsr6.printBlockMatrix();

  bbcsr6.print();

  cout << bbcsr4 ; //.print();

  BCRSmatrix<int,2,4> bbcsr7("input20.dat");

  cout << bbcsr7;

  bbcsr7.printBlockMatrix();

  std::vector<int> v1 = {3,4,0,1,6,8,1,19};

  std::vector<int> v01 = {3,4,0,1,6,8,1,19,15,2};

  std::vector<int> v2 = bbcsr4 *v1 ;

  for(auto& x : v2)
        cout << x << ' ' ;
  cout << endl;

  BCRSmatrix<double,2,2> bbcsr8("input21.dat");

  bbcsr8.print() ;
  bbcsr8.printBlockMatrix();

  return 0;
}
</code>```

答:
rename the original findValue as findVal then define a new findValue that take exactly 2 element defined as follow (I know is orrible):

```<code> template <typename T, std::size_t BS>
T constexpr SqBCSmatrix<T,BS>::findValue(const std::size_t r, const std::size_t c) const noexcept
{
    //for each BCRS row
    for(auto i=0 ,k=0; i < denseRows / BS ; i++){
        //for each Block sub row.
        for(auto rBlock = 0; rBlock < BS; k++ ,rBlock++){
            //for each BCSR col.
            for(auto j = 1 , l=0; j <= denseCols / BS; j++){
                //for each Block sub col.
                for(auto cBlock = 0; cBlock < BS; l++ , cBlock++){
                      if(k == r && c == l )
                          return findVal(i,j,rBlock, cBlock);

                }
            }
        }
    }
    return 0;
}
</code>```

Title: find a value in a block matrix

Body:
I wrote a sparse matrix class, based on Block compressed storage, I wrote almost all the method, but I have not idea to how to write the method findValue(i,j) that give 2 indexes of the original matrix ! the storage consists in four vectors :

`ba_': stored the non zero block (rectangular block in which almost one element is different from zero) of the matrix in top-down left-right order

an_ is the vector of index that points to the first element of the block in the vector ba

aj_ stored the index of the block columns in the blocked matrix.

ai_ stored the first block of each row in the blocked matrix.

the picture clarify anything :

here the following class in which I use two methods to achieve the result, findBlockIndex and findValue(i,j,Brows,Bcols) but I need to get the value of the original i,j index using findValue(i,j) in which i,j are the index in the sparse complete matrix

 # include <iosfwd>
    # include <vector>
    # include <string>
    # include <initializer_list>
    # include "MatrixException.H"
    # include <sstream>
    # include <fstream>
    # include <algorithm>
    # include <iomanip>

    // forward declarations
    template <typename T, std::size_t R, std::size_t C>
    class BCRSmatrix ;

    template <typename T, std::size_t R, std::size_t C>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

    template <typename T, std::size_t Br, std::size_t Bc >
    std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

    template <typename data_type, std::size_t BR , std::size_t BC>
    class BCRSmatrix {

          template <typename T, std::size_t R, std::size_t C>
          friend std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

          template <typename T, std::size_t Br,std::size_t Bc>
          friend std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

       public:

         constexpr BCRSmatrix(std::initializer_list<std::vector<data_type>> dense );

         constexpr BCRSmatrix(const std::string& );

         virtual ~BCRSmatrix() = default ;

         auto constexpr print_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr validate_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr insert_block(const std::vector<std::vector<data_type>>& dense,
                                                           std::size_t i, std::size_t j) noexcept ;

         auto constexpr printBCRS() const noexcept ;

         auto constexpr printBlockMatrix() const noexcept  ;

         auto constexpr size1() const noexcept { return denseRows ;}

         auto constexpr size2() const noexcept { return denseCols ;}

         auto constexpr printBlock(std::size_t i) const noexcept ;

         auto constexpr print() const noexcept ;

       private:

        std::size_t bn  ;
        std::size_t bBR ;
        std::size_t nnz ;
        std::size_t denseRows ;
        std::size_t denseCols ;

        std::vector<data_type>    ba_ ;
        std::vector<std::size_t>  an_ ;
        std::vector<std::size_t>  ai_ ;
        std::vector<std::size_t>  aj_ ;

        std::size_t index =0 ;

        auto constexpr findBlockIndex(const std::size_t r, const std::size_t c) const noexcept ;

        auto constexpr recomposeMatrix() const noexcept ;

        auto constexpr findValue(
                                  const std::size_t i, const std::size_t j,
                                  const std::size_t rBlock, const std::size_t cBlock
                                ) const noexcept ;

    };

    //---------------------------      IMPLEMENTATION
    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(std::initializer_list<std::vector<T>> dense_ )
    {
          this->denseRows = dense_.size();
          auto it         = *(dense_.begin());
          this->denseCols = it.size();

          if( (denseRows*denseCols) % BR != 0 )
          {
                throw InvalidSizeException("Error block size is not multiple of dense matrix size");
          }

         std::vector<std::vector<T>> dense(dense_);
         bBR = BR*BC ;
         bn  = denseRows*denseCols/(BR*BC) ;

        ai_.resize(denseRows/BR +1);
        ai_[0] = 1;

        for(std::size_t i = 0; i < dense.size() / BR ; i++)
        {
            auto rowCount =0;
            for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
            {
                if(validate_block(dense,i,j))
                {
                      aj_.push_back(j+1);
                      insert_block(dense, i, j);
                      rowCount ++ ;
                }

            }
            ai_[i+1] = ai_[i] + rowCount ;
         }
         printBCRS();
    }

    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(const std::string& fname)
    {
        std::ifstream f(fname , std::ios::in);
        if(!f)
        {
           throw OpeningFileException("error opening file in constructor !");
        }
        else
        {
           std::vector<std::vector<T>> dense;
           std::string line, tmp;
           T elem = 0 ;
           std::vector<T> row;
           std::size_t i=0, j=0 ;

           while(getline(f, line))
           {
              row.clear();
              std::istringstream ss(line);
              if(i==0)
              {
                while(ss >> elem)
                {
                  row.push_back(elem);
                  j++;
                }
              }
              else
              {
                while(ss >> elem)
                  row.push_back(elem);
              }
              dense.push_back(row);
              i++;
           }

           this->denseRows = i;
           this->denseCols = j;

           bBR = BR*BR ;
           bn  = denseRows*denseCols/(BR*BC) ;

           ai_.resize(denseRows/BR +1);
           ai_[0] = 1;

           for(std::size_t i = 0; i < dense.size() / BR ; i++)
           {
              auto rowCount =0;
              for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
              {
                  if(validate_block(dense,i,j))
                  {
                        aj_.push_back(j+1);
                        insert_block(dense, i, j);
                        rowCount ++ ;
                  }

              }
              ai_[i+1] = ai_[i] + rowCount ;
           }

        }
        printBCRS();

    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlockMatrix() const noexcept
    {

          for(auto i=0 ; i < denseRows / BR ; i++)
          {
            for(auto j=1 ; j <= denseCols / BC  ; j++)
            {
                std::cout << findBlockIndex(i,j) << ' ' ;
            }
             std::cout << std::endl;
          }
    }

    template <typename T,std::size_t BR,std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlock(std::size_t i) const noexcept
    {
       auto w = i-1 ;
       auto k = 0;
       for(std::size_t i = 0 ; i < BR ; ++i)
       {
          for(std::size_t j=0 ; j < BC ; ++j )
          {
              std::cout << std::setw(8) << ba_.at(an_.at(w)-1+k) << ' ';
              k++;
          }
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::print_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
                      std::cout << dense[m][n] << ' ';
          std::cout << '\n';
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::validate_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       bool nonzero = false ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(dense[m][n] != 0) nonzero = true;
          }
       }
       return nonzero ;
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::insert_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) noexcept
    {

       bool firstElem = true ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(firstElem)
                {
                      an_.push_back(index+1);
                      firstElem = false ;
                }
                ba_.push_back(dense[m][n]);
                index ++ ;
          }
       }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findBlockIndex(const std::size_t r, const std::size_t c) const noexcept
    {
          for(auto j= ai_.at(r) ; j < ai_.at(r+1) ; j++ )
          {
             if( aj_.at(j-1) == c  )
             {
                return j ;
             }
          }
    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::printBCRS() const noexcept
    {

      std::cout << "ba_ :   " ;
      for(auto &x : ba_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

      std::cout << "an_ :   " ;
      for(auto &x : an_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

      std::cout << "aj_ :   " ;
      for(auto &x : aj_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

       std::cout << "ai_ :   " ;
       for(auto &x : ai_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::print() const noexcept
    {
        //for each BCRS row
        for(auto i=0 ; i < denseRows / BR ; i++){
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++){
                //for each BCSR col.
                for(auto j = 1; j <= denseCols / BC; j++){
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        std::cout<< findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                std::cout << std::endl;
            }
        }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::recomposeMatrix() const noexcept
    {

        std::vector<std::vector<T>> sparseMat(denseRows, std::vector<T>(denseCols, 0));
        auto BA_i = 0, AJ_i = 0;
        //for each BCSR row
        for(auto r = 0; r < denseRows/BR; r++){
            //for each Block in row
            for(auto nBlock = 0; nBlock < ai_.at(r+1)-ai_.at(r); nBlock++){
                //for each subMatrix (Block)
                for(auto rBlock = 0; rBlock < BR; rBlock++){
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        //insert value
                        sparseMat.at(rBlock + r*BR).at(cBlock + (aj_.at(AJ_i)-1)*BC) = ba_.at(BA_i);
                        ++BA_i;
                    }
                }
            ++AJ_i;
            }
        }
        return sparseMat;
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findValue(
                                               const std::size_t i, const std::size_t j,
                                               const std::size_t rBlock, const std::size_t cBlock
                                              ) const noexcept
    {
        auto index = findBlockIndex(i,j);
        if(index != 0)
            return ba_.at(an_.at(index-1)-1 + cBlock + rBlock*BC);
        else
          return T(0);
    }

    template <typename T, std::size_t BR,std::size_t BC>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,BR,BC>& m )
    {
        for(auto i=0 ; i < m.denseRows / BR ; i++)
        {
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++)
            {
                //for each BCSR col.
                for(auto j = 1; j <= m.denseCols / BC; j++)
                {
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++)
                    {
                        os << m.findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                os << std::endl;
            }
        }
        return os;
    }

    template <typename T, std::size_t BR, std::size_t BC>
    std::vector<T> operator*(const BCRSmatrix<T,BR,BC>& m, const std::vector<T>& x )
    {
          std::vector<T> y(x.size());
          if(m.size1() != x.size())
          {
           std::string to = "x" ;
           std::string mess = "Error occured in operator* attempt to perfor productor between op1: "
                            + std::to_string(m.size1()) + to + std::to_string(m.size2()) +
                                     " and op2: " + std::to_string(x.size());
                throw InvalidSizeException(mess.c_str());
          }
          else
          {
                auto brows = m.denseRows/BR ;
                auto bnze  = m.an_.size()   ;

                auto z=0;

                for(auto b=0 ; b < brows ; b++)
                {
                   for(auto j= m.ai_.at(b) ; j <= m.ai_.at(b+1)-1; j++ )
                   {
                      for(auto k=0 ; k < BR ; k++ )
                      {
                         for(auto t=0 ; t < BC ; t++)
                         {
                             y.at(BC*b+k) += m.ba_.at(z) * x.at(BC*(m.aj_.at(j-1)-1)+t) ;
                             z++ ;
                         }
                      }
                   }
                }

          }
          return y;

    }

and this is the main

# include "BCSmatrix.H"

using namespace std;

int main(){

  BCRSmatrix<int,2,2> bbcsr1 =  {{11,12,13,14,0,0},{0,22,23,0,0,0},{0,0,33,34,35,36},{0,0,0,44,45,0},
                           {0,0,0,0,0,56},{0,0,0,0,0,66}};

  BCRSmatrix<int,2,2> bbcsr2 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  BCRSmatrix<int,2,4> bbcsr3 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  bbcsr3.printBlockMatrix();

  bbcsr3.print();

  BCRSmatrix<int,2,2> bbcsr4("input17.dat");

  bbcsr4.printBlockMatrix();

  BCRSmatrix<int,2,4> bbcsr5("input18.dat");

  bbcsr5.printBlockMatrix();
  cout << bbcsr5 ;

  BCRSmatrix<int,4,4> bbcsr6("input18.dat");

  bbcsr6.printBlockMatrix();

  bbcsr6.print();

  cout << bbcsr4 ; //.print();

  BCRSmatrix<int,2,4> bbcsr7("input20.dat");

  cout << bbcsr7;

  bbcsr7.printBlockMatrix();

  std::vector<int> v1 = {3,4,0,1,6,8,1,19};

  std::vector<int> v01 = {3,4,0,1,6,8,1,19,15,2};

  std::vector<int> v2 = bbcsr4 *v1 ;

  for(auto& x : v2)
        cout << x << ' ' ;
  cout << endl;

  BCRSmatrix<double,2,2> bbcsr8("input21.dat");

  bbcsr8.print() ;
  bbcsr8.printBlockMatrix();

  return 0;
}

Body:
rename the original findValue as findVal then define a new findValue that take exactly 2 element defined as follow (I know is orrible):

 template <typename T, std::size_t BS>
T constexpr SqBCSmatrix<T,BS>::findValue(const std::size_t r, const std::size_t c) const noexcept
{
    //for each BCRS row
    for(auto i=0 ,k=0; i < denseRows / BS ; i++){
        //for each Block sub row.
        for(auto rBlock = 0; rBlock < BS; k++ ,rBlock++){
            //for each BCSR col.
            for(auto j = 1 , l=0; j <= denseCols / BS; j++){
                //for each Block sub col.
                for(auto cBlock = 0; cBlock < BS; l++ , cBlock++){
                      if(k == r && c == l )
                          return findVal(i,j,rBlock, cBlock);

                }
            }
        }
    }
    return 0;
}


问:
java - object initialization syntax: someVar = (SomeClass[]) Object[aVariable]
In the following code snippet from https://introcs.cs.princeton.edu/java/44st/BinarySearchST.java.html
what does keys = (Key[]) new Comparable[initCapacity]; do?

```<code>public class BinarySearchST<Key extends Comparable<Key>, Value> {
    private static final int INIT_SIZE = 8;

    private Value[] vals;    // symbol table values
    private Key[] keys;      // symbol table keys
    private int n = 0;       // number of elements

    public BinarySearchST() {
        this(INIT_SIZE);
    }

    public BinarySearchST(int initCapacity) {
        vals = (Value[]) new Object[initCapacity];
        keys = (Key[]) new Comparable[initCapacity];
    } ...
</code>```

答:
You can break it down like this:

Initialize a new Object array of size initCapacity

```<code>Object [] someValues = new Object[initCapacity];
Comparable [] someComparable = new Comparable[initCapacity];
</code>```

Then typecast the array to an array of type Value

```<code>vals = (Value[]) someValues;
keys = (Keys[]) someComparable;
</code>```

Your statement above is doing these operations on single lines.
Keep in mind you have declared vals as an array of Values and keys as an array of Keys.

Body:
In the following code snippet from https://introcs.cs.princeton.edu/java/44st/BinarySearchST.java.html
what does keys = (Key[]) new Comparable[initCapacity]; do?

public class BinarySearchST<Key extends Comparable<Key>, Value> {
    private static final int INIT_SIZE = 8;

    private Value[] vals;    // symbol table values
    private Key[] keys;      // symbol table keys
    private int n = 0;       // number of elements

    public BinarySearchST() {
        this(INIT_SIZE);
    }

    public BinarySearchST(int initCapacity) {
        vals = (Value[]) new Object[initCapacity];
        keys = (Key[]) new Comparable[initCapacity];
    } ...

Body:
You can break it down like this:

Initialize a new Object array of size initCapacity

Object [] someValues = new Object[initCapacity];
Comparable [] someComparable = new Comparable[initCapacity];

Then typecast the array to an array of type Value

vals = (Value[]) someValues;
keys = (Keys[]) someComparable;

Your statement above is doing these operations on single lines.
Keep in mind you have declared vals as an array of Values and keys as an array of Keys.


问:
Update trunk with tag created with Maven Release plugin
I have a working Maven release process but I still need to do some manual tasks.

Here's a summary of the process:

release:prepare

release:perform

I run the above in the development branch. This of course creates a tag and then updates the branch with the next development version. In my case I would like it also to update trunk. I like to have trunk with the code of the latest release, but if I do a merge/pull it'll copy the new development version not the last release.

Is there a way to get in there or doing it manually is the only way?

答:
If you know the tag name you can simply:

```<code>git push origin release-x.y.z:refs/heads/master
</code>```

Or if you know that the latest release is the previous commit, then:

```<code>git push origin HEAD~1:refs/heads/master
</code>```

You can probably configure this via Maven SCM Plugin. But if there is a possibility that master was updated, then this would fail and you'd have to merge manually.

PS: Heh, there are still people who use Maven Release Plugin :)

Body:
If you know the tag name you can simply:

git push origin release-x.y.z:refs/heads/master

Or if you know that the latest release is the previous commit, then:

git push origin HEAD~1:refs/heads/master

You can probably configure this via Maven SCM Plugin. But if there is a possibility that master was updated, then this would fail and you'd have to merge manually.

PS: Heh, there are still people who use Maven Release Plugin :)


问:
Transitive efficient comparison and value assignment to dataframe variables in R?
I have 3 data frames:

df1:

```<code>    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     T
4    rs530296     A
5  rs10497340     G
</code>```

df2:

```<code>    key       value
1   rs1057079     T
2   rs4845882     G
3   rs1891932     T
4    rs530296     A
5  rs10497340     A
</code>```

and third control df3:

```<code>    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     C
4    rs530296     G
5  rs10497340     G
</code>```

I want to check for all keys in df1 and df2 if they are equal or not to the control df3. For example check if df1$rs1057079 == df3$rs1057079, same with df2.

I want to do this without a for loop, what is the most simple and efficient way?
I thought about dplyr filter and mutate functions but will be happy to hear from the experts how to compare n df's to a control df?

答:
If we can assume that all keys present in df1 and df2 will be present in df3, and they are sorted in the same order, the solution is fairly straightforward:

```<code>df1$value==df3$value
df2$value==df3$value
</code>```

This output a vector of TRUE and FALSE where every element is the answer for a line in df1 and df2.

Body:
I have 3 data frames:

df1:

    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     T
4    rs530296     A
5  rs10497340     G

df2:

    key       value
1   rs1057079     T
2   rs4845882     G
3   rs1891932     T
4    rs530296     A
5  rs10497340     A

and third control df3:

    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     C
4    rs530296     G
5  rs10497340     G

I want to check for all keys in df1 and df2 if they are equal or not to the control df3. For example check if df1$rs1057079 == df3$rs1057079, same with df2.

I want to do this without a for loop, what is the most simple and efficient way?
I thought about dplyr filter and mutate functions but will be happy to hear from the experts how to compare n df's to a control df?

Body:
If we can assume that all keys present in df1 and df2 will be present in df3, and they are sorted in the same order, the solution is fairly straightforward:

df1$value==df3$value
df2$value==df3$value

This output a vector of TRUE and FALSE where every element is the answer for a line in df1 and df2.


问:
Button to change color of
I am trying to make an interactive periodic table of elements. I need to change the background color of more  with the classname "nemetale" when a button is clicked. It's not working, I don't know what I am doing wrong.

There is the button

```<code> <button onclick="document.getElementsByClassName('.nemetale').style.backgroundColor = 'red';">Nemetale</button>
</code>```

There is one of the s.

```<code><table class="tabel_periodic">
  <!--Randul 1-->
  <tr>

   <td class="nemetale">
    <strong>1</strong><br>
    <acronym>H</acronym><br>
    <em>Hidrogen</em><br>
    <i>1,008</i>
   </td>
 ...
</code>```

答:
Two things:

Firstly, there is a typo in the function you call. It should be getElementsByClassName().

Secondly, getElementsByClassName() returns a NodeList. This is “like” an Array, but it means you have to select each item from the NodeList.

If there is only one element, you can do

document.getElementsByClassName('nemetale')[0].style.backgroundColor = 'red';

If there is more than one element you will have to loop through the items. I recommend making it a function.

```<code><button onclick="highlight">Nemetale</button>

function highlight() {
    var items = document.getElementsByClassName('nemetale');

    Array.from(items).forEach(function(item) {
        item.style.backgroundColor = 'red';
    });
}
</code>```

If you are using ES6, you can make it a bit shorter as well:

```<code>function highlight() {
    const items = document.getElementsByClassName('nemetale');

    Array.from(items).forEach(item => item.style.backgroundColor = 'red');
}
</code>```

Title: Button to change color of <td>

Body:
I am trying to make an interactive periodic table of elements. I need to change the background color of more  with the classname "nemetale" when a button is clicked. It's not working, I don't know what I am doing wrong.

There is the button

 <button onclick="document.getElementsByClassName('.nemetale').style.backgroundColor = 'red';">Nemetale</button>

There is one of the s.

    1

    <acronym>H</acronym>

    Hidrogen

    1,008

 ...

Body:
Two things:

Firstly, there is a typo in the function you call. It should be getElementsByClassName().

Secondly, getElementsByClassName() returns a NodeList. This is “like” an Array, but it means you have to select each item from the NodeList.

If there is only one element, you can do

document.getElementsByClassName('nemetale')[0].style.backgroundColor = 'red';

If there is more than one element you will have to loop through the items. I recommend making it a function.

<button onclick="highlight">Nemetale</button>

function highlight() {
    var items = document.getElementsByClassName('nemetale');

    Array.from(items).forEach(function(item) {
        item.style.backgroundColor = 'red';
    });
}

If you are using ES6, you can make it a bit shorter as well:

function highlight() {
    const items = document.getElementsByClassName('nemetale');

    Array.from(items).forEach(item => item.style.backgroundColor = 'red');
}


问:
Ansible ssh giving permission denied error
I am trying to execute an ansible script against a server1.xxx.com, I am getting a permission denied error.

I have created a ssh key using command

```<code>ssh-keygen -f t11pkey
</code>```

and also have added passphrase, copied the key to the server.

```<code>ssh-copy-id -i /home/user.name/t11pkey.pub user.name@server1.xxx.com
</code>```

my ~/.ssh/config

```<code>Host server?.xxx.com
  User user.name
  Port 22
  IdentityFile /home/user.name/.ssh/t11pkey.pub
</code>```

Permission of my keys:

```<code>-rw-------  1 user.name Domain Users  1766 Dec  5 10:55 t11pkey
-rw-------  1 user.name Domain Users   412 Dec  5 10:55 t11pkey.pub
</code>```

ansible.cfg

```<code>[defaults]
filter_plugins =./filter_plugins
roles_path = ./roles
sudo_user = root
host_key_checking = False
retry_files_enabled = False

[ssh_connection]
ssh_args = -F /home/user.name/.ssh/config -o ControlMaster=auto -o ControlPersist=30m
control_path = ~/.ssh/ansible-%%r@%%h:%%p
</code>```

inventory file

```<code>[new]
server1.xxx.com
</code>```

my ansible-playbook

```<code>- hosts: new
  remote_user: user.name
  become: true
  vars_files:
    - xx.yml
    - xx.yml
    - xx.yml
  roles:
    - role: ~/path/to/the/role
</code>```

Anisble error:

```<code> TASK [Gathering Facts] *****************************************************************************************************************************************************
Enter passphrase for key '/home/user.name/.ssh/t11pkey.pub':
Enter passphrase for key '/home/user.name/.ssh/t11pkey.pub':
Enter passphrase for key '/home/user.name/.ssh/t11pkey.pub':
fatal: [server1.xxx.com]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", "unreachable": true}
</code>```

ansible --version: ansible 2.3.1.0 (stable-2.3 5512c94017) last updated 2017/06/21 22:56:43 (GMT -400)

答: IdentityFile parameter in the config file should point to the private key (t11pkey), not the public one (t11pkey.pub).

Body:
I am trying to execute an ansible script against a server1.xxx.com, I am getting a permission denied error.

I have created a ssh key using command

ssh-keygen -f t11pkey

and also have added passphrase, copied the key to the server.

ssh-copy-id -i /home/user.name/t11pkey.pub user.name@server1.xxx.com

my ~/.ssh/config

Host server?.xxx.com
  User user.name
  Port 22
  IdentityFile /home/user.name/.ssh/t11pkey.pub

Permission of my keys:

-rw-------  1 user.name Domain Users  1766 Dec  5 10:55 t11pkey
-rw-------  1 user.name Domain Users   412 Dec  5 10:55 t11pkey.pub

ansible.cfg

[defaults]
filter_plugins =./filter_plugins
roles_path = ./roles
sudo_user = root
host_key_checking = False
retry_files_enabled = False

[ssh_connection]
ssh_args = -F /home/user.name/.ssh/config -o ControlMaster=auto -o ControlPersist=30m
control_path = ~/.ssh/ansible-%%r@%%h:%%p

inventory file

[new]
server1.xxx.com

my ansible-playbook

- hosts: new
  remote_user: user.name
  become: true
  vars_files:
    - xx.yml
    - xx.yml
    - xx.yml
  roles:
    - role: ~/path/to/the/role

Anisble error:

 TASK [Gathering Facts] *****************************************************************************************************************************************************
Enter passphrase for key '/home/user.name/.ssh/t11pkey.pub':
Enter passphrase for key '/home/user.name/.ssh/t11pkey.pub':
Enter passphrase for key '/home/user.name/.ssh/t11pkey.pub':
fatal: [server1.xxx.com]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", "unreachable": true}

ansible --version: ansible 2.3.1.0 (stable-2.3 5512c94017) last updated 2017/06/21 22:56:43 (GMT -400)


问:
Access Attributes Values of Variable in XML Format in JavaScript
I have a remote Web service that returns to my JavaScript Web app the variable "DATA" defined in XML format.

An example of the data returned by a request would be:

```<code><DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>
</code>```

In JavaScript, how can I access the values of its attributes, i.e. the "1" as the ID and "JOHN SMITH" as the NAME?

For simplification,

```<code>(...)

var DATA = <DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>;
var ID = ??; //HOW TO ACCESS THE VALUE OF ID IN DATA?
var NAME = ??; //HOW TO ACCESS THE VALUE OF NAME IN DATA?

(...)
</code>```

Thank you!

答:
Use DomParser and querySelector

var xml = "<DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>";
var doc = new DOMParser().parseFromString(xml, "text/xml");

console.log(doc.querySelector( "ID" ).innerHTML);
console.log(doc.querySelector( "NAME" ).innerHTML);```

Body:
I have a remote Web service that returns to my JavaScript Web app the variable "DATA" defined in XML format.

An example of the data returned by a request would be:

<DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>

In JavaScript, how can I access the values of its attributes, i.e. the "1" as the ID and "JOHN SMITH" as the NAME?

For simplification,

(...)

var DATA = <DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>;
var ID = ??; //HOW TO ACCESS THE VALUE OF ID IN DATA?
var NAME = ??; //HOW TO ACCESS THE VALUE OF NAME IN DATA?

(...)

Thank you!


问:
QBO3 Attachment Templates - header images from a URL
We have hundreds of attachment templates in QBO that are based on Microsoft Word templates, and each embed our company logo in the header.

Rather than having the template show the header and footer in each document we would like to consider the possibility of saving the Headers & Footers as Images in QBO and just having the Template reference the saved image when it generates the letters.

We are not sure how or where the image would be stored and how the reference in the attachment template would work.

答:
When you are doing this the link to the image needs to be one that the server creating the document (QBO, in this case) can access. If the image is located locally on your computer such as the image below then when creating the document you will get a red x instead of the image.

If the link is to a location that is publically available (like your corporate website), Word will be able to render the image in the document regardless of where Word is running.


问:
Getting files by creation date in .NET
I have a folder which contains many files. Is there any easy way to get the file names in the directory sorted by their creation date/time?

If I use Directory.GetFiles(), it returns the files sorted by their file name.

答:
this could work for you.</p>

```<code>using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}
</code>```

Title: Getting files by creation date in .NET

Body:
this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}