问:
Is there a way to show a "console selection menu" for user input in my script like Ctrl+Space in PSReadLine
PSReadLine has FANTASTIC functionality for it's Ctrl+Space key binding.

Is there a way that I can use this same "console menu" functionality for letting my script users (usually me) select from a list of possible values? I don't want to have a separate grid view (Out-GridView) to make the selection.

答:
Using advanced functions is one of the common ways to achieve this and if you want to have dynamic path completion (as per your comment) then this capability can be added with Register-ArgumentCompleter

```<code>$scriptBlock = {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

    Get-ChildItem -Path $pwd -Directory | Where-Object {
        $_ -like "*$wordToComplete*"
    } | ForEach-Object {
        "'$_'"
    }
}
#Register the above scriptblock to the foo function Path Parameter
Register-ArgumentCompleter -CommandName foo -ParameterName Path -ScriptBlock $scriptBlock

function foo {
    param(
        [ValidateSet("Tom","Dick","Jane")]
        $Name,
        [ValidateRange(21, 65)]
        $Age,
        [string]
        $Path
    )
    Write-Host ($Name + $Age + $Path)
}
</code>```

More information can be found with Get-Help about_Functions_Advanced

The above also works with partial directory names, for example if you know the directory has "test" in the name type foo -path test and press CTRL+Space, you'll get a filtered list - pretty cool, right?

Give it a try

Body:
Using advanced functions is one of the common ways to achieve this and if you want to have dynamic path completion (as per your comment) then this capability can be added with Register-ArgumentCompleter

$scriptBlock = {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

    Get-ChildItem -Path $pwd -Directory | Where-Object {
        $_ -like "*$wordToComplete*"
    } | ForEach-Object {
        "'$_'"
    }
}
#Register the above scriptblock to the foo function Path Parameter
Register-ArgumentCompleter -CommandName foo -ParameterName Path -ScriptBlock $scriptBlock

function foo {
    param(
        [ValidateSet("Tom","Dick","Jane")]
        $Name,
        [ValidateRange(21, 65)]
        $Age,
        [string]
        $Path
    )
    Write-Host ($Name + $Age + $Path)
}

More information can be found with Get-Help about_Functions_Advanced

The above also works with partial directory names, for example if you know the directory has "test" in the name type foo -path test and press CTRL+Space, you'll get a filtered list - pretty cool, right?

Give it a try


来源: stackexchange

问:
Microsoft Graph api code in C# displays only limited number of users
I  am running below Microsoft Graph Api code:

```<code>using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AADConsole2
{
    class Program
    {

        private const string aadInstance = "https://login.microsoftonline.com/{0}";
        //  private const string ResourceUrl = "https://graph.windows.net";

        private const string resource = "https://graph.microsoft.com";
        private const string GraphServiceObjectId = "XXX";
        private const string TenantId = "XXX";
        private const string tenant = "XXXX.onmicrosoft.com";
        private const string ClientId = "XXX";
        private static string appKey= "XXXX";
        static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {

            context = new AuthenticationContext(authority);
            credential = new ClientCredential(ClientId, appKey);
            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);
            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result) {
            //throw new NotImplementedException();
            string users = null;
            var uri = "https://graph.microsoft.com/v1.0/users";
            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);

            if(getResult.Content != null)
            {
                users = await getResult.Content.ReadAsStringAsync();

            }
            return users;

        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;

        }
    }
}
</code>```

I am getting the results of user detail printed on console ,but only limited number of users are printed. i.e only whose name starts with letter 'a'.
And also some user details are missing. How to get all user details .Am i missing some api in this code?
Thanks.

答:
Most Microsoft Graph endpoints return paged result sets. Your initial request only returns the first page of data. To retrieve the next page, you follow the URI provided in the @odata.nextLink property. Each subsequent page will return the next page's @odata.nextLink until you the last page of data (denoted by the lack of a @odata.nextLink in the result). There is a step-by-step walkthrough of how this works at Paging Microsoft Graph data in your app.

The single most important tip I can give you here is to not use $top to force it to return large pages of data. This is an extremely inefficient method for calling the API and inevitably leads to network errors and request throttling. It also doesn't eliminate the need to handle paging since even $top=999 (the maximum) can still return multiple pages.

Implement paging, keep your page sizes small, and process the results after each page is returned before moving on to the next page. This will ensure you capture all of the data and allow your application to pick up where it left off should it encounter any errors during processing.

ContentLicense: CC BY-SA 4.0

Body:
I  am running below Microsoft Graph Api code:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AADConsole2
{
    class Program
    {

        private const string aadInstance = "https://login.microsoftonline.com/{0}";
        //  private const string ResourceUrl = "https://graph.windows.net";

        private const string resource = "https://graph.microsoft.com";
        private const string GraphServiceObjectId = "XXX";
        private const string TenantId = "XXX";
        private const string tenant = "XXXX.onmicrosoft.com";
        private const string ClientId = "XXX";
        private static string appKey= "XXXX";
        static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {

            context = new AuthenticationContext(authority);
            credential = new ClientCredential(ClientId, appKey);
            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);
            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result) {
            //throw new NotImplementedException();
            string users = null;
            var uri = "https://graph.microsoft.com/v1.0/users";
            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);

            if(getResult.Content != null)
            {
                users = await getResult.Content.ReadAsStringAsync();

            }
            return users;

        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;

        }
    }
}

I am getting the results of user detail printed on console ,but only limited number of users are printed. i.e only whose name starts with letter 'a'.
And also some user details are missing. How to get all user details .Am i missing some api in this code?
Thanks.


问:
javascript - if and or (||) statement
```<code>if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}
</code>```

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

答:
One way to keep your if condition as short and sweet as possible. Extract the conditions out to their own functions.

```<code>if (shouldRunSlideShow()) {
   runSlideShow();
}

function shouldRunSlideShow() {
    return currentPathMatchesAny(["/", "/yyy.asp", "/zzzz.html", "/xxx.html"]);
}

function currentPathMatchesAny(paths) {
    return paths.includes(window.location.pathname);
}
</code>```

Quite verbose code but I think it reads well.

Title: javascript - if and or (||) statement

Body:
if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

Body:
One way to keep your if condition as short and sweet as possible. Extract the conditions out to their own functions.

if (shouldRunSlideShow()) {
   runSlideShow();
}

function shouldRunSlideShow() {
    return currentPathMatchesAny(["/", "/yyy.asp", "/zzzz.html", "/xxx.html"]);
}

function currentPathMatchesAny(paths) {
    return paths.includes(window.location.pathname);
}

Quite verbose code but I think it reads well.


问:
Receiving an error in BS4 while amazon web scraping : AttributeError: 'NoneType' object has no attribute 'get_text'
```<code>!pip install requests
!pip install bs4

import requests
from bs4 import BeautifulSoup

url = "https://www.amazon.in/Apple-iPhone-Pro-Max-256GB/dp/B07XVLH744/ref=sr_1_1_sspa?crid=2VCKZNOH3H6SR&keywords=apple+iphone+11+pro+max&qid=1582043410&sprefix=apple+iphone%2Caps%2C388&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyVjdZSE83TzU4UUMmZW5jcnlwdGVkSWQ9QTAyNTI1ODZJUzZOVUwxWDNIUlAmZW5jcnlwdGVkQWRJZD1BMDkxNDg4MzFLMFpVT1M5OFM5Q0smd2lkZ2V0TmFtZT1zcF9hdGYmYWN0aW9uPWNsaWNrUmVkaXJlY3QmZG9Ob3RMb2dDbGljaz10cnVl"

headers = {"User-Agent": "in this section im adding my user agent after typing my user agent in google search"}

page = requests.get(url, headers=headers)

soup = BeautifulSoup(page.content, "html.parser")

print(soup.prettify())

title = soup.find(id = "productTitle").get_text()
price = soup.find(id = "priceblock_ourprice").get_text()

converted_price = price[0:8]

print(converted_price)
print(titles)
</code>```

i am working on google colab when i run this code  i get this error

```<code>AttributeError   Traceback (most recent call last)
<ipython-input-15-14696d9dc778> in <module>()
     16 print(soup.prettify())
     17
---> 18 title = soup.find(id = "productTitle").get_text()
     19 price = soup.find(id = "priceblock_ourprice").get_text()
     20

AttributeError: 'NoneType' object has no attribute 'get_text'
</code>```

