问:
Show popover on button click using jquery
I am trying to display notification message by using popover, it is working but after loading a page if i click button first time it doesn't show the popover after that it works fine here is my code-

```<code><button type="button" id="bulk_actions_btn" class="btn btn-default has-spinner-two" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="Click any question mark icon to get help and tips with specific tasks"> Apply </button>
</code>```

Jquery

```<code>$(document).on('click','#bulk_actions_btn',function(){

   if(condition){
        $('[data-toggle="popover"]').popover(); //here if the condition is true then popover should be display.
    }else{
       //ajax
    }
});
</code>```

答:
You should take a look to popovers methods:

In order to show the popover you need to use:

```<code>$('#element').popover('show');
</code>```

Instead to use:

```<code>$('[data-toggle="popover"]')
</code>```

selector I suggest you to address directly your element.

```<code>$('#bulk_actions_btn_new')  or $(this)
</code>```

If you want to use the data attribute for selecting elements you need to use the filter function.

In order to avoid flickering effects you can show the popover only if it is hidden. If you click too fast on the button you can avoid to hide the popover handling the hide.bs.popover event.

The snippet:

$(document).on('click', '#bulk_actions_btn', function (e) {
    //
    // If popover is visible: do nothing
    //
    if ($(this).prop('popShown') == undefined) {
       $(this).prop('popShown', true).popover('show');
    }
});

$(function () {
    $('#bulk_actions_btn').on('hide.bs.popover', function (e) {
        //
        // on hiding popover stop action
        //
        e.preventDefault();
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<button type="button" id="bulk_actions_btn"
        class="btn btn-default has-spinner-two"
        data-toggle="popover"
        data-placement="bottom" data-original-title=""
        data-content="Click any question mark icon to get help and tips with specific tasks"
        aria-describedby="popover335446"> Apply
</button></code>```

Body:
I am trying to display notification message by using popover, it is working but after loading a page if i click button first time it doesn't show the popover after that it works fine here is my code-

<button type="button" id="bulk_actions_btn" class="btn btn-default has-spinner-two" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="Click any question mark icon to get help and tips with specific tasks"> Apply </button>

Jquery

$(document).on('click','#bulk_actions_btn',function(){

   if(condition){
        $('[data-toggle="popover"]').popover(); //here if the condition is true then popover should be display.
    }else{
       //ajax
    }
});

Body:
You should take a look to popovers methods:

In order to show the popover you need to use:

$('#element').popover('show');

Instead to use:

$('[data-toggle="popover"]')

selector I suggest you to address directly your element.

$('#bulk_actions_btn_new')  or $(this)

If you want to use the data attribute for selecting elements you need to use the filter function.

In order to avoid flickering effects you can show the popover only if it is hidden. If you click too fast on the button you can avoid to hide the popover handling the hide.bs.popover event.

The snippet:

$(document).on('click', '#bulk_actions_btn', function (e) {
    //
    // If popover is visible: do nothing
    //
    if ($(this).prop('popShown') == undefined) {
       $(this).prop('popShown', true).popover('show');
    }
});

$(function () {
    $('#bulk_actions_btn').on('hide.bs.popover', function (e) {
        //
        // on hiding popover stop action
        //
        e.preventDefault();
    });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<button type="button" id="bulk_actions_btn"
        class="btn btn-default has-spinner-two"
        data-toggle="popover"
        data-placement="bottom" data-original-title=""
        data-content="Click any question mark icon to get help and tips with specific tasks"
        aria-describedby="popover335446"> Apply
</button>


来源: stackexchange

问:
Unexpected bitmap size after re-sampling a PNG using BitmapFactory.decodeResource()
I have a PNG file located in the res/drawable folder. Its size is 2524*2524.

Before loading it into an ImageView, I would like to resize it according to the dimension of the ImageView. So I wrote the following utility code to resize the PNG to a Bitmap. (Slightly modified version of the one from https://developer.android.com/topic/performance/graphics/load-bitmap.html)

public static Bitmap decodeSampledBitmapFromResource(
        Resources res, int resId, int targetWidth, int targetHeight) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
    options.inJustDecodeBounds = false;
    Bitmap result = BitmapFactory.decodeResource(res, resId, options);

    Log.d(TAG, "Result bitmap size: " + result.getWidth() + "*" + result.getHeight());
    return result;
}

private static int calculateInSampleSize(
        BitmapFactory.Options options, int targetWidth, int targetHeight) {

    Log.d(TAG, "Target bitmap size: " + targetWidth + "*" + targetHeight);
    int width = options.outWidth;
    int height = options.outHeight;
    Log.d(TAG, "Source bitmap size: " + width + "*" + height);

    int inSampleSize = 1;
    while ((width /= 2) >= targetWidth &&
            (height /= 2) >= targetHeight) {
        inSampleSize *= 2;
    }

    Log.d(TAG, "inSampleSize: " + inSampleSize);
    return inSampleSize;
}
```

<p>In my case, the source PNG image is of <strong>2524*2524</strong>, and the <code>ImageView</code> is of <strong>500*500</strong> in <strong>pixel</strong> size. So I am expecting the value of <code>inSampleSize</code> to be <strong>4</strong> and the re-sampled bitmap's size to be of <strong>631*631</strong> (2524/4 * 2524/4). </p>

<p>However, the log gives me the following info:</p>

```D/ImageResizer: Target bitmap size: 500*500
D/ImageResizer: Source bitmap size: 2524*2524
D/ImageResizer: inSampleSize: 4
D/ImageResizer: Result bitmap size: 1656*1656
```

The value of inSampleSize is correct. But the result bitmap size is not what I am expecting. 2524 is not even divisible by 1656. Why is that?

答:
Decoding from resource will unasked adapt image files to gui dimensions.

Better put the file in assets directory.

And use assets manager and decodeFromStream().

ContentLicense: CC BY-SA 3.0

Body:
I have a PNG file located in the res/drawable folder. Its size is 2524*2524.

Before loading it into an ImageView, I would like to resize it according to the dimension of the ImageView. So I wrote the following utility code to resize the PNG to a Bitmap. (Slightly modified version of the one from https://developer.android.com/topic/performance/graphics/load-bitmap.html)

public static Bitmap decodeSampledBitmapFromResource(
        Resources res, int resId, int targetWidth, int targetHeight) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
    options.inJustDecodeBounds = false;
    Bitmap result = BitmapFactory.decodeResource(res, resId, options);

    Log.d(TAG, "Result bitmap size: " + result.getWidth() + "*" + result.getHeight());
    return result;
}

private static int calculateInSampleSize(
        BitmapFactory.Options options, int targetWidth, int targetHeight) {

    Log.d(TAG, "Target bitmap size: " + targetWidth + "*" + targetHeight);
    int width = options.outWidth;
    int height = options.outHeight;
    Log.d(TAG, "Source bitmap size: " + width + "*" + height);

    int inSampleSize = 1;
    while ((width /= 2) >= targetWidth &&
            (height /= 2) >= targetHeight) {
        inSampleSize *= 2;
    }

    Log.d(TAG, "inSampleSize: " + inSampleSize);
    return inSampleSize;
}

In my case, the source PNG image is of 2524*2524, and the ImageView is of 500*500 in pixel size. So I am expecting the value of inSampleSize to be 4 and the re-sampled bitmap's size to be of 631*631 (2524/4 * 2524/4).

However, the log gives me the following info:

D/ImageResizer: Target bitmap size: 500*500
D/ImageResizer: Source bitmap size: 2524*2524
D/ImageResizer: inSampleSize: 4
D/ImageResizer: Result bitmap size: 1656*1656

The value of inSampleSize is correct. But the result bitmap size is not what I am expecting. 2524 is not even divisible by 1656. Why is that?


问:
VBScript in HTA to hide an HTML div, "Object Required"
I've got some code that is meant to hide a div in HTML if a variable is empty.

Sub checkBattery
    If IsEmpty(e("batremaining")) Then
        batteryShow.style.visibility = "hidden"
    Else
        batteryShow.style.visibility = "visible"
    End If
End Sub

checkBattery
```

<p>This is extremely frustrating me, because I have no idea why it is not working.</p>

<p>Here is my <code><div></code>:</p>

<pre class="lang-html prettyprint-override"><code><div id="batteryShow" class="panel panel-warning batteryShow">
    <div class="panel-heading">
        <h3 class="panel-title">Battery Percentage</h3>
    </div>
    <div class="panel-body">
        <center><div style="font-size:16px;font-weight:bold;">Battery Level: 100%</div></center>
    </div>
</div>
</code>```

I am probably missing something extremely simple and easy to fix, but I cannot for the life of me figure out what.

答:
So my problem was I was running the code too early.

What I did to fix it was I made a new function called handler, which I put calls to do things that I needed to do on page load.

```<code>Function handler()
    checkBattery
    ... ETC ...
End Function
</code>```

And in the body of my script I used

```<code><body onLoad="VBScript:handler()">
</code>```

Body:
I've got some code that is meant to hide a div in HTML if a variable is empty.

Sub checkBattery
    If IsEmpty(e("batremaining")) Then
        batteryShow.style.visibility = "hidden"
    Else
        batteryShow.style.visibility = "visible"
    End If
End Sub

checkBattery

This is extremely frustrating me, because I have no idea why it is not working.

Here is my
:

Battery Percentage

Battery Level: 100%

I am probably missing something extremely simple and easy to fix, but I cannot for the life of me figure out what.

Body:
So my problem was I was running the code too early.

What I did to fix it was I made a new function called handler, which I put calls to do things that I needed to do on page load.

Function handler()
    checkBattery
    ... ETC ...
End Function

And in the body of my script I used

<body onLoad="VBScript:handler()">

ContentLicense: CC BY-SA 4.0


问:
Why is the ternary operator used to define 1 and 0 in a macro?
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

```<code>#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
</code>```

Does the use of the ternary operator here make any difference?

Isn't

```<code>#define FOO (1 > 0)
</code>```

the same as

```<code>#define BAR ( (1 > 0) ? 1 : 0)
</code>```

?

I tried evaluating it by using

```<code>printf("%d", FOO == BAR);
</code>```

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

答:
You are correct, in C it is tautologous. Both your particular ternary conditional and (1 > 0) are of type int.

But it would matter in C++ though, in some curious corner cases (e.g. as parameters to overloaded functions), since your ternary conditional expression is of type int, whereas (1 > 0) is of type bool.

My guess is that the author has put some thought into this, with an eye to preserving C++ compatibility.

Body:
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )

Does the use of the ternary operator here make any difference?

Isn't

#define FOO (1 > 0)

the same as

#define BAR ( (1 > 0) ? 1 : 0)

?

I tried evaluating it by using

printf("%d", FOO == BAR);

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?


问:
What is wrong with my logic my button only changes once and the onclick function stops?
I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to <code>.temp</code>. </p>

```<code>$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" <a class='temp' href='#'>F</a>");
  });
});
</code>```

答:
Check this Fiddle it's working example but missing this part (temp.main.temp):

```<code>$( document ).ready(function() {

$(document).on("click", ".temp", function() {
    $('#temperature').empty();
  $("#temperature").append(" <a class='temper' href='#'>C</a>");
});
$(document).on("click", ".temper", function() {
$('#temperature').empty();
  $("#temperature").append(" <a class='temp' href='#'>F</a>");
  });
});
</code>```

https://jsfiddle.net/Kanzari/n38xs8sn/2/

Body:
I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to .temp.

$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " C");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" F");
  });
});

