问:
Adding a "are you sure you want to leave this page" alert message when exiting a shiny app
Is it possible to add a "Are you sure you want to leave this page?" exit message to a Shiny App when the browser is about to be closed?

I unfortunately can't find the answer elsewhere on StackExchange. I'm thinking that you can possibly do this using javascript, though I'm not super familiar with it. Thanks so much in advance.

答:
With some Jquery/ JS you could accomplish this:

I found the following at:

https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

```<code>    var validNavigation = false;
    function wireUpWindowUnloadEvents() {
     /*
     * List of events which are triggered onbeforeunload on IE
     * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
     */

     // Attach the event keypress to exclude the F5 refresh
     $(document).on('keypress', function(e) {
       if (e.keyCode == 116){
         validNavigation = true;
       }
     });

     // Attach the event click for all links in the page
     $(document).on("click", "a" , function() {
       validNavigation = true;
     });

     // Attach the event submit for all forms in the page
     $(document).on("submit", "form" , function() {
       validNavigation = true;
     });

     // Attach the event click for all inputs in the page
     $(document).bind("click", "input[type=submit]" , function() {
       validNavigation = true;
     });

     $(document).bind("click", "button[type=submit]" , function() {
       validNavigation = true;
     });

    }

    function windowCloseEvent()
           {
            window.onbeforeunload = function() {
             if (!validNavigation){
              callServerForBrowserCloseEvent();
             }
            }
           }

    function callServerForBrowserCloseEvent()
    {
     alert("Are you sure you want to close this window?");
    // Or you could call a bootstrap modal here and give it yes/no buttons
    }

</code>```

Body:
With some Jquery/ JS you could accomplish this:

I found the following at:

https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

    var validNavigation = false;
    function wireUpWindowUnloadEvents() {
     /*
     * List of events which are triggered onbeforeunload on IE
     * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
     */

     // Attach the event keypress to exclude the F5 refresh
     $(document).on('keypress', function(e) {
       if (e.keyCode == 116){
         validNavigation = true;
       }
     });

     // Attach the event click for all links in the page
     $(document).on("click", "a" , function() {
       validNavigation = true;
     });

     // Attach the event submit for all forms in the page
     $(document).on("submit", "form" , function() {
       validNavigation = true;
     });

     // Attach the event click for all inputs in the page
     $(document).bind("click", "input[type=submit]" , function() {
       validNavigation = true;
     });

     $(document).bind("click", "button[type=submit]" , function() {
       validNavigation = true;
     });

    }

    function windowCloseEvent()
           {
            window.onbeforeunload = function() {
             if (!validNavigation){
              callServerForBrowserCloseEvent();
             }
            }
           }

    function callServerForBrowserCloseEvent()
    {
     alert("Are you sure you want to close this window?");
    // Or you could call a bootstrap modal here and give it yes/no buttons
    }


来源: stackexchange

问:
Android Studio - External library folder not refresh
I removed some gradle links from build.gradle(app) but removed libraries still showing in an external library folder.

答:
You need to remove the gradle caches directory, close and re-open Android Studio

rm -rf ~/.gradle/caches

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
ToString() is also called by the .NET Framework implicitly when printing any object out to a string.

```<code>Console.WriteLine("My Object is" + object.ToString());
</code>```

is equivalent to

```<code>Console.WriteLine("My Object is" + object);
</code>```

because the ToString() is implicitly called.

I believe, though am not sure, that it is used by the debugger for the "value" of an object.  This can be fairly handy, though limited.  In most cases writing your own debugger visualizer would be a better idea.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

Body:
ToString() is also called by the .NET Framework implicitly when printing any object out to a string.

Console.WriteLine("My Object is" + object.ToString());

is equivalent to

Console.WriteLine("My Object is" + object);

because the ToString() is implicitly called.

I believe, though am not sure, that it is used by the debugger for the "value" of an object.  This can be fairly handy, though limited.  In most cases writing your own debugger visualizer would be a better idea.


问:
Request types on iPhone || Android?
Is it possible to send GET, POST, PUT and DELETE requests from iPhone || Android applications to a third party server?

I want to build a web service to reuse on all 3 platforms (3rd being the web app itself).

答:
this is an example of how to implement a webservice call in android:

http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

Title: Request types on iPhone || Android?


问:
How can I display videos from my own computer on my website
so I have this website so far

https://imgur.com/a/o4T81MG

Looks like that. I want the play thumbnails to display video I have on my computer. I want to use my computer as a video host. I am trying to play around making a video sharing site. I plan on going down the google cloud route to host my videos but as of right now I wanted to know if its possible to use my own computer as a server to retrieve videos I have saved.

答:
Here's one option...

Step 1: Serving the video

Super Simple Node.js Server

(install Node.js)

At a command-prompt:

Run npm install --global http-server.

Change into (cd) the directory where your videos are stored.

Run http-server.

Apache + GNU/Linux