i have tried searching all over internet but have not found answer addressing my question. i am trying to get iPhone 11 pro max price. when i run this code i get the error mentioned above.

答:
soup.find(id = "productTitle") This is returning None Because its not able to find id = "producTitle". Make sure you are searching for correct element.

For find statements i would suggest always write if condition to avoid and handle this kind of errors.

title = soup.find(id = "productTitle")
if title:
    title = title.get_text()
else:
    title = "default_title"

price = soup.find(id = "priceblock_ourprice").get_text()
```

you can do same with price.

Body:
!pip install requests
!pip install bs4

import requests
from bs4 import BeautifulSoup

url = "https://www.amazon.in/Apple-iPhone-Pro-Max-256GB/dp/B07XVLH744/ref=sr_1_1_sspa?crid=2VCKZNOH3H6SR&keywords=apple+iphone+11+pro+max&qid=1582043410&sprefix=apple+iphone%2Caps%2C388&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyVjdZSE83TzU4UUMmZW5jcnlwdGVkSWQ9QTAyNTI1ODZJUzZOVUwxWDNIUlAmZW5jcnlwdGVkQWRJZD1BMDkxNDg4MzFLMFpVT1M5OFM5Q0smd2lkZ2V0TmFtZT1zcF9hdGYmYWN0aW9uPWNsaWNrUmVkaXJlY3QmZG9Ob3RMb2dDbGljaz10cnVl"

headers = {"User-Agent": "in this section im adding my user agent after typing my user agent in google search"}

page = requests.get(url, headers=headers)

soup = BeautifulSoup(page.content, "html.parser")

print(soup.prettify())

title = soup.find(id = "productTitle").get_text()
price = soup.find(id = "priceblock_ourprice").get_text()

converted_price = price[0:8]

print(converted_price)
print(titles)

i am working on google colab when i run this code  i get this error

AttributeError   Traceback (most recent call last)
<ipython-input-15-14696d9dc778> in <module>()
     16 print(soup.prettify())
     17
---> 18 title = soup.find(id = "productTitle").get_text()
     19 price = soup.find(id = "priceblock_ourprice").get_text()
     20

AttributeError: 'NoneType' object has no attribute 'get_text'

i have tried searching all over internet but have not found answer addressing my question. i am trying to get iPhone 11 pro max price. when i run this code i get the error mentioned above.

Body:
soup.find(id = "productTitle") This is returning None Because its not able to find id = "producTitle". Make sure you are searching for correct element.

For find statements i would suggest always write if condition to avoid and handle this kind of errors.

title = soup.find(id = "productTitle")
if title:
    title = title.get_text()
else:
    title = "default_title"

price = soup.find(id = "priceblock_ourprice").get_text()

you can do same with price.


问:
Why is my sort algorithm changing the array values?
This is a simple bubble sort algorithm, part of my larger program, intended to sort an array of doubles. I previously tried sorting the same values with merge sort but I got the same output. I really fail to notice what I am missing.Can someone please point it out to me
Thanks in advance!</p>

```<code>#include<iostream>
#include<iomanip>

using namespace std;

int const POINTS = 5;
double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2, 0.8 };

void sort(double dataPoints[])
{
    int i, j, flag = 1;
    int temp;
    for (i = 1; (i <= POINTS) && flag; i++)
    {
        flag = 0;
        for (j = 0; j < (POINTS - 1); j++)
        {
            if (dataPoints[j + 1] > dataPoints[j])
            {
                temp = dataPoints[j];
                dataPoints[j] = dataPoints[j + 1];
                dataPoints[j + 1] = temp;
                flag = 1;
            }
        }
    }

}

int main()
{

    sort(dataPoints);

    for (int i = 0; i < POINTS; i++)
    {
        cout << dataPoints[i] << " ";
    }

}
</code>```

```<code>Output:

0.8 0 0 0 0
</code>```

答: change the data type of temp variable to double.</p>

Body:
This is a simple bubble sort algorithm, part of my larger program, intended to sort an array of doubles. I previously tried sorting the same values with merge sort but I got the same output. I really fail to notice what I am missing.Can someone please point it out to me
Thanks in advance!

#include<iostream>
#include<iomanip>

using namespace std;

int const POINTS = 5;
double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2, 0.8 };

void sort(double dataPoints[])
{
    int i, j, flag = 1;
    int temp;
    for (i = 1; (i <= POINTS) && flag; i++)
    {
        flag = 0;
        for (j = 0; j < (POINTS - 1); j++)
        {
            if (dataPoints[j + 1] > dataPoints[j])
            {
                temp = dataPoints[j];
                dataPoints[j] = dataPoints[j + 1];
                dataPoints[j + 1] = temp;
                flag = 1;
            }
        }
    }

}

int main()
{

    sort(dataPoints);

    for (int i = 0; i < POINTS; i++)
    {
        cout << dataPoints[i] << " ";
    }

}

Output:

0.8 0 0 0 0


问:
VSCode Extension: How to debug "Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {."
I have created a vscode extension using typescript. Normally, I'd reduce the problem to the smallest possible piece of code, but whenever I try to do that, the problem disappears.

Whenever I try to run the extension (by pressing Ctrl+Shift+P and selecting my extension's command), I get the error: (name changed)

```<code>Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {.
</code>```

Or, in previous versions of the code when I first encountered the error, ...Unexpected token ,.

The error gives no indication of which line or even which file contains the unexpected token. I have tried to run the debugger on the code that loads the extension (vscode devtools), but I couldn't find any obvious "current file" or some such in the call stack.

How do I even begin to debug this?

package.json: (name changed)

```<code>{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "Extension Descripton",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.41.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension-name.start"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension-name.start",
                "title": "Open a Extension Name window"
            }
        ]
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile",
        "test": "node ./out/test/runTest.js"
    },
    "devDependencies": {
        "@types/glob": "^7.1.1",
        "@types/mocha": "^5.2.7",
        "@types/node": "^12.11.7",
        "@types/vscode": "^1.41.0",
        "awesome-typescript-loader": "^5.2.1",
        "glob": "^7.1.5",
        "html-loader": "^0.5.5",
        "mocha": "^6.2.2",
        "tslint": "^5.20.0",
        "typescript": "^3.6.4",
        "vscode-test": "^1.2.2",
        "webpack": "^4.41.2",
        "webpack-cli": "^3.3.9"
    },
    "dependencies": {
        "cerialize": "^0.1.18",
        "ts_common": "file:../ts_common"
    },
    "private": true
}
</code>```

tsconfig.json:

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "out",
        "lib": [
            "es2018",
            "dom"
        ],
        "sourceMap": true,
        //"rootDir": "src",
        "typeRoots": ["node_modules/@types"],
        "strict": true,   /* enable all strict type-checking options */
        /* Additional Checks */
        "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "awesomeTypescriptLoaderOptions": {
      "useCache": true,
      "isolatedModules": true,
      //"transpileOnly": true, // This is about a 2x speedup to compilation but disable type errors/warnings
      "reportFiles": [
        "src/**/*.{ts,tsx}"
      ]
    },
    "include": [
      "./src/"
    ]/*,
    "exclude": [
        "node_modules",
        "../ts_common",
        "./dist",
        ".vscode-test"
    ]*/
}
</code>```

答:
Same with you. I tried surrounding the problematic statement with try, but nothing was caught.