Body:
Check this Fiddle it's working example but missing this part (temp.main.temp):

$( document ).ready(function() {

$(document).on("click", ".temp", function() {
    $('#temperature').empty();
  $("#temperature").append(" <a class='temper' href='#'>C</a>");
});
$(document).on("click", ".temper", function() {
$('#temperature').empty();
  $("#temperature").append(" <a class='temp' href='#'>F</a>");
  });
});

https://jsfiddle.net/Kanzari/n38xs8sn/2/


问:
Filter items with certain text in a Pivot Table using VBA
I've been trying to build a code to filter all items within a Pivot Table which contain a specific text fragment. I initially imagined I could use asterisks (*) to indicate any string before or after my text, but VBA reads that as a character instead. This is necessary to display the Pivot Table array in a Userform Listbox. Look what I tried:</p>

```<code>Sub FilterCstomers()

    Dim f As String: f = InputBox("Type the text you want to filter:")

    With Sheets("Customers Pivot").PivotTables("Customers_PivotTable")
        .ClearAllFilters
        .PivotFields("Concatenation for filtering").CurrentPage = "*f*"
        End With

End Sub
</code>```

答:
You can tweak Shai's answer to significantly speed things up, by:

removing the TRUE branch of the IF as it is not needed

setting ManualUpdate to TRUE while the code executes, to stop the
PivotTable from recalculating each time you change the visible
status of any PivotItems.

Turning off screen updating and calculation (in case there are
volatile functions in the workbook) until you are done

You probably also want to put an Option CompareText in there if you want your comparisons to be case insensitive.

And you probably want some error handling in case the user types something that doesn't exist in the PivotTable.

You might want to give my blogpost on this stuff a read, because PivotTables are very slow to filter, and it discusses many ways to speed things up

Here's a reworked example of Shai's code:

```<code>Option Explicit
Option Compare Text

Sub FilterCstomers()

    Dim pt  As PivotTable
    Dim pf  As PivotField
    Dim pi  As PivotItem
    Dim f   As String

    f = InputBox("Type the text you want to filter:")
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set pt = Sheets("Customers Pivot").PivotTables("Customers_PivotTable")
    Set pf = pt.PivotFields("Concatenation for filtering")
    pt.ManualUpdate = True
    With pf
        .ClearAllFilters
        On Error GoTo ErrHandler
        For Each pi In .PivotItems
            If Not pi.Name Like "*" & f & "*" Then
                pi.Visible = False
            End If
        Next pi

    End With
ErrHandler:
        If Err.Number <> 0 Then pf.ClearAllFilters
        pt.ManualUpdate = False
        On Error GoTo 0
        With Application
            .ScreenUpdating = True
            .Calculation = xlCalculationAutomatic
        End With
    End Sub
</code>```

Body:
I've been trying to build a code to filter all items within a Pivot Table which contain a specific text fragment. I initially imagined I could use asterisks (*) to indicate any string before or after my text, but VBA reads that as a character instead. This is necessary to display the Pivot Table array in a Userform Listbox. Look what I tried:

Sub FilterCstomers()

    Dim f As String: f = InputBox("Type the text you want to filter:")

    With Sheets("Customers Pivot").PivotTables("Customers_PivotTable")
        .ClearAllFilters
        .PivotFields("Concatenation for filtering").CurrentPage = "*f*"
        End With

End Sub

Body:
You can tweak Shai's answer to significantly speed things up, by:

removing the TRUE branch of the IF as it is not needed

setting ManualUpdate to TRUE while the code executes, to stop the
PivotTable from recalculating each time you change the visible
status of any PivotItems.

Turning off screen updating and calculation (in case there are
volatile functions in the workbook) until you are done

You probably also want to put an Option CompareText in there if you want your comparisons to be case insensitive.

And you probably want some error handling in case the user types something that doesn't exist in the PivotTable.

You might want to give my blogpost on this stuff a read, because PivotTables are very slow to filter, and it discusses many ways to speed things up

Here's a reworked example of Shai's code:

Option Explicit
Option Compare Text

Sub FilterCstomers()

    Dim pt  As PivotTable
    Dim pf  As PivotField
    Dim pi  As PivotItem
    Dim f   As String

    f = InputBox("Type the text you want to filter:")
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set pt = Sheets("Customers Pivot").PivotTables("Customers_PivotTable")
    Set pf = pt.PivotFields("Concatenation for filtering")
    pt.ManualUpdate = True
    With pf
        .ClearAllFilters
        On Error GoTo ErrHandler
        For Each pi In .PivotItems
            If Not pi.Name Like "*" & f & "*" Then
                pi.Visible = False
            End If
        Next pi

    End With
ErrHandler:
        If Err.Number <> 0 Then pf.ClearAllFilters
        pt.ManualUpdate = False
        On Error GoTo 0
        With Application
            .ScreenUpdating = True
            .Calculation = xlCalculationAutomatic
        End With
    End Sub


问:
How can I implement DbContext Connection String in .NET Core?
My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.

Pass connection string to code-first DbContext

My specific code is as follows:

```<code>public partial class CompanyFormsContext : DbContext
{
    public CompanyFormsContext()
        : base("name=CompanyFormsContext")
    {
    }

    public CompanyFormsContext(string connName)
        : base("name=" + connName)
    {
    }
    ...
}
</code>```

I get an error saying:

Error  CS1503  Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'    CompanyForms..NETCoreApp,Version=v1.0

when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).

What is the correct way of implementing this functionality in .NET Core?

Edit:

I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)

```<code>  "Data": {
    "CompanyFormsContext": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    },
    "CompanyFormsContextQA": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    }
  }
</code>```

and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?

From the link:

```<code>services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyDbContext>(
        options =>
        options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
    );
</code>```

Do I need this kind of a service in my Startup.cs?

答:
Another option would be to call the base constructor that takes a DbContextOptions:</p>

```<code>public BooksContext(string connectionString) : base(GetOptions(connectionString))
{
}

private static DbContextOptions GetOptions(string connectionString)
{
    return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
</code>```

Body:
My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.

Pass connection string to code-first DbContext

My specific code is as follows:

public partial class CompanyFormsContext : DbContext
{
    public CompanyFormsContext()
        : base("name=CompanyFormsContext")
    {
    }

    public CompanyFormsContext(string connName)
        : base("name=" + connName)
    {
    }
    ...
}

I get an error saying:

Error  CS1503  Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'    CompanyForms..NETCoreApp,Version=v1.0

when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).

What is the correct way of implementing this functionality in .NET Core?

Edit:

I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)

  "Data": {
    "CompanyFormsContext": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    },
    "CompanyFormsContextQA": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    }
  }

and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?

From the link:

services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyDbContext>(
        options =>
        options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
    );

Do I need this kind of a service in my Startup.cs?

Body:
Another option would be to call the base constructor that takes a DbContextOptions:

public BooksContext(string connectionString) : base(GetOptions(connectionString))
{
}

private static DbContextOptions GetOptions(string connectionString)
{
    return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}


问:
Cannot convert value of type string to type url in coercion

I'm receiving the error Cannot convert value of type string
  to type url in coercion at this constant. Thanks for the help ahead of time :)

```<code>**let safariVC = SFSafariViewController(url: JobUrl as URL)**
</code>```