Run a Linux VM on your computer (or use WSL if you're on Windows, or if you must install it directly follow these instructions: https://www.sitepoint.com/how-to-install-apache-on-windows/).

Install Apache (sudo apt-get install apache2 on Ubuntu; see https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-server-on-ubuntu-16-04).

Put your video in a directory such as /var/www/html or the equivalent for your platform (revisit the first two links for help).

Configure your new server to serve video correctly (https://stackoverflow.com/a/13341700).

Step 2: On the frontend...

Embed a  element on your webpage pointing to the video on the server (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video).

 You're all set up!

TL;DR: you need to serve the videos and then display them. If you want to add logic beyond that, consider building an Express web app.


Title: How to print elements in a vector of vectors

Body:
I have a vector of vectors, and I want to print elements in each vector

I tried the pprint but did not work as wanted

This is the vector of vectors I wish to print:

[["+" "+" "+" "#" "!" "-" "#" "#" "#" "-" "-" "-" "-"]
 ["!" "#" "+" "+" "+" "#" "+" "+" "+" "-" "#" "#" "-"]
 ["#" "#" "#" "#" "+" "#" "+" "#" "+" "#" "-" "#" "#"]
 ["+" "+" "+" "#" "+" "+" "+" "#" "+" "#" "-" "-" "-"]
 ["+" "#" "+" "#" "#" "#" "#" "+" "+" "-" "#" "#" "-"]
 ["+" "#" "+" "+" "+" "+" "+" "+" "#" "-" "-" "-" "-"]
 ["+" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
 ["+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "@"]]

This is the output I want:

+++#--###--#-
!#+++#+++-##-
####+#+#+#!##
+++#+++#+#!!!
+#+####++!##!
+#++++++#!!!!
+############
++++++++++++@

Body:
You can use cl-format to handle list (and list of list in this case) with a control string:

(def input
  [["+" "+" "+" "#" "!" "-" "#" "#" "#" "-" "-" "-" "-"]
   ["!" "#" "+" "+" "+" "#" "+" "+" "+" "-" "#" "#" "-"]
   ["#" "#" "#" "#" "+" "#" "+" "#" "+" "#" "-" "#" "#"]
   ["+" "+" "+" "#" "+" "+" "+" "#" "+" "#" "-" "-" "-"]
   ["+" "#" "+" "#" "#" "#" "#" "+" "+" "-" "#" "#" "-"]
   ["+" "#" "+" "+" "+" "+" "+" "+" "#" "-" "-" "-" "-"]
   ["+" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
   ["+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "@"]])

(use 'clojure.pprint)

(cl-format *out* "~{~{~a~}~%~}" input)

Output:

+++#!-###----
!#+++#+++-##-
####+#+#+#-##
+++#+++#+#---
+#+####++-##-
+#++++++#----
+############
++++++++++++@

Explanation:
~a is the format argument of any type.  When enclosed in ~{ and ~}, the format argument will be iterated over a list.  So when enclosed twice with ~{ and ~}, ~a will be applied over each element (character) in the nested list.  The ~% before the last ~} is to output a newline.
With this, you can easily change the output with control string.  For example:

(cl-format *out* "~{~{(~a)~^ ~}~^~%~%~}" input)

(+) (+) (+) (#) (!) (-) (#) (#) (#) (-) (-) (-) (-)

(!) (#) (+) (+) (+) (#) (+) (+) (+) (-) (#) (#) (-)

(#) (#) (#) (#) (+) (#) (+) (#) (+) (#) (-) (#) (#)

(+) (+) (+) (#) (+) (+) (+) (#) (+) (#) (-) (-) (-)

(+) (#) (+) (#) (#) (#) (#) (+) (+) (-) (#) (#) (-)

(+) (#) (+) (+) (+) (+) (+) (+) (#) (-) (-) (-) (-)

(+) (#) (#) (#) (#) (#) (#) (#) (#) (#) (#) (#) (#)

(+) (+) (+) (+) (+) (+) (+) (+) (+) (+) (+) (+) (@)

Note that "~^" is the directive to stop iteration when a list is run out. So "~^<space>" will suppress the space after the last element in each line.  And "~^~%~%" will suppress the double newline after the last line.


问:
Ask the user for the length of the list (n). Generate a linear list of n integers. Insert a zero after each even value. Print the new list
I am supposed to ask the user to input a number then print all the numbers preceding that but, I have to insert a 0 after every even number.
I am a beginner in Python so, I don't know much.

```<code>n=0
length_even=[]
length_odd=[]

def length_list(n):
    length=int(input('Enter the length of the list: '))
    for i in range(1,length+1):
        if(i%2 != 0):
            length_odd.append(i)
        elif(i%2 == 0) :
            length_even.append(i)
            length_even.insert(i,0)

    total=length_odd+length_even
    return total

length_list(n)
</code>```

If a user enters 5, I expect the output to be [1,2,0,3,4,0,5] but, the actual output is (1,3,5,2,0,4,0].

答:
The problem is that you create two independent lists (length_even and length_odd) and concatenate (+ operator) them after you have added the values to each list (length_odd contains: 1,3,5 and length_even contains: 2,0,4,0). The result you get is therefore: 1,3,5,2,0,4,0. Why don't you just use one list? Have a look at the code below (I made only slight changes to avoid confusion):

 n=0
 lengthList = []

 def length_list(n):
     length=int(input('Enter the length of the list: '))
     for i in range(1,length+1):
         if(i%2 != 0):
             lengthList.append(i)
         elif(i%2 == 0) :
             lengthList.append(i)
             lengthList.append(0)

     return lengthList

length_list(n)
```

Body:
I am supposed to ask the user to input a number then print all the numbers preceding that but, I have to insert a 0 after every even number.
I am a beginner in Python so, I don't know much.

n=0
length_even=[]
length_odd=[]

def length_list(n):
    length=int(input('Enter the length of the list: '))
    for i in range(1,length+1):
        if(i%2 != 0):
            length_odd.append(i)
        elif(i%2 == 0) :
            length_even.append(i)
            length_even.insert(i,0)

    total=length_odd+length_even
    return total

length_list(n)

If a user enters 5, I expect the output to be [1,2,0,3,4,0,5] but, the actual output is (1,3,5,2,0,4,0].


问:
Creating VM in AWS
Recently I started to use Azure.
In Azure, I created Resources Group, Virtual Network, Availability Set and Virtual Machine.
Then I connected VM using RDP

Same way, I want to create and connect VM in AWS.
Please let me know, what steps I need to follow.

答:
Virtual Machines on AWS are provided by the Amazon Elastic Compute Cloud service, more commonly known as Amazon EC2. Individual VMs are referred to as instances. Thus, the terminology to seek is "Amazon EC2 instance".

There are many ways to launch an Amazon EC2 instance, such as using a web interface, making an API call or using the AWS Command-Line Interface (CLI).

See: Launch Your Instance - Amazon Elastic Compute Cloud

To launch an instance from the EC2 management console, click Launch instance and provide the desired configuration.

See: Launching an Instance Using the Launch Instance Wizard - Amazon Elastic Compute Cloud

Title: Creating VM in AWS


问:
Trouble with While
While code freezes debug.   Loops infinitely?  But I'm not sure how as I have a defined end condition which should be met.

The sheet I am working with is an inventory sheet.  I have another script that automatically catalogs shipments when they leave the warehouse on a separate tab, which then leaves empty rows of data.  I want to shift the data up to the first empty row.  The script will do this when ran multiple times, however, if all data is condensed when the script is ran, it will move the last data row to the first empty row, which is actually below the last data row at this point.

```<code>function shift() {
  //this sheet
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var thissheet = spr.getSheetByName('CURRENT MONTH');

  //define last row with data
  var lastRow = thissheet.getLastRow();
  var range = thissheet.getRange("A" + lastRow);
  if (range.getValue() !== "") {
    var lastDataRow = lastRow;
  } else {
    var lastDataRow = range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
  }

  //define first empty row
  var column = thissheet.getRange('A11:A');
  var values = column.getValues();
  var ct = 0;
  while (values[ct] && values[ct][0] != "") {
    ct++;
  }
  console.log(ct + 1);
  var firstEmptyRow = (ct + 1) + 10 //+10 accounts for header

  //the range to copy to (first empty row)
  var emptyrange = thissheet.getRange(firstEmptyRow, 1, 1, 15);

  //the copy and clear code
  while (lastDataRow > firstEmptyRow) {
    thissheet.getRange(lastDataRow, 1, 1, 15).copyTo(emptyrange);
    thissheet.getRange(lastDataRow, 1, 1, 15).clearContent();
  }
}
</code>```

My solution was to use While to shift data until the last data row number is less than the first empty row number, thus While (lastDataRow > firstEmptyRow) should run as long as there is data below an empty row.

答:
You need to decrement lastDataRow each time through the loop

```<code>  while (lastDataRow > firstEmptyRow) {
    thissheet.getRange(lastDataRow, 1, 1, 15).copyTo(emptyrange);
    thissheet.getRange(lastDataRow, 1, 1, 15).clearContent();
    lastDataRow--;
  }
</code>```

Title: Trouble with While

Body:
While code freezes debug.   Loops infinitely?  But I'm not sure how as I have a defined end condition which should be met.

The sheet I am working with is an inventory sheet.  I have another script that automatically catalogs shipments when they leave the warehouse on a separate tab, which then leaves empty rows of data.  I want to shift the data up to the first empty row.  The script will do this when ran multiple times, however, if all data is condensed when the script is ran, it will move the last data row to the first empty row, which is actually below the last data row at this point.

function shift() {
  //this sheet
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var thissheet = spr.getSheetByName('CURRENT MONTH');

  //define last row with data
  var lastRow = thissheet.getLastRow();
  var range = thissheet.getRange("A" + lastRow);
  if (range.getValue() !== "") {
    var lastDataRow = lastRow;
  } else {
    var lastDataRow = range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
  }

  //define first empty row
  var column = thissheet.getRange('A11:A');
  var values = column.getValues();
  var ct = 0;
  while (values[ct] && values[ct][0] != "") {
    ct++;
  }
  console.log(ct + 1);
  var firstEmptyRow = (ct + 1) + 10 //+10 accounts for header

  //the range to copy to (first empty row)
  var emptyrange = thissheet.getRange(firstEmptyRow, 1, 1, 15);

  //the copy and clear code
  while (lastDataRow > firstEmptyRow) {
    thissheet.getRange(lastDataRow, 1, 1, 15).copyTo(emptyrange);
    thissheet.getRange(lastDataRow, 1, 1, 15).clearContent();
  }
}

My solution was to use While to shift data until the last data row number is less than the first empty row number, thus While (lastDataRow > firstEmptyRow) should run as long as there is data below an empty row.

Body:
You need to decrement lastDataRow each time through the loop

  while (lastDataRow > firstEmptyRow) {
    thissheet.getRange(lastDataRow, 1, 1, 15).copyTo(emptyrange);
    thissheet.getRange(lastDataRow, 1, 1, 15).clearContent();
    lastDataRow--;
  }


问:
How to deploy Next.js with GraphQL backend on Zeit Now?
I have an Next.js/Express/Apollo GraphQL app running fine on localhost.

I try to deploy it on Zeit Now, and the Next.js part works fine, but the GraphQL backend fails because /graphql route returns:

```<code>502: An error occurred with your deployment
Code: NO_STATUS_CODE_FROM_LAMBDA
</code>```

My now.json looks like:

```<code>{
  "version": 2,
  "builds": [
    { "src": "next.config.js", "use": "@now/next" },
    { "src": "server/server.js", "use": "@now/node" }
  ],
  "routes": [
    { "src": "/api/(.*)", "dest": "server/server.js" },
    { "src": "/graphql", "dest": "server/server.js" }
  ]
}
</code>```

Suggestions?

答:
I was getting that error until I found on a solution on the Wes Bos slack channel.

The following worked for me, but it's possible you could be getting that error for a different reason.

I'm not sure why it works.

You can see it working here

cd backend

Run npm install graphql-import

Update scripts in package.json:

```<code>"deploy": "prisma deploy --env-file variables.env&& npm run writeSchema",
"writeSchema": "node src/writeSchema.js"
</code>```

Note: For non windows users make sure to place space before &&

Create src/writeSchema.js:

```<code>const fs = require('fs');
const { importSchema } = require('graphql-import');
const text = importSchema("src/generated/prisma.graphql");
fs.writeFileSync("src/schema_prep.graphql", text)
</code>```

Update src/db.js:

```<code>const db = new Prisma({
typeDefs: __dirname + "/schema_prep.graphql",
...
});
</code>```

Update src/createServer.js:

```<code>return new GraphQLServer({
typeDefs: __dirname + '/schema.graphql',
...
});
</code>```

Update src/schema.graphql:

```<code># import * from './schema_prep.graphql'
</code>```

Create now.json

```<code>{
    "version": 2,
    "name": "Project Name",
    "builds": [
        { "src": "src/index.js", "use": "@now/node-server" }
    ],
    "routes": [
        { "src": "/.*", "dest": "src/index.js" }
    ],
    "env": {
        "SOME_VARIABLE": "xxx",
        ...
    }
}
</code>```

Run npm run deploy to initially create schema_prep.graphql.

Run now

Another reply said this:

You should not mix graphql imports and js/ts imports. The syntax on the graphql file will be interpreted by graphql-import and will be ignored by ncc (the compiler which reads the __dirname stuff and move the file to the correct directory etc)
  In my example 'schema_prep.graphql' is already preprocessed with the imports from the generated graphql file.

Hopefully this helps.

Body:
I have an Next.js/Express/Apollo GraphQL app running fine on localhost.

I try to deploy it on Zeit Now, and the Next.js part works fine, but the GraphQL backend fails because /graphql route returns:

502: An error occurred with your deployment
Code: NO_STATUS_CODE_FROM_LAMBDA

My now.json looks like:

{
  "version": 2,
  "builds": [
    { "src": "next.config.js", "use": "@now/next" },
    { "src": "server/server.js", "use": "@now/node" }
  ],
  "routes": [
    { "src": "/api/(.*)", "dest": "server/server.js" },
    { "src": "/graphql", "dest": "server/server.js" }
  ]
}

Suggestions?

Body:
I was getting that error until I found on a solution on the Wes Bos slack channel.

The following worked for me, but it's possible you could be getting that error for a different reason.

I'm not sure why it works.

You can see it working here

cd backend

Run npm install graphql-import

Update scripts in package.json:

"deploy": "prisma deploy --env-file variables.env&& npm run writeSchema",
"writeSchema": "node src/writeSchema.js"

Note: For non windows users make sure to place space before &&

Create src/writeSchema.js:

const fs = require('fs');
const { importSchema } = require('graphql-import');
const text = importSchema("src/generated/prisma.graphql");
fs.writeFileSync("src/schema_prep.graphql", text)

Update src/db.js:

const db = new Prisma({
typeDefs: __dirname + "/schema_prep.graphql",
...
});

Update src/createServer.js:

return new GraphQLServer({
typeDefs: __dirname + '/schema.graphql',
...
});

Update src/schema.graphql:

# import * from './schema_prep.graphql'

Create now.json

{
    "version": 2,
    "name": "Project Name",
    "builds": [
        { "src": "src/index.js", "use": "@now/node-server" }
    ],
    "routes": [
        { "src": "/.*", "dest": "src/index.js" }
    ],
    "env": {
        "SOME_VARIABLE": "xxx",
        ...
    }
}

Run npm run deploy to initially create schema_prep.graphql.

Run now

Another reply said this:

You should not mix graphql imports and js/ts imports. The syntax on the graphql file will be interpreted by graphql-import and will be ignored by ncc (the compiler which reads the __dirname stuff and move the file to the correct directory etc)
  In my example 'schema_prep.graphql' is already preprocessed with the imports from the generated graphql file.

Hopefully this helps.


问:
Custom Authorization attribute asp.net core
I am trying to figure out what is the best way to create custom authorization attribute for my asp.net core application. I have seen this post and I am aware of the 2 approaches discussed here.
How do you create a custom AuthorizeAttribute in ASP.NET Core?

1) Using IAuthorizationFilter

2) Using Policies

I saw that the official document suggests that we should be using policies and not  IAuthorizationFilter but I felt that using policies for my scenario is an overkill. I personally liked IAuthorizationFilter approach more.

I have a very basic requirement. I want to create an authorize attribute for my web api and need to throw 403 if the current user is not whitelisted to use this API. I really don't care about the scopes(canRead, canWrite, can readWrite etc). If I go ahead with policy approach, I may be using the same policy for all my APIs.
What is the best way to achieve this?

答:
Using policies for something like this isn't overkill. You need a requirement:

```<code>public class WhitelistRequirement: IAuthorizationRequirement
{
}
</code>```

A handler:

```<code>public class WhitelistHandler : AuthorizationHandler<WhitelistRequirement>
{

    // Implement a constructor to inject dependencies, such as your whitelist

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   WhitelistRequirement requirement)
    {
        if (isInWhitelist) // Your implementation here
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}
</code>```

Register both in ConfigureServices:

```<code>services.AddAuthorization(options =>
            options.AddPolicy("WhitelistPolicy",
            b => b.AddRequirements(new WhitelistRequirement())));

services.AddSingleton<IAuthorizationHandler, WhitelistHandler>();
</code>```

Then use your policy:

```<code>[Authorize(Policy = "WhitelistPolicy")]
</code>```

You can apply the policy globally with a global filter:

```<code>services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .AddRequirements(new WhitelistRequirement())
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
})
</code>```

The resulting behavior for unauthenticated or forbidden users depends on the implementation of the "challenge" and "forbid" behaviors in your app's authentication handler.

See here.

Body:
Using policies for something like this isn't overkill. You need a requirement:

public class WhitelistRequirement: IAuthorizationRequirement
{
}

A handler:

public class WhitelistHandler : AuthorizationHandler<WhitelistRequirement>
{

    // Implement a constructor to inject dependencies, such as your whitelist

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   WhitelistRequirement requirement)
    {
        if (isInWhitelist) // Your implementation here
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

Register both in ConfigureServices:

services.AddAuthorization(options =>
            options.AddPolicy("WhitelistPolicy",
            b => b.AddRequirements(new WhitelistRequirement())));

services.AddSingleton<IAuthorizationHandler, WhitelistHandler>();

Then use your policy:

[Authorize(Policy = "WhitelistPolicy")]

You can apply the policy globally with a global filter:

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .AddRequirements(new WhitelistRequirement())
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
})

The resulting behavior for unauthenticated or forbidden users depends on the implementation of the "challenge" and "forbid" behaviors in your app's authentication handler.

See here.


问:
How to get applescript to compare application version against a Variable
I have a line in my applescript that will not read a variable set for the name of an Application

```<code>set ReadAppVersion to value of version of application TheApp
</code>```

but if I use this below it works.

```<code>set ReadAppVersion to value of version of application "OsiriX"
</code>```

For some reason, I cannot read the version of the application if I have it as a variable name.

But if I use this below it works.

```<code>set ReadAppVersion to value of version of application "OsiriX"
</code>```

```<code>on AppOsirixChecks(TheApp)
  delay 1
  tell application "Finder"
    close every window
  end tell
  do shell script "defaults write com.apple.finder AppleShowAllFiles FALSE"
  tell application "Dock"
    tell application "System Events"
      tell process "Dock"
        click UI element "Finder" of list 1
      end tell
    end tell
  end tell
  menu_click({"Finder", "Go", "Applications"})
  delay 1
  set ReadAppName to 0
  set ReadAppVersion to 0
  set TheRow to 2
  tell application "System Events"
    tell process "Finder"
      repeat until ReadAppName is equal to TheApp
        set ReadAppVersion to value of version of application "osirix"
        set ReadAppName to value of text field 1 of UI element 1 of row TheRow of outline 1 of scroll area 1 of splitter group 1 of splitter group 1 of window "Applications"
        set TheRow to TheRow + 1
        if ReadAppVersion doesn't equal AppVersionOsiriX then
          log "TEST FAILURE !: The current version is: " & ReadAppVersion
        end if
      end repeat
    end tell
  end tell
  log ">>>                 Current Application Name is: " & ReadAppName
  log ">>>              Current Application version is: " & ReadAppVersion
  --return TheRow  -- this line does not seem necessary
  tell application "Finder"
    activate
    delay 2
    close every window
    do shell script "defaults write com.apple.finder AppleShowAllFiles TRUE"
  end tell
end AppOsirixChecks
</code>```

<filepath>/upgrade_test_validation_checklist.scpt:10612:10617: execution error: OsiriX got an error: Can’t make «class valL» of version into type specifier. (-1700)

答:
Try asking it by it's name instead of it's reference. This works for me (without even being in a tell "Finder" block).</p>

```<code>set theApplication to "EasyFind"
set theVersion to version of application named theApplication
</code>```

Body:
I have a line in my applescript that will not read a variable set for the name of an Application

set ReadAppVersion to value of version of application TheApp

but if I use this below it works.

set ReadAppVersion to value of version of application "OsiriX"

For some reason, I cannot read the version of the application if I have it as a variable name.

But if I use this below it works.

set ReadAppVersion to value of version of application "OsiriX"

on AppOsirixChecks(TheApp)
  delay 1
  tell application "Finder"
    close every window
  end tell
  do shell script "defaults write com.apple.finder AppleShowAllFiles FALSE"
  tell application "Dock"
    tell application "System Events"
      tell process "Dock"
        click UI element "Finder" of list 1
      end tell
    end tell
  end tell
  menu_click({"Finder", "Go", "Applications"})
  delay 1
  set ReadAppName to 0
  set ReadAppVersion to 0
  set TheRow to 2
  tell application "System Events"
    tell process "Finder"
      repeat until ReadAppName is equal to TheApp
        set ReadAppVersion to value of version of application "osirix"
        set ReadAppName to value of text field 1 of UI element 1 of row TheRow of outline 1 of scroll area 1 of splitter group 1 of splitter group 1 of window "Applications"
        set TheRow to TheRow + 1
        if ReadAppVersion doesn't equal AppVersionOsiriX then
          log "TEST FAILURE !: The current version is: " & ReadAppVersion
        end if
      end repeat
    end tell
  end tell
  log ">>>                 Current Application Name is: " & ReadAppName
  log ">>>              Current Application version is: " & ReadAppVersion
  --return TheRow  -- this line does not seem necessary
  tell application "Finder"
    activate
    delay 2
    close every window
    do shell script "defaults write com.apple.finder AppleShowAllFiles TRUE"
  end tell
end AppOsirixChecks

<filepath>/upgrade_test_validation_checklist.scpt:10612:10617: execution error: OsiriX got an error: Can’t make «class valL» of version into type specifier. (-1700)

Body:
Try asking it by it's name instead of it's reference. This works for me (without even being in a tell "Finder" block).

set theApplication to "EasyFind"
set theVersion to version of application named theApplication


问:
Proper way to do rolling file sink with Serilog from multiple machines
I am using Serilog.Sinks.RollingFile, which was recently deprecated in favor of Serilog.Sinks.File and I'll upgrade soon hopefully.

For now, my question is how to properly log to a shared log file from multiple machines (either with the new or old package).  When 10 different servers are logging to this single file, sometimes fragments of the lines end up on different lines.  Example and the appsettings.json are below.

So 2 questions.

How do I resolve the problem of fragments ending up on different lines.  Or is this problem inherent with writing to file from multiple machines at once?

If this something the newer library

```<code>"Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "\\\\server\\share\\log-{Date}.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} | {Level:u3} | {MachineName} | {SourceContext} | {RequestId} | {RequestPath} | {ThreadId} | {Message}{NewLine}{Exception}",
          "shared": true
        }
      }
    ]
  }
</code>```

答:
The generally-accepted way to do this is for each app instance to take an exclusive lock on the file prior to writing, and release it when done.

Unfortunately, this requires opening and closing the file a lot, which is VERY slow, and serializes work, which has a cost as the number of machines grows. Serilog doesn't implement this currently, since its one of those features that appears to work in testing, but performs very poorly in production.

Having each app instance write to its own file is a better scheme, but using a network-based log collector/service will be less hassle in the long run.

Body:
I am using Serilog.Sinks.RollingFile, which was recently deprecated in favor of Serilog.Sinks.File and I'll upgrade soon hopefully.

For now, my question is how to properly log to a shared log file from multiple machines (either with the new or old package).  When 10 different servers are logging to this single file, sometimes fragments of the lines end up on different lines.  Example and the appsettings.json are below.

So 2 questions.

How do I resolve the problem of fragments ending up on different lines.  Or is this problem inherent with writing to file from multiple machines at once?

If this something the newer library

"Serilog": {
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "\\\\server\\share\\log-{Date}.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} | {Level:u3} | {MachineName} | {SourceContext} | {RequestId} | {RequestPath} | {ThreadId} | {Message}{NewLine}{Exception}",
          "shared": true
        }
      }
    ]
  }


问:
Send whatsapp message using android/IOS aplication
What is the best way to open the WhatsApp application to send a message?

I wrote this code because I want it to open in one way through the computer browser, and otherwise by the mobile application.

First I made a condition to check where the user is accessing. If it is by some mobile device, it falls in the first condition, otherwise, it falls on the second link.

The condition of opening the application is not working, I think it may be the 'whatsapp: // ...' link can anyone help me?

```<code>        function MakeLink() {
            if ( isMobile.any ) {
                let target = 'whatsapp://send?'
                    target += 'phone='+ encodeURIComponent(phone);
                return target
            } else {
                let target = 'https://web.whatsapp.com/send?'
                    target += 'phone='+ phone;
                return target
            }

        }

    window.location.href = MakeLink();
</code>```

Ps: I do not want to use the 'api.whatsapp' address because it drops to an intermediate page, increasing the client path.

答:
I dont know if there is another way without api

```<code>let target = 'https://api.whatsapp.com/send?'
  target += 'phone='+ phone;
</code>```

EDIT: it suddenly stopped working since yesterday.

Body:
What is the best way to open the WhatsApp application to send a message?

I wrote this code because I want it to open in one way through the computer browser, and otherwise by the mobile application.

First I made a condition to check where the user is accessing. If it is by some mobile device, it falls in the first condition, otherwise, it falls on the second link.

The condition of opening the application is not working, I think it may be the 'whatsapp: // ...' link can anyone help me?

        function MakeLink() {
            if ( isMobile.any ) {
                let target = 'whatsapp://send?'
                    target += 'phone='+ encodeURIComponent(phone);
                return target
            } else {
                let target = 'https://web.whatsapp.com/send?'
                    target += 'phone='+ phone;
                return target
            }

        }

    window.location.href = MakeLink();

Ps: I do not want to use the 'api.whatsapp' address because it drops to an intermediate page, increasing the client path.

Body:
I dont know if there is another way without api

let target = 'https://api.whatsapp.com/send?'
  target += 'phone='+ phone;

EDIT: it suddenly stopped working since yesterday.


问:
merge elements in forestplot format a single element
I am creating a forestplot using the forestplot package in R, and am having trouble with a few things.

Questions:

Is it possible to merge two adjacent text elements

Is it possible to modify either a single text element font, or the font of an entire row

My Code:

```<code>library(forestplot)

# creating text
text <- rbind(c('', 'N (%)', 'SRT', 'ART',  'HR [95% CI]'),
              c('', '', '5 year survival %',  '5 year survival %', ''),
              c('Seminal Vesicle Involvement', '', '', '', ''),
              c('        Yes', '10 (20%)',   '94', '12', '0.73  [0.36, 1.50]'),
              c('        No', '40 (80%)',   '96', '10', '1.78  [0.73, 4.35]'),
              c('Gender', '', '', '', ''),
              c('        Male', '13 (22.5%)', '84', '22', '0.06  [-0.2, 0.86]'),
              c('        Female', '37 (77.5%)', '93', '13', '1.89  [0.90, 6.67]'))

# creating the plot
forestplot(text,
           mean = c(NA, NA, NA, 0.73, 1.78, NA, 0.06, 1.89),
           lower = c(NA, NA, NA, 0.36, 0.73, NA, -0.2, 0.90),
           upper = c(NA, NA, NA, 1.50, 4.35, NA, 0.86, 6.67),
           is.summary=c(T, T, T, F, F, T, F, F),
           lineheight = unit(0.9, "cm"),
           graph.pos = 5,
           graphwidth = unit(4, 'cm'),
           xticks = c(-1, 0, 1, 2, 3, 4),
           ci.vertices = T,
           txt_gp = fpTxtGp(ticks = gpar(cex = 1),
                            xlab  = gpar(cex = 1),
                            label = gpar(cex = 0.8),
                            summary = gpar(cex = 0.8)),
           col=fpColors(box="black",
                        line="darkgrey",
                        summary="black",
                        zero='grey20',
                        axes='grey20'),
           hrzl_lines = list("2" = gpar(lwd=1, col = "#000044")))
</code>```

Output:

Desired:

I would like the two 5 year survival % text bits to be combined into 1 (and centered between the two headings above), and either just those elements or the whole row to be italic font.

I have tried using summary=list(gpar(...)) for the txt_gp option, but that only seems to be able to modify the whole column, and I have found nothing on merging cells at all.

答:
If you make the colgap much smaller in forestplot than usual, you can split the text that is currently duplicated in row 2 in columns 3 and 4 into two parts:

```<code>> text[2, 4] <- 'survival % '
> text[2, 3] <- '5 year '
>
> forestplot(text,
+            mean = c(NA, NA, NA, 0.73, 1.78, NA, 0.06, 1.89),
+            lower = c(NA, NA, NA, 0.36, 0.73, NA, -0.2, 0.90),
+            upper = c(NA, NA, NA, 1.50, 4.35, NA, 0.86, 6.67),
+            is.summary=c(T, T, T, F, F, T, F, F),
+            lineheight = unit(0.9, "cm"),
+            graph.pos = 5,
+            graphwidth = unit(4, 'cm'),
+            xticks = c(-1, 0, 1, 2, 3, 4),
+            ci.vertices = T,
#   add line---------
          colgap=unit(.0011,"npc"),
#
+            txt_gp = fpTxtGp(ticks = gpar(cex = 1),
+                             xlab  = gpar(cex = 1),
+                             label = gpar(cex = 0.8),
+                             summary = gpar(cex = 0.8)),
+            col=fpColors(box="black",
+                         line="darkgrey",
+                         summary="black",
+                         zero='grey20',
+                         axes='grey20'),
+            hrzl_lines = list("2" = gpar(lwd=1, col = "#000044")))
</code>```

Body:
I am creating a forestplot using the forestplot package in R, and am having trouble with a few things.

Questions:

Is it possible to merge two adjacent text elements

Is it possible to modify either a single text element font, or the font of an entire row

My Code:

library(forestplot)

# creating text
text <- rbind(c('', 'N (%)', 'SRT', 'ART',  'HR [95% CI]'),
              c('', '', '5 year survival %',  '5 year survival %', ''),
              c('Seminal Vesicle Involvement', '', '', '', ''),
              c('        Yes', '10 (20%)',   '94', '12', '0.73  [0.36, 1.50]'),
              c('        No', '40 (80%)',   '96', '10', '1.78  [0.73, 4.35]'),
              c('Gender', '', '', '', ''),
              c('        Male', '13 (22.5%)', '84', '22', '0.06  [-0.2, 0.86]'),
              c('        Female', '37 (77.5%)', '93', '13', '1.89  [0.90, 6.67]'))

# creating the plot
forestplot(text,
           mean = c(NA, NA, NA, 0.73, 1.78, NA, 0.06, 1.89),
           lower = c(NA, NA, NA, 0.36, 0.73, NA, -0.2, 0.90),
           upper = c(NA, NA, NA, 1.50, 4.35, NA, 0.86, 6.67),
           is.summary=c(T, T, T, F, F, T, F, F),
           lineheight = unit(0.9, "cm"),
           graph.pos = 5,
           graphwidth = unit(4, 'cm'),
           xticks = c(-1, 0, 1, 2, 3, 4),
           ci.vertices = T,
           txt_gp = fpTxtGp(ticks = gpar(cex = 1),
                            xlab  = gpar(cex = 1),
                            label = gpar(cex = 0.8),
                            summary = gpar(cex = 0.8)),
           col=fpColors(box="black",
                        line="darkgrey",
                        summary="black",
                        zero='grey20',
                        axes='grey20'),
           hrzl_lines = list("2" = gpar(lwd=1, col = "#000044")))

Output:

Desired:

I would like the two 5 year survival % text bits to be combined into 1 (and centered between the two headings above), and either just those elements or the whole row to be italic font.

I have tried using summary=list(gpar(...)) for the txt_gp option, but that only seems to be able to modify the whole column, and I have found nothing on merging cells at all.

Body:
If you make the colgap much smaller in forestplot than usual, you can split the text that is currently duplicated in row 2 in columns 3 and 4 into two parts:

> text[2, 4] <- 'survival % '
> text[2, 3] <- '5 year '
>
> forestplot(text,
+            mean = c(NA, NA, NA, 0.73, 1.78, NA, 0.06, 1.89),
+            lower = c(NA, NA, NA, 0.36, 0.73, NA, -0.2, 0.90),
+            upper = c(NA, NA, NA, 1.50, 4.35, NA, 0.86, 6.67),
+            is.summary=c(T, T, T, F, F, T, F, F),
+            lineheight = unit(0.9, "cm"),
+            graph.pos = 5,
+            graphwidth = unit(4, 'cm'),
+            xticks = c(-1, 0, 1, 2, 3, 4),
+            ci.vertices = T,
#   add line---------
          colgap=unit(.0011,"npc"),
#
+            txt_gp = fpTxtGp(ticks = gpar(cex = 1),
+                             xlab  = gpar(cex = 1),
+                             label = gpar(cex = 0.8),
+                             summary = gpar(cex = 0.8)),
+            col=fpColors(box="black",
+                         line="darkgrey",
+                         summary="black",
+                         zero='grey20',
+                         axes='grey20'),
+            hrzl_lines = list("2" = gpar(lwd=1, col = "#000044")))


问:
SAP gateway unauthorized when trying to get a csrf token
SAP gateway we are getting 403 unauthorized when trying to get a csrf token.

The same username / password is working for read operations.

I've looked at some other posts in the sap forums and also posted there:
https://answers.sap.com/questions/715798/sap-gateway-unauthorized-when-trying-to-get-a-csrf.html

We are using http, but we have the login/ticket_only_by_https set to 0.

I also looked at the service and did not see the parameter ~CHECK_CSRF_TOKEN = 0 as described at: https://archive.sap.com/discussions/thread/3723417

The parameters list came up as blank.

Any other ideas?

I wrote a small c# program to just try to get the csrf token and it works against our test system but it is failing on a customer's system. I haven't been able to figure out why.

答:
One way to fix it was to append the following to the URL:
“?spnego=disabled”.

I found this info at:

https://launchpad.support.sap.com/#/notes/0002462330

2462330 - Your browser is not configured for using SPNego error on Fiori Client - FC/KAP
Version 1 from 24 Apr 2017 in English
Component:MOB-FC
Priority:Normal
Category:Problem
Release Status:Released to Customer
Rated Helpful:
(2 people)
Quality Rating:

DescriptionProductThis document is referenced byLanguagesRate This Document
Symptom
Attempting to connect Fiori Client iOS to Netweaver Gateway receives error "Your browser is not configured for using SPNego  Press F5 (Page Refresh) to continue".
Environment
•   Fiori Client 1.8.7 iOS
•   Netweaver Gateway with SPNego configured
Reproducing the Issue
1.  Configure Netweaver Gateway and Fiori Launchpad with SPNego (Negotiate) authentication.
2.  Attempt to connect with iOS Fiori Client.
3.  Observer error "Your browser is not configured for using SPNego".
Cause
Fiori Client on all platforms does not support SPNego (Negotiate) authentication.
Resolution
User added URL parameter spnego=disabled to Fiori URL and issue was resolved.  Example:
http://:/sap/bc/ui5_ui5/ui2/ushell/shells/abap/FioriLaunchpad.html/?spnego=disabled


问:
RestSharp AddFile Using Stream
I am using RestSharp (version 105.2.3.0 in Visual Studio 2013, .net 4.5) to call a NodeJS hosted webservice.  One of the calls I need to make is to upload a file.  Using a RESTSharp request, if I retrieve the stream from my end into a byte array and pass that to AddFile, it works fine.  However, I would much rather stream the contents and not load up entire files in server memory (the files can be 100's of MB).

If I set up an Action to copy my stream (see below), I get an exception at the "MyStream.CopyTo" line of System.Net.ProtocolViolationException (Bytes to be written to the stream exceed the Content-Length bytes size specified).  This exception is thrown within the Action block after client.Execute is called.

From what I read, I should not be manually adding a Content-Length header, and it doesn't help if I do.  I have tried setting CopyTo buffer too small and large values, as well as omitting it entirely, to no avail.  Can somebody give me a hint on what I've missed?

```<code>    // Snippet...
    protected T PostFile<T>(string Resource, string FieldName, string FileName,
        string ContentType, Stream MyStream,
        IEnumerable<Parameter> Parameters = null) where T : new()
    {
        RestRequest request = new RestRequest(Resource);
        request.Method = Method.POST;

        if (Parameters != null)
        {
            // Note:  parameters are all UrlSegment values
            request.Parameters.AddRange(Parameters);
        }

        // _url, _username and _password are defined configuration variables
        RestClient client = new RestClient(_url);
        if (!string.IsNullOrEmpty(_username))
        {
            client.Authenticator = new HttpBasicAuthenticator(_username, _password);
        }

        /*
        // Does not work, throws System.Net.ProtocolViolationException,
        // Bytes to be written to the stream exceed the
        // Content-Length bytes size specified.
        request.AddFile(FieldName, (s) =>
        {
            MyStream.CopyTo(s);
            MyStream.Flush();
        }, FileName, ContentType);
        */

        // This works, but has to load the whole file in memory
        byte[] data = new byte[MyStream.Length];
        MyStream.Read(data, 0, (int) MyStream.Length);
        request.AddFile(FieldName, data, FileName, ContentType);

        var response = client.Execute<T>(request);

        // check response and continue...
    }
</code>```

答:
The following code works for me for uploading a csv file using rest sharp. Web services API has been called.</p>

```<code>var client = new RestClient(<YOUR API END URL >);
var request = new RestRequest(Method.POST) ;
request.AlwaysMultipartFormData = true;
request. AddHeader("Content-Type", "multipart/form-data");
request.AddHeader("X-API-TOKEN", <Your Unique Token - again not needed for certain calls>);
request.AddParameter(<Your parameters.....>);
request.AddFile("file", currentFileLocation, contentType);
request.AddParameter("multipart/form-data", fileName, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var response = client.Execute(request);
</code>```

Title: RestSharp AddFile Using Stream

Body:
I am using RestSharp (version 105.2.3.0 in Visual Studio 2013, .net 4.5) to call a NodeJS hosted webservice.  One of the calls I need to make is to upload a file.  Using a RESTSharp request, if I retrieve the stream from my end into a byte array and pass that to AddFile, it works fine.  However, I would much rather stream the contents and not load up entire files in server memory (the files can be 100's of MB).

If I set up an Action to copy my stream (see below), I get an exception at the "MyStream.CopyTo" line of System.Net.ProtocolViolationException (Bytes to be written to the stream exceed the Content-Length bytes size specified).  This exception is thrown within the Action block after client.Execute is called.

From what I read, I should not be manually adding a Content-Length header, and it doesn't help if I do.  I have tried setting CopyTo buffer too small and large values, as well as omitting it entirely, to no avail.  Can somebody give me a hint on what I've missed?

    // Snippet...
    protected T PostFile<T>(string Resource, string FieldName, string FileName,
        string ContentType, Stream MyStream,
        IEnumerable<Parameter> Parameters = null) where T : new()
    {
        RestRequest request = new RestRequest(Resource);
        request.Method = Method.POST;

        if (Parameters != null)
        {
            // Note:  parameters are all UrlSegment values
            request.Parameters.AddRange(Parameters);
        }

        // _url, _username and _password are defined configuration variables
        RestClient client = new RestClient(_url);
        if (!string.IsNullOrEmpty(_username))
        {
            client.Authenticator = new HttpBasicAuthenticator(_username, _password);
        }

        /*
        // Does not work, throws System.Net.ProtocolViolationException,
        // Bytes to be written to the stream exceed the
        // Content-Length bytes size specified.
        request.AddFile(FieldName, (s) =>
        {
            MyStream.CopyTo(s);
            MyStream.Flush();
        }, FileName, ContentType);
        */

        // This works, but has to load the whole file in memory
        byte[] data = new byte[MyStream.Length];
        MyStream.Read(data, 0, (int) MyStream.Length);
        request.AddFile(FieldName, data, FileName, ContentType);

        var response = client.Execute<T>(request);

        // check response and continue...
    }

Body:
The following code works for me for uploading a csv file using rest sharp. Web services API has been called.

var client = new RestClient(<YOUR API END URL >);
var request = new RestRequest(Method.POST) ;
request.AlwaysMultipartFormData = true;
request. AddHeader("Content-Type", "multipart/form-data");
request.AddHeader("X-API-TOKEN", <Your Unique Token - again not needed for certain calls>);
request.AddParameter(<Your parameters.....>);
request.AddFile("file", currentFileLocation, contentType);
request.AddParameter("multipart/form-data", fileName, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var response = client.Execute(request);


问:
Creating a query from an XML input parameter in a stored procedure and verifying the output
I have created a stored procedure that reads XML data as its input. I am having two issues that I am hoping someone can help with.

Issue 1: When I execute the stored procedure, I only get back the first value for AccountType (9). I am expecting/wanting to get back all values for AccountType.

Issue 2: Once I have fixed the above issue I would like to use values from AccountType to select users from another table e.g. dbo.UserData

What I have tried:

I saw this on another SO post that you can debug but I am not sure exactly how to use this or what it's doing.

```<code>select col.query('.') as Debug
</code>```

XML:

<root>
    <From>4</From>
    <AccountType>9</AccountType>
    <AccountType>5</AccountType>
    <AccountType>6</AccountType>
    <AccountType>7</AccountType>
    <AccountType>5</AccountType>
    <AccountType>4</AccountType>
    <AccountType>1</AccountType>
    <AccountType>15</AccountType>
    <AccountType>16</AccountType>
    <AccountType>1</AccountType>
    <AccountType>ivs</AccountType>
    <AccountType>10</AccountType>
    <AccountType>12</AccountType>
    <AccountType>11</AccountType>
    <AccountType>tfs</AccountType>
    <AccountType>vsa</AccountType>
    <AccountType>13</AccountType>
    <AccountType>14</AccountType>
    <GroupID>1</GroupID>
    <GroupID>5</GroupID>
</root>
```

<p>Stored procedure:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE PROCEDURE dbo.UserSelect
    @XMLInput XML
AS
BEGIN
    SET NOCOUNT ON;

    SELECT DISTINCT
        'AccountType' = x.v('AccountType[1]', 'nvarchar(2)')
    FROM
        @XMLInput.nodes('/root') AS x(v)
END
</code>```

Execution of stored procedure:

DECLARE @XML as XML

SET @XML = '<root>
    <From>4</From>
    <AccountType>9</AccountType>
    <AccountType>5</AccountType>
    <AccountType>6</AccountType>
    <AccountType>7</AccountType>
    <AccountType>5</AccountType>
    <AccountType>4</AccountType>
    <AccountType>1</AccountType>
    <AccountType>15</AccountType>
    <AccountType>16</AccountType>
    <AccountType>1</AccountType>
    <AccountType>ivs</AccountType>
    <AccountType>10</AccountType>
    <AccountType>12</AccountType>
    <AccountType>11</AccountType>
    <AccountType>tfs</AccountType>
    <AccountType>vsa</AccountType>
    <AccountType>13</AccountType>
    <AccountType>14</AccountType>
    <GroupID>1</GroupID>
    <GroupID>5</GroupID>
</root>'

EXEC dbo.UserSelect @XML
```

答:
You were close, but you needed to specify the 'AccountType' node in the nodes function. And then use the value function to get the value.

```<code>select distinct x.v.[value]('.','nvarchar(2)') AccountType
from @XML.nodes('/root/AccountType') x(v)
</code>```

In an ITVF (Inline Table Valued Function) it looks like:

```<code>create function dbo.GetAccountTypeFromXML
(
  @Xml xml
)
returns table
return
  select distinct x.v.[value]('.','nvarchar(2)') AccountType
  from @XML.nodes('/root/AccountType') x(v)
</code>```

Which can then be used as, for example:

```<code>select *
from dbo.UserData
where AccountType in (select AccountType from dbo.GetAccountTypeFromXML(@Xml))
</code>```

Body:
I have created a stored procedure that reads XML data as its input. I am having two issues that I am hoping someone can help with.

Issue 1: When I execute the stored procedure, I only get back the first value for AccountType (9). I am expecting/wanting to get back all values for AccountType.

Issue 2: Once I have fixed the above issue I would like to use values from AccountType to select users from another table e.g. dbo.UserData

What I have tried:

I saw this on another SO post that you can debug but I am not sure exactly how to use this or what it's doing.

select col.query('.') as Debug

XML:

<root>
    <From>4</From>
    <AccountType>9</AccountType>
    <AccountType>5</AccountType>
    <AccountType>6</AccountType>
    <AccountType>7</AccountType>
    <AccountType>5</AccountType>
    <AccountType>4</AccountType>
    <AccountType>1</AccountType>
    <AccountType>15</AccountType>
    <AccountType>16</AccountType>
    <AccountType>1</AccountType>
    <AccountType>ivs</AccountType>
    <AccountType>10</AccountType>
    <AccountType>12</AccountType>
    <AccountType>11</AccountType>
    <AccountType>tfs</AccountType>
    <AccountType>vsa</AccountType>
    <AccountType>13</AccountType>
    <AccountType>14</AccountType>
    <GroupID>1</GroupID>
    <GroupID>5</GroupID>
</root>

Stored procedure:

CREATE PROCEDURE dbo.UserSelect
    @XMLInput XML
AS
BEGIN
    SET NOCOUNT ON;

    SELECT DISTINCT
        'AccountType' = x.v('AccountType[1]', 'nvarchar(2)')
    FROM
        @XMLInput.nodes('/root') AS x(v)
END

Execution of stored procedure:

DECLARE @XML as XML

SET @XML = '<root>
    <From>4</From>
    <AccountType>9</AccountType>
    <AccountType>5</AccountType>
    <AccountType>6</AccountType>
    <AccountType>7</AccountType>
    <AccountType>5</AccountType>
    <AccountType>4</AccountType>
    <AccountType>1</AccountType>
    <AccountType>15</AccountType>
    <AccountType>16</AccountType>
    <AccountType>1</AccountType>
    <AccountType>ivs</AccountType>
    <AccountType>10</AccountType>
    <AccountType>12</AccountType>
    <AccountType>11</AccountType>
    <AccountType>tfs</AccountType>
    <AccountType>vsa</AccountType>
    <AccountType>13</AccountType>
    <AccountType>14</AccountType>
    <GroupID>1</GroupID>
    <GroupID>5</GroupID>
</root>'

EXEC dbo.UserSelect @XML

Body:
You were close, but you needed to specify the 'AccountType' node in the nodes function. And then use the value function to get the value.

select distinct x.v.[value]('.','nvarchar(2)') AccountType
from @XML.nodes('/root/AccountType') x(v)

In an ITVF (Inline Table Valued Function) it looks like:

create function dbo.GetAccountTypeFromXML
(
  @Xml xml
)
returns table
return
  select distinct x.v.[value]('.','nvarchar(2)') AccountType
  from @XML.nodes('/root/AccountType') x(v)

Which can then be used as, for example:

select *
from dbo.UserData
where AccountType in (select AccountType from dbo.GetAccountTypeFromXML(@Xml))


问:
what schema permissions are entailed when a SQL Server 2005 database role owns a schema?
In SQL Server 2005, a user-defined database role can "own" a schema. You can see this in the properties window of the database role.  What exactly does this mean in terms of permissions/privileges against the tables in that schema?  What does owning a schema mean?

Or, to ask another way:  If I want a particular user-defined database role to have select/insert/update/delete privileges against every table in a schema, what is the best/smartest way to accomplish this?

I could go into the permissions of every individual table in the schema and grant the privs to the role, but this seems dumb.  How do I do it for the whole schema?

thanks
aj

答:
"Own" means "has full access" or "can do anything."

If that is what you want, just make the group the schema owner.

Otherwise, grant schema-wide permissions to this group. You can grant select permission for the schema, and members of the group will be able to select from all tables in the schema, and so on.

See GRANT Schema Permissions for more info.


问:
Single use/visit presigned url to view S3 object
I am attempting to generate a presigned url that only allows one visit/use of the url.

I have been trying just using an expire time but from what I have tested anything under 70 seconds always gives an expired url error.

```<code>aws s3 presign s3://bucket/object --expires-in 70
</code>```

The other alternative would be a short url expire time (e.g. 5 seconds) but I cannot get anything under 70 seconds to work without an expired url error.

答:
If anything under 70 seconds gives you an error, your clock is almost certainly wrong on the machine where you are generating the signed URL.

Expiration is calculated as --expires-in seconds in the future relative to the clock on the machine where you are running aws-cli.  There's an assumption that this is a trusted environment (your credentials are there) and the clock is also trusted to have been set accurately.

(The clock on the machine where the browser is being used to access the URL doesn't matter.)

Note that the fixed expiration time associated with a given URL is shown in the error message.

Body:
I am attempting to generate a presigned url that only allows one visit/use of the url.

I have been trying just using an expire time but from what I have tested anything under 70 seconds always gives an expired url error.

aws s3 presign s3://bucket/object --expires-in 70

The other alternative would be a short url expire time (e.g. 5 seconds) but I cannot get anything under 70 seconds to work without an expired url error.


问:
Java 8 Filter list based on condition from the part of the list
I have a list of objects N, where N is

```<code>N
|--- type (1,2,3)
|--- A (applicable if type 1)
|--- B (applicable if type 2)
|--- C (applicable if type 3)
|--- List<Integer> p
</code>```

Now, the result I want is filtered version of List such that:

```<code>create a list List<Integer> l
</code>```

Do this first:

```<code>if(type == 1) && (A > some_value):
  Add all elements of p to l
  select this N
</code>```

Later once L is formed:

```<code>if(type != 1)
  if(l contains any element from p):
    select this N
</code>```

How to achieve this using streams in one step?

I can filter and create a list "l" first and then use that list to filter.

```<code>l = stream.filter(a -> a.type == 1 && a.A > some_value).collect(..)
</code>```

Then, use l to filter further.

But is there a better and precise way?

答:
```<code>if(type == 1) && (A > some_value):
  Add all elements of p to l
  select this N
</code>```

Don't know what "select this N" means here, since you're selecting p values, so I'm ignoring that line.

```<code>Set<Integer> set = listOfN.stream()
    .filter(n -> n.type == 1 && n.A > some_value)
    .flatMap(n -> n.p.stream())
    .collect(Collectors.toSet());
</code>```

For better performance of the next step (contains()), the result was changes from List to Set.

```<code>if(type != 1)
  if(l contains any element from p):
    select this N
</code>```

```<code>List<N> result = listOfN.stream()
    .filter(n -> n.type != 1 && n.p.stream().anyMatch(set::contains))
    .collect(Collectors.toList());
</code>```

Body:
I have a list of objects N, where N is

N
|--- type (1,2,3)
|--- A (applicable if type 1)
|--- B (applicable if type 2)
|--- C (applicable if type 3)
|--- List<Integer> p

Now, the result I want is filtered version of List such that:

create a list List<Integer> l

Do this first:

if(type == 1) && (A > some_value):
  Add all elements of p to l
  select this N

Later once L is formed:

if(type != 1)
  if(l contains any element from p):
    select this N

How to achieve this using streams in one step?

I can filter and create a list "l" first and then use that list to filter.

l = stream.filter(a -> a.type == 1 && a.A > some_value).collect(..)

Then, use l to filter further.

But is there a better and precise way?

Body:
if(type == 1) && (A > some_value):
  Add all elements of p to l
  select this N

Don't know what "select this N" means here, since you're selecting p values, so I'm ignoring that line.

Set<Integer> set = listOfN.stream()
    .filter(n -> n.type == 1 && n.A > some_value)
    .flatMap(n -> n.p.stream())
    .collect(Collectors.toSet());

For better performance of the next step (contains()), the result was changes from List to Set.

if(type != 1)
  if(l contains any element from p):
    select this N

List<N> result = listOfN.stream()
    .filter(n -> n.type != 1 && n.p.stream().anyMatch(set::contains))
    .collect(Collectors.toList());


问:
What does ::numeric and ::text mean in mysql
While I am practicing mysql in codewars, this query confused me because I can't find the meaning of ::numeric and ::text in this query.

Query: in baseball, the batting average is a simple and most common way to measure a hitter's performace. Batting average is calculated by taking all the players hits and dividing it by their number of at_bats, and it is usually displayed as a 3 digit decimal (i.e. 0.300).

Given a yankees table with the following schema,

player_id STRING

player_name STRING

primary_position STRING

games INTEGER

at_bats INTEGER

hits INTEGER

return a table with player_name, games, and batting_average.

We want batting_average to be rounded to the nearest thousandth, since that is how baseball fans are used to seeing it. Format it as text and make sure it has 3 digits to the right of the decimal (pad with zeroes if neccesary).

Next, order our resulting table by batting_average, with the highest average in the first row.

Finally, since batting_average is a rate statistic, a small number of at_bats can change the average dramatically. To correct for this, exclude any player who doesn't have at least 100 at bats.

Expected result as output:

player_name STRING

games INTEGER

batting_average STRING

Solution by codewars:-

```<code>select player_name,
       games,
       round(hits::numeric / at_bats, 3)::text as batting_average
from yankees
where at_bats > 100
order by 3 desc
</code>```

答:
It's not MySQL syntax.

It's PostgreSQL syntax for typecasts, as a more concise alternative to CAST(hits AS numeric).

See: https://www.postgresql.org/docs/current/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS

The CAST syntax conforms to SQL; the syntax with :: is historical PostgreSQL usage.

In other words, it's a non-standard syntax that only works in PostgreSQL, not in MySQL or other brands of RDBMS.

Body:
While I am practicing mysql in codewars, this query confused me because I can't find the meaning of ::numeric and ::text in this query.

Query: in baseball, the batting average is a simple and most common way to measure a hitter's performace. Batting average is calculated by taking all the players hits and dividing it by their number of at_bats, and it is usually displayed as a 3 digit decimal (i.e. 0.300).

Given a yankees table with the following schema,

player_id STRING

player_name STRING

primary_position STRING

games INTEGER

at_bats INTEGER

hits INTEGER

return a table with player_name, games, and batting_average.

We want batting_average to be rounded to the nearest thousandth, since that is how baseball fans are used to seeing it. Format it as text and make sure it has 3 digits to the right of the decimal (pad with zeroes if neccesary).

Next, order our resulting table by batting_average, with the highest average in the first row.

Finally, since batting_average is a rate statistic, a small number of at_bats can change the average dramatically. To correct for this, exclude any player who doesn't have at least 100 at bats.

Expected result as output:

player_name STRING

games INTEGER

batting_average STRING

Solution by codewars:-

select player_name,
       games,
       round(hits::numeric / at_bats, 3)::text as batting_average
from yankees
where at_bats > 100
order by 3 desc


问:
Cannot move std::any
The following code

```<code>using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));
</code>```

Fails to compile, complaining about using of deleted copy constructor of unique_ptr. After replacing std::any with vptr in template argument this code compiles, so the issue is clearly with any

How can I force std::any to be moved instead of copied?

答:
The problem is not moving std::any, it's that std::any itself does not support move-only types (std::unique_ptr for example)

as per cppreference

```<code>template< class ValueType >
any( ValueType&& value );
</code>```

Constructs an object with initial content an object of type std::decay_t< ValueType>, direct-initialized from std::forward< ValueType>(value). If std::is_copy_constructible< std::decay_t< ValueType>>::value is false, the program is ill-formed

You can check that is_copy_constructible ... is false with a static_assert, see on coliru

Easiest workaround I can think of is to use shared_ptr instead and still call the std::move.

Title: Cannot move std::any

Body:
The following code

using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));

Fails to compile, complaining about using of deleted copy constructor of unique_ptr. After replacing std::any with vptr in template argument this code compiles, so the issue is clearly with any

How can I force std::any to be moved instead of copied?

Body:
The problem is not moving std::any, it's that std::any itself does not support move-only types (std::unique_ptr for example)

as per cppreference

template< class ValueType >
any( ValueType&& value );

Constructs an object with initial content an object of type std::decay_t< ValueType>, direct-initialized from std::forward< ValueType>(value). If std::is_copy_constructible< std::decay_t< ValueType>>::value is false, the program is ill-formed

You can check that is_copy_constructible ... is false with a static_assert, see on coliru

Easiest workaround I can think of is to use shared_ptr instead and still call the std::move.


问:
trouble starting lift
I'm running through setting up my first lift web-app from Lift in Action. When I run the jetty command after running sbt, I get the following:

```<code>[root@localhost lift-app]# sbt
[info] Building project lift-travel 1.0 against Scala 2.8.0
[info]    using LiftProject with sbt 0.7.7 and Scala 2.7.7
> jetty
[info]
[info] == copy-resources ==
[info] == copy-resources ==
[info]
[info] == compile ==
[info]   Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed.
[info] Compiling main sources...
[error] /home/Ramy/lift-app/src/main/scala/bootstrap/liftweb/Boot.scala:5: value liftweb is not a member of package net
[error] import net.liftweb._
[error]            ^
[error] one error found
[info] == compile ==
[error] Error running compile: Compilation failed
[info]
[info] Total time: 3 s, completed Jan 29, 2012 8:11:59 PM
</code>```

I can post my config if need be but i'm hoping this is enough.

答: Using sbt reload the problem has been solved for me.

Title: trouble starting lift

Body:
I'm running through setting up my first lift web-app from Lift in Action. When I run the jetty command after running sbt, I get the following:

[root@localhost lift-app]# sbt
[info] Building project lift-travel 1.0 against Scala 2.8.0
[info]    using LiftProject with sbt 0.7.7 and Scala 2.7.7
> jetty
[info]
[info] == copy-resources ==
[info] == copy-resources ==
[info]
[info] == compile ==
[info]   Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed.
[info] Compiling main sources...
[error] /home/Ramy/lift-app/src/main/scala/bootstrap/liftweb/Boot.scala:5: value liftweb is not a member of package net
[error] import net.liftweb._
[error]            ^
[error] one error found
[info] == compile ==
[error] Error running compile: Compilation failed
[info]
[info] Total time: 3 s, completed Jan 29, 2012 8:11:59 PM

I can post my config if need be but i'm hoping this is enough.


问:
C standard regarding pointer arithmetic outside arrays
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

```<code>char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))
</code>```

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

```<code>#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

</code>```

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?

答:
Actually, to prove that any arbitrary pointer arithmetic is "unrelated to any array" is very hard (maybe similar to the Halting Problem? Not sure) because a pointer can be assigned "sneakily", through global variable, pointer to pointer, looking at the map file to find the pointer's actual address and modify that etc.

What the standard is saying is that the compiler will probably do the "expected things" in terms of generated code (i.e. usual pointer arithmetic), but that the resulting pointer is not guaranteed to point to anything valid. So the behavior is "undefined". In particular, if you declare a variable before and after an array, and if your pointer goes even one element before or after the array, you are not guarantee that you will be touching those variables or in fact, any valid memory. On a system with with memory protection, it may even crash. The actual behavior depends on the system running the code.

Body:
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?


问:
xkbcommon: ERROR: failed to add default include path
Whenever I start a python script that tries to access the keyboard, for example, with OpenCV's waitKey() method, I get the following error:

```<code>Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .
</code>```

This error started to appear when I installed the keyboard library (or pynput, I am not quite sure) and persisted after I uninstalled them. I do not have QT installed.
Also, neither OpenCV's waitKey nor the two installed libraries can detect any key events (I suspect this is connected), which was already the case before I got the error though.

I am running on Ubuntu 18.04.

How can I go about this problem?

答:
I think this recent issue was resolved here:
https://github.com/conda-forge/qt-feedstock/issues/104

I think the solution is

export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb
```

but I'm not an expert... somebody back me up here please.

Body:
Whenever I start a python script that tries to access the keyboard, for example, with OpenCV's waitKey() method, I get the following error:

Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .

This error started to appear when I installed the keyboard library (or pynput, I am not quite sure) and persisted after I uninstalled them. I do not have QT installed.
Also, neither OpenCV's waitKey nor the two installed libraries can detect any key events (I suspect this is connected), which was already the case before I got the error though.

I am running on Ubuntu 18.04.

How can I go about this problem?

Body:
I think this recent issue was resolved here:
https://github.com/conda-forge/qt-feedstock/issues/104

I think the solution is

export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb

but I'm not an expert... somebody back me up here please.


问:
AWS CLI command query ebs volume-id based on EC tag name
Need some help to fix this query

```<code>aws ec2 describe-instances --filters "Name=tag:Name,Values=UST1TWASDEVP02A" --query "Reservations[*].Instances[*].BlockDeviceMappings[*].Ebs.[VolumeId]"
</code>```

This keeps given me this output :

```<code>[
    [
        [
            [
                "vol-0eb27ed4482aa6b72"
            ],
            [
                "vol-0a8a5716d4abb92cc"
            ],
            [
                "vol-0adb47a85b3541697"
            ]
        ]
    ]
]

</code>```

I only need to extract the second value.

I was able to use jq to get the result

```<code>aws ec2 describe-instances --filters Name=tag:Name,Values=UST1TWASDEVP02A" | jq -r .Reservations[0].Instances[0].BlockDeviceMappings[1].Ebs.VolumeId
</code>```

Thanks

答:
If you only wish to extract the second value, you could use:

```<code>aws ec2 describe-instances --filters "Name=tag:Name,Values=UST1TWASDEVP02A" --query "Reservations[*].Instances[*].BlockDeviceMappings[1].Ebs.[VolumeId]" --output text
</code>```

The difference is using BlockDeviceMappings[1], which will the second BlockDeviceMappings entry for each Reservation+Instance combination.

Body:
Need some help to fix this query

aws ec2 describe-instances --filters "Name=tag:Name,Values=UST1TWASDEVP02A" --query "Reservations[*].Instances[*].BlockDeviceMappings[*].Ebs.[VolumeId]"

This keeps given me this output :

[
    [
        [
            [
                "vol-0eb27ed4482aa6b72"
            ],
            [
                "vol-0a8a5716d4abb92cc"
            ],
            [
                "vol-0adb47a85b3541697"
            ]
        ]
    ]
]

I only need to extract the second value.

I was able to use jq to get the result

aws ec2 describe-instances --filters Name=tag:Name,Values=UST1TWASDEVP02A" | jq -r .Reservations[0].Instances[0].BlockDeviceMappings[1].Ebs.VolumeId

Thanks

Body:
If you only wish to extract the second value, you could use:

aws ec2 describe-instances --filters "Name=tag:Name,Values=UST1TWASDEVP02A" --query "Reservations[*].Instances[*].BlockDeviceMappings[1].Ebs.[VolumeId]" --output text

The difference is using BlockDeviceMappings[1], which will the second BlockDeviceMappings entry for each Reservation+Instance combination.


问:
Changes in the variable are not sent
i have a service, component and module.

in the service, which I want to send the changes of flag$ variable.

```<code>export class ListUserService {
    public flag$ = new Subject< boolean >();
}
</code>```

This component makes the changes for the variable

```<code>export class ListUserComponent implements OnInit {
    private flagPerfil = false;

    getFlag() {
        return this.flagPerfil;
    }

  constructor(private listUserService: ListUserService) {

  }

  functionThatGetsCalledWhenTheFlagIsChanged(){
     this.listUserService.flags$.next(this.flagPerfil);
  }
}
</code>```

I need to receive the variable flag$ in this module:

```<code>export class Tab1PageModule {
    public flagPerfil: boolean;

    constructor(private listUserService: ListUserService) {
        listUserService.flag$.subscribe((flag)=>{
           console.log('FLAG', flag); //never show the console
           this.flagPerfil = flag;
      });
    }
}
</code>```

never enters this console console.log('FLAG', flag); but ocurs this error TS2322:Type 'Subject' is not assignable to type 'boolean', and in the view of the module nothing is displayed

```<code><ion-card-title> {{flagPerfil}} Puedes agregarlos para iniciar una amistad</ion-card-title>
</code>```

答:
Use a behavior subject as they have a default value and any new observers get the last value emitted, subjects only notify observers when they emit, the last value is lost to new observers.

```<code>export class ListUserService {
  public flag$ = new BehaviorSubject<boolean>(false);
}
</code>```

const { Subject, BehaviorSubject } = rxjs;

const subject$ = new Subject();
subject$.next('Subject initial val');
const behaviorSubject$ = new BehaviorSubject('BehaviorSubject initial val');

subject$.subscribe(val => { console.log(val); });
behaviorSubject$.subscribe(val => { console.log(val); });

subject$.next('Subject new val');
behaviorSubject$.next('BehaviorSubject new val');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script></code>```

And use the async pipe in your component so you don't need to subscribe in the code.

```<code>export class ListUserComponent implements OnInit {
  flags$ = this.listUserService.flags$;

  constructor(private listUserService: ListUserService) {

  }

  functionThatGetsCalledWhenTheFlagIsChanged(value: boolean){
     this.listUserService.flags$.next(value);
  }
}
</code>```

and in the view template

```<code><ion-card-title> {{flag$ | async}} Puedes agregarlos para iniciar una amistad</ion-card-title>
</code>```

Title: Changes in the variable are not sent

Body:
i have a service, component and module.

in the service, which I want to send the changes of flag$ variable.

export class ListUserService {
    public flag$ = new Subject< boolean >();
}

This component makes the changes for the variable

export class ListUserComponent implements OnInit {
    private flagPerfil = false;

    getFlag() {
        return this.flagPerfil;
    }

  constructor(private listUserService: ListUserService) {

  }

  functionThatGetsCalledWhenTheFlagIsChanged(){
     this.listUserService.flags$.next(this.flagPerfil);
  }
}

I need to receive the variable flag$ in this module:

export class Tab1PageModule {
    public flagPerfil: boolean;

    constructor(private listUserService: ListUserService) {
        listUserService.flag$.subscribe((flag)=>{
           console.log('FLAG', flag); //never show the console
           this.flagPerfil = flag;
      });
    }
}

never enters this console console.log('FLAG', flag); but ocurs this error TS2322:Type 'Subject' is not assignable to type 'boolean', and in the view of the module nothing is displayed

<ion-card-title> {{flagPerfil}} Puedes agregarlos para iniciar una amistad</ion-card-title>

Body:
Use a behavior subject as they have a default value and any new observers get the last value emitted, subjects only notify observers when they emit, the last value is lost to new observers.

export class ListUserService {
  public flag$ = new BehaviorSubject<boolean>(false);
}

const { Subject, BehaviorSubject } = rxjs;

const subject$ = new Subject();
subject$.next('Subject initial val');
const behaviorSubject$ = new BehaviorSubject('BehaviorSubject initial val');

subject$.subscribe(val => { console.log(val); });
behaviorSubject$.subscribe(val => { console.log(val); });

subject$.next('Subject new val');
behaviorSubject$.next('BehaviorSubject new val');

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

And use the async pipe in your component so you don't need to subscribe in the code.

export class ListUserComponent implements OnInit {
  flags$ = this.listUserService.flags$;

  constructor(private listUserService: ListUserService) {

  }

  functionThatGetsCalledWhenTheFlagIsChanged(value: boolean){
     this.listUserService.flags$.next(value);
  }
}

and in the view template

<ion-card-title> {{flag$ | async}} Puedes agregarlos para iniciar una amistad</ion-card-title>


问:
Functions in Haskell
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

```<code>fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)
</code>```

This gives me a syntax error :-S

```<code>ERROR - Syntax error in input (unexpected `=')
</code>```

答:
The syntax is incorrect. In Haskell, whitespace matters, much like it does in Python. More specifically, if you have text that starts on the first column of a line, the interpreter will think it's a top-level declaration. The correct syntax would be (for example):

```<code>fact :: Int -> Int
fact n = if n == 0
  then 1
  else n * fact (n-1)
</code>```

You could also put the if in one line if you'd like to. So if you're using an interactive prompt you could do:

```<code>λ> let fact n = if n == 0 then 1 else n * fact (n-1)
</code>```

Notice that you'll need to use let in order to define functions on the prompt (at least this is how it's done in GHCi, I'm not sure about Hugs). You'll be better off putting them in a separate file and then loading that in the interpreter. But anyway, a much nicer solution would use pattern-matching in my opinion anyway:

```<code>fact :: Int -> Int
fact 0 = 1
fact n = n * fact (n-1)
</code>```

Here, the interpreter would pattern-match the first argument of the function against the possible cases listed. So if the first argument is null, the result if 1, otherwise apply the function recursively.

Title: Functions in Haskell

Body:
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)

This gives me a syntax error :-S

ERROR - Syntax error in input (unexpected `=')

Body:
The syntax is incorrect. In Haskell, whitespace matters, much like it does in Python. More specifically, if you have text that starts on the first column of a line, the interpreter will think it's a top-level declaration. The correct syntax would be (for example):

fact :: Int -> Int
fact n = if n == 0
  then 1
  else n * fact (n-1)

You could also put the if in one line if you'd like to. So if you're using an interactive prompt you could do:

λ> let fact n = if n == 0 then 1 else n * fact (n-1)

Notice that you'll need to use let in order to define functions on the prompt (at least this is how it's done in GHCi, I'm not sure about Hugs). You'll be better off putting them in a separate file and then loading that in the interpreter. But anyway, a much nicer solution would use pattern-matching in my opinion anyway:

fact :: Int -> Int
fact 0 = 1
fact n = n * fact (n-1)

Here, the interpreter would pattern-match the first argument of the function against the possible cases listed. So if the first argument is null, the result if 1, otherwise apply the function recursively.


问:
Running Google BigQuery sample network analysis script, I get a syntax error: Was expecting: <EOF>
I am trying to use sample code  for Google BigQuery.  The query is in legacy SQL.

I have this set in BigQuery query:

SELECT
  a.name,
  b.name,
  COUNT(*) AS count
FROM (FLATTEN(
    SELECT
      GKGRECORDID,
      UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', "))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 and DATE < 20150304000000 and V2Persons like
'%Tsipras%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ")) name
    FROM
      [gdelt-bq:gdeltv2.gkg]
    WHERE
      DATE>20150302000000
      AND DATE < 20150304000000
      AND V2Persons LIKE '%Tsipras%')) b
ON
  a.GKGRECORDID=b.GKGRECORDID
WHERE
  a.name<b.name
GROUP EACH BY
  1,
  2
ORDER BY
  3 DESC
LIMIT
  250
```

But it raises the error:

Error: Encountered " "ON" "ON "" at line 11, column 1. Was expecting:

答:
You have 1 to many ) characters after the join. Specifically '%Tsipras%')) b should likely be '%Tsipras%') b.
Most errors where you see "Was expecting: " after because of mismatched opening and closing pairs with too many closings.

Body:
I am trying to use sample code  for Google BigQuery.  The query is in legacy SQL.

I have this set in BigQuery query:

SELECT
  a.name,
  b.name,
  COUNT(*) AS count
FROM (FLATTEN(
    SELECT
      GKGRECORDID,
      UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', "))
name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20150302000000 and DATE < 20150304000000 and V2Persons like
'%Tsipras%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*', ")) name
    FROM
      [gdelt-bq:gdeltv2.gkg]
    WHERE
      DATE>20150302000000
      AND DATE < 20150304000000
      AND V2Persons LIKE '%Tsipras%')) b
ON
  a.GKGRECORDID=b.GKGRECORDID
WHERE
  a.name<b.name
GROUP EACH BY
  1,
  2
ORDER BY
  3 DESC
LIMIT
  250

But it raises the error:

Error: Encountered " "ON" "ON "" at line 11, column 1. Was expecting:


问:
How can i put the hyperlink in a contact form in wordpress next to the checkbox message?
I have added a required checkbox field to contact form 7 in wordpress. I added and the hyperlink to send the user in Terms and Conditions page.
This is the checkbox field I added:
[checkbox* term_and_conditions "I have read and accepted the"]Terms and Conditions
But when i run the contact form, the hyperlink: "Terms and Conditions", appears in the next line from the message: "I have read and accepted the" and the message it appears just like that:
I have read and accepted the
Terms and Conditions.

My question is, how can i make the "Terms and Conditions" appears in the same line with "I have read and accepted the"?

Thank you in advance.

答:
I would recommend to write it this way:

```<code>[checkbox* term_and_conditions] I have read and accepted the <a href="https://example">Terms and Conditions</a>
</code>```

...and add CSS to place the text on the same line as the checkbox, for example by adding display: flex to the label tag. This is best done by adding a CSS class to the checkbox element in the form definition and using that class as a selector (possibly also containing the parent elements) for a CSS rule that contains display: flex

Body:
I would recommend to write it this way:

[checkbox* term_and_conditions] I have read and accepted the <a href="https://example">Terms and Conditions</a>

...and add CSS to place the text on the same line as the checkbox, for example by adding display: flex to the label tag. This is best done by adding a CSS class to the checkbox element in the form definition and using that class as a selector (possibly also containing the parent elements) for a CSS rule that contains display: flex


问:
In material-ui, how can I set different theme-styles for different breakpoints?
This questions targets material-ui 1.0.

When I create a theme with createMuiTheme, how can I set, for example for typography.title, different styles for different breakpoints? On a component level I can achieve this with something like this:

```<code>const styles = theme => ({
  title: {
    fontSize: 34,
  },
  [theme.breakpoints.down('sm')]: {
    title: {
      fontSize: 28,
    }
  },
})
</code>```

答:
There is another way to work with createMuiTheme with the breakpoints methods.

If you check the createMuiTheme core, you will see that it uses the createBreakpoints class.

So, you can do like that:

```<code>// theme.js

import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
import { createMuiTheme } from '@material-ui/core/styles'

const breakpoints = createBreakpoints({})

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        [breakpoints.up('lg')]: {
          minWidth: '200px',
          backgroundColor: 'yellow',
        },
      },
      wrapper: {
        padding: '0 10px',
        backgroundColor: 'black',
      },
    },
  },
})

export default theme
</code>```

(tested: @material-ui/core 4.0.1)

Body:
This questions targets material-ui 1.0.

When I create a theme with createMuiTheme, how can I set, for example for typography.title, different styles for different breakpoints? On a component level I can achieve this with something like this:

const styles = theme => ({
  title: {
    fontSize: 34,
  },
  [theme.breakpoints.down('sm')]: {
    title: {
      fontSize: 28,
    }
  },
})

Body:
There is another way to work with createMuiTheme with the breakpoints methods.

If you check the createMuiTheme core, you will see that it uses the createBreakpoints class.

So, you can do like that:

// theme.js

import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
import { createMuiTheme } from '@material-ui/core/styles'

const breakpoints = createBreakpoints({})

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        [breakpoints.up('lg')]: {
          minWidth: '200px',
          backgroundColor: 'yellow',
        },
      },
      wrapper: {
        padding: '0 10px',
        backgroundColor: 'black',
      },
    },
  },
})

export default theme

(tested: @material-ui/core 4.0.1)