After some examination I found it's caused by optional chaining syntax in my source code, then I realized my project is initialized before ts 3.7 arrived so it's not supported. Checking the compiler output in Terminal window confirmed this. (I didn't notice it because current vscode comes with ts 3.7 so no error is highlighted in source code.) The error is not in program execution. It's syntax error during compilation. Check it.

Body:
I have created a vscode extension using typescript. Normally, I'd reduce the problem to the smallest possible piece of code, but whenever I try to do that, the problem disappears.

Whenever I try to run the extension (by pressing Ctrl+Shift+P and selecting my extension's command), I get the error: (name changed)

Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {.

Or, in previous versions of the code when I first encountered the error, ...Unexpected token ,.

The error gives no indication of which line or even which file contains the unexpected token. I have tried to run the debugger on the code that loads the extension (vscode devtools), but I couldn't find any obvious "current file" or some such in the call stack.

How do I even begin to debug this?

package.json: (name changed)

{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "Extension Descripton",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.41.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension-name.start"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension-name.start",
                "title": "Open a Extension Name window"
            }
        ]
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile",
        "test": "node ./out/test/runTest.js"
    },
    "devDependencies": {
        "@types/glob": "^7.1.1",
        "@types/mocha": "^5.2.7",
        "@types/node": "^12.11.7",
        "@types/vscode": "^1.41.0",
        "awesome-typescript-loader": "^5.2.1",
        "glob": "^7.1.5",
        "html-loader": "^0.5.5",
        "mocha": "^6.2.2",
        "tslint": "^5.20.0",
        "typescript": "^3.6.4",
        "vscode-test": "^1.2.2",
        "webpack": "^4.41.2",
        "webpack-cli": "^3.3.9"
    },
    "dependencies": {
        "cerialize": "^0.1.18",
        "ts_common": "file:../ts_common"
    },
    "private": true
}

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "out",
        "lib": [
            "es2018",
            "dom"
        ],
        "sourceMap": true,
        //"rootDir": "src",
        "typeRoots": ["node_modules/@types"],
        "strict": true,   /* enable all strict type-checking options */
        /* Additional Checks */
        "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "awesomeTypescriptLoaderOptions": {
      "useCache": true,
      "isolatedModules": true,
      //"transpileOnly": true, // This is about a 2x speedup to compilation but disable type errors/warnings
      "reportFiles": [
        "src/**/*.{ts,tsx}"
      ]
    },
    "include": [
      "./src/"
    ]/*,
    "exclude": [
        "node_modules",
        "../ts_common",
        "./dist",
        ".vscode-test"
    ]*/
}


问:
Update / EXISTS or MERGE for better performance? Slow updating on big table (millions of records)
I need some help with some performance issues:

I have a table CONTRATOS with 27 millions of records. This table has multiple columns but the important ones are: CONTRATO, CODIGO_ORIGEN.

It can exist more than one CONTRATO for each CODIGO_ORIGEN so i need to do this:

```<code>SELECT DISTINCT
    CODIGO_ORIGEN,
    FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
FROM TABLE CONTRATOS;
</code>```

After this we have 6 millions of records, the good ones...

What i need to do is update the "NOT FOUND" records (CONTRATO) in the table CONTRATOS with the value 'E' on the column ESTADO.

At first, i tried to do it everything in one step (query):

```<code>UPDATE / NOT EXISTS METHOD
--------------------------

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM
        (
            SELECT DISTINCT
                CODIGO_ORIGEN,
                FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
            FROM TABLE CONTRATOS
        ) C2
        WHERE C.CONTRATO = C2.MAX_CONTRATO
    );

MERGE METHOD
---------------

    MERGE INTO CONTRATOS C
    USING
    (
        SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
        FROM TABLE CONTRATOS
    ) C2 ON (C.CONTRATO = C2.MAX_CONTRATO)
    WHEN MATCHED THEN UPDATE SET ESTADO = 'E';
</code>```

But after seeing that it was too slow (both methods) i tried to do it using a temporal table where i can insert the valid rows: TEMP_CONTRATOS

```<code>    Note: This point goes pretty fast (15 min)

    INSERT INTO TEMP_CONTRATOS (MAX_CONTRATO, CODIGO_ORIGEN)
    SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
    FROM TABLE CONTRATOS;

    Note: Here is the problem again

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM TEMP_CONTRATOS TMP
        WHERE C.CONTRATO = TMP.MAX_CONTRATO
    );
</code>```

I have an index on both tables with the columns (CONTRATO/MAX_CONTRATO and CODIGO_ORIGEN) so i can improve the performance (right?) but im still getting too slow results...

The execution plan gives me over 700.000 of cost for 27 millions of records... Is it too much or is it ok considering the amount of records? It´s doing a TABLE FULL SCAN of both tables.

Is it a good idea using hints? is it a good idea going through indexes?... What is the best option? using Merge or Exists/Not exists / Not in??

Also, i´m not sure about creating an index for the ESTADO column because im updating that field and i read it´s not a good idea to create a index in a column where you perform updates... but i have to do a lot of queries joining with it.

Im using the V$SESSION_LONGOPS view and the session view of the sysdba user  to monitorize the process... Any better alternative?

I don´t know if i forget something important, i guess i do.

Bring me some light please. Any advice is appreciated.

Thank you in advance

Regards.

答:
Please see if this helps ..

```<code>    merge into contratos c
            using
            (   select /*+ parallel */ rowid rw,
                    codigo_origen,
                    first_value(contrato) over (partition by codigo_origen order by fecha desc) max_contrato
                from contratos
            ) c2 on (c.contrato <> c2.max_contrato -- "NOT FOUND" records
                    and c.rowid = c2.rw
            ) when matched then update set estado = 'E'
            ;
</code>```

Also, you may want to gather stats to let the optimizer choose the best plan

Body:
I need some help with some performance issues:

I have a table CONTRATOS with 27 millions of records. This table has multiple columns but the important ones are: CONTRATO, CODIGO_ORIGEN.

It can exist more than one CONTRATO for each CODIGO_ORIGEN so i need to do this:

SELECT DISTINCT
    CODIGO_ORIGEN,
    FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
FROM TABLE CONTRATOS;

After this we have 6 millions of records, the good ones...

What i need to do is update the "NOT FOUND" records (CONTRATO) in the table CONTRATOS with the value 'E' on the column ESTADO.

At first, i tried to do it everything in one step (query):

UPDATE / NOT EXISTS METHOD
--------------------------

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM
        (
            SELECT DISTINCT
                CODIGO_ORIGEN,
                FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
            FROM TABLE CONTRATOS
        ) C2
        WHERE C.CONTRATO = C2.MAX_CONTRATO
    );

MERGE METHOD
---------------

    MERGE INTO CONTRATOS C
    USING
    (
        SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
        FROM TABLE CONTRATOS
    ) C2 ON (C.CONTRATO = C2.MAX_CONTRATO)
    WHEN MATCHED THEN UPDATE SET ESTADO = 'E';

But after seeing that it was too slow (both methods) i tried to do it using a temporal table where i can insert the valid rows: TEMP_CONTRATOS

    Note: This point goes pretty fast (15 min)

    INSERT INTO TEMP_CONTRATOS (MAX_CONTRATO, CODIGO_ORIGEN)
    SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
    FROM TABLE CONTRATOS;

    Note: Here is the problem again

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM TEMP_CONTRATOS TMP
        WHERE C.CONTRATO = TMP.MAX_CONTRATO
    );

I have an index on both tables with the columns (CONTRATO/MAX_CONTRATO and CODIGO_ORIGEN) so i can improve the performance (right?) but im still getting too slow results...

The execution plan gives me over 700.000 of cost for 27 millions of records... Is it too much or is it ok considering the amount of records? It´s doing a TABLE FULL SCAN of both tables.

Is it a good idea using hints? is it a good idea going through indexes?... What is the best option? using Merge or Exists/Not exists / Not in??

Also, i´m not sure about creating an index for the ESTADO column because im updating that field and i read it´s not a good idea to create a index in a column where you perform updates... but i have to do a lot of queries joining with it.

Im using the V$SESSION_LONGOPS view and the session view of the sysdba user  to monitorize the process... Any better alternative?

I don´t know if i forget something important, i guess i do.

Bring me some light please. Any advice is appreciated.

Thank you in advance

Regards.

Body:
Please see if this helps ..

    merge into contratos c
            using
            (   select /*+ parallel */ rowid rw,
                    codigo_origen,
                    first_value(contrato) over (partition by codigo_origen order by fecha desc) max_contrato
                from contratos
            ) c2 on (c.contrato <> c2.max_contrato -- "NOT FOUND" records
                    and c.rowid = c2.rw
            ) when matched then update set estado = 'E'
            ;

Also, you may want to gather stats to let the optimizer choose the best plan


问:
How to display text depending on the number in UILabel
I work on the app with some calculate function. I have a UITextField where user enter a number and UILabel where is result. How can I display some text in second UILabel depending on the number in the first UILabel?

Example:

```<code>If number in *firstLabel less than 20, then display in *secondLabel: small

If number in *firstLabel from 20 to 30, then display in *secondLabel: normal

If number in *firstLabel greater than 40, then display in *secondLabel: big
</code>```