```<code>import UIKit
import SafariServices

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //Indeed API Query as JSON
   final let urlString = "http://api.indeed.com/ads/apisearch?publisher=9727336427429597&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=parttime&st=&salary=&radius=25&l=32304&fromage=any&limit=25&sort=&psf=advsrch=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&format=json"

    @IBOutlet weak var tableView: UITableView!

    var jobTitleArray = [String]()
    var snippetArray = [String]()
    var companyArray = [String]()
    var cityArray = [String]()
    var jobUrlArray = [String]()

//    url = URL(string: epsDictionary["link"] as! String)

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadJsonWithURL()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        //dispose of any resources that can be recreated
    }

    //fetch Json
    func downloadJsonWithURL() {
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
            Void in

            if let JsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                as? NSDictionary {
                print(JsonObj!.value(forKey: "results")!)

                if let resultsArray = JsonObj!.value(forKey: "results") as? NSArray {
                    for result in resultsArray {
                        if let resultDict = result as? NSDictionary {

                            if let jobTitle = resultDict.value(forKey: "jobtitle") {
                                self.jobTitleArray.append(jobTitle as! String)
                            }
                            if let snippet = resultDict.value(forKey: "snippet") {
                                self.snippetArray.append(snippet as! String)
                            }
                            if let company = resultDict.value(forKey: "company") {
                                self.companyArray.append(company as! String)
                            }
                            if let city = resultDict.value(forKey: "formattedRelativeTime") {
                                self.cityArray.append(city as! String)
                            }
                            if let jobUrl1 = resultDict.value(forKey: "url") {
                                self.jobUrlArray.append(jobUrl1 as! String)
                            }

                            OperationQueue.main.addOperation({
                                self.tableView.reloadData()
                            })
                        }

                    }
                }

            }

        }).resume()
    }

    func downloadJsonWithTask() {
        let url = NSURL(string: urlString)

        var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

        downloadTask.httpMethod = "Get"

        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
        Void in

        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

            print(jsonData!)

        }).resume()

    }

     var jobToUrl = URL(string: "http://www.indeed.com/viewjob?jk=5de353a4c580dce0&qd=8FiWEXDXvmdNb_GJC9BAOpLFMiNO7rztIOPtGp_-cISTa1VWcmBigetsBoobMSCXdNyr-z6ge7UiYg2Mx15EH6m1Aj3izkOw87NHJgxznYA&indpubnum=9727336427429597&atk=1bchrhjof5hgga1k")

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        print("USER SELECTED CELL")
        let JobUrl = jobUrlArray[indexPath.row]

        **let safariVC = SFSafariViewController(url: JobUrl as URL)**
        self.present(safariVC, animated: true, completion: nil)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return jobTitleArray.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        cell.jobTitle.text = jobTitleArray[indexPath.row]
        cell.jobSummary.text = snippetArray[indexPath.row]
        cell.employerName.text = companyArray[indexPath.row]
        cell.cityName.text = cityArray[indexPath.row]
        cell.ApplyButton.text = jobUrlArray[indexPath.row]

//        let imageUrl = NSURL(string: imageUrlArray[indexPath.row])

//        if imageUrl != nil {
//            let data = NSData(contentsOf: (imageUrl as? URL)!)
//            cell.imageView?.image = UIImage (data: data as! Data)
//        }

        return cell

    }

}
</code>```

答:
URL is an object which has different properties (like absoluteString,path, scheme etc. which are String objects themselves) so you cannot cast URL to String, they are different types.

With an URL you can use the URLSession class to access the contents of remote resource or represent a local path for example. Check the documentation and be sure that you know the classes you're using.

https://developer.apple.com/reference/foundation/nsurl

In Swift try to create a URL with String (through unwrapping):

```<code>if let url = URL(String: jobUrlArray[indexPath.row]) {
     let safariVC = SFSafariViewController(url: jobUrl)
}
</code>```

or use url? in code

but be sure you don't use explicitly unwrapped optional like:

```<code>let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)
</code>```

your code might crash, it's not safe.

Body:
I'm receiving the error Cannot convert value of type string
  to type url in coercion at this constant. Thanks for the help ahead of time :)

**let safariVC = SFSafariViewController(url: JobUrl as URL)**

import UIKit
import SafariServices

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //Indeed API Query as JSON
   final let urlString = "http://api.indeed.com/ads/apisearch?publisher=9727336427429597&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=parttime&st=&salary=&radius=25&l=32304&fromage=any&limit=25&sort=&psf=advsrch=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&format=json"

    @IBOutlet weak var tableView: UITableView!

    var jobTitleArray = [String]()
    var snippetArray = [String]()
    var companyArray = [String]()
    var cityArray = [String]()
    var jobUrlArray = [String]()

//    url = URL(string: epsDictionary["link"] as! String)

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadJsonWithURL()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        //dispose of any resources that can be recreated
    }

    //fetch Json
    func downloadJsonWithURL() {
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
            Void in

            if let JsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                as? NSDictionary {
                print(JsonObj!.value(forKey: "results")!)

                if let resultsArray = JsonObj!.value(forKey: "results") as? NSArray {
                    for result in resultsArray {
                        if let resultDict = result as? NSDictionary {

                            if let jobTitle = resultDict.value(forKey: "jobtitle") {
                                self.jobTitleArray.append(jobTitle as! String)
                            }
                            if let snippet = resultDict.value(forKey: "snippet") {
                                self.snippetArray.append(snippet as! String)
                            }
                            if let company = resultDict.value(forKey: "company") {
                                self.companyArray.append(company as! String)
                            }
                            if let city = resultDict.value(forKey: "formattedRelativeTime") {
                                self.cityArray.append(city as! String)
                            }
                            if let jobUrl1 = resultDict.value(forKey: "url") {
                                self.jobUrlArray.append(jobUrl1 as! String)
                            }

                            OperationQueue.main.addOperation({
                                self.tableView.reloadData()
                            })
                        }

                    }
                }

            }

        }).resume()
    }

    func downloadJsonWithTask() {
        let url = NSURL(string: urlString)

        var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

        downloadTask.httpMethod = "Get"

        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
        Void in

        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

            print(jsonData!)

        }).resume()

    }

     var jobToUrl = URL(string: "http://www.indeed.com/viewjob?jk=5de353a4c580dce0&qd=8FiWEXDXvmdNb_GJC9BAOpLFMiNO7rztIOPtGp_-cISTa1VWcmBigetsBoobMSCXdNyr-z6ge7UiYg2Mx15EH6m1Aj3izkOw87NHJgxznYA&indpubnum=9727336427429597&atk=1bchrhjof5hgga1k")

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        print("USER SELECTED CELL")
        let JobUrl = jobUrlArray[indexPath.row]

        **let safariVC = SFSafariViewController(url: JobUrl as URL)**
        self.present(safariVC, animated: true, completion: nil)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return jobTitleArray.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        cell.jobTitle.text = jobTitleArray[indexPath.row]
        cell.jobSummary.text = snippetArray[indexPath.row]
        cell.employerName.text = companyArray[indexPath.row]
        cell.cityName.text = cityArray[indexPath.row]
        cell.ApplyButton.text = jobUrlArray[indexPath.row]

//        let imageUrl = NSURL(string: imageUrlArray[indexPath.row])

//        if imageUrl != nil {
//            let data = NSData(contentsOf: (imageUrl as? URL)!)
//            cell.imageView?.image = UIImage (data: data as! Data)
//        }

        return cell

    }

}

Body:
URL is an object which has different properties (like absoluteString,path, scheme etc. which are String objects themselves) so you cannot cast URL to String, they are different types.

With an URL you can use the URLSession class to access the contents of remote resource or represent a local path for example. Check the documentation and be sure that you know the classes you're using.

https://developer.apple.com/reference/foundation/nsurl

In Swift try to create a URL with String (through unwrapping):

if let url = URL(String: jobUrlArray[indexPath.row]) {
     let safariVC = SFSafariViewController(url: jobUrl)
}

or use url? in code

but be sure you don't use explicitly unwrapped optional like:

let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)

your code might crash, it's not safe.


问:
Event Driven SDL2
I'm in the process of wrapping SDL into C++ objects. Basically, I'm just tired of seeing SDL_ in my code. I'd like at least namespaces... SDL::Window. I've done that, its going more or less fine.

Issue arises with events. I'd like it to be event driven (callbacks) rather than me having to poll an events queue. (the propagation routines you have to write to get SDL_Event fit the abstraction I've designed is painful).

Take for example, a Window class. Its constructor calls

```<code>SDL_AddEventWatch(window_events, this);
</code>```

where window_events is a static member of the Window class. It catches anything of type SDL_WINDOWEVENT.

```<code>int Window::window_events(void* data, SDL::Events::Event* ev)
{
    if (ev->type == SDL::Events::Window::Any)
    {
        auto win = static_cast<Window *>(data);
        if (ev->window.windowID == SDL_GetWindowID(win->mWindow))
        {
            std::vector<event_callback> callbacks = win->mWindowCallbacks;
            for (const auto cbk : callbacks)
            {
                cbk(*ev);
            }
        }
    }
    return 0;
}
</code>```

My Window class also contains hook and unhook methods. Each takes a std::function. This is what mWindowCallbacks is a collection of. Any external routine interested in an event gets a copy forwarded to it.

