问:
Loop to unfilter multiple excel workbooks VBA
I am trying to do a loop to unfilter the column A for all the workbooks (as they are the same, alwyas column A).
I want to show all the cells as the filter romve the empty cells.
I have many of folders ( more than 50) so the loop is very useful and important for the next step of my code.

I have a code that works for one folder:

```<code>`Sub unfilterr()
Dim y As Workbook, myfile, FolderPath, path
Dim ws As Excel.Worksheet
Set y = Workbooks.Open("Z:\VBA\Copie de Devis_65 Version
avec G35.xlsx")
With y.Worksheets("Para RF")
    If Not y.Worksheets("Para RF").AutoFilter Is Nothing Then
            y.Sheets("Para RF").Range("A1").AutoFilter Field:=1
    End If
End With
End Sub`
</code>```

and now trying to do the loop:

```<code>`Sub unfilter1()
Dim y As Workbook, myfile, FolderPath, path
Dim ws As Excel.Worksheet

'## Open workbooks first:
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

FolderPath = "Z:\VBA\Test\"
path = FolderPath & "*.xls*"
myfile = Dir(FolderPath & "*.xls*")

Do While myfile <> ""

Set y = Workbooks.Open(path) 'I put path instead of myfile because I have error if I put myfile

Set ws = y.Worksheets("Para RF")
'With ws
    If Not ws.AutoFilter Is Nothing Then
            y.Sheets("Para RF").Range("A1").AutoFilter Field:=1
    End If
'End With

myfile = Dir()
y.Close saveChanges:=True
Loop

MsgBox ("Task Complete")
End Sub
</code>```

can you please tell what is the problem with this loop!?
I am trying it on 4 workbooks in the test folder! only the first one is unfiltered while the others are not. It seems like the loop is repeting on only the first workbook in the folder.

So with this loop no error message but the result is unsatisfing.

Thank you a lot for your help.

cheers!

答:
The Workbook.Open() method needs a full path and the filename.

Replace

```<code> Set y = Workbooks.Open(path)
</code>```

With

```<code>Set y = Workbooks.Open(FolderPath & myfile)
</code>```

and you should be good to go.
You don't need the path variable.

Edit: I minimized your whole script to the bare minimum to loop through all ".xls" files and open all off them within a folder:

```<code>Sub OpenWorkbooks()
Dim y As Workbook
Dim myfile As String
Dim FolderPath As String

FolderPath = "C:\TestDirectory\"
myfile = Dir(FolderPath & "*.xls*")

Do While myfile <> ""
    Set y = Workbooks.Open(FolderPath & myfile)
    myfile = Dir()
Loop
End Sub
</code>```

The above opens each Excel file in C:\TestDirectory\ on my machine.
N.b. make sure you have the "\" at the end of the FolderPath variable, otherwise it'll look for C:\TestDirectorySomeFileName.xlsx which is not going to work.

Body:
I am trying to do a loop to unfilter the column A for all the workbooks (as they are the same, alwyas column A).
I want to show all the cells as the filter romve the empty cells.
I have many of folders ( more than 50) so the loop is very useful and important for the next step of my code.

I have a code that works for one folder:

`Sub unfilterr()
Dim y As Workbook, myfile, FolderPath, path
Dim ws As Excel.Worksheet
Set y = Workbooks.Open("Z:\VBA\Copie de Devis_65 Version
avec G35.xlsx")
With y.Worksheets("Para RF")
    If Not y.Worksheets("Para RF").AutoFilter Is Nothing Then
            y.Sheets("Para RF").Range("A1").AutoFilter Field:=1
    End If
End With
End Sub`

and now trying to do the loop:

`Sub unfilter1()
Dim y As Workbook, myfile, FolderPath, path
Dim ws As Excel.Worksheet

'## Open workbooks first:
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

FolderPath = "Z:\VBA\Test\"
path = FolderPath & "*.xls*"
myfile = Dir(FolderPath & "*.xls*")

Do While myfile <> ""

Set y = Workbooks.Open(path) 'I put path instead of myfile because I have error if I put myfile

Set ws = y.Worksheets("Para RF")
'With ws
    If Not ws.AutoFilter Is Nothing Then
            y.Sheets("Para RF").Range("A1").AutoFilter Field:=1
    End If
'End With

myfile = Dir()
y.Close saveChanges:=True
Loop

MsgBox ("Task Complete")
End Sub

can you please tell what is the problem with this loop!?
I am trying it on 4 workbooks in the test folder! only the first one is unfiltered while the others are not. It seems like the loop is repeting on only the first workbook in the folder.

So with this loop no error message but the result is unsatisfing.

Thank you a lot for your help.

cheers!

Body:
The Workbook.Open() method needs a full path and the filename.

Replace

 Set y = Workbooks.Open(path)

With

Set y = Workbooks.Open(FolderPath & myfile)

and you should be good to go.
You don't need the path variable.

Edit: I minimized your whole script to the bare minimum to loop through all ".xls" files and open all off them within a folder:

Sub OpenWorkbooks()
Dim y As Workbook
Dim myfile As String
Dim FolderPath As String

FolderPath = "C:\TestDirectory\"
myfile = Dir(FolderPath & "*.xls*")

Do While myfile <> ""
    Set y = Workbooks.Open(FolderPath & myfile)
    myfile = Dir()
Loop
End Sub

The above opens each Excel file in C:\TestDirectory\ on my machine.
N.b. make sure you have the "\" at the end of the FolderPath variable, otherwise it'll look for C:\TestDirectorySomeFileName.xlsx which is not going to work.


来源: stackexchange

问:
how to fetch post api?
I have an API which returns data from database.

this is my form

```<code>            <form action="<c:url value="/getCandidateDetails"/>" method="post">
                <div class="form-group">
                    <label for="masterId">Master Id:</label><br/>
                    <input type="text" id="masterId"
path="studentmasterid" name="studentmasterid" class="form-control">
                    </div>
                    <input type="hidden" value="Pending" name="paymentStatus"/>
                    <button class="btn btn-primary" type="submit" id="search">Search</button>
                </form>
</code>```

the controller part looks like this.

```<code>@RequestMapping(value = "/getCandidateDetails", method = RequestMethod.POST)
public @ResponseBody List<CandidateappearagainstadvtcodeEntity> getCandidateDetails
(Model model, @RequestParam("studentmasterid") String studentmasterid,

@RequestParam("paymentStatus")String paymentstatus){
    List<CandidateappearagainstadvtcodeEntity> candidates=
    candidateappearagainstadvtcodeEntityRepository.findByStudentmasteridAndPaymentstatus
    (studentmasterid,paymentstatus);
            return candidates;
        }
</code>```

it throws json

```<code>    [{"id":393,"advertisementcode":"15206-15206/2071-
72","ageonlastdateday":0,"ageonlastdatemonth":0,"ageonlastdateyear":0,
"applicationnumber":"38483928614","attendancestatus":"Pending",
"candidatefirstname":"RAJENDRA","dateofbirthinnepali":null,
"interviewmarksallocationstatus":null,"interviewscheduledstatus":null,
"mothername":"धनराज्य लक्ष्मी पाण्डे",
"candidatenameinnepali":"राजेन्द्रपाण्डे",
"marksobtained":0.0,"optionalpaperid":"NA","panelname":null,
"paymentstatus":"Pending","studentmasterid":"1161"}]
</code>```

as you can see my form sends two parameters studentmasterid and payment details.
Whenever I click the search button it should hit the api with post method, grab the returned data and view it on jsp page. How can I do it by using ajax?

答:
Your form currently does an HTML POST. Instead you intend to use AJAX. This is how you can do it in jQuery:

HTML

```<code>            <form id="myform" action="<c:url value="/getCandidateDetails"/>" method="post">
                <div class="form-group">
                    <label for="masterId">Master Id:</label><br/>
                    <input type="text" id="masterId"
path="studentmasterid" name="studentmasterid" class="form-control">
                    </div>
                    <input type="hidden" value="Pending" name="paymentStatus"/>
                    <button class="btn btn-primary" type="submit" id="search">Search</button>
                </form>
</code>```

Javascript

```<code>$("#myform").submit(function(submitEvent) {
    submitEvent.preventDefault(); //Prevents HTML POST
    var items = $(this).find("[name]"); //Finds all the named items in the form
    //Builds the data object
    var data = {};
    for (var index in items) {
        data[items[index].prop("name")] = items[index].val();
    }
    $.ajax({
        url: $(this).prop("action"),
        data: data,
        method: "POST"
    }).done(function(responseData) {
        //Do something with the response you have received from the server.
    });
});
</code>```

If you prefer plain Javascript, you can achieve the same with adding an onsubmit handler to the form's Javascript object

```<code><form onsubmit="event.preventDefault(); sendAJAX();">
</code>```

and you need to define sendAJAX to send your AJAX in plain Javascript.

ContentLicense: CC BY-SA 3.0

Title: how to fetch post api?

Body:
I have an API which returns data from database.

this is my form

            <form action="<c:url value="/getCandidateDetails"/>" method="post">

                    Master Id:

                    <input type="text" id="masterId"
path="studentmasterid" name="studentmasterid" class="form-control">

                    <input type="hidden" value="Pending" name="paymentStatus"/>
                    <button class="btn btn-primary" type="submit" id="search">Search</button>
                </form>

the controller part looks like this.

@RequestMapping(value = "/getCandidateDetails", method = RequestMethod.POST)
public @ResponseBody List<CandidateappearagainstadvtcodeEntity> getCandidateDetails
(Model model, @RequestParam("studentmasterid") String studentmasterid,

@RequestParam("paymentStatus")String paymentstatus){
    List<CandidateappearagainstadvtcodeEntity> candidates=
    candidateappearagainstadvtcodeEntityRepository.findByStudentmasteridAndPaymentstatus
    (studentmasterid,paymentstatus);
            return candidates;
        }

it throws json

    [{"id":393,"advertisementcode":"15206-15206/2071-
72","ageonlastdateday":0,"ageonlastdatemonth":0,"ageonlastdateyear":0,
"applicationnumber":"38483928614","attendancestatus":"Pending",
"candidatefirstname":"RAJENDRA","dateofbirthinnepali":null,
"interviewmarksallocationstatus":null,"interviewscheduledstatus":null,
"mothername":"धनराज्य लक्ष्मी पाण्डे",
"candidatenameinnepali":"राजेन्द्रपाण्डे",
"marksobtained":0.0,"optionalpaperid":"NA","panelname":null,
"paymentstatus":"Pending","studentmasterid":"1161"}]

as you can see my form sends two parameters studentmasterid and payment details.
Whenever I click the search button it should hit the api with post method, grab the returned data and view it on jsp page. How can I do it by using ajax?

Body:
Your form currently does an HTML POST. Instead you intend to use AJAX. This is how you can do it in jQuery:

HTML

            <form id="myform" action="<c:url value="/getCandidateDetails"/>" method="post">
                <div class="form-group">
                    <label for="masterId">Master Id:</label><br/>
                    <input type="text" id="masterId"
path="studentmasterid" name="studentmasterid" class="form-control">
                    </div>
                    <input type="hidden" value="Pending" name="paymentStatus"/>
                    <button class="btn btn-primary" type="submit" id="search">Search</button>
                </form>

Javascript

$("#myform").submit(function(submitEvent) {
    submitEvent.preventDefault(); //Prevents HTML POST
    var items = $(this).find("[name]"); //Finds all the named items in the form
    //Builds the data object
    var data = {};
    for (var index in items) {
        data[items[index].prop("name")] = items[index].val();
    }
    $.ajax({
        url: $(this).prop("action"),
        data: data,
        method: "POST"
    }).done(function(responseData) {
        //Do something with the response you have received from the server.
    });
});

If you prefer plain Javascript, you can achieve the same with adding an onsubmit handler to the form's Javascript object

<form onsubmit="event.preventDefault(); sendAJAX();">

and you need to define sendAJAX to send your AJAX in plain Javascript.


问:
How to convert buttons to a text box and button (Javascript)
I am in the process of learning Javascript and found a guide for a text based game. Currently I have a game that you are supposed to find a cat in a 10x10 area. I use 4 buttons (North, South, East, West) and was wondering if it is possible to convert this into a text-box (user typing in North and they will move up one space north) then click a button to submit the command. I also am not sure how to connect the textbox, button, and Javascript but I tried to do it with what I could find online.

HTML

```<code>   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Text Based Game </title>

</head>
<body>
<h1>Find The Cat!</h1>
    <p> Can you find the cat somewhere in this 10x10 world?</p>

<p><img id="myImage" onclick="changeImage()" src="http://www.noonco.com/rc/java_art/picture_doorway.jpg" width="200" height="150">
</p>
    <p> You can type in any of these words: <br>
    north, east, south, west, hint, help</p>

    <div id="hint"></div>
    <div id="help"></div>
    <div id='none'></div>

<input id="choice" type="text">
<input id="submit" type="button" onclick="processInput" value="submit command">

<!--  <ul>
<p>
<button onclick="myFunction01()">North</button> <br>
<button onclick="myFunction02()">West</button> <br>
<button onclick="myFunction03()">East</button><br>
<button onclick="myFunction04()">South</button>
    </p>
</ul>-->
<p id="demo"></p>
<script src="TextGame.js"></script>

</body>

</html>
</code>```

JAVASCRIPT

```<code>    var north=0;
var south=0;
var west=0;
var east=0;
var position = "Central Room";
var worldsize=10;

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {

        myFunction01();
    }
    else if (command == "south") {

        myFunction04();
    }
    else if (command == "west") {

        myFunction02();
    }
    else if (command == "east") {

        myFunction03();
    }
    else if (command == "hint"){

        myfunction
    }
}

function myFunction01() {
if (north > worldsize){
return;
}
if (south < 1) {
        north = north + 1;
}else {
        south = south - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction02() {
if (west > worldsize){
return;
}
if (east < 1) {
        west = west + 1;
}else{
        east = east - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction03() {

if (east > worldsize){
return;
}
if (west < 1) {
        east = east + 1;
}else{
        west = west - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction04() {
if (south > worldsize){
return;
}
if (north > 0) {
        north = north - 1;
}else{
south = south + 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myposition() {
var image = document.getElementById('myImage');
if (north == 7 && east == 4){
position = "Cat Freak Out!";
image.src = "https://s-media-cache-ak0.pinimg.com/736x/32/ba/19/32ba192e9eb99068a91fd2e8a1e21189.jpg";
}

else{
position = "lost";
image.src = "http://www.noonco.com/rc/java_art/picture_field.jpg";
}
}
</code>```

答:
Just pass the value to a function:</p>

```<code><p>Click the button submit the command.</p>
<input id="command" type="text" value="North">
<button onclick="performCommand(document.getElementById('command').value)">Submit</button>

<script>
function performCommand(command)
{
  alert(command);
}
</script>
</code>```

Body:
I am in the process of learning Javascript and found a guide for a text based game. Currently I have a game that you are supposed to find a cat in a 10x10 area. I use 4 buttons (North, South, East, West) and was wondering if it is possible to convert this into a text-box (user typing in North and they will move up one space north) then click a button to submit the command. I also am not sure how to connect the textbox, button, and Javascript but I tried to do it with what I could find online.

HTML

   <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Text Based Game </title>

Find The Cat!

 Can you find the cat somewhere in this 10x10 world?

 You can type in any of these words:

    north, east, south, west, hint, help

<input id="choice" type="text">
<input id="submit" type="button" onclick="processInput" value="submit command">

JAVASCRIPT

    var north=0;
var south=0;
var west=0;
var east=0;
var position = "Central Room";
var worldsize=10;

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {

        myFunction01();
    }
    else if (command == "south") {

        myFunction04();
    }
    else if (command == "west") {

        myFunction02();
    }
    else if (command == "east") {

        myFunction03();
    }
    else if (command == "hint"){

        myfunction
    }
}

function myFunction01() {
if (north > worldsize){
return;
}
if (south < 1) {
        north = north + 1;
}else {
        south = south - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myFunction02() {
if (west > worldsize){
return;
}
if (east < 1) {
        west = west + 1;
}else{
        east = east - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myFunction03() {

if (east > worldsize){
return;
}
if (west < 1) {
        east = east + 1;
}else{
        west = west - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myFunction04() {
if (south > worldsize){
return;
}
if (north > 0) {
        north = north - 1;
}else{
south = south + 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myposition() {
var image = document.getElementById('myImage');
if (north == 7 && east == 4){
position = "Cat Freak Out!";
image.src = "https://s-media-cache-ak0.pinimg.com/736x/32/ba/19/32ba192e9eb99068a91fd2e8a1e21189.jpg";
}

else{
position = "lost";
image.src = "http://www.noonco.com/rc/java_art/picture_field.jpg";
}
}

Body:
Just pass the value to a function:

<p>Click the button submit the command.</p>
<input id="command" type="text" value="North">
<button onclick="performCommand(document.getElementById('command').value)">Submit</button>

<script>
function performCommand(command)
{
  alert(command);
}
</script>


问:
How to perform backup with Azure App Service
I tried backing up Azure App Service according to the following URL.

However, if you press the backup button on the App Service menu, the next screen will be displayed and you will not be able to proceed.

Backup Not Configured, Configure you backup by setting up a storage account, schedule and select databases to be backed up for safe keeping and disaster recovery.

I tried the App Service Plan with Standard and Premium.
I also created Azure Storage Account.
I have created a new App Service in several regions.

However, both of them got the same result.
Does anyone know the procedure?

Best regards.

答:
The Backup and Restore feature in Azure App Service lets you easily create app backups manually or on a schedule. Also, remember, the Backup and Restore feature requires the App Service plan to be in the Standard tier or higher. However, before backup any Azure App Service you need to configure it properly. As your error message said you should configure,

Storage Account,
Schedule and
Select the Databases to backups

To configure your backups please follows below steps.

Configure Manual Backup

In the Azure portal, navigate to your app's blade, select Settings, then Backups. The Backups blade is displayed.

In the Backups blade, click Configure.

In the Backups Configuration blade, click Storage Settings: Storage not configured to configure a storage account.

Choose storage account Choose your backup destination by selecting a Storage Account and Container. The storage account must belong to the same subscription as the app you want to backup. If you wish, you can create a storage account or a new container in the respective blades. When you're done, click Select.

In the Backups Configuration blade that is still left open, click Database Settings, then select the databases you want to include in the backups. (SQL database, MySQL, or PostgreSQL) (In my case I don’t have any database to select)

In the Backups Configuration blade, click Save. At this point you can click Backup button in the command bar of the Backups blade, this will create a Manual Backup of your app.

Configure Schedule Backup

On the Backups Configuration blade, set Schedule backup to On. Then configure the backup schedule as desired.

In the Backups Configuration blade, click Save. That’s it your backups should works now as you scheduled.


问:
A suitable PC for Visual Studio 2010 programming
I'm planning on buying a new PC for programming under Visual Studio 2010. My main other usages are:

Programming under Microsoft Visual Studio.

Running VMWare Virtual Machines.

Probably multi-monitor (if my budget lets me buy an extra one)

Here are my questions:

Do I need to purchase a high performance display adapter considering my usage described above? or a medium-range one will suffice? In general, I'd like to know how much a display adapter could affect my usages?

Which CPU could perform better? Core i7, Core 2 Quad, AMD?  I have a limited budget but I really need a good performance and buying a good CPU/MB/RAM is my first priority.

答:
i7 or core 2, whichever. I'd go quad core if possible,and I'd use as much money as I could on ram.

The Quadcore AMD processors are also quite good now.

finally, considering 2010 is WPF based, a fast video card would also help, maybe not as much as more ram, but I'd go with something more than onboard video.

ContentLicense: CC BY-SA 2.5


问:
Laravel send post request to another subdomain
I have a Laravel application where I have the main app set up, and I have a subdomain that handles a specific task related to main app.

Let's say main app is: app.xyz.com
and subdomain is: review.xyz.com

The question is, how can I send a post request from a controller in review.xyz.com to a route in app.xyz.com?

Here's what I have tried using Guzzle, which just silently failed (the response was just the login screen of main app. Nothing happened in the log):

```<code>Route::post('approve', function(){
    $client = new Client(['base_uri' => env("MAIN_APP_URL")]);

    $response = $client->request('POST', 'public/approve');
    $body = $response->getBody();

    return $body;
});
</code>```

How does the CSRF protection work in this case?

答:
Normally if calling to another json api, will not use csrf. Instead, we use api token such as jwt and laravel api_token. Thus, in your guzzle, you will be adding header for authorization.

```<code>$client->request('GET', 'example.com/get', [
    'headers' => [
        'Authorization' => 'Bearer your-long-api-token',
        'Accept'     => 'application/json'
    ]
]);
</code>```

Body:
I have a Laravel application where I have the main app set up, and I have a subdomain that handles a specific task related to main app.

Let's say main app is: app.xyz.com
and subdomain is: review.xyz.com

The question is, how can I send a post request from a controller in review.xyz.com to a route in app.xyz.com?

Here's what I have tried using Guzzle, which just silently failed (the response was just the login screen of main app. Nothing happened in the log):

Route::post('approve', function(){
    $client = new Client(['base_uri' => env("MAIN_APP_URL")]);

    $response = $client->request('POST', 'public/approve');
    $body = $response->getBody();

    return $body;
});

How does the CSRF protection work in this case?

Body:
Normally if calling to another json api, will not use csrf. Instead, we use api token such as jwt and laravel api_token. Thus, in your guzzle, you will be adding header for authorization.

$client->request('GET', 'example.com/get', [
    'headers' => [
        'Authorization' => 'Bearer your-long-api-token',
        'Accept'     => 'application/json'
    ]
]);


问:
Swagger does not recognize WebAPI controller parameter with custom attribute [FromContent]
I want to have a custom attribute to parse data as stream and be testable with Swagger.

So I created controller which reads from POST body:

[SwaggerOperation("Create")]
[SwaggerResponse(HttpStatusCode.Created)]
public async Task<string> Post([FromContent]Stream contentStream)
{
    using (StreamReader reader = new StreamReader(contentStream, Encoding.UTF8))
    {
        var str = reader.ReadToEnd();
        Console.WriteLine(str);
    }
    return "OK";
}
```

<p><strong>How to define stream so it is visible in Swagger UI?</strong> </p>

<p>Here is my implementation of <code>FromContent</code> attribute and <code>ContentParameterBinding</code> binding:</p>

<pre class="lang-cs prettyprint-override"><code>public class ContentParameterBinding : HttpParameterBinding
{
    private struct AsyncVoid{}
    public ContentParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor)
    {

    }

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                HttpActionContext actionContext,
                                                CancellationToken cancellationToken)
    {
        var binding = actionContext.ActionDescriptor.ActionBinding;

        if (binding.ParameterBindings.Length > 1 ||
            actionContext.Request.Method == HttpMethod.Get)
        {
            var taskSource = new TaskCompletionSource<AsyncVoid>();
            taskSource.SetResult(default(AsyncVoid));
            return taskSource.Task as Task;
        }

        var type = binding.ParameterBindings[0].Descriptor.ParameterType;

        if (type == typeof(HttpContent))
        {
            SetValue(actionContext, actionContext.Request.Content);
            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(actionContext.Request.Content);
            return tcs.Task;
        }
        if (type == typeof(Stream))
        {
            return actionContext.Request.Content
            .ReadAsStreamAsync()
            .ContinueWith((task) =>
            {
                SetValue(actionContext, task.Result);
            });
        }

        throw new InvalidOperationException("Only HttpContent and Stream are supported for [FromContent] parameters");
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class FromContentAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
    {
        if (parameter == null)
            throw new ArgumentException("Invalid parameter");

        return new ContentParameterBinding(parameter);
    }
}
</code>```

Update

When I create Stream using [FromBody] is shows correctly in Swagger, however Stream is not initiated and ==null

[SwaggerOperation("Create")]
[SwaggerResponse(HttpStatusCode.Created)]
public async Task<string> Post([FromBody]Stream contentStream)
{
    using (StreamReader reader = new StreamReader(contentStream, Encoding.UTF8))
    {
        var str = reader.ReadToEnd();
        Console.WriteLine(str);
    }
    return "OK";
}
```

So I want to have the same UI but with my custom attribute which let's me have Stream from content.

With my custom attribute it shows without TextArea for the parameter but could be tested using Postman and work correctly and Stream is available

答:
Inherit your binding from FormatterParameterBinding class:</p>

```<code>public class ContentParameterBinding : FormatterParameterBinding
{
    public ContentParameterBinding(HttpParameterDescriptor descriptor)
            : base(descriptor,
                   descriptor.Configuration.Formatters,
                   descriptor.Configuration.Services.GetBodyModelValidator())
    {
    }

    //your code
}
</code>```

Body:
I want to have a custom attribute to parse data as stream and be testable with Swagger.

So I created controller which reads from POST body:

[SwaggerOperation("Create")]
[SwaggerResponse(HttpStatusCode.Created)]
public async Task<string> Post([FromContent]Stream contentStream)
{
    using (StreamReader reader = new StreamReader(contentStream, Encoding.UTF8))
    {
        var str = reader.ReadToEnd();
        Console.WriteLine(str);
    }
    return "OK";
}

How to define stream so it is visible in Swagger UI?

Here is my implementation of FromContent attribute and ContentParameterBinding binding:

public class ContentParameterBinding : HttpParameterBinding
{
    private struct AsyncVoid{}
    public ContentParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor)
    {

    }

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                HttpActionContext actionContext,
                                                CancellationToken cancellationToken)
    {
        var binding = actionContext.ActionDescriptor.ActionBinding;

        if (binding.ParameterBindings.Length > 1 ||
            actionContext.Request.Method == HttpMethod.Get)
        {
            var taskSource = new TaskCompletionSource<AsyncVoid>();
            taskSource.SetResult(default(AsyncVoid));
            return taskSource.Task as Task;
        }

        var type = binding.ParameterBindings[0].Descriptor.ParameterType;

        if (type == typeof(HttpContent))
        {
            SetValue(actionContext, actionContext.Request.Content);
            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(actionContext.Request.Content);
            return tcs.Task;
        }
        if (type == typeof(Stream))
        {
            return actionContext.Request.Content
            .ReadAsStreamAsync()
            .ContinueWith((task) =>
            {
                SetValue(actionContext, task.Result);
            });
        }

        throw new InvalidOperationException("Only HttpContent and Stream are supported for [FromContent] parameters");
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class FromContentAttribute : ParameterBindingAttribute
{
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
    {
        if (parameter == null)
            throw new ArgumentException("Invalid parameter");

        return new ContentParameterBinding(parameter);
    }
}

Update

When I create Stream using [FromBody] is shows correctly in Swagger, however Stream is not initiated and ==null

[SwaggerOperation("Create")]
[SwaggerResponse(HttpStatusCode.Created)]
public async Task<string> Post([FromBody]Stream contentStream)
{
    using (StreamReader reader = new StreamReader(contentStream, Encoding.UTF8))
    {
        var str = reader.ReadToEnd();
        Console.WriteLine(str);
    }
    return "OK";
}

So I want to have the same UI but with my custom attribute which let's me have Stream from content.

With my custom attribute it shows without TextArea for the parameter but could be tested using Postman and work correctly and Stream is available

Body:
Inherit your binding from FormatterParameterBinding class:

public class ContentParameterBinding : FormatterParameterBinding
{
    public ContentParameterBinding(HttpParameterDescriptor descriptor)
            : base(descriptor,
                   descriptor.Configuration.Formatters,
                   descriptor.Configuration.Services.GetBodyModelValidator())
    {
    }

    //your code
}


问:
How to restrict controller/view access based on domain ad group
I want to restrict certain parts of my web app to certain user groups located in AD groups inside our domain.

I am using .Net Core 1.1. I have also tried decorating my controller with the [Authorize] attribute but with little success.

Does .Net Core currently have a way to do this?

答:
Make sure you pass windows authentication token with in your Services:

```<code>services.Configure<IISOptions>(options =>
            {
                options.ForwardWindowsAuthentication = true;
            });
</code>```

And then use the [Authorize] attribute as follows
[Authorize(Roles = "AD Role")]

Body:
Make sure you pass windows authentication token with in your Services:

services.Configure<IISOptions>(options =>
            {
                options.ForwardWindowsAuthentication = true;
            });

And then use the [Authorize] attribute as follows
[Authorize(Roles = "AD Role")]


问:
Trying to scrape a product from Aliexpress on Python 2.7
I found the following python code on the internet but I am unsure as to how to make it work. The author stated to "In Terminal navigate to script path and type:

```<code>python aliexpresscrape.py Then type out the path to your file Path to File:/path/to/your/url/file"
</code>```

I am somewhat confused as to where I enter the aliexpress product URL.

One of the messages that I get back from terminal is

```<code>Traceback (most recent call last):
  File "aliexpresscrape.py", line 70, in <module>
    read(selection)
  File "aliexpresscrape.py", line 64, in read
    with open(selection) as f:
IOError: [Errno 2] No such file or directory: '/Users/MyMacbookAir/Desktop/Songs\\  '
</code>```

Here is the code:

```<code>from lxml import html
import lxml.html
import requests
import csv
from csv import writer
#variables
selection = raw_input("Path to File: ")
csv_header = ("post_title","post_name","ID","post_excerpt","post_content","post_status","menu_order","post_date","post_parent","post_author","comment_status","sku","downloadable","virtual","visibility","stock","stock_status","backorders","manage_stock","regular_price","sale_price","weight","length","width","height","tax_status","tax_class","upsell_ids","crosssell_ids","featured","sale_price_dates_from","sale_price_dates_to","download_limit","download_expiry","product_url","button_text","meta:_yoast_wpseo_focuskw","meta:_yoast_wpseo_title","meta:_yoast_wpseo_metadesc","meta:_yoast_wpseo_metakeywords","images","downloadable_files","tax:product_type","tax:product_cat","tax:product_tag","tax:product_shipping_class","meta:total_sales","attribute:pa_color","attribute_data:pa_color","attribute_default:pa_color","attribute:size","attribute_data:size","attribute_default:size")

#write header to output file (runs once)
with open('output.csv', 'w') as f:
        writer=csv.writer(f)
        writer.writerow(csv_header)

def scrape(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    title2 = str(lxml.html.parse(url).find(".//title").text)
    title2 = title2.replace('-' + title2.split("-", 1)[1], '')
    price = tree.xpath("//span[@itemprop='price']//text()")
    i = 0
    for span in tree.cssselect('span'):
        clas = span.get('class')
        rel = span.get('rel')
        if clas == "packaging-des":
            if rel != None:
                if i == 0:
                    weight = rel
                elif i == 1:
                    dim = str(rel)
                i = i+1

    weight = weight
    height = dim.split("|", 3)[0]
    length = dim.split("|", 3)[1]
    width = dim.split("|", 3)[2]
    #Sometimes aliexpress doesn't list a price
    #This dumps a 0 into price in that case to stop the errors
    if len(price) == 1:
        price = float(str(price[0]))
    elif len(price) == 0:
        price = int(0)
    for inpu in tree.cssselect('input'):
        if inpu.get("id") == "hid-product-id":
            sku = inpu.get('value')
    for meta in tree.cssselect('meta'):
        name = meta.get("name")
        prop = meta.get("property")
        content = meta.get('content')
        if prop == 'og:image':
            image = meta.get('content')
        if name == 'keywords':
             keywords = meta.get('content')
        if name == 'description':
            desc = meta.get('content')
    listvar = ([str(title2),str(name), '', '', str(desc), 'publish', '', '', '0', '1', 'open', str(sku), 'no', 'no', 'visible', '', 'instock', 'no', 'no', str(price*2),str(price*1.5), str(weight), str(length), str(width), str(height), 'taxable', '', '', '', 'no', '', '', '', '', '', '', '', '', '', str(keywords), str(image), '', 'simple', '', '', '', '0', '', '', '', '', '', '', '', ''])
    with open("output.csv",'ab') as f:
        writer=csv.writer(f)
        writer.writerow(listvar)

def read(selection):
    lines = []
    j = 0
    with open(selection) as f:
        for line in f:
            lines.append(line)
        lines = map(lambda s: s.strip(), lines)
    for j in range(len(lines)):
        scrape(str(lines[j]))
read(selection)
</code>```

答:
Without looking at the documentation of the script (can you provide a link?) it looks like you should create a file containing all the urls of the pages you want to scape. For example lets say i create a file looking like this:

```<code>https://www.aliexpress.com/category/100003070/men-clothing-accessories.html?spm=2114.11010108.102.1.jGW0U0
https://www.aliexpress.com/category/100003109/women-clothing-accessories.html?spm=2114.11010108.101.1.jGW0U0
https://www.aliexpress.com/category/509/phones-telecommunications.html?spm=2114.11010108.103.1.jGW0U0
</code>```

and save it to C:\ali.txt

Then to start scraping these three links, i type in my terminal:

```<code>python aliexpresscrape.py
</code>```

Then the first thing the program will do, is to ask for a filename:

```<code>selection = raw_input("Path to File: ")
</code>```

And you now give the path to your file by typing

```<code>C:\ali.txt
</code>```

and hit enter.

Then, for each line that the script finds in your text file, it will call scrape with the line-content (which is a url) and start scaping that url.

Body:
I found the following python code on the internet but I am unsure as to how to make it work. The author stated to "In Terminal navigate to script path and type:

python aliexpresscrape.py Then type out the path to your file Path to File:/path/to/your/url/file"

I am somewhat confused as to where I enter the aliexpress product URL.

One of the messages that I get back from terminal is

Traceback (most recent call last):
  File "aliexpresscrape.py", line 70, in <module>
    read(selection)
  File "aliexpresscrape.py", line 64, in read
    with open(selection) as f:
IOError: [Errno 2] No such file or directory: '/Users/MyMacbookAir/Desktop/Songs\\  '

Here is the code:

from lxml import html
import lxml.html
import requests
import csv
from csv import writer
#variables
selection = raw_input("Path to File: ")
csv_header = ("post_title","post_name","ID","post_excerpt","post_content","post_status","menu_order","post_date","post_parent","post_author","comment_status","sku","downloadable","virtual","visibility","stock","stock_status","backorders","manage_stock","regular_price","sale_price","weight","length","width","height","tax_status","tax_class","upsell_ids","crosssell_ids","featured","sale_price_dates_from","sale_price_dates_to","download_limit","download_expiry","product_url","button_text","meta:_yoast_wpseo_focuskw","meta:_yoast_wpseo_title","meta:_yoast_wpseo_metadesc","meta:_yoast_wpseo_metakeywords","images","downloadable_files","tax:product_type","tax:product_cat","tax:product_tag","tax:product_shipping_class","meta:total_sales","attribute:pa_color","attribute_data:pa_color","attribute_default:pa_color","attribute:size","attribute_data:size","attribute_default:size")

#write header to output file (runs once)
with open('output.csv', 'w') as f:
        writer=csv.writer(f)
        writer.writerow(csv_header)

def scrape(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    title2 = str(lxml.html.parse(url).find(".//title").text)
    title2 = title2.replace('-' + title2.split("-", 1)[1], '')
    price = tree.xpath("//span[@itemprop='price']//text()")
    i = 0
    for span in tree.cssselect('span'):
        clas = span.get('class')
        rel = span.get('rel')
        if clas == "packaging-des":
            if rel != None:
                if i == 0:
                    weight = rel
                elif i == 1:
                    dim = str(rel)
                i = i+1

    weight = weight
    height = dim.split("|", 3)[0]
    length = dim.split("|", 3)[1]
    width = dim.split("|", 3)[2]
    #Sometimes aliexpress doesn't list a price
    #This dumps a 0 into price in that case to stop the errors
    if len(price) == 1:
        price = float(str(price[0]))
    elif len(price) == 0:
        price = int(0)
    for inpu in tree.cssselect('input'):
        if inpu.get("id") == "hid-product-id":
            sku = inpu.get('value')
    for meta in tree.cssselect('meta'):
        name = meta.get("name")
        prop = meta.get("property")
        content = meta.get('content')
        if prop == 'og:image':
            image = meta.get('content')
        if name == 'keywords':
             keywords = meta.get('content')
        if name == 'description':
            desc = meta.get('content')
    listvar = ([str(title2),str(name), '', '', str(desc), 'publish', '', '', '0', '1', 'open', str(sku), 'no', 'no', 'visible', '', 'instock', 'no', 'no', str(price*2),str(price*1.5), str(weight), str(length), str(width), str(height), 'taxable', '', '', '', 'no', '', '', '', '', '', '', '', '', '', str(keywords), str(image), '', 'simple', '', '', '', '0', '', '', '', '', '', '', '', ''])
    with open("output.csv",'ab') as f:
        writer=csv.writer(f)
        writer.writerow(listvar)

def read(selection):
    lines = []
    j = 0
    with open(selection) as f:
        for line in f:
            lines.append(line)
        lines = map(lambda s: s.strip(), lines)
    for j in range(len(lines)):
        scrape(str(lines[j]))
read(selection)

Body:
Without looking at the documentation of the script (can you provide a link?) it looks like you should create a file containing all the urls of the pages you want to scape. For example lets say i create a file looking like this:

https://www.aliexpress.com/category/100003070/men-clothing-accessories.html?spm=2114.11010108.102.1.jGW0U0
https://www.aliexpress.com/category/100003109/women-clothing-accessories.html?spm=2114.11010108.101.1.jGW0U0
https://www.aliexpress.com/category/509/phones-telecommunications.html?spm=2114.11010108.103.1.jGW0U0

and save it to C:\ali.txt

Then to start scraping these three links, i type in my terminal:

python aliexpresscrape.py

Then the first thing the program will do, is to ask for a filename:

selection = raw_input("Path to File: ")

And you now give the path to your file by typing

C:\ali.txt

and hit enter.

Then, for each line that the script finds in your text file, it will call scrape with the line-content (which is a url) and start scaping that url.


问:
Change window size depending on user control c#
So I have a MainForm, in which I got a Panel.
To this I have created several UserControls that I will put in my Panel on request from different buttons.

My question is: I need to change the windowsize on MainForm depending on which UC I have in the Panel. How do I do this?

I was thinking of creating a public method in MainForm and then call it in the different UC on load, what do you think? Give me your best solutions. Thanks.

Edit: If this is to any help, this is in my MainUC-code to bring in other UC to replace MainUC in panel

```<code>private void UC1Button_Click(object sender, EventArgs e)
    {
        Panel MainPanel = MainForm.MainPanel;
        if (!MainPanel.Controls.Contains(UC1.Instance))
        {
            MainPanel.Controls.Add(UC1.Instance);
            UC1.Instance.Dock = DockStyle.Fill;
            UC1.Instance.BringToFront();
        }
        else
        {
            UC1.Instance.BringToFront();
        }
</code>```

答:
In each UserControl you can create an event which is triggered when content should change. For example you can create an event when a button is clicked

```<code>public partial class MyControl : UserControl
{
    public event OnButtonClicked ButtonClicked;

    public MyControl()
    {
        InitializeComponent();
    }

    private void MyButton_Click(object sender, EventArgs e)
    {
        if(ButtonClicked != null)
        {
            ButtonClicked((Button)sender);
        }
    }
}

public delegate void OnButtonClicked(Button button);
</code>```

Then in your MainForm you can subscribe to events and change panel content and window size when appropriate.

```<code>public partial class MainForm : Form
{
    MyControl myControl;

    void Subscribe()
    {
        myControl.ButtonClicked += myControl_ButtonClicked;
    }

    void myControl_ButtonClicked(Button button)
    {
        // Change panel content
        // Resize window
    }
}
</code>```

Body:
So I have a MainForm, in which I got a Panel.
To this I have created several UserControls that I will put in my Panel on request from different buttons.

My question is: I need to change the windowsize on MainForm depending on which UC I have in the Panel. How do I do this?

I was thinking of creating a public method in MainForm and then call it in the different UC on load, what do you think? Give me your best solutions. Thanks.

Edit: If this is to any help, this is in my MainUC-code to bring in other UC to replace MainUC in panel

private void UC1Button_Click(object sender, EventArgs e)
    {
        Panel MainPanel = MainForm.MainPanel;
        if (!MainPanel.Controls.Contains(UC1.Instance))
        {
            MainPanel.Controls.Add(UC1.Instance);
            UC1.Instance.Dock = DockStyle.Fill;
            UC1.Instance.BringToFront();
        }
        else
        {
            UC1.Instance.BringToFront();
        }

Body:
In each UserControl you can create an event which is triggered when content should change. For example you can create an event when a button is clicked

public partial class MyControl : UserControl
{
    public event OnButtonClicked ButtonClicked;

    public MyControl()
    {
        InitializeComponent();
    }

    private void MyButton_Click(object sender, EventArgs e)
    {
        if(ButtonClicked != null)
        {
            ButtonClicked((Button)sender);
        }
    }
}

public delegate void OnButtonClicked(Button button);

Then in your MainForm you can subscribe to events and change panel content and window size when appropriate.

public partial class MainForm : Form
{
    MyControl myControl;

    void Subscribe()
    {
        myControl.ButtonClicked += myControl_ButtonClicked;
    }

    void myControl_ButtonClicked(Button button)
    {
        // Change panel content
        // Resize window
    }
}


问:
ld: file not found: linker command failed with exit code 1
I've got the following error when building the project in Xcode:

ld: file not found

/Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events
      clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'm stuck with this error for the past hour.. Any solutions?
Code worked fine in iOS 7 and xCode 5.0. Now for iOS8 it gives me this error.

Using frameworks:

CoreTelephony

Mapkit

Facebook.SDK v3.20

Foundation

CoreGraphics

UIKit Framework

FULL ERROR:

```<code>```
Ld /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests normal arm64
    cd /Users/MacBookPro/Desktop/Social_Events/Social_Events/Social_Events
    export IPHONEOS_DEPLOYMENT_TARGET=7.1
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
```

>/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -bundle -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -L/Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos -F/Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/Developer/Library/Frameworks -filelist /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests.LinkFileList -dead_strip -bundle_loader /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events -framework XCTest -fobjc-arc -fobjc-link-runtime -miphoneos-version-min=7.1 -framework XCTest -framework UIKit -framework Foundation -Xlinker -dependency_info -Xlinker /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests_dependency_info.dat -o /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests

>ld: file not found: /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events
clang: error: linker command failed with exit code 1 (use -v to see invocation)

>(null): File not found: /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events
</code>```

答:
Had similar kind of problem when I added unit test target to my existing project. Got all sorts of error. Had to run through some loops to get it finally running. Listing them below

Make sure your entry under Header search path for test target matches that for Header Search Path in your main project folder

If you are using pods you might run in some error such 'No Module found Firebase'. For this simply add the following lines of code to your pod file and run pod install

target 'YourProjectNameTests' do

inherit! :search_paths

# Pods for testing

end

If you also get Bridging header file not found error like I did make sure you add the same for your test target in Build settings under Swift compile code general

Also you will have to follow the steps mentioned by @Jose Llausas

Body:
I've got the following error when building the project in Xcode:

ld: file not found

/Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events
      clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'm stuck with this error for the past hour.. Any solutions?
Code worked fine in iOS 7 and xCode 5.0. Now for iOS8 it gives me this error.

Using frameworks:

CoreTelephony

Mapkit

Facebook.SDK v3.20

Foundation

CoreGraphics

UIKit Framework

FULL ERROR:

Ld /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests normal arm64
    cd /Users/MacBookPro/Desktop/Social_Events/Social_Events/Social_Events
    export IPHONEOS_DEPLOYMENT_TARGET=7.1
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"

>/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -bundle -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -L/Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos -F/Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/Developer/Library/Frameworks -filelist /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests.LinkFileList -dead_strip -bundle_loader /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events -framework XCTest -fobjc-arc -fobjc-link-runtime -miphoneos-version-min=7.1 -framework XCTest -framework UIKit -framework Foundation -Xlinker -dependency_info -Xlinker /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests_dependency_info.dat -o /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Intermediates/Social_Events.build/Debug-iphoneos/Social_EventsTests.build/Objects-normal/arm64/Social_EventsTests

>ld: file not found: /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events
clang: error: linker command failed with exit code 1 (use -v to see invocation)

>(null): File not found: /Users/MacBookPro/Library/Developer/Xcode/DerivedData/Social_Events-cfnteabiivwfdzcoulzznhmgobhy/Build/Products/Debug-iphoneos/Social_Events.app/Social_Events


问:
saving values of toggle(yes or no) in database php
i am trying to use toggle buttons to save response in db as yes or no. for some reason the only response i am getting is 'on'. even when i switch off the button. i tried searching for problem and got a match but the problem was asked for android platform.now i am stuck with no answer there where similar questions but none of them is useful for me at this moment. sharing the code down below.Thanks in advance for those who are going to suggest or provide a solution.i am using class handicap to save data into variable inside JQUERY and then send that variable to AJAX page to perform db operation.i am not sharing CSS for toggle as i don't think that is required right now. if u need any additional info, do inform me.this input is inside a form with method POST. i am using a submit button with id that is calling this JQUERY.
   html part

```<code><div class="switch">
    <input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat handicap" type="checkbox" name="handicap">
    <label for="cmn-toggle-4"></label>
    </div>
</code>```

jquery

```<code>     $("#save-medical-1").click(function () {
        var m11 = $(".handicap").val();
    alert(m11);
        $.ajax({
          url: "ajexupdate.php",
          type: "POST",
          data: {smsgs11: m11},
          dataType: 'text',
          cache: false,
          success: function (e) {
            //           alert(e);
            $("#user_medical_form").html(e);
            $("#medidetail").modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();

          }
        });
        return false;
      });
</code>```

答:
By writing a php command you are setting the initial value of that input into m11. You have to catch the client side value of input instead:

your code:

```<code>var m11 = '<?php echo $_POST['handicap']; ?>'; // always returns the initial value
</code>```

Correct clien-side code:

```<code>var m11 = $(this).val();
</code>```

Body:
i am trying to use toggle buttons to save response in db as yes or no. for some reason the only response i am getting is 'on'. even when i switch off the button. i tried searching for problem and got a match but the problem was asked for android platform.now i am stuck with no answer there where similar questions but none of them is useful for me at this moment. sharing the code down below.Thanks in advance for those who are going to suggest or provide a solution.i am using class handicap to save data into variable inside JQUERY and then send that variable to AJAX page to perform db operation.i am not sharing CSS for toggle as i don't think that is required right now. if u need any additional info, do inform me.this input is inside a form with method POST. i am using a submit button with id that is calling this JQUERY.
   html part

    <input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat handicap" type="checkbox" name="handicap">

jquery

     $("#save-medical-1").click(function () {
        var m11 = $(".handicap").val();
    alert(m11);
        $.ajax({
          url: "ajexupdate.php",
          type: "POST",
          data: {smsgs11: m11},
          dataType: 'text',
          cache: false,
          success: function (e) {
            //           alert(e);
            $("#user_medical_form").html(e);
            $("#medidetail").modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();

          }
        });
        return false;
      });

Body:
By writing a php command you are setting the initial value of that input into m11. You have to catch the client side value of input instead:

your code:

var m11 = '<?php echo $_POST['handicap']; ?>'; // always returns the initial value

Correct clien-side code:

var m11 = $(this).val();


问:
Why Android change 'compile' to 'implementation' configuration in Gradle dependencies?
As seen in Android Studio 3.0 (canary 3.0), we now add depedencies by declaring implementation instead of compile configuration.

```<code>// Before
compile 'com.android.support:appcompat-v7:25.3.1'

// Currently
implementation 'com.android.support:appcompat-v7:25.3.1'
</code>```

We can still use compile, but I would like to understand:

What is the difference between implementation and compile configuration?

Why do Android Gradle build change to use implementation as default?

答:
It seems like compile has been deprecated and api or implementation should be used instead. According to The Java Library Plugin - Gradle User Guide Version 3.5:

The compile configuration still exists but should not be used as it will not offer the guarantees that the api and implementation configurations provide.

Body:
As seen in Android Studio 3.0 (canary 3.0), we now add depedencies by declaring implementation instead of compile configuration.

// Before
compile 'com.android.support:appcompat-v7:25.3.1'

// Currently
implementation 'com.android.support:appcompat-v7:25.3.1'

We can still use compile, but I would like to understand:

What is the difference between implementation and compile configuration?

Why do Android Gradle build change to use implementation as default?


问:
build a "fake" stake using startActivity()
I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.

Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.

This is what I got so far when building the stack but I am not sure how to use it in startActivity method

```<code>    Intent detailActivity = new Intent(aContext, DetailsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
    stackBuilder.addNextIntentWithParentStack(detailActivity);
    PendingIntent pendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

答:
Why don't you just use onBackPressed

```<code>Context context = this;

@Override
    public void onBackPressed()
    {
        Intent intent = new Intent(context,YourActivity.class);
        startActivity(intent);
    }
</code>```

Body:
I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.

Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.

This is what I got so far when building the stack but I am not sure how to use it in startActivity method

    Intent detailActivity = new Intent(aContext, DetailsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
    stackBuilder.addNextIntentWithParentStack(detailActivity);
    PendingIntent pendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

Body:
Why don't you just use onBackPressed

Context context = this;

@Override
    public void onBackPressed()
    {
        Intent intent = new Intent(context,YourActivity.class);
        startActivity(intent);
    }


问:
Distinct method doesn't work for class with overriden Equals
I created class with overriden Equals. The problem is that Distinct method doesn't work for my class.

```<code>class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass x = new MyClass(1, 0);
        MyClass y = new MyClass(1, 0);
        var list = new List<MyClass>();
        list.Add(x);
        list.Add(y);

        bool b = x.Equals(y));  //True
        var distincts = list.Distinct(); //Doesn't work, contains both
    }
}
</code>```

How can I fix that and why it doesn't use my Equals in Distinct?

答:
You have to override GetHashCode as well:

```<code>public override int GetHashCode()
{
    return Item1; // or something
}
</code>```

Distinct first compares the hashcodes, which should be computed faster than the actual Equals. Equals is only further evaulated if the hashcodes are equal  for two instances.

Body:
I created class with overriden Equals. The problem is that Distinct method doesn't work for my class.

class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass x = new MyClass(1, 0);
        MyClass y = new MyClass(1, 0);
        var list = new List<MyClass>();
        list.Add(x);
        list.Add(y);

        bool b = x.Equals(y));  //True
        var distincts = list.Distinct(); //Doesn't work, contains both
    }
}

How can I fix that and why it doesn't use my Equals in Distinct?

Body:
You have to override GetHashCode as well:

public override int GetHashCode()
{
    return Item1; // or something
}

Distinct first compares the hashcodes, which should be computed faster than the actual Equals. Equals is only further evaulated if the hashcodes are equal  for two instances.


问:
Java 8 Read File + Stream
I want to read a file line by line using Java 8 Stream
I have this piece of code:

```<code>@RequestMapping(value = { "/viewlog" }, method = { RequestMethod.GET })
public String viewLoad(final ModelMap model) throws IOException {
    System.out.println ("reading file from userHome -> " + userHome);
    String content = null;
    try {
        content = new String(Files.readAllBytes(Paths.get(userHome + "/logs/nicinc/nicinc.log")));
    } catch (Exception e) {
        System.out.println ("Exception e -> " + e.getMessage());
    } finally {
        System.out.println ("content -> " + content);
    }
    //System.out.println ("content -> " + content);
    return serverContextPath +  SYSTEM_LOG_VIEW;
}
</code>```

But this is what I got from the console, that it really makes no sense for me:

```<code>65630 [http-nio-8080-exec-4] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/nicinc] threw exception
java.nio.file.NoSuchFileException: C:\Users\carbonelllogs\nicinc\nicinc.log
</code>```

答:
The file you are looking for is missing a path seperator.

```<code>C:\Users\carbonelllogs\nicinc\nicinc.log
</code>```

should be

```<code>C:\Users\carbonell\logs\nicinc\nicinc.log
</code>```

the most likely explanation is that you have fixed the code at some point, but haven't redeployed it successfully.

Title: Java 8 Read File + Stream

Body:
I want to read a file line by line using Java 8 Stream
I have this piece of code:

@RequestMapping(value = { "/viewlog" }, method = { RequestMethod.GET })
public String viewLoad(final ModelMap model) throws IOException {
    System.out.println ("reading file from userHome -> " + userHome);
    String content = null;
    try {
        content = new String(Files.readAllBytes(Paths.get(userHome + "/logs/nicinc/nicinc.log")));
    } catch (Exception e) {
        System.out.println ("Exception e -> " + e.getMessage());
    } finally {
        System.out.println ("content -> " + content);
    }
    //System.out.println ("content -> " + content);
    return serverContextPath +  SYSTEM_LOG_VIEW;
}

But this is what I got from the console, that it really makes no sense for me:

65630 [http-nio-8080-exec-4] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/nicinc] threw exception
java.nio.file.NoSuchFileException: C:\Users\carbonelllogs\nicinc\nicinc.log

Body:
The file you are looking for is missing a path seperator.

C:\Users\carbonelllogs\nicinc\nicinc.log

should be

C:\Users\carbonell\logs\nicinc\nicinc.log

the most likely explanation is that you have fixed the code at some point, but haven't redeployed it successfully.


问:
sql : how to find duplicates rows?
i got a table users (id,first_name,last_name,...)
i want to find duplicate users in that table (users which has the same first_name AND the same last_name).

let's say my data is :

```<code> 1;bill;campton
 2;sarah;connor
 3;bill;campton
</code>```

i need to get

```<code>  1;bill;campton;3;bill;campton
</code>```

i dont want to get

```<code>  1;bill;campton;3;bill;campton
  3;bill;campton;1;bill;campton
</code>```

How could i do that?
I use SQL Server 2005

thank you

答:
You could use:

```<code>select u1.id, u2.id, u1.first_name, u1.last_name
from users u1
inner join users u2
on u1.first_name = u2.first_name
and u1.last_name = u2.last_name
where u2.id > u1.id
</code>```

Or, to get your 6 rows, use

```<code>select u1.id, u1.first_name, u1.last_name, u2.id, u2.first_name, u2.last_name
</code>```

etc.

Title: sql : how to find duplicates rows?

Body:
i got a table users (id,first_name,last_name,...)
i want to find duplicate users in that table (users which has the same first_name AND the same last_name).

let's say my data is :

 1;bill;campton
 2;sarah;connor
 3;bill;campton

i need to get

  1;bill;campton;3;bill;campton

i dont want to get

  1;bill;campton;3;bill;campton
  3;bill;campton;1;bill;campton

How could i do that?
I use SQL Server 2005

thank you

Body:
You could use:

select u1.id, u2.id, u1.first_name, u1.last_name
from users u1
inner join users u2
on u1.first_name = u2.first_name
and u1.last_name = u2.last_name
where u2.id > u1.id

Or, to get your 6 rows, use

select u1.id, u1.first_name, u1.last_name, u2.id, u2.first_name, u2.last_name

etc.


问:
Eloquent model not updating updated_at timestamp
I'm using Laravel 5.1. To make it simple, I have the following code

Migration:

```<code>Schema::create('sitemap_data', function (Blueprint $table) {
    // Primary and foreign keys
    $table->increments('id');
    $table->string('postUrl');
    // Database functions
    $table->timestamps();
});
</code>```

And this is the code somewhere else I'm using

```<code>$sitemapData = SitemapData::firstOrNew([
                'postUrl' => $post
            ]);
$sitemapData->save();
</code>```

Now, according to the Laravel documentation

Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value

The updated_at value should be updated in the table. However, this is not happening.

It get's only set on the first insert, but not on updating. When I do it manually, like this

```<code>$sitemapData = SitemapData::firstOrNew([
                    'postUrl' => $post
                ]);
$sitemapData->updated_at = Carbon::now();
$sitemapData->save();
</code>```

it works. However, the docs say this should happend automatically, so what is wrong here?

I've searched some sites on stackoverflow for this question, but the ones I found where for Laravel 3 or 4.1, 4.2 etc.

How would I do that correctly?

答:
Yeah what Musterknabe has done is correct but he should also check his model SitemapData.php it should have to have set $timestamps = true;

```<code><?php

 class SitemapData extends Eloquent {

        public $timestamps = true;
}
</code>```

Body:
I'm using Laravel 5.1. To make it simple, I have the following code

Migration:

Schema::create('sitemap_data', function (Blueprint $table) {
    // Primary and foreign keys
    $table->increments('id');
    $table->string('postUrl');
    // Database functions
    $table->timestamps();
});

And this is the code somewhere else I'm using

$sitemapData = SitemapData::firstOrNew([
                'postUrl' => $post
            ]);
$sitemapData->save();

Now, according to the Laravel documentation

Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value

The updated_at value should be updated in the table. However, this is not happening.

It get's only set on the first insert, but not on updating. When I do it manually, like this

$sitemapData = SitemapData::firstOrNew([
                    'postUrl' => $post
                ]);
$sitemapData->updated_at = Carbon::now();
$sitemapData->save();

it works. However, the docs say this should happend automatically, so what is wrong here?

I've searched some sites on stackoverflow for this question, but the ones I found where for Laravel 3 or 4.1, 4.2 etc.

How would I do that correctly?

Body:
Yeah what Musterknabe has done is correct but he should also check his model SitemapData.php it should have to have set $timestamps = true;

<?php

 class SitemapData extends Eloquent {

        public $timestamps = true;
}

ContentLicense: CC BY-SA 4.0


问:
Nested layout using bootstrap causes misalignment
I am trying to create a nested layout using bootstrap 3. I followed the the tutorial (see the part regarding nesting). The layout basically only contains rows consisting of single columns, however I still need the nesting for technical reasons. My current version is in this fiddle.

In a nutshell, I use alternating row / column divs to achieve the nesting:

```<code><div class="row">
  <div class="col">
    <div class="row">
      <div class="col">
        Content row 1 (misaligned)
      </div>
    </div>
  </div>
</div>
</code>```

The problem is that the inner content is misaligned with respect to the surrounding one. I suspect that this is because rows have a negative margin. Is there a way to fix or circumvent this problem?

答:
there is no class called ".col1" in bootstrap. you need to give proper column class to get rid if the row margin. try to use the blow code </p>

```<code><div class="row">
  <div class="col-xs-4 col-sm-4 col-md-4 "> Content row 1</div>
  <div class="col-xs-4 col-sm-4 col-md-4"> Content row 2 </div>
  <div class="col-xs-4 col-sm-4 col-md-4"> Content row 3 </div>
</div>
</code>```

Body:
I am trying to create a nested layout using bootstrap 3. I followed the the tutorial (see the part regarding nesting). The layout basically only contains rows consisting of single columns, however I still need the nesting for technical reasons. My current version is in this fiddle.

In a nutshell, I use alternating row / column divs to achieve the nesting:

        Content row 1 (misaligned)

The problem is that the inner content is misaligned with respect to the surrounding one. I suspect that this is because rows have a negative margin. Is there a way to fix or circumvent this problem?

Body:
there is no class called ".col1" in bootstrap. you need to give proper column class to get rid if the row margin. try to use the blow code

<div class="row">
  <div class="col-xs-4 col-sm-4 col-md-4 "> Content row 1</div>
  <div class="col-xs-4 col-sm-4 col-md-4"> Content row 2 </div>
  <div class="col-xs-4 col-sm-4 col-md-4"> Content row 3 </div>
</div>


问:
insert data into table that have one primary key, another foreign key using query
I wanna know how I can insert new fresh data into Doctor table that have one primary key another foreign key.

For example, I have I added values for person table as below, please show me how it's done on Doctor Table.

```<code>create table Doctor(
    DoctorID char(6) Primary Key,
    MedicalDegrees varchar(20),
    PersonID int not null REFERENCES Person (PersonID),
    check(DoctorID like '[a-z][a-z][0-9][0-9][0-9][0-9]'));
</code>```

```<code>create table Person(
    PersonID int Primary Key,
    FirstName varchar(15),
    LastName varchar(15),
    StreetAddress varchar(25),
    City varchar(15),
    State varchar(2),
    Zip varchar(5),
    PhoneNumber varchar(10),
    SSN varchar(9) UNIQUE);
</code>```

```<code>insert into person values('1', 'John', 'Smith', '2343 sdf', 'Tacoma', 'WA', 98001, 5268964563, 564657415)
</code>```

Much thanks in advance

答:
I am not sure why do you think that you need a different query for inserting data into a table that has both a primary key and a foreign key, queries doesn't change according to tables design.

Since you already have a query that you posted in your question, we'll use it to insert data into Doctor table.

Your query is:

```<code>insert into person values('1', 'John', 'Smith', '2343 sdf', 'Tacoma', 'WA', 98001, 5268964563, 564657415)
</code>```

According to this query, now you have data in your Person table with an id = 1. Therefor now you can insert data into Doctor table like this:

```<code>Insert INTO Doctor Values('1','Brain Damage','1')
</code>```

The 1 we used in the foreign key is the one we inserted into the Person table.

Note that you won't be able to insert data into Doctor table with an invalid PersonId that doesn't exist in Person table because it is a Foreign key and it has to exists.

Body:
I wanna know how I can insert new fresh data into Doctor table that have one primary key another foreign key.

For example, I have I added values for person table as below, please show me how it's done on Doctor Table.

create table Doctor(
    DoctorID char(6) Primary Key,
    MedicalDegrees varchar(20),
    PersonID int not null REFERENCES Person (PersonID),
    check(DoctorID like '[a-z][a-z][0-9][0-9][0-9][0-9]'));

create table Person(
    PersonID int Primary Key,
    FirstName varchar(15),
    LastName varchar(15),
    StreetAddress varchar(25),
    City varchar(15),
    State varchar(2),
    Zip varchar(5),
    PhoneNumber varchar(10),
    SSN varchar(9) UNIQUE);

insert into person values('1', 'John', 'Smith', '2343 sdf', 'Tacoma', 'WA', 98001, 5268964563, 564657415)

Much thanks in advance

Body:
I am not sure why do you think that you need a different query for inserting data into a table that has both a primary key and a foreign key, queries doesn't change according to tables design.

Since you already have a query that you posted in your question, we'll use it to insert data into Doctor table.

Your query is:

insert into person values('1', 'John', 'Smith', '2343 sdf', 'Tacoma', 'WA', 98001, 5268964563, 564657415)

According to this query, now you have data in your Person table with an id = 1. Therefor now you can insert data into Doctor table like this:

Insert INTO Doctor Values('1','Brain Damage','1')

The 1 we used in the foreign key is the one we inserted into the Person table.

Note that you won't be able to insert data into Doctor table with an invalid PersonId that doesn't exist in Person table because it is a Foreign key and it has to exists.


问:
modal in same window and redirection in new window on href click using css only
I am working on AMP complaint pages which do not allow to write java script except its predefined tags, so i must have to use css for this purpose.

i need to open a modal pop up href click and open href link url in new window.

tried some tricks like using checkbox with label, but not working in my case.

```<code>    <label for="modal-1">this</label>
    <input class="modal-state" id="modal-1" type="checkbox" />
    <div class="modal">
    <label class="modal__bg" for="modal-1"></label>
<div class="modal__inner">
     <label class="modal__close" for="modal-1"></label>
     <h2>Caaaats FTW!</h2>
     <p><img src="" alt="" />Aliquam in sagittis nulla. Curabitur euismod diam eget risus venenatis, sed dictum lectus bibendum. Nunc nunc nisi, hendrerit eget nisi id, rhoncus rutrum velit. Nunc vel mauris dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam fringilla quis nisi eget imperdiet.</p>
  </div>
</div>
</code>```

click on href --> modal pop up + link open in new tab

答:
You can't change the destination of a link in CSS. You have to add the target-attribute to the -tag.

You have to use

```<code><a href="#" target="_blank"></a>
</code>```

for a new tab/window.

Also, opening a modal can most likely only be done with JavaScript. It might be possible using CSS selectors but it would be extremely hard to do.

Body:
I am working on AMP complaint pages which do not allow to write java script except its predefined tags, so i must have to use css for this purpose.

i need to open a modal pop up href click and open href link url in new window.

tried some tricks like using checkbox with label, but not working in my case.

    this
    <input class="modal-state" id="modal-1" type="checkbox" />

Caaaats FTW!

Aliquam in sagittis nulla. Curabitur euismod diam eget risus venenatis, sed dictum lectus bibendum. Nunc nunc nisi, hendrerit eget nisi id, rhoncus rutrum velit. Nunc vel mauris dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam fringilla quis nisi eget imperdiet.

click on href --> modal pop up + link open in new tab

Body:
You can't change the destination of a link in CSS. You have to add the target-attribute to the <a>-tag.

You have to use

<a href="#" target="_blank"></a>

for a new tab/window.

Also, opening a modal can most likely only be done with JavaScript. It might be possible using CSS selectors but it would be extremely hard to do.


问:
Where is $PATH coming from on my mac
So I've been trying to install laravel for quite sometime now on my mac

I run :- export PATH="$PATH:$HOME/.composer/vendor/bin" and everything works for that current terminal session. But if I close and open terminal again, it doesn't work.

I've tried adding path to :-

~/bashrc

~/bash_rc

~/bash_profile

/Users/myusername/bash_profile

but it still doesn't work.

If I run echo $PATH , the out put is "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Where is this coming from ? I don't see this anywhere in any files.

答:
I believe ~/.profile is the file you should use.

You can put your export your export command in the file, and then it will work after next login. And if you want to make it work right now, just run source ~/.profile.

More details, please refer to http://hayne.net/MacDev/Notes/unixFAQ.html#shellStartup

Title: Where is $PATH coming from on my mac


问:
App uses https - what is the correct value of ITSAppUsesNonExemptEncryption
The ONLY encryption my App uses is calls over HTTPS. Currently (7 June 2017) iTunes Connect requires an Export Compliance according to this information in iTunes Connect.

I've entered the iTunesConnect -> My Apps -> Features -> Encryption page, clicked the plus symbol besides "iOS Documentation" and in the Export Compliance form answered YES.

The following two screen shots show more details of the export compliance box as I scroll down.

The last 2 screen shots suggest using HTTPS is an EXEMPT use of encryption and I should therefore in info.plist set ITSAppUsesNonExemptEncryption=false. But this is not clear, and is contradicted in my 1st screen shot that says if you are making a call to HTTPS ... required to submit a year-end classification report to the US government.

So my questions:

is it correct to set ITSAppUsesNonExemptEncryption=false if the only encryption I use is via HTTPS calls?

if I must set ITSAppUsesNonExemptEncryption=true, where do I go to submit a report to the US government and how does this report get passed to Apple? I cannot find any clear information on the process. I don't want to screw this up as the consequences can be major as threatened in the last screen shot.

regardless of how I set ITSAppUsesNonExemptEncryption, according to my 1st screen shot if I use HTTPS I must submit a year-end self classification to the US government. Is that true, and what is the process? (clicking the "learn more" link doesn't help)

答:
I unfortunately do not have enough rep to comment but at the minute I am looking into the exact same issue and I believe that you are correct when you say that you can set the ITSAppUsesNonExemptEncryption key to false, at least this was the conclusion I came to from my research.

For the self classification report it does look like you have to submit one by February of next year, I found this link helpful in explaining the report and what to do

https://www.bis.doc.gov/index.php/policy-guidance/encryption/reports-and-reviews/annual-self-classification

Like I said this is all from my own investigation like you and I think this is correct but if anyone does have any more information would be greatly appreciated.


问:
delete lines before and after a string is found using sed
below is my xml file content -

```<code><?xml version="1.0" encoding="UTF-8"?>
<artifactListing>
    <folder id="REPORTMART" path="/Repository Objects" pathAlias="/00"
        modifiedBy="Maria" lastUpdated="1480426973000" description="Hyperion Root Folder"/>
    <folder id="DATASOURCESFOLD"
        path="/Repository Objects/HRInternalFolder/DataSources"
        pathAlias="/00/HRInternal/DataSources" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="HRINTERNALFOLD"
        path="/Repository Objects/HRInternalFolder"
        pathAlias="/00/HRInternal" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="00000158e031595b-0000-0782-0ae57730"
        path="/Repository Objects/TRCS" pathAlias="/00/0"
        modifiedBy="demoadmin" lastUpdated="1492814854000" description="TRCS"/>
    <resource id="JavaScriptUpdateResizeOn_dds_js"
        path="/Repository Objects/Administration/Impact Manager/Script Repository"
        pathAlias="/00/Administration/0/Script_Repository"
        modifiedBy="Maria" lastUpdated="1492814880000"
        description="JavaScript Update DDS configuration with Layout Manager"
        name="JavaScriptUpdateResizeOn_dds.js" type="text/im-javascript" size="-1"/>
    <resource id="449cb46e6b4492f3afb8ef693dffb43a90cdd992"
        path="/Security" pathAlias="/02"
        description="Shared Services Administrator"
        name="epm_default_cloud_admin" type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacob"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Henry"
        type="UserPreferences" size="-1"/>
    <resource id="33dca1c0c1c5ae78f67580a76d9c6aba6a172e20"
        path="/Security" pathAlias="/02" description="" name="Susan"
        type="UserPreferences" size="-1"/>
    <resource id="3e182b1ea9376483a38614d916a0b666ef531b6d"
        path="/Security" pathAlias="/02" description="" name="Maria"
        type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacques"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Frank"
        type="UserPreferences" size="-1"/>
    <resource id="PP_3e182b1ea9376483a38614d916a0b666ef531b6d_0"
        path="/Product Preferences" pathAlias="/05"
        description="This is your default Personal Page."
        name="My Personal Page" type="PersonalPageContent" size="-1"/>
</artifactListing>
</code>```

now using sed I would like to delete entire resource tag if "Susan" string is found within it, other non-Susan resource tag's should not be considered.
In this scenario, it's only 1 line before and after string, I've other cases where there are more line within the resource tag.

答:
For your scenario, try this:

```<code>$ sed -ibak -r '/^\s*<resource/!bend;:loop;N;/\/>.*$/{/Susan/d;bend};bloop;:end' filename
</code>```

Explains:

/^\s*<resource/!bend: if pattern space does NOT start with ^\s*<resource, jump to the label named end to start a new loop.

:loop: set a label named loop to deal with the whole resource tag.

N: use N command to append a \n and next line into pattern space.

/\/>.*$/{/Susan/d}: if current pattern space ends with />$, which means we have got a complete resource tag in pattern space, then we can deal with it; if this complete resource tag contains Susan, which is your pattern, use d command to delete all contents in pattern space and then jump to label named end to start a new loop.

bloop: use a loop to append the remaining lines of current resource tag into pattern space.

use -ibak to backup the origin file.

P.S: It will ALSO work for other cases where there are more lines within the resource tag.

Body:
below is my xml file content -

<?xml version="1.0" encoding="UTF-8"?>
<artifactListing>
    <folder id="REPORTMART" path="/Repository Objects" pathAlias="/00"
        modifiedBy="Maria" lastUpdated="1480426973000" description="Hyperion Root Folder"/>
    <folder id="DATASOURCESFOLD"
        path="/Repository Objects/HRInternalFolder/DataSources"
        pathAlias="/00/HRInternal/DataSources" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="HRINTERNALFOLD"
        path="/Repository Objects/HRInternalFolder"
        pathAlias="/00/HRInternal" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="00000158e031595b-0000-0782-0ae57730"
        path="/Repository Objects/TRCS" pathAlias="/00/0"
        modifiedBy="demoadmin" lastUpdated="1492814854000" description="TRCS"/>
    <resource id="JavaScriptUpdateResizeOn_dds_js"
        path="/Repository Objects/Administration/Impact Manager/Script Repository"
        pathAlias="/00/Administration/0/Script_Repository"
        modifiedBy="Maria" lastUpdated="1492814880000"
        description="JavaScript Update DDS configuration with Layout Manager"
        name="JavaScriptUpdateResizeOn_dds.js" type="text/im-javascript" size="-1"/>
    <resource id="449cb46e6b4492f3afb8ef693dffb43a90cdd992"
        path="/Security" pathAlias="/02"
        description="Shared Services Administrator"
        name="epm_default_cloud_admin" type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacob"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Henry"
        type="UserPreferences" size="-1"/>
    <resource id="33dca1c0c1c5ae78f67580a76d9c6aba6a172e20"
        path="/Security" pathAlias="/02" description="" name="Susan"
        type="UserPreferences" size="-1"/>
    <resource id="3e182b1ea9376483a38614d916a0b666ef531b6d"
        path="/Security" pathAlias="/02" description="" name="Maria"
        type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacques"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Frank"
        type="UserPreferences" size="-1"/>
    <resource id="PP_3e182b1ea9376483a38614d916a0b666ef531b6d_0"
        path="/Product Preferences" pathAlias="/05"
        description="This is your default Personal Page."
        name="My Personal Page" type="PersonalPageContent" size="-1"/>
</artifactListing>

now using sed I would like to delete entire resource tag if "Susan" string is found within it, other non-Susan resource tag's should not be considered.
In this scenario, it's only 1 line before and after string, I've other cases where there are more line within the resource tag.

Body:
For your scenario, try this:

$ sed -ibak -r '/^\s*<resource/!bend;:loop;N;/\/>.*$/{/Susan/d;bend};bloop;:end' filename

Explains:

/^\s*<resource/!bend: if pattern space does NOT start with ^\s*<resource, jump to the label named end to start a new loop.

:loop: set a label named loop to deal with the whole resource tag.

N: use N command to append a \n and next line into pattern space.

/\/>.*$/{/Susan/d}: if current pattern space ends with />$, which means we have got a complete resource tag in pattern space, then we can deal with it; if this complete resource tag contains Susan, which is your pattern, use d command to delete all contents in pattern space and then jump to label named end to start a new loop.

bloop: use a loop to append the remaining lines of current resource tag into pattern space.

use -ibak to backup the origin file.

P.S: It will ALSO work for other cases where there are more lines within the resource tag.


问:
Is it possible to host an ASPX web site on Linux?
We are trying to convert a lot of things at work over to Linux Red hat.  Recently Windows Server 2003 was installed.  We are currently hosting an asp .net web site on the windows server machine, what I'm wondering is if there is any software that will allow you to host the same web site on linux?</p>

答: You could consider running a windows virutal machine on a linux host using virtualization software like vmware.  I don't know if this fits with what you're trying to do, but it is another option.</p>

OwnerDisplayName: Kyle

OwnerDisplayName: Matt Brunell


问:
proper javascript usage of "this"
Which of the following two ways is better to call the Color property and why? Or does it make a difference?

```<code>lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
</code>```

OR

```<code>lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},
</code>```

Context CODE:

```<code>var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};
</code>```

答:
Personally I'd probably stick with this.Color.  If you do that, then things would continue to work if you decided someday to clone the "LatLongLines" object.

The Tao of this is pretty involved, but it this case it's going to be the contextual object bound from calling the function "through" the "LatLongLines" reference. If those functions might wander away from the original object, then steps would have to be taken to retain a memory of the context object so that it would be correct upon invocation, but that's a complication not evident in anything you've posted.

Title: proper javascript usage of "this"

Body:
Which of the following two ways is better to call the Color property and why? Or does it make a difference?

lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},

OR

lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},

Context CODE:

var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};