I hope you understood what i mean. Thank you! Sorry for my english.

答:
you need to get the int value from your firstLabel, Which is stored as text, you could get it by using NSString intValue function.

Use the below

```<code>int intValueFromFirstLabel = [firstLabel.text intValue];

if(intValueFromFirstLabel < 20)
{
  secondLabel.text = @"small";
}
else if(intValueFromFirstLabel >= 20 && intValueFromFirstLabel <= 30)
{
  secondLabel.text = @"normal";
}
else if(intValueFromFirstLabel > 40)
{
  secondLabel.text = @"big";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I work on the app with some calculate function. I have a UITextField where user enter a number and UILabel where is result. How can I display some text in second UILabel depending on the number in the first UILabel?

Example:

If number in *firstLabel less than 20, then display in *secondLabel: small

If number in *firstLabel from 20 to 30, then display in *secondLabel: normal

If number in *firstLabel greater than 40, then display in *secondLabel: big

I hope you understood what i mean. Thank you! Sorry for my english.

Body:
you need to get the int value from your firstLabel, Which is stored as text, you could get it by using NSString intValue function.

Use the below

int intValueFromFirstLabel = [firstLabel.text intValue];

if(intValueFromFirstLabel < 20)
{
  secondLabel.text = @"small";
}
else if(intValueFromFirstLabel >= 20 && intValueFromFirstLabel <= 30)
{
  secondLabel.text = @"normal";
}
else if(intValueFromFirstLabel > 40)
{
  secondLabel.text = @"big";
}


问:
No podspec found for `FBLazyVector` after RN upgrade

EDIT: the solution for me was to use my previous PodFile before upgrading, ios app is working now.

I upgraded an RN app to 0.59.1 (it was at 0.57.8) using react-native upgrade,
android version is working but for the ios version i'm stuck with pod install which trows this error:

[!] No podspec found for `FBLazyVector` in `../node_modules/react-native/Libraries/FBLazyVector
almost all react-native dependencies are giving similar errors, i know that by commenting pods one by one and running pod install

here is my Podfile:

# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
 require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
target 'MdcIos' do
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  pod 'GoogleAnalytics'
  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for MdcIos

  pod 'RNLanguages', :path => '../node_modules/react-native-languages'
  pod 'RNIap', :path => '../node_modules/react-native-iap'

  pod 'Firebase/Core'
  pod 'Firebase/AdMob'
  pod 'Fabric', '~> 1.9.0'
  pod 'Crashlytics', '~> 3.12.0'

  pod 'RNBackgroundFetch', :path => '../node_modules/react-native-background-fetch'

  pod 'react-native-orientation', :path => '../node_modules/react-native-orientation'

  pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob'

  pod 'RNReanimated', :path => '../node_modules/react-native-reanimated'

  pod 'RNScreens', :path => '../node_modules/react-native-screens'

  pod 'RNZipArchive', :path => '../node_modules/react-native-zip-archive'

  pod 'RNGestureHandler', :path => '../node_modules/react-native-gesture-handler'

  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'

  pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'

  pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage'

end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'react-native-google-maps'
      target.build_configurations.each do |config|
        config.build_settings['CLANG_ENABLE_MODULES'] = 'No'
      end
    end
    if target.name == "React"
      target.remove_from_project
    end
    if target.name == 'yoga'
      target.remove_from_project
      target.build_configurations.each do |config|
          config.build_settings['GCC_TREAT_WARNINGS_AS_ERRORS'] = 'NO'
          config.build_settings['GCC_WARN_64_TO_32_BIT_CONVERSION'] = 'NO'
      end
    end
  end
end

```
<p>and package.json:</p>
<pre class="lang-js prettyprint-override"><code>{
  "name": "MdcIos",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios/'",
    "build:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res --verbose"
  },
  "dependencies": {
    "@react-native-community/async-storage": "1.6.1",
    "@react-native-community/netinfo": "4.4.0",
    "abortcontroller-polyfill": "^1.4.0",
    "buffer": "5.2.1",
    "i18next": "14.0.1",
    "jetifier": "^1.6.4",
    "moment": "2.24.0",
    "react": "16.8.3",
    "react-i18next": "9.0.8",
    "react-native": "0.59.1",
    "react-native-android-open-settings": "1.3.0",
    "react-native-app-store-review": "0.0.3",
    "react-native-appstore-version-checker": "2.7.2",
    "react-native-background-fetch": "2.6.0",
    "react-native-bottomsheet": "1.9.5",
    "react-native-communications": "2.2.1",
    "react-native-countdown-component": "2.4.0",
    "react-native-device-info": "0.24.3",
    "react-native-elements": "1.2.6",
    "react-native-firebase": "5.2.1",
    "react-native-gesture-handler": "1.2.1",
    "react-native-iap": "2.4.0-beta13",
    "react-native-image-picker": "0.27.2",
    "react-native-image-zoom-viewer": "2.2.26",
    "react-native-keyboard-aware-scroll-view": "0.8.0",
    "react-native-languages": "3.0.2",
    "react-native-loading-spinner-overlay": "1.0.1",
    "react-native-maps": "github:jerolimov/react-native-maps#fix-rn59rc-compile-issues",
    "react-native-material-menu": "0.4.2",
    "react-native-orientation": "3.1.3",
    "react-native-permissions": "1.2.0",
    "react-native-photo-upload": "1.3.0",
    "react-native-picker-select": "6.1.0",
    "react-native-progress": "3.6.0",
    "react-native-reanimated": "1.2.0",
    "react-native-screens": "2.0.0-alpha.1",
    "react-native-simple-radio-button": "2.7.3",
    "react-native-vector-icons": "6.6.0",
    "react-native-zip-archive": "5.0.0",
    "react-navigation": "4.0.0",
    "react-navigation-stack": "1.9.4",
    "react-redux": "6.0.0",
    "react-timer-mixin": "0.13.4",
    "redux": "4.0.4",
    "redux-persist": "6.0.0",
    "rn-fetch-blob": "0.10.15"
  },
  "devDependencies": {
    "@react-native-community/cli-platform-ios": "3.0.0",
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.49.1",
    "react-test-renderer": "16.6.1"
  },
  "jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    }
  }
}

</code>```

THANKS!

答:
This is what worked for me: using my podFile before upgrading.

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
platform :ios, '9.0'
target 'MdcIos' do
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga/Yoga.podspec'
  pod 'React', path: '../node_modules/react-native', :subspecs => [
    'Core', 'ART', 'DevSupport',
    'RCTAnimation', 'RCTImage', 'RCTLinkingIOS', 'RCTNetwork',
    'RCTPushNotification', 'RCTText', 'RCTWebSocket', 'RCTGeolocation',
  ]

  pod 'RNPermissions', :path => '../node_modules/react-native-permissions'
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications.podspec"

  pod 'GoogleAnalytics'
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for MdcIos

  pod 'RNLanguages', :path => '../node_modules/react-native-languages'
  pod 'RNIap', :path => '../node_modules/react-native-iap'

  pod 'Google-Mobile-Ads-SDK', '~> 7.41'
  pod 'Firebase/Core', '~> 6.13.0'
  pod 'Firebase/Messaging', '~> 6.13.0'
  pod 'Firebase/RemoteConfig', '~> 6.13.0'
  pod 'Firebase/AdMob', '~> 6.13.0'
  # Crashlytics
  pod 'Fabric', '~> 1.10.2'
  pod 'Crashlytics', '~> 3.14.0'

  pod 'RNBackgroundFetch', :path => '../node_modules/react-native-background-fetch'

  pod 'react-native-orientation', :path => '../node_modules/react-native-orientation'

  pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob'

  pod 'RNReanimated', :path => '../node_modules/react-native-reanimated'

  pod 'RNGestureHandler', :path => '../node_modules/react-native-gesture-handler'

  pod 'RNScreens', :path => '../node_modules/react-native-screens'

  pod 'RNZipArchive', :path => '../node_modules/react-native-zip-archive'

  pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage'

  pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'

  pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen'

  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'

  pod 'RNCPushNotificationIOS', :path => '../node_modules/@react-native-community/push-notification-ios'

  pod 'react-native-settings', :path => '../node_modules/react-native-settings'

  pod 'react-native-maps', :path => '../node_modules/react-native-maps'