```<code>//...
using event_callback = std::function<void(SDL::Events::Event)>;
//...

template<typename T> bool
find_func(const T & object,
    const std::vector<T> & list,
    int * location=nullptr)
{
    int offset = 0;

    for (auto single : list)
    {
        if (single.target<T>() ==
            object.target<T>())
        {
            if (location != nullptr) *location = offset;
            return true;
        }
        offset++;
    }
    return false;
}

void
Window::hook(event_callback cbk)
{
    if (!find_func(cbk, mWindowCallbacks))
    {
        mWindowCallbacks.push_back(cbk);
    }
}

void
Window::unhook(event_callback cbk)
{
    int offset = 0;
    if (find_func(cbk, mWindowCallbacks, &offset))
    {
        mWindowCallbacks.erase(mWindowCallbacks.begin() + offset);
    }
}
</code>```

Usage:

```<code>///...
void cbk_close(SDL::Events::Event e)
{
    if (e.window.event == SDL::Events::Window::Close)
    {
        window.close();
        quit = true;
    }
}
///...
std::function<void(SDL::Events::Event)> handler = cbk_close;
SDL::Window window;
window.hook(handler);
</code>```

Close:

```<code>void Window::close()
{
    SDL_DelEventWatch(window_events, this);
    SDL_DestroyWindow(mWindow);
    mWindowCallbacks.clear();
}
</code>```

To me, this doesn't seem like terrible design.
Once you press close on the window the cbk_close is invoked, it calls close, it sets the quit flag... Then it returns to the window_events loop. As expected... However that function doesn't seem to return control to the program.

This is what I need help with. I don't really understand why. I think its hijacking the main thread, as the program will exit once that function exits if you have one window, or... crash if you have two.

Am I on the right lines with that? I've been stuck on this for a week. Its really rather infuriating. To anyone willing to have a play about with it; here's the git repo for the full code.

Windows, Visual Studio 2015/VC solution.
https://bitbucket.org/andywm/sdl_oowrapper/

答:
Okay, so I think I more or less understand what's going on here now.

```<code>SDL_AddEventWatch(void (*)(void *, SDL_Event*), void *)
</code>```

If you're using C++, you should set the calling convention.

```<code>SDLCALL
</code>```

In my case;

```<code>int SDLCALL
Window::window_events(void* data, SDL::Events::Event* ev)
</code>```

This seems to stop the sdl events system from nabbing the main thread.

As for why its crashing with multiple windows... Well, if I remove this line

```<code>SDL_DelEventWatch(window_events, this);
</code>```

it doesn't crash... Not really sure why yet, but if I figure it out I'll amend my answer - and if anyone with more experienced with SDL could fill me in.. That'd be great.

Title: Event Driven SDL2

Body:
I'm in the process of wrapping SDL into C++ objects. Basically, I'm just tired of seeing SDL_ in my code. I'd like at least namespaces... SDL::Window. I've done that, its going more or less fine.

Issue arises with events. I'd like it to be event driven (callbacks) rather than me having to poll an events queue. (the propagation routines you have to write to get SDL_Event fit the abstraction I've designed is painful).

Take for example, a Window class. Its constructor calls

SDL_AddEventWatch(window_events, this);

where window_events is a static member of the Window class. It catches anything of type SDL_WINDOWEVENT.

int Window::window_events(void* data, SDL::Events::Event* ev)
{
    if (ev->type == SDL::Events::Window::Any)
    {
        auto win = static_cast<Window *>(data);
        if (ev->window.windowID == SDL_GetWindowID(win->mWindow))
        {
            std::vector<event_callback> callbacks = win->mWindowCallbacks;
            for (const auto cbk : callbacks)
            {
                cbk(*ev);
            }
        }
    }
    return 0;
}

My Window class also contains hook and unhook methods. Each takes a std::function. This is what mWindowCallbacks is a collection of. Any external routine interested in an event gets a copy forwarded to it.

//...
using event_callback = std::function<void(SDL::Events::Event)>;
//...

template<typename T> bool
find_func(const T & object,
    const std::vector<T> & list,
    int * location=nullptr)
{
    int offset = 0;

    for (auto single : list)
    {
        if (single.target<T>() ==
            object.target<T>())
        {
            if (location != nullptr) *location = offset;
            return true;
        }
        offset++;
    }
    return false;
}

void
Window::hook(event_callback cbk)
{
    if (!find_func(cbk, mWindowCallbacks))
    {
        mWindowCallbacks.push_back(cbk);
    }
}

void
Window::unhook(event_callback cbk)
{
    int offset = 0;
    if (find_func(cbk, mWindowCallbacks, &offset))
    {
        mWindowCallbacks.erase(mWindowCallbacks.begin() + offset);
    }
}

Usage:

///...
void cbk_close(SDL::Events::Event e)
{
    if (e.window.event == SDL::Events::Window::Close)
    {
        window.close();
        quit = true;
    }
}
///...
std::function<void(SDL::Events::Event)> handler = cbk_close;
SDL::Window window;
window.hook(handler);

Close:

void Window::close()
{
    SDL_DelEventWatch(window_events, this);
    SDL_DestroyWindow(mWindow);
    mWindowCallbacks.clear();
}

To me, this doesn't seem like terrible design.
Once you press close on the window the cbk_close is invoked, it calls close, it sets the quit flag... Then it returns to the window_events loop. As expected... However that function doesn't seem to return control to the program.

This is what I need help with. I don't really understand why. I think its hijacking the main thread, as the program will exit once that function exits if you have one window, or... crash if you have two.

Am I on the right lines with that? I've been stuck on this for a week. Its really rather infuriating. To anyone willing to have a play about with it; here's the git repo for the full code.

Windows, Visual Studio 2015/VC solution.
https://bitbucket.org/andywm/sdl_oowrapper/

Body:
Okay, so I think I more or less understand what's going on here now.

SDL_AddEventWatch(void (*)(void *, SDL_Event*), void *)

If you're using C++, you should set the calling convention.

SDLCALL

In my case;

int SDLCALL
Window::window_events(void* data, SDL::Events::Event* ev)

This seems to stop the sdl events system from nabbing the main thread.

As for why its crashing with multiple windows... Well, if I remove this line

SDL_DelEventWatch(window_events, this);

it doesn't crash... Not really sure why yet, but if I figure it out I'll amend my answer - and if anyone with more experienced with SDL could fill me in.. That'd be great.


问:
How to prevent Vue.js from automatically merging CSS classes?
I recently started working with Vue.js and I really enjoy it but I have come across something that I just can't figure out how to do. I have searched and read the documentation but found no solution.

When you add a CSS class to any of your components Vue.js will automatically add or merge the CSS classes with the root element in your child component.

This is a nice feature but I need to deactivate this feature for a specific component since I want the classes to be added to a child element of the root element.

I made this fiddle to illustrate http://jsfiddle.net/rasmuswoelk/9m2j0a9s/3

```<code><div id="demo">
  <child-component class="some-class"></child-component>
</div>
</code>```

(The "some-class" is being added automatically and adds a green background color)

How can I prevent Vue.js from automatically merging CSS classes?

答:
I think that you will want to wrap the whole thing in another

 as Vue will merge the classes on the top element. If you just want the style for
 then try doing this:

```<code>template: `<div><h1 class="child">Hello</h1></div>`
</code>```

This should give you the expected behavior, let me know if it doesn't work.

Body:
I recently started working with Vue.js and I really enjoy it but I have come across something that I just can't figure out how to do. I have searched and read the documentation but found no solution.

When you add a CSS class to any of your components Vue.js will automatically add or merge the CSS classes with the root element in your child component.

This is a nice feature but I need to deactivate this feature for a specific component since I want the classes to be added to a child element of the root element.

I made this fiddle to illustrate http://jsfiddle.net/rasmuswoelk/9m2j0a9s/3

  <child-component class="some-class"></child-component>

(The "some-class" is being added automatically and adds a green background color)

How can I prevent Vue.js from automatically merging CSS classes?

Body:
I think that you will want to wrap the whole thing in another <div></div> as Vue will merge the classes on the top element. If you just want the style for <h1> then try doing this:

template: `<div><h1 class="child">Hello</h1></div>`

This should give you the expected behavior, let me know if it doesn't work.


问:
Does the order of fields in C# matter?
This question is inspired by Jon Skeet's answer:
Is there a c# equivalent to c++'s access-modifier regions

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

答: I believe XmlSerializer serializes members in the order they appear in the source file.</p>

OwnerDisplayName: Josh

ContentLicense: CC BY-SA 2.5

Title: Does the order of fields in C# matter?

LastEditorDisplayName: Mehrdad Afshari

OwnerDisplayName: Joe


问:
What is AspectJ good for?
First let me note, that I use AspectJ and I like it, but what else can I do with it.

I know AspectJ can be/is used for Logging. In some cases it is used for Transaction controlling – mostly implemented in conjunction with annotations.
AspectJ can also be used to enhance classes with (code-generated) methods, like Spring Roo does.

But I believe AspectJ and AOP in general, can be used for more than: logging, transaction controlling, and simulation partial classes.

So what are other useful use cases for AspectJ and AOP?

答:
permission check

interrupt action that takes too long

run action in separate thread or even in context of different process or event on other machine

monitoring

preparing any data / environment before call  and processing results after call

opening / closing resources

EDIT

Although many years passed since I gave this answer I decided to add the following to make the answer more complete.

security check.

fixes of incorrect or behavior of API that you cannot change. For example boolean method that returns false in some conditions but should return true. You can fix this using AspectJ.

Title: What is AspectJ good for?


问:
A function in a controller is completely ignored by a web browser. No error is shown but anything inside of function cannot be shown anyhow
I am currently working on a project with AngularJS and I have a controller named "categoryController" which is looking like this:

```<code>controller('CategoryController',
        [
            '$scope',
            'dataService',
            function ($scope, dataService){
                console.log("Here is working");
                var getCategory = function () {
                    dataService.getCategory().then(  // then() is called when the promise is resolve or rejected
                        function (response){
                            console.log("But this is not working");
                            //$scope.BooksCount  = response.rowCount + ' books';
                            $scope.category      = response.data;
                        },
                        function(err){
                            $scope.status = 'Unable to load data ' + err;
                        },
                        function(notify){
                            console.log(notify);
                        }
                    ); // end of getBooks().then
                };
            }
        ]
    );
</code>```

So as you see, the first console.log somehow shows the message, while the second one cannot be seen in the console in the browser.
Does anyone have any idea why this function getCategory is completely ignored?

答:
The problem is that you have only defined the getCategory function in the controller.

You also need to invoke the function

```<code>controller('CategoryController',
        [
            '$scope',
            'dataService',
            function ($scope, dataService){
                console.log("Here is working");
                var getCategory = function () {
                    dataService.getCategory().then(  // then() is called when the promise is resolve or rejected
                        function (response){
                            console.log("But this is not working");
                            //$scope.BooksCount  = response.rowCount + ' books';
                            $scope.category      = response.data;
                        },
                        function(err){
                            $scope.status = 'Unable to load data ' + err;
                        },
                        function(notify){
                            console.log(notify);
                        }
                    ); // end of getBooks().then
                };
                //Invoke the function
                getCategory();
            }
        ]
    );
</code>```

Body:
I am currently working on a project with AngularJS and I have a controller named "categoryController" which is looking like this:

controller('CategoryController',
        [
            '$scope',
            'dataService',
            function ($scope, dataService){
                console.log("Here is working");
                var getCategory = function () {
                    dataService.getCategory().then(  // then() is called when the promise is resolve or rejected
                        function (response){
                            console.log("But this is not working");
                            //$scope.BooksCount  = response.rowCount + ' books';
                            $scope.category      = response.data;
                        },
                        function(err){
                            $scope.status = 'Unable to load data ' + err;
                        },
                        function(notify){
                            console.log(notify);
                        }
                    ); // end of getBooks().then
                };
            }
        ]
    );

So as you see, the first console.log somehow shows the message, while the second one cannot be seen in the console in the browser.
Does anyone have any idea why this function getCategory is completely ignored?

Body:
The problem is that you have only defined the getCategory function in the controller.

You also need to invoke the function

controller('CategoryController',
        [
            '$scope',
            'dataService',
            function ($scope, dataService){
                console.log("Here is working");
                var getCategory = function () {
                    dataService.getCategory().then(  // then() is called when the promise is resolve or rejected
                        function (response){
                            console.log("But this is not working");
                            //$scope.BooksCount  = response.rowCount + ' books';
                            $scope.category      = response.data;
                        },
                        function(err){
                            $scope.status = 'Unable to load data ' + err;
                        },
                        function(notify){
                            console.log(notify);
                        }
                    ); // end of getBooks().then
                };
                //Invoke the function
                getCategory();
            }
        ]
    );


问:
plsql show only 1 date, view
In my View the description field is filled with a date field, but there are like seven times the same datefield but with different order_keys (thats how it supposed to be). How can i make the view only show always one of the date fields?

```<code>    CREATE OR REPLACE FORCE VIEW CCI.VW_TA04_BAG_5B
(
   ID,
   LIST_DESCRIPTION,
   ORDER_KEY
)
AS
   SELECT
          distinct LPAD (bac.bag_id, 4, '0') || LPAD (bac.ID, 4, '0'),
          '      ' || bar.SCORE_RULE_VALID_TO,
          LPAD (bac.order_key, 4, '0')  || LPAD (bar.order_key, 4, '0')
     FROM BART_CATEGORIES bac,
          BART_CATEGORIES_LAE bacl,
          BART_CATEGORY_rules bar
    WHERE     bacl.lae_id = pkg_process.language
          AND (bar.BAC_ID = bac.id)
          AND Bacl.BAC_ID = bac.id
          AND bar.SCORE_RULE_VALID_TO IS NOT NULL
    order by 3
</code>```

The output looks like this:

```<code>ID                Description order key
00010001          20-MAR-17 00020168
00010001          20-MAR-17 00020169
00010001          20-MAR-17 00020170
00010001          20-MAR-17 00020171
00010001          20-MAR-17 00020172
00010001          20-MAR-17 00020173
00010001          20-MAR-17 00020174
00010001          08-MAR-17 00020175
00010001          08-MAR-17 00020176
00010001          08-MAR-17 00020177
00010001          08-MAR-17 00020178
00010001          08-MAR-17 00020179
</code>```

答:
If you're after one row per id and list_description, here's one way you could do it:</p>

```<code>CREATE OR REPLACE FORCE VIEW CCI.VW_TA04_BAG_5B
  (ID,
   LIST_DESCRIPTION,
   ORDER_KEY)
AS
SELECT ID,
       list_desciption,
       MAX(order_key) order_key
FROM   (SELECT lpad(bac.bag_id, 4, '0') || lpad(bac.id, 4, '0') id,
               '      ' || bar.score_rule_valid_to list_description,
               lpad(bac.order_key, 4, '0') || lpad(bar.order_key, 4, '0') order_key
        FROM   bart_categories bac, bart_categories_lae bacl, bart_category_rules bar
        WHERE  bacl.lae_id = pkg_process.language
        AND    (bar.bac_id = bac.id)
        AND    bacl.bac_id = bac.id
        AND    bar.score_rule_valid_to IS NOT NULL)
GROUP BY ID,
         list_description
ORDER BY order_key;
</code>```

Title: plsql show only 1 date, view

Body:
In my View the description field is filled with a date field, but there are like seven times the same datefield but with different order_keys (thats how it supposed to be). How can i make the view only show always one of the date fields?

    CREATE OR REPLACE FORCE VIEW CCI.VW_TA04_BAG_5B
(
   ID,
   LIST_DESCRIPTION,
   ORDER_KEY
)
AS
   SELECT
          distinct LPAD (bac.bag_id, 4, '0') || LPAD (bac.ID, 4, '0'),
          '      ' || bar.SCORE_RULE_VALID_TO,
          LPAD (bac.order_key, 4, '0')  || LPAD (bar.order_key, 4, '0')
     FROM BART_CATEGORIES bac,
          BART_CATEGORIES_LAE bacl,
          BART_CATEGORY_rules bar
    WHERE     bacl.lae_id = pkg_process.language
          AND (bar.BAC_ID = bac.id)
          AND Bacl.BAC_ID = bac.id
          AND bar.SCORE_RULE_VALID_TO IS NOT NULL
    order by 3

The output looks like this:

ID                Description order key
00010001          20-MAR-17 00020168
00010001          20-MAR-17 00020169
00010001          20-MAR-17 00020170
00010001          20-MAR-17 00020171
00010001          20-MAR-17 00020172
00010001          20-MAR-17 00020173
00010001          20-MAR-17 00020174
00010001          08-MAR-17 00020175
00010001          08-MAR-17 00020176
00010001          08-MAR-17 00020177
00010001          08-MAR-17 00020178
00010001          08-MAR-17 00020179

Body:
If you're after one row per id and list_description, here's one way you could do it:

CREATE OR REPLACE FORCE VIEW CCI.VW_TA04_BAG_5B
  (ID,
   LIST_DESCRIPTION,
   ORDER_KEY)
AS
SELECT ID,
       list_desciption,
       MAX(order_key) order_key
FROM   (SELECT lpad(bac.bag_id, 4, '0') || lpad(bac.id, 4, '0') id,
               '      ' || bar.score_rule_valid_to list_description,
               lpad(bac.order_key, 4, '0') || lpad(bar.order_key, 4, '0') order_key
        FROM   bart_categories bac, bart_categories_lae bacl, bart_category_rules bar
        WHERE  bacl.lae_id = pkg_process.language
        AND    (bar.bac_id = bac.id)
        AND    bacl.bac_id = bac.id
        AND    bar.score_rule_valid_to IS NOT NULL)
GROUP BY ID,
         list_description
ORDER BY order_key;


问:
Apollo GraphQL - Multiple components sharing the same mutation
I am using react-apollo and creating an app that needs to sync the entire local data store of the application once every X seconds.

So essentially, imagine <input1 /> and <input2 /> both need to be synced to the server periodically.

```<code><App>
   <input1 />
   <input2 />
</App>
</code>```

Which component should GraphQL wrap in order to achieve the sync?

Is it possible to use a graphql mutation in a redux action so that the mutation can occur upon the dispatch of an action?

答:
The "Apollo Way" would be to let the inputs be like React bound inputs, but the binding would happen via query and mutations, with optimistic responses added to improve interactivity.

Create mutations for each input, and call these when the inputs change. Provide optimistic responses so that user actions take hold immediately.

Likewise, create a query to get the input values, and use these to initialize the inputs.

If others can change the inputs as well, you will need to set up a subscription.

Body:
I am using react-apollo and creating an app that needs to sync the entire local data store of the application once every X seconds.

So essentially, imagine <input1 /> and <input2 /> both need to be synced to the server periodically.

<App>
   <input1 />
   <input2 />
</App>

Which component should GraphQL wrap in order to achieve the sync?