end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'react-native-google-maps'
      target.build_configurations.each do |config|
        config.build_settings['CLANG_ENABLE_MODULES'] = 'No'
      end
    end
    if target.name == "React"
      target.remove_from_project
    end
    if target.name == 'yoga'
      target.remove_from_project
      target.build_configurations.each do |config|
          config.build_settings['GCC_TREAT_WARNINGS_AS_ERRORS'] = 'NO'
          config.build_settings['GCC_WARN_64_TO_32_BIT_CONVERSION'] = 'NO'
      end
    end
  end
end
```

Body:
EDIT: the solution for me was to use my previous PodFile before upgrading, ios app is working now.

I upgraded an RN app to 0.59.1 (it was at 0.57.8) using react-native upgrade,
android version is working but for the ios version i'm stuck with pod install which trows this error:

[!] No podspec found for `FBLazyVector` in `../node_modules/react-native/Libraries/FBLazyVector
almost all react-native dependencies are giving similar errors, i know that by commenting pods one by one and running pod install

here is my Podfile:

# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
 require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
target 'MdcIos' do
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  pod 'GoogleAnalytics'
  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for MdcIos

  pod 'RNLanguages', :path => '../node_modules/react-native-languages'
  pod 'RNIap', :path => '../node_modules/react-native-iap'

  pod 'Firebase/Core'
  pod 'Firebase/AdMob'
  pod 'Fabric', '~> 1.9.0'
  pod 'Crashlytics', '~> 3.12.0'

  pod 'RNBackgroundFetch', :path => '../node_modules/react-native-background-fetch'

  pod 'react-native-orientation', :path => '../node_modules/react-native-orientation'

  pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob'

  pod 'RNReanimated', :path => '../node_modules/react-native-reanimated'

  pod 'RNScreens', :path => '../node_modules/react-native-screens'

  pod 'RNZipArchive', :path => '../node_modules/react-native-zip-archive'

  pod 'RNGestureHandler', :path => '../node_modules/react-native-gesture-handler'

  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'

  pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'

  pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage'

end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'react-native-google-maps'
      target.build_configurations.each do |config|
        config.build_settings['CLANG_ENABLE_MODULES'] = 'No'
      end
    end
    if target.name == "React"
      target.remove_from_project
    end
    if target.name == 'yoga'
      target.remove_from_project
      target.build_configurations.each do |config|
          config.build_settings['GCC_TREAT_WARNINGS_AS_ERRORS'] = 'NO'
          config.build_settings['GCC_WARN_64_TO_32_BIT_CONVERSION'] = 'NO'
      end
    end
  end
end

and package.json:

{
  "name": "MdcIos",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios/'",
    "build:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res --verbose"
  },
  "dependencies": {
    "@react-native-community/async-storage": "1.6.1",
    "@react-native-community/netinfo": "4.4.0",
    "abortcontroller-polyfill": "^1.4.0",
    "buffer": "5.2.1",
    "i18next": "14.0.1",
    "jetifier": "^1.6.4",
    "moment": "2.24.0",
    "react": "16.8.3",
    "react-i18next": "9.0.8",
    "react-native": "0.59.1",
    "react-native-android-open-settings": "1.3.0",
    "react-native-app-store-review": "0.0.3",
    "react-native-appstore-version-checker": "2.7.2",
    "react-native-background-fetch": "2.6.0",
    "react-native-bottomsheet": "1.9.5",
    "react-native-communications": "2.2.1",
    "react-native-countdown-component": "2.4.0",
    "react-native-device-info": "0.24.3",
    "react-native-elements": "1.2.6",
    "react-native-firebase": "5.2.1",
    "react-native-gesture-handler": "1.2.1",
    "react-native-iap": "2.4.0-beta13",
    "react-native-image-picker": "0.27.2",
    "react-native-image-zoom-viewer": "2.2.26",
    "react-native-keyboard-aware-scroll-view": "0.8.0",
    "react-native-languages": "3.0.2",
    "react-native-loading-spinner-overlay": "1.0.1",
    "react-native-maps": "github:jerolimov/react-native-maps#fix-rn59rc-compile-issues",
    "react-native-material-menu": "0.4.2",
    "react-native-orientation": "3.1.3",
    "react-native-permissions": "1.2.0",
    "react-native-photo-upload": "1.3.0",
    "react-native-picker-select": "6.1.0",
    "react-native-progress": "3.6.0",
    "react-native-reanimated": "1.2.0",
    "react-native-screens": "2.0.0-alpha.1",
    "react-native-simple-radio-button": "2.7.3",
    "react-native-vector-icons": "6.6.0",
    "react-native-zip-archive": "5.0.0",
    "react-navigation": "4.0.0",
    "react-navigation-stack": "1.9.4",
    "react-redux": "6.0.0",
    "react-timer-mixin": "0.13.4",
    "redux": "4.0.4",
    "redux-persist": "6.0.0",
    "rn-fetch-blob": "0.10.15"
  },
  "devDependencies": {
    "@react-native-community/cli-platform-ios": "3.0.0",
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.49.1",
    "react-test-renderer": "16.6.1"
  },
  "jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    }
  }
}

THANKS!


问:
Apps Script Utilities.parseCsv assumes new row on line breaks within double quotes
When using Utilities.parseCsv() linebreaks encased inside double quotes are assumed to be new rows entirely. The output array from this function will have several incorrect rows.

How can I fix this, or work around it?

Edit: Specifically, can I escape line breaks that exist only within double quotes? ie.

```<code>/r/n "I have some stuff to do:/r/n Go home/r/n Take a Nap"/r/n
</code>```

Would be escaped to:

```<code>/r/n "I have some stuff to do://r//n Go home//r//n Take a Nap"/r/n
</code>```

Edit2: Bug report from 2012: https://code.google.com/p/google-apps-script-issues/issues/detail?id=1871

答:
So I had a somewhat large csv file about 10MB 50k rows, which contained a field at the end of each row with comments that users enter with all sorts of characters inside. I found the proposed regex solution was working when I tested a small set of the rows, but when I threw the big file to it, there was an error again and after trying a few things with the regex I even got to crash the whole runtime.

BTW I'm running my code on the V8 runtime.

After scratching my head for about an hour and with not really helpful error messages from AppsSript runtime. I had an idea, what if some weird users where deciding to use back-slashes in some weird ways making some escapes go wrong.
So I tried replacing all back-slashes in my data with something else for a while until I had the array that parseCsv() returns.
It worked!
My hypothesis is that having a \ at the end of lines was breaking the replacement.

So my final solution is:

function testParse() {
    let csv =
        '"title1","title2","title3"\r\n' +
        '1,"person1","A ""comment"" with a \\ and \\\r\n a second line"\r\n' +
        '2,"person2","Another comment"';

    let sanitizedString =
        csv.replace(/\\/g, '::back-slash::')
            .replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r?\n(?:\\[\s\S][^'\\]\r?\n)*')/g,
                match => match.replace(/\r?\n/g, "::newline::"));
    let arr = Utilities.parseCsv(sanitizedString);
    for (let i = 0, rows = arr.length; i < rows; i++) {
        for (let j = 0, cols = arr[i].length; j < cols; j++) {
            arr[i][j] =
                arr[i][j].replace(/::back-slash::/g,'\\')
                    .replace(/::newline::/g,'\r\n');

        }
    }
    Logger.log(arr)
}```
</div>
</div>
</p>

<p>Output:</p>

```[20-02-18 11:29:03:980 CST] [[title1, title2, title3], [1, person1, A "comment" with a \ and \
 a second line], [2, person2, Another comment]]