Is it possible to use a graphql mutation in a redux action so that the mutation can occur upon the dispatch of an action?


问:
How to filter with a list of ADTs in scala with slick 3.2
I have a list of the following case class

```<code>case class caseClass
(
  field1: Option[String],
  field2: Option[String],
  field3: Option[String]
)
</code>```

These fields are corresponding to the columns of a mySQL table, which I want to search in. Basically I want to filter with each of the case class instances, where there is an AND relation between field1,field2 and field3 and an OR relation between the instances. In SQL it would be something like this:

```<code>SELECT
    field4,
    field5
FROM
    tablename
WHERE
    (field1 = ? AND field2 = ?) OR
    (field3 = ?) OR
    (field1 = ? AND field2 = ? AND field3 = ?) OR
    ...etc
</code>```

Of course it would be generated with string concatenations as all the case class fields are all optional.
How can I solve this with slick elegantly (not using slick's plain SQL queries)?

答:
We figured out how to solve this problem based on this answer </p>

```<code>def queryGenerator
(
  listOfCaseClasses: List[CaseClass],
  table: TableQuery[CaseClassvTable]
) = {
  val query = table.filter { row =>
    listOfCaseClasses.map { parameter =>
      List(
        (row.field1vTable === parameter.field1, parameter.field1),
        (row.field2vTable === parameter.field2, parameter.field2),
        (row.field3vTable === parameter.field3, parameter.field3),
      ).collect{ case (x, Some(_)) => x }.reduce(_ && _)
    }.reduce(_ || _)
  }.result
  query
}
</code>```

<p>I couldn't figure out how to filter based on the Rep[Option[Boolean]] expressions (which are the first part of the tuple), so I thought I make the list a list of tuples where the second part is the parameters of the CaseClass. And it's easy to filter plain Option[_]'s. </p>

Body:
I have a list of the following case class

case class caseClass
(
  field1: Option[String],
  field2: Option[String],
  field3: Option[String]
)

These fields are corresponding to the columns of a mySQL table, which I want to search in. Basically I want to filter with each of the case class instances, where there is an AND relation between field1,field2 and field3 and an OR relation between the instances. In SQL it would be something like this:

SELECT
    field4,
    field5
FROM
    tablename
WHERE
    (field1 = ? AND field2 = ?) OR
    (field3 = ?) OR
    (field1 = ? AND field2 = ? AND field3 = ?) OR
    ...etc

Of course it would be generated with string concatenations as all the case class fields are all optional.
How can I solve this with slick elegantly (not using slick's plain SQL queries)?

Body:
We figured out how to solve this problem based on this answer

def queryGenerator
(
  listOfCaseClasses: List[CaseClass],
  table: TableQuery[CaseClassvTable]
) = {
  val query = table.filter { row =>
    listOfCaseClasses.map { parameter =>
      List(
        (row.field1vTable === parameter.field1, parameter.field1),
        (row.field2vTable === parameter.field2, parameter.field2),
        (row.field3vTable === parameter.field3, parameter.field3),
      ).collect{ case (x, Some(_)) => x }.reduce(_ && _)
    }.reduce(_ || _)
  }.result
  query
}

I couldn't figure out how to filter based on the Rep[Option[Boolean]] expressions (which are the first part of the tuple), so I thought I make the list a list of tuples where the second part is the parameters of the CaseClass. And it's easy to filter plain Option[_]'s.


问:
No known class method for selector 'circleOfButtons:buttonSize:radius:'
A function circleOfButtons:buttonSize:radius: in SGView (below) is called from ParentView and I want ParentView to define the values inside SGView whenever ParentView sends a message to SGView.

This is the implementation file.

```<code>#import <UIKit/UIKit.h>
#import “ParentView.h"
#import "SGView.h"

@implementation ParentView : UIView

- (id)initWithFrame:(CGRect)frame {
    self                        = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {

    self.backgroundColor        = [UIColor lightGrayColor];

    int     count               = 5;
    CGFloat size                = 80.0;
    CGFloat radius              = 68;

    SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
    [self addSubview:myView];
    }
return self;
}
</code>```

SGView arranges multiple UIButtons in a circle and is essentially like this

```<code>#import "SGView.h"

@implementation SGView : UIView

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews       = [self new];

    // … circular geometry …
    [multipleViews addSubview:circleButton];
    }
    return multipleViews;
}
@end
</code>```

The error message - at the line SGView *myView - is:

No known class method for selector
  'circleOfButtons:buttonSize:radius:'

My guess is the compiler wants a declaration in the interface. I’m working through these tutorials trying to decide what the interface file should look like and though there are 6 SO questions that may already have answered my question, only this one had an example that seemed vaguely relevant.

This is my interface file.

```<code>#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "SGView.h"

@interface ParentView : UIView {
}

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

@end
</code>```

Can anyone please give an example showing what this interface file should look like ? Thanks.

UPDATE

Here is SGView.h (revised)

```<code>#import <UIKit/UIKit.h>
@interface SGView : UIView {
}
+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;
@end
</code>```

I also noticed if the statement

```<code>        SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
</code>```

is changed to

```<code>        SGView *myView              = [self circleOfButtons:count buttonSize:size radius:radius];
</code>```

the error changes to

No visible @interface for 'ParentView' declares the selector 'circleOfButtons:buttonSize:radius:'

it was previously

No known class method for selector 'circleOfButtons:buttonSize:radius:'

答:
Declare +(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius in SGView.h file.
Now you will get the method in ParentView class.

Happy coding :) .

Body:
A function circleOfButtons:buttonSize:radius: in SGView (below) is called from ParentView and I want ParentView to define the values inside SGView whenever ParentView sends a message to SGView.

This is the implementation file.

#import <UIKit/UIKit.h>
#import “ParentView.h"
#import "SGView.h"

@implementation ParentView : UIView

- (id)initWithFrame:(CGRect)frame {
    self                        = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {

    self.backgroundColor        = [UIColor lightGrayColor];

    int     count               = 5;
    CGFloat size                = 80.0;
    CGFloat radius              = 68;

    SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
    [self addSubview:myView];
    }
return self;
}

SGView arranges multiple UIButtons in a circle and is essentially like this

#import "SGView.h"

@implementation SGView : UIView

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews       = [self new];

    // … circular geometry …
    [multipleViews addSubview:circleButton];
    }
    return multipleViews;
}
@end

The error message - at the line SGView *myView - is:

No known class method for selector
  'circleOfButtons:buttonSize:radius:'

My guess is the compiler wants a declaration in the interface. I’m working through these tutorials trying to decide what the interface file should look like and though there are 6 SO questions that may already have answered my question, only this one had an example that seemed vaguely relevant.

This is my interface file.

#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "SGView.h"

@interface ParentView : UIView {
}

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

@end

Can anyone please give an example showing what this interface file should look like ? Thanks.

UPDATE

Here is SGView.h (revised)

#import <UIKit/UIKit.h>
@interface SGView : UIView {
}
+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;
@end

I also noticed if the statement

        SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];

is changed to

        SGView *myView              = [self circleOfButtons:count buttonSize:size radius:radius];

the error changes to

No visible @interface for 'ParentView' declares the selector 'circleOfButtons:buttonSize:radius:'

it was previously

No known class method for selector 'circleOfButtons:buttonSize:radius:'


问:
Design Pattern to use existing classes
I am at the moment struggling with which design pattern should I use. My situation is as follows:

I have a few existing classes e.g. Address, Client and Invoices.

I need to create a class let's say a javabean that comprises possibly all fields from above mentioned classes as its getters and
setters.

Later on, I can create a object of the javabean and assign it to a Jasperreport as its datasource.

Can anyone suggest me which design pattern would ease my job as I don't want to reinvent the wheel?
Thank you.

答: For such a case, where you want to mix multiple classes functionalities into one object, you can use Mixin design pattern Some languages support Multi-inheritance, but sometimes it is hard to control what gets overridden. I don't recommend to create an Inheritance Chain, because it adds overhead and makes your code harder to read and debug.

Title: Design Pattern to use existing classes


问:
Want to pass ArrayList contain class objects in javascript
I have a ArrayList which contain objects of a Java Class.I want to pass that list to javascript and want to populate the data within the object in to jsp.
The ArrayList is present in the jsp.Each class object only contain 2 parameter values.Class name is 'Certificate' and it contain 'certId' and 'certName'

jsp:

```<code><%
 ArrayList getAllCertificateNamewithId=new ArrayList();
 getAllCertificateNamewithId=(ArrayList)mainMap.get("getAllCertificateNamewithIdMap");%>
<input type="button"  width="16" height="16"  onclick="fetchAndShow('<%=getAllCertificateNamewithId %>')" />
</code>```

Javascript

```<code>function fetchAndShow(certObj){
//How to fetch the list's each object  and cast to java class 'Certificate'
}
</code>```

List contain

```<code>[com.dto.Certificate@9b44a1, com.dto.Certificate@1b6b3ac]
</code>```

答:
That's not the correct way. Just because of the contents are in the same page, they can't communicate directly.

Java plays on server side and javascript on server side. A client doesn't execute the java code.

To send a Java value to javascript you have to make a server request, So the server process your request and send the results back to Javascript.

Inshort  you need to make a server (AJAX) request.

Body:
I have a ArrayList which contain objects of a Java Class.I want to pass that list to javascript and want to populate the data within the object in to jsp.
The ArrayList is present in the jsp.Each class object only contain 2 parameter values.Class name is 'Certificate' and it contain 'certId' and 'certName'

jsp:

<%
 ArrayList getAllCertificateNamewithId=new ArrayList();
 getAllCertificateNamewithId=(ArrayList)mainMap.get("getAllCertificateNamewithIdMap");%>
<input type="button"  width="16" height="16"  onclick="fetchAndShow('<%=getAllCertificateNamewithId %>')" />

Javascript

function fetchAndShow(certObj){
//How to fetch the list's each object  and cast to java class 'Certificate'
}

List contain

[com.dto.Certificate@9b44a1, com.dto.Certificate@1b6b3ac]


问:
How do I add a "New" button to ALL ActiveAdmin show pages?
When creating objects in ActiveAdmin I typically need to add multiple, and wish there was an option to add another object on the show page (which appears after submitting the new object).

I have been doing this model by model:

```<code>ActiveAdmin.register Color do

  action_item :add, only: :show do
    link_to "New", new_administration_color_path
  end

end
</code>```

答:
Add this to admin/administration_color.rb

```<code>controller do
    def create
      create! do |format|
        format.html { redirect_to admin_administration_color_path(resource, add_more: true) }
      end
    end
  end
</code>```

and some modified your code

```<code>  action_item :add, only: :show do
    link_to "New", new_administration_color_path if params['add_more'] == true
  end
</code>```

Body:
When creating objects in ActiveAdmin I typically need to add multiple, and wish there was an option to add another object on the show page (which appears after submitting the new object).

I have been doing this model by model:

ActiveAdmin.register Color do

  action_item :add, only: :show do
    link_to "New", new_administration_color_path
  end

end

Body:
Add this to admin/administration_color.rb

controller do
    def create
      create! do |format|
        format.html { redirect_to admin_administration_color_path(resource, add_more: true) }
      end
    end
  end

and some modified your code

  action_item :add, only: :show do
    link_to "New", new_administration_color_path if params['add_more'] == true
  end


问:
TinyMCE Editor dosen't have all the features
I used TinyMCE Editor for my text box in my web site, I followed this https://www.tinymce.com/docs/get-started/first-steps/  and it works fine but the problem is that I don't have all the features. mine is like the image below

but here is what I Expect

答:
Here are the full features (except premium plugins) you can use: https://www.tinymce.com/docs/demo/full-featured/. You may want to modify menubar, plugins and toolbar for your need.

```<code>tinymce.init({
  selector: 'textarea',
  height: 500,
  theme: 'modern',
  plugins: [
    'advlist autolink lists link image charmap print preview hr anchor pagebreak',
    'searchreplace wordcount visualblocks visualchars code fullscreen',
    'insertdatetime media nonbreaking save table contextmenu directionality',
    'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc'
  ],
  toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
  toolbar2: 'print preview media | forecolor backcolor emoticons | codesample',
  image_advtab: true,
  templates: [
    { title: 'Test template 1', content: 'Test 1' },
    { title: 'Test template 2', content: 'Test 2' }
  ],
  content_css: [
    '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
    '//www.tinymce.com/css/codepen.min.css'
  ]
 });
</code>```

Body:
Here are the full features (except premium plugins) you can use: https://www.tinymce.com/docs/demo/full-featured/. You may want to modify menubar, plugins and toolbar for your need.

tinymce.init({
  selector: 'textarea',
  height: 500,
  theme: 'modern',
  plugins: [
    'advlist autolink lists link image charmap print preview hr anchor pagebreak',
    'searchreplace wordcount visualblocks visualchars code fullscreen',
    'insertdatetime media nonbreaking save table contextmenu directionality',
    'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc'
  ],
  toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
  toolbar2: 'print preview media | forecolor backcolor emoticons | codesample',
  image_advtab: true,
  templates: [
    { title: 'Test template 1', content: 'Test 1' },
    { title: 'Test template 2', content: 'Test 2' }
  ],
  content_css: [
    '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
    '//www.tinymce.com/css/codepen.min.css'
  ]
 });


问:
How to list the deleted contacts by Microsoft Graph API
I want to do a sync action in my client side, so need to know how to get all deleted contact list.

By the api (GET /me/contacts), I could get all contact list
But it wastes much time when the user has large contacts.

This api (GET /me/contacts/{id}) tell us the contact is exist or not.

it is inefficient to check every contacts are deleted or not for me.

Which apis do I use? thanks for your help.

答:
More efficient way for you to check which contacts were removed is getting just the list of contact ID's and then doing the diff between list of ID's returned by graph, and local list.

You can use query parameters to retrieve just the ID's of the contacts, instead of getting the whole objects.

Method url:
    https://graph.microsoft.com/v1.0/me/contacts?$select=id


问:
Yeshello signup form
I need a little button on my site so people can subscribe to my newsletter.

Here is what i have:

```<code><form name="yeshello" method="post" target="_blank" action="https://forms.yeshello.net/sub.htm?mycode"> <input type="text" name="email"> <input type="submit" value="Subscribe"</form>
</code>```

Now the responseType needs to be 0
and the successUrl needs to be http://www.myspecificthankyoupage.html

How to get the responsetype and succesUrl in the code?
From what I understood both can be sended as a hidden field in the web form.

Any help would be appreciated.

答:
Ok, i found out. The reason it didn't work because i was given the wrong url.

Here is the right code:

```<code>    <form name="yeshello" method="post" target="_blank" action="https://www.yeshello.net/myuniquecode">
        <input type="text" name="email" />
        <input type="submit" value="Subscribe" />
        <input type="hidden" name="responseType" value="0" />
        <input type="hidden" name="successUrl" value="http://myrequestedwebsiteurl" />
    </form>
</code>```

Title: Yeshello signup form

Body:
I need a little button on my site so people can subscribe to my newsletter.

Here is what i have:

<form name="yeshello" method="post" target="_blank" action="https://forms.yeshello.net/sub.htm?mycode"> <input type="text" name="email"> <input type="submit" value="Subscribe"</form>

Now the responseType needs to be 0
and the successUrl needs to be http://www.myspecificthankyoupage.html

How to get the responsetype and succesUrl in the code?
From what I understood both can be sended as a hidden field in the web form.

Any help would be appreciated.

Body:
Ok, i found out. The reason it didn't work because i was given the wrong url.

Here is the right code:

    <form name="yeshello" method="post" target="_blank" action="https://www.yeshello.net/myuniquecode">
        <input type="text" name="email" />
        <input type="submit" value="Subscribe" />
        <input type="hidden" name="responseType" value="0" />
        <input type="hidden" name="successUrl" value="http://myrequestedwebsiteurl" />
    </form>


问:
Pandas groupby nlargest sum
I am trying to use groupby, nlargest, and sum functions in Pandas together, but having trouble making it work.

```<code>State    County    Population
Alabama  a         100
Alabama  b         50
Alabama  c         40
Alabama  d         5
Alabama  e         1
...
Wyoming  a.51      180
Wyoming  b.51      150
Wyoming  c.51      56
Wyoming  d.51      5
</code>```

I want to use groupby to select by state, then get the top 2 counties by population. Then use only those top 2 county population numbers to get a sum for that state.

In the end, I'll have a list that will have the state and the population (of it's top 2 counties).

I can get the groupby and nlargest to work, but getting the sum of the nlargest(2) is a challenge.

The line I have right now is simply: df.groupby('State')['Population'].nlargest(2)

答:
Using agg, the grouping logic looks like:

df.groupby('State').agg({'Population': {lambda x: x.nlargest(2).sum() }})

This results in another dataframe object; which you could query to find the most populous states, etc.

```<code>           Population
State
Alabama    150
Wyoming    330
</code>```

Title: Pandas groupby nlargest sum

Body:
I am trying to use groupby, nlargest, and sum functions in Pandas together, but having trouble making it work.

State    County    Population
Alabama  a         100
Alabama  b         50
Alabama  c         40
Alabama  d         5
Alabama  e         1
...
Wyoming  a.51      180
Wyoming  b.51      150
Wyoming  c.51      56
Wyoming  d.51      5

I want to use groupby to select by state, then get the top 2 counties by population. Then use only those top 2 county population numbers to get a sum for that state.

In the end, I'll have a list that will have the state and the population (of it's top 2 counties).

I can get the groupby and nlargest to work, but getting the sum of the nlargest(2) is a challenge.

The line I have right now is simply: df.groupby('State')['Population'].nlargest(2)

Body:
Using agg, the grouping logic looks like:

df.groupby('State').agg({'Population': {lambda x: x.nlargest(2).sum() }})

This results in another dataframe object; which you could query to find the most populous states, etc.

           Population
State
Alabama    150
Wyoming    330


问:
Marshmallow permission Android
I am currently working on an application that requires several "dangerous" permissions.

So I tried adding "ask for permission" as required in Android Marshmallow(API Level 23), and its working fine.

now user can see all related permission of app in setting screen(App Permission option).

What happen if user toggle off permission from setting screen and how to prevent user to toggle off that?

If so is there any broadcast fire when user do that?

According to my need I want to prevent user to toggle off runtime permission  from setting screen, is it possible or not?

答:
what happen if user toggle off permission from setting screen

Your process is terminated. When your code runs again, you would have to ask for the permission, just as you do when your app first runs.

how to prevent user to toggle off that?

Don't write an Android app that uses dangerous permissions.

i want to prevent user to toggle off runtime permission from setting screen, is it possible or not?

Fortunately, no.