```

Body:
When using Utilities.parseCsv() linebreaks encased inside double quotes are assumed to be new rows entirely. The output array from this function will have several incorrect rows.

How can I fix this, or work around it?

Edit: Specifically, can I escape line breaks that exist only within double quotes? ie.

/r/n "I have some stuff to do:/r/n Go home/r/n Take a Nap"/r/n

Would be escaped to:

/r/n "I have some stuff to do://r//n Go home//r//n Take a Nap"/r/n

Edit2: Bug report from 2012: https://code.google.com/p/google-apps-script-issues/issues/detail?id=1871

Body:
So I had a somewhat large csv file about 10MB 50k rows, which contained a field at the end of each row with comments that users enter with all sorts of characters inside. I found the proposed regex solution was working when I tested a small set of the rows, but when I threw the big file to it, there was an error again and after trying a few things with the regex I even got to crash the whole runtime.

BTW I'm running my code on the V8 runtime.

After scratching my head for about an hour and with not really helpful error messages from AppsSript runtime. I had an idea, what if some weird users where deciding to use back-slashes in some weird ways making some escapes go wrong.
So I tried replacing all back-slashes in my data with something else for a while until I had the array that parseCsv() returns.
It worked!
My hypothesis is that having a \ at the end of lines was breaking the replacement.

So my final solution is:

function testParse() {
    let csv =
        '"title1","title2","title3"\r\n' +
        '1,"person1","A ""comment"" with a \\ and \\\r\n a second line"\r\n' +
        '2,"person2","Another comment"';

    let sanitizedString =
        csv.replace(/\\/g, '::back-slash::')
            .replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r?\n(?:\\[\s\S][^'\\]\r?\n)*')/g,
                match => match.replace(/\r?\n/g, "::newline::"));
    let arr = Utilities.parseCsv(sanitizedString);
    for (let i = 0, rows = arr.length; i < rows; i++) {
        for (let j = 0, cols = arr[i].length; j < cols; j++) {
            arr[i][j] =
                arr[i][j].replace(/::back-slash::/g,'\\')
                    .replace(/::newline::/g,'\r\n');

        }
    }
    Logger.log(arr)
}

Output:

[20-02-18 11:29:03:980 CST] [[title1, title2, title3], [1, person1, A "comment" with a \ and \
 a second line], [2, person2, Another comment]]


问:
Find all indices of each letter in a string
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

```<code>a = 'string of letters'
b = [a.index(x) for x in a]
</code>```

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

答:
A dict is probably better than a list for this purpose:

```<code>foo = {x : [] for x in a}   #creates dict with keys being unique values in a
for i,x in enumerate(a):
    foo[x].append(i)        #adds each index into dict
</code>```

for example for string 'abababababa':

```<code>{'a': [0, 2, 4, 6, 8], 'b': [1, 3, 5, 7, 9]}
</code>```

Body:
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

a = 'string of letters'
b = [a.index(x) for x in a]

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

Body:
A dict is probably better than a list for this purpose:

foo = {x : [] for x in a}   #creates dict with keys being unique values in a
for i,x in enumerate(a):
    foo[x].append(i)        #adds each index into dict

for example for string 'abababababa':

{'a': [0, 2, 4, 6, 8], 'b': [1, 3, 5, 7, 9]}


问:
typescript variable with generic extending
I have a predefined interface:

```<code>export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}
</code>```

I would like to have a class attribute that constraint the generic type. Something like this:

```<code>public componentType: Type<any extends MyComponentType>;
</code>```

Is it possible ? Because I did not find the solution on Typescript doc and I can't find a syntax that is working.

Thanks.

答:
Does this do what you want</p>

```<code>export declare interface Type<A,T extends A = A> extends Function {
    new (...args: any[]): T;
}

class MyComponentType {

}

class MyComponentType2 extends MyComponentType{

}

class foo {
    public componentType: Type<MyComponentType>;

    constructor() {
        this.componentType = MyComponentType2;
    }
}
</code>```

Body:
I have a predefined interface:

export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}

I would like to have a class attribute that constraint the generic type. Something like this:

public componentType: Type<any extends MyComponentType>;

Is it possible ? Because I did not find the solution on Typescript doc and I can't find a syntax that is working.

Thanks.

Body:
Does this do what you want

export declare interface Type<A,T extends A = A> extends Function {
    new (...args: any[]): T;
}

class MyComponentType {

}

class MyComponentType2 extends MyComponentType{

}

class foo {
    public componentType: Type<MyComponentType>;

    constructor() {
        this.componentType = MyComponentType2;
    }
}


问:
Getting a Random hexadecimal using an array in JavaScript
I have written a little code that generates a random color. It is based in an array that goes from 0 to 9 and A,B,C,D,E,F:

```<code><!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="utf-8">
    <title>Ejercicio 7</title>
    <script type="text/javascript">

        function changeColor() {
            const intensity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "A", "B", "C", "D", "E", "F"];
            let randomColor1 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor2 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor3 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor4 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor5 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor6 = intensity[Math.floor(Math.random() * intensity.length)];
            const randomColor = `#${randomColor1}${randomColor2}${randomColor3}${randomColor4}${randomColor5}${randomColor6}`;
            document.body.style.backgroundColor = randomColor;

        }
    </script>
</head>

<body onload="changeColor()">
    <button onclick="changeColor()">Pincha aquí</button>
</body>

</html>
</code>```

The problem is I don't understand this piece of repeated code:

```<code>intensity[Math.floor(Math.random() * intensity.length)]

</code>```

I know it gives me a random element from the array "intensity", but I don't know  how it works. Can someone explain to me? Thank you in advance.

答:
you may find a lot of examples of random hex color generators online, for example, https://css-tricks.com/snippets/javascript/random-hex-color/:</p>

```<code>function randomHexColor() {
  return Math.floor(Math.random()*16777215).toString(16);
}
</code>```

Body:
I have written a little code that generates a random color. It is based in an array that goes from 0 to 9 and A,B,C,D,E,F:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Ejercicio 7</title>

    <button onclick="changeColor()">Pincha aquí</button>

The problem is I don't understand this piece of repeated code:

intensity[Math.floor(Math.random() * intensity.length)]

I know it gives me a random element from the array "intensity", but I don't know  how it works. Can someone explain to me? Thank you in advance.

Body:
you may find a lot of examples of random hex color generators online, for example, https://css-tricks.com/snippets/javascript/random-hex-color/:

function randomHexColor() {
  return Math.floor(Math.random()*16777215).toString(16);
}


问:
Adding file names from array in dataframe column in spark scala
```<code>val hadoopConf = new Configuration()

val fs = FileSystem.get(hadoopConf)

val status = fs.listStatus(new Path("/home/Test/")).map(_.getPath().toString)