Title: Marshmallow permission Android


问:
Javascript is not working inside a accordion bootstrap
I am using accordion tabs in my web application and in that I am facing an issue, each tab opens when i press the "Continue" button which is present in all the tabs.

Here the issue is, when I manually toggle from the 5th tab to the 4th tab and return to the 5th tab by pressing continue button, the Javascript scripts which are written in the 5th tab are completely not working. Even a simple alert() is not working. This happens only when we toggle the tabs manually.

Need help in fixing this. TIA

答:
$(".button").click(function(){
  $(this).closest(".panel-default").find(".panel-collapse").removeClass("in");
  $(this).closest(".panel-default").next().find(".panel-collapse").addClass("in");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

        Collapsible Group 1
      </h4>
    </div>
    <div id="collapse1" class="panel-collapse collapse in">
      <div class="panel-body">
      <input type="button" class="btn btn-default button" value="continue"/>
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

        Collapsible Group 2
      </h4>
    </div>
    <div id="collapse2" class="panel-collapse collapse">
      <div class="panel-body">
      <input type="button" class="btn btn-default button" value="continue2"/>
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

        Collapsible Group 3
      </h4>
    </div>
    <div id="collapse3" class="panel-collapse collapse">
      <div class="panel-body">
      <input type="button" class="btn btn-default button" value="continue3"/>
      </div>
    </div>
  </div>
</div></code>```

Body:
$(".button").click(function(){
  $(this).closest(".panel-default").find(".panel-collapse").removeClass("in");
  $(this).closest(".panel-default").next().find(".panel-collapse").addClass("in");
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">
        Collapsible Group 1</a>
      </h4>
    </div>
    <div id="collapse1" class="panel-collapse collapse in">
      <div class="panel-body">
      <input type="button" class="btn btn-default button" value="continue"/>
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">
        Collapsible Group 2</a>
      </h4>
    </div>
    <div id="collapse2" class="panel-collapse collapse">
      <div class="panel-body">
      <input type="button" class="btn btn-default button" value="continue2"/>
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">
        Collapsible Group 3</a>
      </h4>
    </div>
    <div id="collapse3" class="panel-collapse collapse">
      <div class="panel-body">
      <input type="button" class="btn btn-default button" value="continue3"/>
      </div>
    </div>
  </div>
</div>


问:
Blocked HTTP redirect due to missing preflight request in Chrome
We are currently building an Angular application backed with a RESTful API. The app tries to fetch a user's information with the following request URL: http://example.com:1337/api/users/1. This resource responses with a HTTP 301 (Moved Permanently) and sets the location header where the resource has been moved to, e.g. Location=http://another-hostname.com:8088/new/users/1.
Angular's HTTP client or rather the browser is handling this response automatically and redirects to this new location.

Sadly, in Chrome we get the following error message:

```<code>XMLHttpRequest cannot load http://example.com:1337/api/users/1. Redirect from 'http://example.com:1337/api/users/1' to 'http://another-hostname.com:8088/new/users/1' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
</code>```

Chrome skips a preflight request (CORS) before calling the GET to the new resource. We tested this with Firefox and there it is working quite well. Firefox issues a new preflight request and the GET request afterwards will be handled successfully.

So, I'm wondering what's the correct behavior here. Has anyone made a similar experience with 30x responses?

Is there a possibility to disable the automatic browser (or Angular HTTP client) redirect handling? So that we can handle the new GET manually with a brand new this.http.get(...).

Thanks for any advice,

Michael

答:
Is there a possibility to disable the automatic browser (or Angular HTTP client) redirect handling?

No way for  XMLHttpRequest (and Angular's $http therefore). Such option is provided in fetch(), which is not crossbrowser yet.

But there's a workaround:

Determine the final request destination by a special preliminary
request (by examining XHR.responseURL).

This should be a simple request: only GET/POST/HEAD and only simple headers — so that it won't produce a preflight.

Make your "real" request to that destination.

what's the correct behavior here

Cross-site redirects originally were forbidden, but now (since 4 Aug 2016) are allowed — but most browsers have not yet implemented the change.

This is very clearly explained in the MDN https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests_and_redirects

Body:
We are currently building an Angular application backed with a RESTful API. The app tries to fetch a user's information with the following request URL: http://example.com:1337/api/users/1. This resource responses with a HTTP 301 (Moved Permanently) and sets the location header where the resource has been moved to, e.g. Location=http://another-hostname.com:8088/new/users/1.
Angular's HTTP client or rather the browser is handling this response automatically and redirects to this new location.

Sadly, in Chrome we get the following error message:

XMLHttpRequest cannot load http://example.com:1337/api/users/1. Redirect from 'http://example.com:1337/api/users/1' to 'http://another-hostname.com:8088/new/users/1' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

Chrome skips a preflight request (CORS) before calling the GET to the new resource. We tested this with Firefox and there it is working quite well. Firefox issues a new preflight request and the GET request afterwards will be handled successfully.

So, I'm wondering what's the correct behavior here. Has anyone made a similar experience with 30x responses?

Is there a possibility to disable the automatic browser (or Angular HTTP client) redirect handling? So that we can handle the new GET manually with a brand new this.http.get(...).

Thanks for any advice,

Michael


问:
How do I make a splash screen?
I want my app to look more professional, so I decided to add a splash screen.

How should I go about the implementation?

答:
```<code>public class SplashActivity extends Activity {

  Context ctx;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ctx = this;
      setContentView(R.layout.activity_splash);

      Thread thread = new Thread(){
          public void run(){
              try {
                  sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }

              Intent in = new Intent(ctx,MainActivity.class);
              startActivity(in);
              finish();
          }
      };
      thread.start();
  }
}
</code>```

Title: How do I make a splash screen?


问:
Error in data binding in Xaml
```<code>I have tried data binding in WPF.
But it is showing few errors.Please help me.
</code>```

I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.

```<code>Xaml code
<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Window.DataContext>
        <l:DataBinding />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

**Code behind**

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            Setupviewmodel();
        }
        private void Setupviewmodel
        {
            TextString="this worked";
        }
        public string TextString{get;set;}
    }
}
</code>```

答:
In order to make this work you have to set the DataContext properly. I'd suggest to create a viewmodel class and bind to that. Also I initialized the binding in the codebehind because your namespaces are missing. You can do that in xaml aswell. For now to give you something to work with try this for your codebehind:

```<code>public partial class DataBinding : Window
{
  public DataBinding()
  {
    InitializeComponent();
    DataContext = new DataBindingViewModel();
  }
}

public class DataBindingViewModel
{
  public DataBindingViewModel()
  {
    Setupviewmodel();
  }
  private void Setupviewmodel()
  {
    TextString = "this worked";
  }
  public string TextString { get; set; }
}
</code>```

And change your view to this:

```<code><Window x:Class="Shweta.DataBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataBinding" Height="300" Width="300">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="54*" />
        <ColumnDefinition Width="224*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="59*" />
        <RowDefinition Height="202*" />
    </Grid.RowDefinitions>
    <Grid Grid.Column="1" Grid.Row="1">
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
    </Grid>
</Grid>
</code>```

Note that the Text property will only be set at initialization. If you want DataBinding at runtime your DataBindingViewModel will have to implememnt INPC and throw the PropertyChanged Event after setting the property bound to.

Title: Error in data binding in Xaml

Body:
I have tried data binding in WPF.
But it is showing few errors.Please help me.

I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.

Xaml code
<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Window.DataContext>
        <l:DataBinding />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

**Code behind**

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            Setupviewmodel();
        }
        private void Setupviewmodel
        {
            TextString="this worked";
        }
        public string TextString{get;set;}
    }
}

Body:
In order to make this work you have to set the DataContext properly. I'd suggest to create a viewmodel class and bind to that. Also I initialized the binding in the codebehind because your namespaces are missing. You can do that in xaml aswell. For now to give you something to work with try this for your codebehind:

public partial class DataBinding : Window
{
  public DataBinding()
  {
    InitializeComponent();
    DataContext = new DataBindingViewModel();
  }
}

public class DataBindingViewModel
{
  public DataBindingViewModel()
  {
    Setupviewmodel();
  }
  private void Setupviewmodel()
  {
    TextString = "this worked";
  }
  public string TextString { get; set; }
}

And change your view to this:

<Window x:Class="Shweta.DataBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DataBinding" Height="300" Width="300">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="54*" />
        <ColumnDefinition Width="224*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="59*" />
        <RowDefinition Height="202*" />
    </Grid.RowDefinitions>
    <Grid Grid.Column="1" Grid.Row="1">
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
    </Grid>
</Grid>

Note that the Text property will only be set at initialization. If you want DataBinding at runtime your DataBindingViewModel will have to implememnt INPC and throw the PropertyChanged Event after setting the property bound to.


问:
Is There An Easy Way To Comment Out XAML Code in Microsoft Blend?
I've been using Blend 4 for a while, especially when customizing templates, and one thing irks me.  There's no 'comment' button, so I can't easily wrap a highlighted section of XAML with HTML comments ().

Is there any workaround for this, or am I forever stuck having to type those.

NOTE: I did see a macro extension that allows you to open/close comment with a shortcut key, but sadly it doesn't install with my version of Blend.

答:
Keyboard:  CTRL + K, CTRL + C (comment)
           CTRL + K, CTRL + U (uncomment)

Menu:  Edit -> Advanced -> Comment Selection
       Edit -> Advanced -> Uncomment Selection