val df =  spark.read.format("json").load(status : _*)
</code>```

How to add the file name in a new column in df?

I tried:

```<code>val dfWithCol = df.withColumn("filename",input_file_name())
</code>```

But it adds the same file name in all the columns?
Can anyone suggest a better approach?

答:
It is expected behaviour because your json file having more than one record in it.

Spark adds the filenames for each record and you want to check all the unique filenames then do distinct on filename column

```<code>//to get unique filenames
df.select("filename").distinct().show()
</code>```

Example:

```<code>#source data
hadoop fs -cat /user/shu/json/*.json
{"id":1,"name":"a"}
{"id":1,"name":"a"}
</code>```

```<code>val hadoopConf = new Configuration()

val fs = FileSystem.get(hadoopConf)

val status = fs.listStatus(new Path("/user/shu/json")).map(_.getPath().toString)

val df =  spark.read.format("json").load(status : _*)

df.withColumn("filename",input_file_name()).show(false)

//unique filenames for each record
+---+----+----------------------------------------------------------------------------+
|id |name|input                                                                       |
+---+----+----------------------------------------------------------------------------+
|1  |a   |hdfs://nn:8020/user/shu/json/i.json                                         |
|1  |a   |hdfs://nn:8020/user/shu/json/i1.json                                        |
+---+----+----------------------------------------------------------------------------+
</code>```

in the above example you can see unique filenames for each record (as i have 1 record in each json file).

Body:
val hadoopConf = new Configuration()

val fs = FileSystem.get(hadoopConf)

val status = fs.listStatus(new Path("/home/Test/")).map(_.getPath().toString)

val df =  spark.read.format("json").load(status : _*)

How to add the file name in a new column in df?

I tried:

val dfWithCol = df.withColumn("filename",input_file_name())

But it adds the same file name in all the columns?
Can anyone suggest a better approach?

Body:
It is expected behaviour because your json file having more than one record in it.

Spark adds the filenames for each record and you want to check all the unique filenames then do distinct on filename column

//to get unique filenames
df.select("filename").distinct().show()

Example:

#source data
hadoop fs -cat /user/shu/json/*.json
{"id":1,"name":"a"}
{"id":1,"name":"a"}

val hadoopConf = new Configuration()

val fs = FileSystem.get(hadoopConf)

val status = fs.listStatus(new Path("/user/shu/json")).map(_.getPath().toString)

val df =  spark.read.format("json").load(status : _*)

df.withColumn("filename",input_file_name()).show(false)

//unique filenames for each record
+---+----+----------------------------------------------------------------------------+
|id |name|input                                                                       |
+---+----+----------------------------------------------------------------------------+
|1  |a   |hdfs://nn:8020/user/shu/json/i.json                                         |
|1  |a   |hdfs://nn:8020/user/shu/json/i1.json                                        |
+---+----+----------------------------------------------------------------------------+

in the above example you can see unique filenames for each record (as i have 1 record in each json file).


问:
Wait for async task to complete in request in Vapor
I am writing an API using the server side swift framework Vapor. My model is very simple. I have a Workout table, which has a to many relationship to the Circuit table, which has a to many relationship with the Exercise table. When the api consumer creates a workout, the json contains all circuits and exercises in the workout. Here is an example:

```<code>{
    ...
    circuits: [{
        ...,
        exercises: [{
            "title": ...
        }, {
            "title": ...
        }]
    }, {
        ...,
        exercises: [{
            "title": ...
        }, {
            "title": ...
        }]
    }]
}
</code>```

The problem I am running into is duplicate exercises being created, when the user has the same exercise in multiple circuits. I query the db before creating a new exercise, but it seems like the saves are all happening asynchronously, which prevents me from detecting an existing exercise with the same id/title in the db before saving a new one. Here is my code:

```<code>private func saveExercise(on conn: DatabaseConnectable, with content: WorkoutCreateExerciseContent, for authUser: User) throws -> Future<Exercise> {

        if let exerciseId: UUID = content.id {

            return Exercise.find(exerciseId, on: conn)
                .unwrap(or: Abort(.badRequest, reason: "No exercise for id: \(exerciseId.uuidString)"))

        } else if let title: String = content.title, let isPublicallyVisible: Bool = content.isPublicallyVisible {

            return Exercise.query(on: conn).filter(\.title == title).filter(\.directions == content.directions).first().flatMap({ (possibleMatchingExercise: Exercise?) -> Future<Exercise> in

                if let matchingExercise: Exercise = possibleMatchingExercise {

                    return conn.future(matchingExercise)

                } else {
                    print("xxx Found no match for \(title)")
                    let newExercise: Exercise = Exercise(
                        title: title,
                        directions: content.directions,
                        isPublicallyVisible: isPublicallyVisible
                    )
                    newExercise.userId = authUser.id
                    return newExercise.save(on: conn)

                }

            })

        } else {

            throw Abort(.badRequest, reason: """
                Bad data for exercise. Expecting either of the following:
                {
                    /"id/": /"some id/"
                }
                or
                {
                    /"title/": /"some title/"
                    /"directions/": /"(optional)/",
                    /"isPublicallyVisible/": false
                }
                id takes priority over other properties.
            """)
        }

    }

    private func saveCircuit(on conn: DatabaseConnectable, with content: CircuitCreateContent, order: Int, workoutId: UUID, authUser: User) throws -> Future<Circuit> {

        return try content.exercises.map({ (exerciseContent: WorkoutCreateExerciseContent) throws -> Future<Exercise> in

            let createdExercise: Future<Exercise> = try self.saveExercise(
                on: conn,
                with: exerciseContent,
                for: authUser
            )

            return createdExercise

        })
        .flatten(on: conn)
        .flatMap({ (exercises: [Exercise]) -> Future<Circuit> in

            let circuit: Circuit = Circuit(
                workoutId: workoutId,
                order: order,
                exerciseDuration: content.exerciseDuration,
                restDuration: content.restDuration,
                exerciseIDs: exercises.compactMap({ $0.id })
            )

            return circuit.save(on: conn)

        })

    }

    func saveWorkout(_ conn: DatabaseConnectable,  _ authentiatedUser: User, _ content: WorkoutCreateContent) throws -> Future<Workout> {

        let workout: Workout = content.makeWorkout()

        workout.userId = authentiatedUser.id

        // First save the exercises

        let createdWorkout: Future<Workout> = workout.save(on: conn).flatMap({ (savedWorkout: Workout) -> Future<Workout> in

            let createdCircuits: Future<[Circuit]> = try content.circuits.enumerated().map({ (order: Int, circuitContent: CircuitCreateContent) throws -> Future<Circuit> in

                let createdCircuit: Future<Circuit> = try self.saveCircuit(
                    on: conn, with: circuitContent,
                    order: order,
                    workoutId: savedWorkout.id!,
                    authUser: authentiatedUser
                )

                return createdCircuit

            })
            .flatten(on: conn)

            return createdCircuits.then({ _ -> Future<Workout> in
                return conn.future(savedWorkout)
            })

        })

        return createdWorkout

    }
</code>```

Does anyone see what I'm missing here? Is there a way to wait for a Future to fulfill before starting a new Future? I am new to Vapor, so I'm not that familiar with Vapor's fluent api.

答:
let's say we have two imaginary methods returning Future<>

```<code>func randomUInt() -> Future<UInt> { ... }
func multiply(value: UInt, by multiplier: UInt) -> Future<UInt> { ... }
</code>```

and we wanna multiply a random number by 5, but if random number is zero or 1 wanna throw error. therefore we need to wait for the random number before calling the multiply(value: ,by: ) method.

```<code>let result: Future<UInt> = randomUInt().flatMap { (value) -> Future<UInt> in
    guard value > 1 else { throw YourError }
    return multiply(value: value, by: 5)
}
</code>```

Body:
I am writing an API using the server side swift framework Vapor. My model is very simple. I have a Workout table, which has a to many relationship to the Circuit table, which has a to many relationship with the Exercise table. When the api consumer creates a workout, the json contains all circuits and exercises in the workout. Here is an example:

{
    ...
    circuits: [{
        ...,
        exercises: [{
            "title": ...
        }, {
            "title": ...
        }]
    }, {
        ...,
        exercises: [{
            "title": ...
        }, {
            "title": ...
        }]
    }]
}

The problem I am running into is duplicate exercises being created, when the user has the same exercise in multiple circuits. I query the db before creating a new exercise, but it seems like the saves are all happening asynchronously, which prevents me from detecting an existing exercise with the same id/title in the db before saving a new one. Here is my code:

private func saveExercise(on conn: DatabaseConnectable, with content: WorkoutCreateExerciseContent, for authUser: User) throws -> Future<Exercise> {

        if let exerciseId: UUID = content.id {

            return Exercise.find(exerciseId, on: conn)
                .unwrap(or: Abort(.badRequest, reason: "No exercise for id: \(exerciseId.uuidString)"))

        } else if let title: String = content.title, let isPublicallyVisible: Bool = content.isPublicallyVisible {

            return Exercise.query(on: conn).filter(\.title == title).filter(\.directions == content.directions).first().flatMap({ (possibleMatchingExercise: Exercise?) -> Future<Exercise> in

                if let matchingExercise: Exercise = possibleMatchingExercise {

                    return conn.future(matchingExercise)

                } else {
                    print("xxx Found no match for \(title)")
                    let newExercise: Exercise = Exercise(
                        title: title,
                        directions: content.directions,
                        isPublicallyVisible: isPublicallyVisible
                    )
                    newExercise.userId = authUser.id
                    return newExercise.save(on: conn)

                }

            })

        } else {

            throw Abort(.badRequest, reason: """
                Bad data for exercise. Expecting either of the following:
                {
                    /"id/": /"some id/"
                }
                or
                {
                    /"title/": /"some title/"
                    /"directions/": /"(optional)/",
                    /"isPublicallyVisible/": false
                }
                id takes priority over other properties.
            """)
        }

    }

    private func saveCircuit(on conn: DatabaseConnectable, with content: CircuitCreateContent, order: Int, workoutId: UUID, authUser: User) throws -> Future<Circuit> {

        return try content.exercises.map({ (exerciseContent: WorkoutCreateExerciseContent) throws -> Future<Exercise> in

            let createdExercise: Future<Exercise> = try self.saveExercise(
                on: conn,
                with: exerciseContent,
                for: authUser
            )

            return createdExercise

        })
        .flatten(on: conn)
        .flatMap({ (exercises: [Exercise]) -> Future<Circuit> in

            let circuit: Circuit = Circuit(
                workoutId: workoutId,
                order: order,
                exerciseDuration: content.exerciseDuration,
                restDuration: content.restDuration,
                exerciseIDs: exercises.compactMap({ $0.id })
            )

            return circuit.save(on: conn)

        })

    }

    func saveWorkout(_ conn: DatabaseConnectable,  _ authentiatedUser: User, _ content: WorkoutCreateContent) throws -> Future<Workout> {

        let workout: Workout = content.makeWorkout()

        workout.userId = authentiatedUser.id

        // First save the exercises

        let createdWorkout: Future<Workout> = workout.save(on: conn).flatMap({ (savedWorkout: Workout) -> Future<Workout> in

            let createdCircuits: Future<[Circuit]> = try content.circuits.enumerated().map({ (order: Int, circuitContent: CircuitCreateContent) throws -> Future<Circuit> in

                let createdCircuit: Future<Circuit> = try self.saveCircuit(
                    on: conn, with: circuitContent,
                    order: order,
                    workoutId: savedWorkout.id!,
                    authUser: authentiatedUser
                )

                return createdCircuit

            })
            .flatten(on: conn)

            return createdCircuits.then({ _ -> Future<Workout> in
                return conn.future(savedWorkout)
            })

        })

        return createdWorkout

    }

Does anyone see what I'm missing here? Is there a way to wait for a Future to fulfill before starting a new Future? I am new to Vapor, so I'm not that familiar with Vapor's fluent api.

Body:
let's say we have two imaginary methods returning Future<>

func randomUInt() -> Future<UInt> { ... }
func multiply(value: UInt, by multiplier: UInt) -> Future<UInt> { ... }

and we wanna multiply a random number by 5, but if random number is zero or 1 wanna throw error. therefore we need to wait for the random number before calling the multiply(value: ,by: ) method.

let result: Future<UInt> = randomUInt().flatMap { (value) -> Future<UInt> in
    guard value > 1 else { throw YourError }
    return multiply(value: value, by: 5)
}


问:
CSS states on ion-button are not being applied
I am trying to either apply a background color when a ion-button has been clicked or to keep the ion-ripple after it filled the button with Ionic 4.

I tried to apply custom css states in global.scss but it didn't really work as the active state looks like it is quickly removed after you click the button (added and then removed half a second after):

```<code>ion-button {
    &:active {
        color: red;
    }
    &:visited {
        background-color: black !important; // --background didn't change anything here
    }
}
</code>```

I tried also with --background-activated which worked but doesn't have the effect I'm looking for. I want to persist the ripple background after the button has been clicked.

Looked everywhere for the ion-ripple configuration but there's not such thing to make it persists.
A solution would be to use the ion-ripple component it-self but I would like to avoid that as it means going through the entire app and replace every ion-button...

So how can I get a generic ion-button to keep a background-color after it has been clicked ?

答:
You may have seen this too. Looking into the ion-ripple component source it looks like is has a removeRipple function that removes the ripple after 200 milliseconds. I can't see anywhere that would allow you to add configuration to change that and keep the ripple effect forever.

But maybe using NgClass could be a possible solution. I was thinking something like this...

home.page.html

```<code><ion-button (click)="clickAction()" [ngClass]="{'clicked':beenClicked}">
  Change Color When Clicked
</ion-button>
</code>```

home.page.ts

```<code>export class HomePage {
  beenClicked: boolean = false;

  clickAction() {
    this.beenClicked = true;
  }

}
</code>```

home.page.scss

```<code>.clicked {
  --background: green;
}
</code>```

You could move the style to the global.scss and make it available everywhere, although you probably still have to have the boolean property in every component unless you have a service or some kind of state management to help keep track of all of your button states for you.

Hope this helps.

Body:
I am trying to either apply a background color when a ion-button has been clicked or to keep the ion-ripple after it filled the button with Ionic 4.

I tried to apply custom css states in global.scss but it didn't really work as the active state looks like it is quickly removed after you click the button (added and then removed half a second after):

ion-button {
    &:active {
        color: red;
    }
    &:visited {
        background-color: black !important; // --background didn't change anything here
    }
}

I tried also with --background-activated which worked but doesn't have the effect I'm looking for. I want to persist the ripple background after the button has been clicked.

Looked everywhere for the ion-ripple configuration but there's not such thing to make it persists.
A solution would be to use the ion-ripple component it-self but I would like to avoid that as it means going through the entire app and replace every ion-button...

So how can I get a generic ion-button to keep a background-color after it has been clicked ?

Body:
You may have seen this too. Looking into the ion-ripple component source it looks like is has a removeRipple function that removes the ripple after 200 milliseconds. I can't see anywhere that would allow you to add configuration to change that and keep the ripple effect forever.

But maybe using NgClass could be a possible solution. I was thinking something like this...

home.page.html

<ion-button (click)="clickAction()" [ngClass]="{'clicked':beenClicked}">
  Change Color When Clicked
</ion-button>

home.page.ts

export class HomePage {
  beenClicked: boolean = false;

  clickAction() {
    this.beenClicked = true;
  }

}

home.page.scss

.clicked {
  --background: green;
}

You could move the style to the global.scss and make it available everywhere, although you probably still have to have the boolean property in every component unless you have a service or some kind of state management to help keep track of all of your button states for you.

Hope this helps.


问:
How do I deploy a React Production Build with GCP?
I'm trying to deploy my React project to Production and it seems that Google App Engine is building the development rather than the Production Build folder. Perhaps I'm missing something very simple...

I first run the "npm run build", then I run "npm run deploy" or "gcloud app deploy app.yaml --project [project_name]"

Folder Structure:

here is my app.yaml file

```<code>runtime: nodejs
env: flex

env_variables:
    APP_ENV: "production"

handlers:
  - url: /
    static_files: build/index.html
    upload: build/index.html
  - url: /
    static_dir: build
  - url: /static
    static_dir: build/static

automatic_scaling:
    min_num_instances: 2
    max_num_instances: 4
    cool_down_period_sec: 180
    cpu_utilization:
       target_utilization: 0.50

resources:
    cpu: 1
    memory_gb: 3.5
    disk_size_gb: 10
</code>```

Here is my package.json:

```<code> "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "deploy": "gcloud app deploy app.yaml --project ....",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
</code>```

When it finish deploying, I still the development warnings and when I run page speed - the js files arent minified/ optimized. What am I missing?

答:
When the gcloud app deploy command is executed, it runs the npm start command to start the application. This is specified in the Docs.

In your case, the npm start command executes "react-scripts start", which starts the development server.

In order to serve your app in a production environent, your start command should start a web server that serves the static files of your react app. In order to do so, you can do as follows:

```<code>npm install -s serve
</code>```

Then, change the start script in your package.json from:

```<code>"start": "react-scripts start"
</code>```

To:

```<code>"start": "serve -s build -l 8080"
</code>```

And then deploy normally

Body:
I'm trying to deploy my React project to Production and it seems that Google App Engine is building the development rather than the Production Build folder. Perhaps I'm missing something very simple...

I first run the "npm run build", then I run "npm run deploy" or "gcloud app deploy app.yaml --project [project_name]"

Folder Structure:

here is my app.yaml file

runtime: nodejs
env: flex

env_variables:
    APP_ENV: "production"

handlers:
  - url: /
    static_files: build/index.html
    upload: build/index.html
  - url: /
    static_dir: build
  - url: /static
    static_dir: build/static

automatic_scaling:
    min_num_instances: 2
    max_num_instances: 4
    cool_down_period_sec: 180
    cpu_utilization:
       target_utilization: 0.50

resources:
    cpu: 1
    memory_gb: 3.5
    disk_size_gb: 10

Here is my package.json:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "deploy": "gcloud app deploy app.yaml --project ....",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

When it finish deploying, I still the development warnings and when I run page speed - the js files arent minified/ optimized. What am I missing?

Body:
When the gcloud app deploy command is executed, it runs the npm start command to start the application. This is specified in the Docs.

In your case, the npm start command executes "react-scripts start", which starts the development server.

In order to serve your app in a production environent, your start command should start a web server that serves the static files of your react app. In order to do so, you can do as follows:

npm install -s serve

Then, change the start script in your package.json from:

"start": "react-scripts start"

To:

"start": "serve -s build -l 8080"

And then deploy normally