问:
Best way to setup cross domain tracking between blog and e-commerce site?
I run a blog that has an e-commerce site attached to it. I want to use a separate root domain for the e-commerce site to debloat the site but also want to continue being able to attribute what content leads to sales.

I hear that I need to implement both sites under the same Property View. Is this advisable or should I create a separate property view?

Also, my biggest concern is how do I identify traffic that is solely going to the e-commerce site without being referred to from the blog site? Is there a way of filtering this out?

Thank you.

答:
For the first question, the answer is "yes", by tracking everything in a Property (with the necessary setup), if a user lands on the blog from google search then he moves to the shop and buys, the sale will be organic.

For the second question, the answer is "you can see it with a segment". By creating a segment that excludes sessions (or users) who have seen the blog domain, you will only get those who landed and remained exclusively in the shop.


来源: stackexchange

问:
How to replace spaces with %20 in  tags
I would like to replace all spaces in the image tags of a html text.

Example:

```<code><img src="photo 1.jpg" />
</code>```

to

```<code><img src="photo%201.jpg"/>
</code>```

I didn't find a soultion with preg_replace, but it may be a simple regexp line.
Thanks!

Edit: Sorry guys, my description was not very clear. So, I have a full html page and I only want to replace inside the img tags. I can't use urlencode here as it encodes the other stuff as well.

答:
Hey,
I've found a simple solution, using preg_replace_callback. I've never heard of this function before, but it's great.

Posting the code here:

```<code>$text = preg_replace_callback("/src=[\'\"](.*?)[\'\"]/", "removeSpaces", $text);
function removeSpaces($matches) {
  return "src='" . str_replace(" ", "%20", $matches[1]) . "'";
}
</code>```

Thanks for all the replies.

ContentLicense: CC BY-SA 3.0

Title: How to replace spaces with %20 in <img> tags

Body:
I would like to replace all spaces in the image tags of a html text.

Example:

to

I didn't find a soultion with preg_replace, but it may be a simple regexp line.
Thanks!

Edit: Sorry guys, my description was not very clear. So, I have a full html page and I only want to replace inside the img tags. I can't use urlencode here as it encodes the other stuff as well.

Body:
Hey,
I've found a simple solution, using preg_replace_callback. I've never heard of this function before, but it's great.

Posting the code here:

$text = preg_replace_callback("/src=[\'\"](.*?)[\'\"]/", "removeSpaces", $text);
function removeSpaces($matches) {
  return "src='" . str_replace(" ", "%20", $matches[1]) . "'";
}

Thanks for all the replies.


问:
Youtube Data Api V3 using React js showing results of previous fetch
I was making a youtube clone in which user can search for a term and the youtube data API will show the desired results in react js but every time I am querying the data of the previous query is being shown.
When I am logging 'Post' ie the JSON data

**Searchquery Component*

```<code>    import React,{useEffect,useState} from 'react'
    import axios from 'axios'
    import Cards from './Cards'

    function SearchResults(props) {
        const query = props.match.params.query;
        const [posts, setPosts] = useState([])
        useEffect(() => {
            axios({
                "method": "GET",
                "url": 'https://www.googleapis.com/youtube/v3/search',
                "params":{
                    'part':'snippet',
                    'maxResults':'20',
                    'key':'[API_KEY]',
                    'q':query
                }
            })
                .then((res) => {
                    setPosts(res.data.items)
                })
                .catch((error) => {
                    console.log(error)
                })
                console.log(posts);
        },[query])

        return (
            <div>
                <Cards/>
            </div>
        )
    }

    export default SearchResults
</code>```

答:
Your console.log(posts) step is happening earlier than setPosts(res.data.items) one.

To capture changes for posts I recommend to use useEffect hook as :

```<code>useEffect(() => {
   console.log(posts);
}, [posts]);
</code>```

Read further about useEffect here.

ContentLicense: CC BY-SA 4.0

Body:
I was making a youtube clone in which user can search for a term and the youtube data API will show the desired results in react js but every time I am querying the data of the previous query is being shown.
When I am logging 'Post' ie the JSON data

**Searchquery Component*

    import React,{useEffect,useState} from 'react'
    import axios from 'axios'
    import Cards from './Cards'

    function SearchResults(props) {
        const query = props.match.params.query;
        const [posts, setPosts] = useState([])
        useEffect(() => {
            axios({
                "method": "GET",
                "url": 'https://www.googleapis.com/youtube/v3/search',
                "params":{
                    'part':'snippet',
                    'maxResults':'20',
                    'key':'[API_KEY]',
                    'q':query
                }
            })
                .then((res) => {
                    setPosts(res.data.items)
                })
                .catch((error) => {
                    console.log(error)
                })
                console.log(posts);
        },[query])

        return (

                <Cards/>

        )
    }

    export default SearchResults

Body:
Your console.log(posts) step is happening earlier than setPosts(res.data.items) one.

To capture changes for posts I recommend to use useEffect hook as :

useEffect(() => {
   console.log(posts);
}, [posts]);

Read further about useEffect here.


问:
Iterating through Array of objects containing arrays

 const endpoint =
        'https://raw.githubusercontent.com/FormidableLabs/radon-typeahead/master/demo/car-models.json';
      const cars = [];
      //fetch the data on the cars, convert the json raw into json and the add it to the array cars
      fetch(endpoint)
        .then((blob) => blob.json())
        .then((data) => cars.push(...data));

      function findMatches(wordToMatch, cars) {
        return cars.filter((Carbrand) => {
          //check if the brand matches what was searched
          //create a regular expression
          const regex = new RegExp(wordToMatch, 'gi');
          return Carbrand.brand.match(regex);
        });
      }

      function displayMatches() {
        const matchArray = findMatches(this.value, cars);
        const htmlCars = matchArray
          .map((carBrand) => {
            return `

${carBrand.brand}

          `;
          })
          .join('');

        const htmlModels = matchArray.map((carBrands) => {
          carBrands.models.map((carModels) => {
            //return carModels + 'this';
            //console.log('li ' + carModels);
            return
            `

${carModels}

            `;
          });
        });
        console.log('htmlModels ' + htmlModels);
        suggestions.innerHTML = htmlCars + htmlModels;
      }

      const searchInput = document.querySelector('.search');
      const suggestions = document.querySelector('.suggestions');

      searchInput.addEventListener('change', displayMatches);
      searchInput.addEventListener('keyup', displayMatches);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8" />

    <title>Car filter</title>
    <meta name="description" content="The HTML5 Herald" />
    <meta name="author" content="SitePoint" />

    <link rel="stylesheet" href="css/styles.css?v=1.0" />
  </head>
  <style></style>
  <body>
    <form class="search-form">
      <input type="text" class="search" placeholder="City or State" />
      <ul class="suggestions">
        <li>Filter for a car</li>
        <li>or a state</li>
      </ul>
    </form>
    </body>
</html></code>```

I'm trying to iterate through and array made of objects that contain keys and Arrays. I'm nesting a map function to display an array that is in the object. I'm trying to get it in a html list

Here is an example of the object.

```<code>{
    "brand": "Acura",
    "models": [
      "2.2CL",
      "2.3CL",
      "3.0CL",
      "3.2CL",
      "ILX",
      "Integra",
      "Legend",
      "MDX",
      "NSX",
      "RDX",
      "3.5 RL",
      "RL",
      "RSX",
      "SLX",
      "2.5TL",
      "3.2TL",
      "TL",
      "TSX",
      "Vigor",
      "ZDX"
    ]
</code>```

The first part getting the car brand works, I'm just struggling to get it to display the models that are in an array.

If I console.log 'carModels'I can see the models as strings but trying to return them is not working. I see ,,,,,, in my console.

findMatches returns an array of matches which works fine.

What I am trying to do is display results for a car brand and then in a nested list all the models of that brand, using a nested map inside my function. Its's working when console logging but I cant seem to return the results.

答:
I managed to get it right

const htmlModels = matchArray
  .map((carBrand) => {
    return carBrand.models
      .map((model) => {
        //console.log(model);
        return '
' + model + '
';
      })
      .join(' ');
  })
  .join(' ');```

Body:
 const endpoint =
        'https://raw.githubusercontent.com/FormidableLabs/radon-typeahead/master/demo/car-models.json';
      const cars = [];
      //fetch the data on the cars, convert the json raw into json and the add it to the array cars
      fetch(endpoint)
        .then((blob) => blob.json())
        .then((data) => cars.push(...data));

      function findMatches(wordToMatch, cars) {
        return cars.filter((Carbrand) => {
          //check if the brand matches what was searched
          //create a regular expression
          const regex = new RegExp(wordToMatch, 'gi');
          return Carbrand.brand.match(regex);
        });
      }

      function displayMatches() {
        const matchArray = findMatches(this.value, cars);
        const htmlCars = matchArray
          .map((carBrand) => {
            return `

${carBrand.brand}

          `;
          })
          .join('');

        const htmlModels = matchArray.map((carBrands) => {
          carBrands.models.map((carModels) => {
            //return carModels + 'this';
            //console.log('li ' + carModels);
            return
            `

${carModels}

            `;
          });
        });
        console.log('htmlModels ' + htmlModels);
        suggestions.innerHTML = htmlCars + htmlModels;
      }

      const searchInput = document.querySelector('.search');
      const suggestions = document.querySelector('.suggestions');

      searchInput.addEventListener('change', displayMatches);
      searchInput.addEventListener('keyup', displayMatches);

<!DOCTYPE html>

    <meta charset="utf-8" />

    <title>Car filter</title>
    <meta name="description" content="The HTML5 Herald" />
    <meta name="author" content="SitePoint" />

    <link rel="stylesheet" href="css/styles.css?v=1.0" />

    <form class="search-form">
      <input type="text" class="search" placeholder="City or State" />

Filter for a car

or a state

    </form>

I'm trying to iterate through and array made of objects that contain keys and Arrays. I'm nesting a map function to display an array that is in the object. I'm trying to get it in a html list

Here is an example of the object.

{
    "brand": "Acura",
    "models": [
      "2.2CL",
      "2.3CL",
      "3.0CL",
      "3.2CL",
      "ILX",
      "Integra",
      "Legend",
      "MDX",
      "NSX",
      "RDX",
      "3.5 RL",
      "RL",
      "RSX",
      "SLX",
      "2.5TL",
      "3.2TL",
      "TL",
      "TSX",
      "Vigor",
      "ZDX"
    ]

The first part getting the car brand works, I'm just struggling to get it to display the models that are in an array.

If I console.log 'carModels'I can see the models as strings but trying to return them is not working. I see ,,,,,, in my console.

findMatches returns an array of matches which works fine.

What I am trying to do is display results for a car brand and then in a nested list all the models of that brand, using a nested map inside my function. Its's working when console logging but I cant seem to return the results.

Body:
I managed to get it right

const htmlModels = matchArray
  .map((carBrand) => {
    return carBrand.models
      .map((model) => {
        //console.log(model);
        return '<li>' + model + '</li>';
      })
      .join(' ');
  })
  .join(' ');


问:
Devise - openid + ldap
So, I've been studying about Devise and I've really liked it, but one thing I didn't understand is, can you use multiple providers (e.g. ldap login + facebook/google/etc.)? So, what I want is:

User - information connected to my website

Linked provides - so, I want Users to be able to link their accounts to multiple providers.

For example, let's say we have user example_user. It has its facebook, google and ldap account linked to its account, so if it tries to login in with ldap, google or facebook account, it'll succeed and give me its instance of model User.

Sorry for my bad language, I'm quite bad at explaining my issue.

Thanks!

EDIT: I've resolved it by using omniauth.

答:
maybe these three pointers will help:

http://wiki.phys.ethz.ch/readme/devise_with_ldap_for_authentication_in_rails_3

http://random-rails.blogspot.com/2010/07/ldap-authentication-with-devise.html

http://vimeo.com/13105005

ContentLicense: CC BY-SA 2.5

Title: Devise - openid + ldap


问:
net.corda.core.CordaRuntimeException: The Initiator of CollectSignaturesFlow must pass in exactly the sessions required to sign the transaction
I'm trying to follow a corda tutorial but I don't understand where I'm wrong...

The unit test is run successfuly, but when I try to issue new IOU via api, the exception is thrown.

This is my flow code of IOU.
The exception is in the title, thanks in advance.

```<code>        //get notary reference
        final Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        //builder
        final TransactionBuilder builder = new TransactionBuilder(notary);

        final List<PublicKey> partiesKey = this.state.getParticipants()
                .stream().map(AbstractParty::getOwningKey)
                .collect(Collectors.toList());

        //create new issue command
        final Command<IOUContract.Commands.Issue> cmd = new Command<>(
                new IOUContract.Commands.Issue(), partiesKey
                );

        //create a transaction state
        TransactionState<IOUState> txState = new TransactionState<>(this.state,
                IOUContract.IOU_CONTRACT_ID, notary);

        //add to builder command and state
        builder.withItems(cmd, txState);

        //verify sign it
        builder.verify(getServiceHub());

        // Sign the transaction.
        final Party me = getOurIdentity();

        final SignedTransaction ptx = getServiceHub().signInitialTransaction(builder, me.getOwningKey());

        List<Party> otherParties = this.state.getParticipants().stream()
                .filter(x -> x.getOwningKey() != me.getOwningKey())
                .map(el -> (Party)el)
                .collect(Collectors.toList());

        //open flow session with other parties
        List<FlowSession> sessions = otherParties.stream()
                .map(el -> initiateFlow(el))
                .collect(Collectors.toList());

        SignedTransaction fullSign = subFlow(
            new CollectSignaturesFlow(
                ptx,
                sessions,
                ImmutableList.of(me.getOwningKey()),
                CollectSignaturesFlow.Companion.tracker()
            )
        );

        return subFlow(new FinalityFlow(fullSign, sessions));
</code>```

If I change code in the last 3 lines:

FROM

```<code>//open flow session with other parties
    List<FlowSession> sessions = otherParties.stream()
            .map(el -> initiateFlow(el))
            .collect(Collectors.toList());

    SignedTransaction fullSign = subFlow(
        new CollectSignaturesFlow(
            ptx,
            sessions,
            ImmutableList.of(me.getOwningKey()),
            CollectSignaturesFlow.Companion.tracker()
        )
    );

    return subFlow(new FinalityFlow(fullSign, sessions));
</code>```

TO

```<code>//open flow session with counter party
        FlowSession lenderFlow = initiateFlow(state.getLender());

        SignedTransaction fullSign = subFlow(
            new CollectSignaturesFlow(
                ptx,
                ImmutableSet.of(lenderFlow),
                ImmutableList.of(me.getOwningKey()),
                CollectSignaturesFlow.Companion.tracker()
            )
        );

        return subFlow(new FinalityFlow(fullSign, ImmutableSet.of(lenderFlow)));
</code>```

It's work correctly, WHY? what's the difference?

答:
I believe Adel is right that you're passing the wrong parties to the collectSignatures subflow.

I'd double-check the contents of that list to make sure that the node running the flow isn't in that list.

Just a simple check or something like this will do it:

```<code>    //Collect all of the required signatures from other Players / Corda nodes using the CollectSignaturesFlow
    for (int i = 0; i < input.getPlayers().length; i++) {
        Party p = input.getPlayers()[i];

        if (p.equals(me)) {
            continue;
        }

        FlowSession session = initiateFlow(p);

        new IdentitySyncFlow.Send(session, partStx.getTx());

        sessionList.add(session);
    }
</code>```

Body:
I'm trying to follow a corda tutorial but I don't understand where I'm wrong...

The unit test is run successfuly, but when I try to issue new IOU via api, the exception is thrown.

This is my flow code of IOU.
The exception is in the title, thanks in advance.

        //get notary reference
        final Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        //builder
        final TransactionBuilder builder = new TransactionBuilder(notary);

        final List<PublicKey> partiesKey = this.state.getParticipants()
                .stream().map(AbstractParty::getOwningKey)
                .collect(Collectors.toList());

        //create new issue command
        final Command<IOUContract.Commands.Issue> cmd = new Command<>(
                new IOUContract.Commands.Issue(), partiesKey
                );

        //create a transaction state
        TransactionState<IOUState> txState = new TransactionState<>(this.state,
                IOUContract.IOU_CONTRACT_ID, notary);

        //add to builder command and state
        builder.withItems(cmd, txState);

        //verify sign it
        builder.verify(getServiceHub());

        // Sign the transaction.
        final Party me = getOurIdentity();

        final SignedTransaction ptx = getServiceHub().signInitialTransaction(builder, me.getOwningKey());

        List<Party> otherParties = this.state.getParticipants().stream()
                .filter(x -> x.getOwningKey() != me.getOwningKey())
                .map(el -> (Party)el)
                .collect(Collectors.toList());

        //open flow session with other parties
        List<FlowSession> sessions = otherParties.stream()
                .map(el -> initiateFlow(el))
                .collect(Collectors.toList());

        SignedTransaction fullSign = subFlow(
            new CollectSignaturesFlow(
                ptx,
                sessions,
                ImmutableList.of(me.getOwningKey()),
                CollectSignaturesFlow.Companion.tracker()
            )
        );

        return subFlow(new FinalityFlow(fullSign, sessions));

If I change code in the last 3 lines:

FROM

//open flow session with other parties
    List<FlowSession> sessions = otherParties.stream()
            .map(el -> initiateFlow(el))
            .collect(Collectors.toList());

    SignedTransaction fullSign = subFlow(
        new CollectSignaturesFlow(
            ptx,
            sessions,
            ImmutableList.of(me.getOwningKey()),
            CollectSignaturesFlow.Companion.tracker()
        )
    );

    return subFlow(new FinalityFlow(fullSign, sessions));

TO

//open flow session with counter party
        FlowSession lenderFlow = initiateFlow(state.getLender());

        SignedTransaction fullSign = subFlow(
            new CollectSignaturesFlow(
                ptx,
                ImmutableSet.of(lenderFlow),
                ImmutableList.of(me.getOwningKey()),
                CollectSignaturesFlow.Companion.tracker()
            )
        );

        return subFlow(new FinalityFlow(fullSign, ImmutableSet.of(lenderFlow)));

It's work correctly, WHY? what's the difference?

Body:
I believe Adel is right that you're passing the wrong parties to the collectSignatures subflow.

I'd double-check the contents of that list to make sure that the node running the flow isn't in that list.

Just a simple check or something like this will do it:

    //Collect all of the required signatures from other Players / Corda nodes using the CollectSignaturesFlow
    for (int i = 0; i < input.getPlayers().length; i++) {
        Party p = input.getPlayers()[i];

        if (p.equals(me)) {
            continue;
        }

        FlowSession session = initiateFlow(p);

        new IdentitySyncFlow.Send(session, partStx.getTx());

        sessionList.add(session);
    }


问:
Make angular using CanActive only some path at childRoutes
i'm new with Angular

In my case, i want to use guard in some path

Shell.ts

```<code>export class Shell {
   static childRoutes(routes: Routes): Route {
       return {
           path: '',
           component: ShellComponent, // Component that have a navbar
           children: routes,
           canActivateChild: [AuthenticationGuard],
       };
   }
}
</code>```

shell.component.html

```<code>// some code html of navbar here
<router-outlet></router-outlet>
</code>```

app-routing.module.ts

```<code>const routes: Routes = [
   Shell.childRoutes([
      { path: 'module1', loadChildren: () => import('./module1/module1.module').then(m => m.module1) },
      { path: 'module2', loadChildren: () => import('./module2/module2.module').then(m => m.module2) },
      { path: 'module3', loadChildren: () => import('./module3/module3.module').then(m => m.module3) },
   ]),
];
</code>```

I only want using canActivateChild for module3. How can I do it?

答:
in can activate check like  :- </p>

```<code>allowedModules = ['module2','module3']

   filteredModule = allowedModules.find((module)=>state.url.includes(module));

   return !!filteredModule;
</code>```

Body:
i'm new with Angular

In my case, i want to use guard in some path

Shell.ts

export class Shell {
   static childRoutes(routes: Routes): Route {
       return {
           path: '',
           component: ShellComponent, // Component that have a navbar
           children: routes,
           canActivateChild: [AuthenticationGuard],
       };
   }
}

shell.component.html

// some code html of navbar here
<router-outlet></router-outlet>

app-routing.module.ts

const routes: Routes = [
   Shell.childRoutes([
      { path: 'module1', loadChildren: () => import('./module1/module1.module').then(m => m.module1) },
      { path: 'module2', loadChildren: () => import('./module2/module2.module').then(m => m.module2) },
      { path: 'module3', loadChildren: () => import('./module3/module3.module').then(m => m.module3) },
   ]),
];

I only want using canActivateChild for module3. How can I do it?

Body:
in can activate check like  :-

allowedModules = ['module2','module3']

   filteredModule = allowedModules.find((module)=>state.url.includes(module));

   return !!filteredModule;


问:
Convert to Specific Format Given an Int Number in C#
In this occasion my goal is to convert to a specific format given a number (int), for example:

Convert 12345678 to 123,456.78

Convert 1234 to 12.34

Convert 12 to 0.12

etcetera

Always setting a decimal part to the last two numbers of my int number and adding the "," separator respectively. I tried the following solution but it doesn't work, anyway, my solution is:

```<code>decimal xy = Convert.ToDecimal("20014725");
xy.ToString("##.##");
xy.ToString("C2");
xy.ToString("C2", CultureInfo.InvariantCulture);
xy.ToString("##.00",CultureInfo.InvariantCulture);
</code>```

With this code, for example:

```<code>xy = 123456
</code>```

I got 123456.00 instead of 1,234.56 the number that I need.

So, which changes need my code to get my desire solution? or there is any other way to get my desire result?

As always, thank you for your time and attention.

答:
```<code>var no = 12345678;
Console.WriteLine(((double)no / 100).ToString("N2"));
no = 1234;
Console.WriteLine(((double)no / 100).ToString("N2"));
no = 12;
Console.WriteLine(((double)no / 100).ToString("N2"));
</code>```

Output:

```<code>123,456.78
12.34
0.12
</code>```

Body:
In this occasion my goal is to convert to a specific format given a number (int), for example:

Convert 12345678 to 123,456.78

Convert 1234 to 12.34

Convert 12 to 0.12

etcetera

Always setting a decimal part to the last two numbers of my int number and adding the "," separator respectively. I tried the following solution but it doesn't work, anyway, my solution is:

decimal xy = Convert.ToDecimal("20014725");
xy.ToString("##.##");
xy.ToString("C2");
xy.ToString("C2", CultureInfo.InvariantCulture);
xy.ToString("##.00",CultureInfo.InvariantCulture);

With this code, for example:

xy = 123456

I got 123456.00 instead of 1,234.56 the number that I need.

So, which changes need my code to get my desire solution? or there is any other way to get my desire result?

As always, thank you for your time and attention.

Body:
var no = 12345678;
Console.WriteLine(((double)no / 100).ToString("N2"));
no = 1234;
Console.WriteLine(((double)no / 100).ToString("N2"));
no = 12;
Console.WriteLine(((double)no / 100).ToString("N2"));

Output:

123,456.78
12.34
0.12


问:
Is there a way to securely delete files on aws?
We store some sensitive stuff on S3 and on our instance filesystems on AWS.  Is there a way to securely wipe it?</p>

答:
The short answer is no, there is no wipe utility.  If you delete the file permanently, the file is gone and it cannot be recovered (unless you have snapshots or other items that might keep the file stored).  However, there is not a way to wipe the disk.  Don't forget, though, that AWS uses server virtualization so that your disk storage does not necessarily correspond to one physical disk platter.  Instead, it is a virtual storage system spread over many drives.  When your file is deleted, it is gone from public access.  Then Amazon designates that area of disk for write-only operations so that your data gets overwritten quickly.

Here is a quote from an Amazon document about their data security:

When an object is deleted from Amazon S3, removal of the mapping from the public name to the object starts immediately, and is generally processed across the distributed system within several seconds. Once the mapping is removed, there is no external access to the deleted object. That storage area is then made available only for write operations and the data is overwritten by newly stored data.

Retrieved from: http://aws.amazon.com/whitepapers/overview-of-security-processes/


问:
Can we track each audience's actions' duration on a webpage?
I have a webpage consisting of a modal popup that would show up on click. I want to give the link to several audiences, and track each audience's duration when opening the open button until they finally click the close button.

How do we track the duration?

答:
You must track an event to be sent to Google Analytics when the user clicks on the buttons (both on Open and Close).

Time is calculated by Analytics for the difference between the first and last interaction.


问:
java codility training Genomic-range-query
The task is:

A non-empty zero-indexed string S is given. String S consists of N characters from the set of upper-case English letters A, C, G, T.

This string actually represents a DNA sequence, and the upper-case letters represent single nucleotides.

You are also given non-empty zero-indexed arrays P and Q consisting of M integers. These arrays represent queries about minimal nucleotides. We represent the letters of string S as integers 1, 2, 3, 4 in arrays P and Q, where A = 1, C = 2, G = 3, T = 4, and we assume that A < C < G < T.

Query K requires you to find the minimal nucleotide from the range (P[K], Q[K]), 0 ≤ P[i] ≤ Q[i] < N.

For example, consider string S = GACACCATA and arrays P, Q such that:

```<code>P[0] = 0    Q[0] = 8
P[1] = 0    Q[1] = 2
P[2] = 4    Q[2] = 5
P[3] = 7    Q[3] = 7
</code>```

The minimal nucleotides from these ranges are as follows:

```<code>    (0, 8) is A identified by 1,
    (0, 2) is A identified by 1,
    (4, 5) is C identified by 2,
    (7, 7) is T identified by 4.
</code>```

Write a function:

```<code>class Solution { public int[] solution(String S, int[] P, int[] Q); }
</code>```

that, given a non-empty zero-indexed string S consisting of N characters and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M characters specifying the consecutive answers to all queries.

The sequence should be returned as:

```<code>    a Results structure (in C), or
    a vector of integers (in C++), or
    a Results record (in Pascal), or
    an array of integers (in any other programming language).
</code>```

For example, given the string S = GACACCATA and arrays P, Q such that:

```<code>P[0] = 0    Q[0] = 8
P[1] = 0    Q[1] = 2
P[2] = 4    Q[2] = 5
P[3] = 7    Q[3] = 7
</code>```

the function should return the values [1, 1, 2, 4], as explained above.

Assume that:

```<code>    N is an integer within the range [1..100,000];
    M is an integer within the range [1..50,000];
    each element of array P, Q is an integer within the range [0..N − 1];
    P[i] ≤ Q[i];
    string S consists only of upper-case English letters A, C, G, T.
</code>```

Complexity:

```<code>    expected worst-case time complexity is O(N+M);
    expected worst-case space complexity is O(N),
         beyond input storage
         (not counting the storage required for input arguments).
</code>```

Elements of input arrays can be modified.

My solution is:

```<code>class Solution {
    public int[] solution(String S, int[] P, int[] Q) {
        final  char c[] = S.toCharArray();
        final int answer[] = new int[P.length];
        int tempAnswer;
        char tempC;

        for (int iii = 0; iii < P.length; iii++) {
            tempAnswer = 4;
            for (int zzz = P[iii]; zzz <= Q[iii]; zzz++) {
                tempC = c[zzz];
                if (tempC == 'A') {
                    tempAnswer = 1;
                    break;
                } else if (tempC == 'C') {
                    if (tempAnswer > 2) {
                        tempAnswer = 2;
                    }
                } else if (tempC == 'G') {
                    if (tempAnswer > 3) {
                        tempAnswer = 3;
                    }

                }
            }
            answer[iii] = tempAnswer;
        }

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

It is not optimal, I believe it's supposed to be done within one loop, any hint how can I achieve it?

You can check quality of your solution here https://codility.com/train/ test name is Genomic-range-query.

答:
Javascript solution 100/100</p>

```<code>function solution(S, P, Q) {
    const values = { A: 1, C: 2, G: 3, T: 4};
    const keys = Object.keys(values)
    const result = []
    for (i = 0; i < P.length; i++) {
        const string = S.slice(P[i], Q[i] + 1)
        let min;
        for (j = 0; j < keys.length; j++) {
            if (string.includes(keys[j])) {
                min = values[keys[j]];
                break;
            }
        }
        result.push(min)
    }
    return result
}
</code>```

Body:
The task is:

A non-empty zero-indexed string S is given. String S consists of N characters from the set of upper-case English letters A, C, G, T.

This string actually represents a DNA sequence, and the upper-case letters represent single nucleotides.

You are also given non-empty zero-indexed arrays P and Q consisting of M integers. These arrays represent queries about minimal nucleotides. We represent the letters of string S as integers 1, 2, 3, 4 in arrays P and Q, where A = 1, C = 2, G = 3, T = 4, and we assume that A < C < G < T.

Query K requires you to find the minimal nucleotide from the range (P[K], Q[K]), 0 ≤ P[i] ≤ Q[i] < N.

For example, consider string S = GACACCATA and arrays P, Q such that:

P[0] = 0    Q[0] = 8
P[1] = 0    Q[1] = 2
P[2] = 4    Q[2] = 5
P[3] = 7    Q[3] = 7

The minimal nucleotides from these ranges are as follows:

    (0, 8) is A identified by 1,
    (0, 2) is A identified by 1,
    (4, 5) is C identified by 2,
    (7, 7) is T identified by 4.

Write a function:

class Solution { public int[] solution(String S, int[] P, int[] Q); }

that, given a non-empty zero-indexed string S consisting of N characters and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M characters specifying the consecutive answers to all queries.

The sequence should be returned as:

    a Results structure (in C), or
    a vector of integers (in C++), or
    a Results record (in Pascal), or
    an array of integers (in any other programming language).

For example, given the string S = GACACCATA and arrays P, Q such that:

P[0] = 0    Q[0] = 8
P[1] = 0    Q[1] = 2
P[2] = 4    Q[2] = 5
P[3] = 7    Q[3] = 7

the function should return the values [1, 1, 2, 4], as explained above.

Assume that:

    N is an integer within the range [1..100,000];
    M is an integer within the range [1..50,000];
    each element of array P, Q is an integer within the range [0..N − 1];
    P[i] ≤ Q[i];
    string S consists only of upper-case English letters A, C, G, T.

Complexity:

    expected worst-case time complexity is O(N+M);
    expected worst-case space complexity is O(N),
         beyond input storage
         (not counting the storage required for input arguments).

Elements of input arrays can be modified.

My solution is:

class Solution {
    public int[] solution(String S, int[] P, int[] Q) {
        final  char c[] = S.toCharArray();
        final int answer[] = new int[P.length];
        int tempAnswer;
        char tempC;

        for (int iii = 0; iii < P.length; iii++) {
            tempAnswer = 4;
            for (int zzz = P[iii]; zzz <= Q[iii]; zzz++) {
                tempC = c[zzz];
                if (tempC == 'A') {
                    tempAnswer = 1;
                    break;
                } else if (tempC == 'C') {
                    if (tempAnswer > 2) {
                        tempAnswer = 2;
                    }
                } else if (tempC == 'G') {
                    if (tempAnswer > 3) {
                        tempAnswer = 3;
                    }

                }
            }
            answer[iii] = tempAnswer;
        }

        return answer;
    }
}

It is not optimal, I believe it's supposed to be done within one loop, any hint how can I achieve it?

You can check quality of your solution here https://codility.com/train/ test name is Genomic-range-query.

Body:
Javascript solution 100/100

function solution(S, P, Q) {
    const values = { A: 1, C: 2, G: 3, T: 4};
    const keys = Object.keys(values)
    const result = []
    for (i = 0; i < P.length; i++) {
        const string = S.slice(P[i], Q[i] + 1)
        let min;
        for (j = 0; j < keys.length; j++) {
            if (string.includes(keys[j])) {
                min = values[keys[j]];
                break;
            }
        }
        result.push(min)
    }
    return result
}


问:
Cell value dependant on Active cell
Not sure if this is possible but there's so many creatives here i thought Id ask, I have a customer list with emails and amounts they owe in a table.

What I want to do is to select a cell with customers name(active cell"A1") and have another cell, lets say K2 show that customer's email address. I would like the same cell K2 to always display email address of the customers who's name is selected.

Then I can create 1 button that reads that cell(k2) and uses that as the 'email to'. Otherwise i will have hundreds of email buttons, one for each customer. I've tried a few codes online but can't figure it out.

I want to make a little more complex later on by adding their details into 1 hyperlink(to prefill form), but hopefully if i can get the basics right above i may be able to do the rest.

Any help is hugely appreciated.

答:
I put a bit more complex solution here. The advantage of it that you can select any cells in the row of your data and it is limited to a specific range, which could be improve your speed.</p>

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rngData As Range
    Set rngData = Range("A2:D20") 'This is the range that holds your data
    'If you not selected anything in this range, there is nothing to do, leave the sub
    If Intersect(Target, rngData) Is Nothing Then Exit Sub

    'I think it is a good practice to turn off the possible other events, though you not need it now
    Application.EnableEvents = False
    ' Define in which column is the data you would like to put in K2
    Dim iColumnOfEmailAddress As Long
    iColumnOfEmailAddress = 2
    Range("K2").Value2 = Cells(Target.Row, iColumnOfEmailAddress).Value2
    Application.EnableEvents = True 'turn the events back
End Sub
</code>```

Title: Cell value dependant on Active cell

Body:
I put a bit more complex solution here. The advantage of it that you can select any cells in the row of your data and it is limited to a specific range, which could be improve your speed.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rngData As Range
    Set rngData = Range("A2:D20") 'This is the range that holds your data
    'If you not selected anything in this range, there is nothing to do, leave the sub
    If Intersect(Target, rngData) Is Nothing Then Exit Sub

    'I think it is a good practice to turn off the possible other events, though you not need it now
    Application.EnableEvents = False
    ' Define in which column is the data you would like to put in K2
    Dim iColumnOfEmailAddress As Long
    iColumnOfEmailAddress = 2
    Range("K2").Value2 = Cells(Target.Row, iColumnOfEmailAddress).Value2
    Application.EnableEvents = True 'turn the events back
End Sub


问:
How set background-image for different screen variation?
I am having trouble with how to set different background images (or make responsive background images) for different screen sizes. My intention is to set 2 background images. First is for the size of a mobile screen and another of the size of a PC screen. I tried browsing the internet and watching tutorials on Youtube but it drives me no closer to what I want to happen. I am new to programming web applications and any help, tips and suggestions would be very much appreciated. Thank you. </p>

答:
Follow the simple procedure

# Usual CSS for Big screens
.myClass{
  background-image: url();
  }

#for small screeens or whatever width you want

@media (max-width:768px){
.myClass{
  background-image: url();
  }
}
  ```


Title: Find the last sequence of occurance of a value in a time series data in pandas

Body:
I have per minute time series data for 10 days with three columns: time stamp, category, alarm. Given a date, I want to groupby category and find the timestamps for which the alarm was set to 1 consecutively before the given date and create a dataframe from this subset.

   'Category'       'Date'              'Alarm'
0      A        1999-11-10 12:01:00        1
1      A        1999-11-10 12:02:00        1
2      A        1999-11-10 12:03:00        1
3      A        1999-11-10 12:04:00        1
4      A        1999-11-10 12:05:00        0
5      A        1999-11-10 12:06:00        0
.
.
.
1101   A        1999-11-13 10:07:00        1
1102   A        1999-11-13 10:08:00        1
1103   A        1999-11-13 10:09:00        1
1104   B        1999-11-23 13:09:00        0
1105   B        1999-11-23 13:10:00        0
1106   B        1999-11-23 13:11:00        1
1107   B        1999-11-23 13:12:00        1
1108   B        1999-11-23 13:13:00        1
1109   B        1999-11-23 13:14:00        0
.
.
.
.
2110   B        1999-11-26 13:13:00        0
2110   B        1999-11-26 13:14:00        0
2110   B        1999-11-26 13:15:00        1
2111   B        1999-11-26 13:16:00        1
2112   B        1999-11-26 13:17:00        1
2113   B        1999-11-26 13:18:00        1
2114   B        1999-11-26 13:19:00        1
2115   B        1999-11-26 13:20:00        0
2116   B        1999-11-26 13:21:00        0
2117   C        1999-12-02 17:11:00        1
.
.
.

I would like the output to be a new dataframe which has only these rows:

     'Category'       'Date'              'Alarm'
 1101   A        1999-11-13 10:07:00        1
 1102   A        1999-11-13 10:08:00        1
 1103   A        1999-11-13 10:09:00        1
 2110   B        1999-11-23 13:15:00        1
 2111   B        1999-11-23 13:16:00        1
 2112   B        1999-11-23 13:17:00        1
 2113   B        1999-11-23 13:18:00        1
 2114   B        1999-11-23 13:19:00        1

i.e, the rows in each group with the last consecutive sequence of 1s in alarm.
What I have tried:

df.groupby('category')['alarm'].apply(lambda x: x==1)

But this gives all the rows which have alarm as 1 and not just the last sequence of consecutive 1. Any directions on how to get this is appreciated. Thanks! :)

Edit 1: I just provided a subset of the dataframe.The the last consecutive sequence of 1s can occur any number of days before (e.g, if the timeseries is from Nov 1- Nov 10, for a category the last consecutive 1s could have occurred on nov 2 or nov 8. And the length of the 1s can also vary.

Body:
Let's try

# convert to datetime type
df.Date = pd.to_datetime(df.Date)

# blocks of consecutive `1`:
s = (1-df.Alarm).cumsum()*df.Alarm

# last group of `1` within Category and day:
last_groups = s.groupby(df.Category).transform('max')

# output:
df[s==last_groups]

Ooutput:

     Category                Date  Alarm
1101        A 1999-11-13 10:07:00      1
1102        A 1999-11-13 10:08:00      1
1103        A 1999-11-13 10:09:00      1
2110        B 1999-11-26 13:15:00      1
2111        B 1999-11-26 13:16:00      1
2112        B 1999-11-26 13:17:00      1
2113        B 1999-11-26 13:18:00      1
2114        B 1999-11-26 13:19:00      1
2117        C 1999-12-02 17:11:00      1


问:
Remove underline from DropdownButtonFormField
How can I remove the underline from DropdownButtonFormField (check photo below), I have tried various combinations of options with InputDecortaion couldn't find any way.

```<code>SizedBox(
  width: 100.0,
  child: DropdownButtonFormField<int>(
    decoration: InputDecoration(
        border: UnderlineInputBorder(
            borderSide:
                BorderSide(color: Colors.white))),
    value: 2,
    items: <DropdownMenuItem<int>>[
      DropdownMenuItem<int>(
        value: 1,
        child: Text("Owner"),
      ),
      DropdownMenuItem<int>(
        value: 2,
        child: Text("Member"),
      ),
    ],
  ),
</code>```

答:
The proper/clean solution nowadays is to use InputBorder.none:

DropdownButtonFormField<int>(
  decoration: InputDecoration(
    enabledBorder: InputBorder.none,
    ...
  ),
  ...
)
```

You might also want to set border, focusedBorder, errorBorder, and disabledBorder to InputBorder.none if you want to avoid the border from showing in all cases.

Body:
How can I remove the underline from DropdownButtonFormField (check photo below), I have tried various combinations of options with InputDecortaion couldn't find any way.

SizedBox(
  width: 100.0,
  child: DropdownButtonFormField<int>(
    decoration: InputDecoration(
        border: UnderlineInputBorder(
            borderSide:
                BorderSide(color: Colors.white))),
    value: 2,
    items: <DropdownMenuItem<int>>[
      DropdownMenuItem<int>(
        value: 1,
        child: Text("Owner"),
      ),
      DropdownMenuItem<int>(
        value: 2,
        child: Text("Member"),
      ),
    ],
  ),

Body:
The proper/clean solution nowadays is to use InputBorder.none:

DropdownButtonFormField<int>(
  decoration: InputDecoration(
    enabledBorder: InputBorder.none,
    ...
  ),
  ...
)

You might also want to set border, focusedBorder, errorBorder, and disabledBorder to InputBorder.none if you want to avoid the border from showing in all cases.


问:
Not able to create a SignUp page using Django
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

```<code>def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)
</code>```

forms.py:

```<code>class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']
</code>```

models.py:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'
</code>```

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.

答:
It could be because there's a typo in your meta class declaration.
Change it to - class Meta. Note the case.

Body:
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)

forms.py:

class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.


问:
How to reverse the index value in Python using for loop with a given list
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

```<code> X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X
</code>```

I wrote this function:

```<code>def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
</code>```

But i get this print out when i call the function with the given list:

```<code>test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)
</code>```

Output:

```<code> X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

</code>```

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

```<code>print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")
</code>```

答:
You can use join to insert the vertical lines and then loop in reverse order. </p>

```<code>test_board = ['O','O','X','X','X','O','X','O','X']

for i in range(3,-1,-1):
    li=test_board[i*3:(i+1)*3]
    print('|'.join(li))
    if 0<i<3: print('-'*5)
</code>```

Body:
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

 X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X

I wrote this function:

def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

But i get this print out when i call the function with the given list:

test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)

Output:

 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")

Body:
You can use join to insert the vertical lines and then loop in reverse order.

test_board = ['O','O','X','X','X','O','X','O','X']

for i in range(3,-1,-1):
    li=test_board[i*3:(i+1)*3]
    print('|'.join(li))
    if 0<i<3: print('-'*5)


问:
ASP.Net Core: Get User Roles with LinQ Select method
I had a problem when select user roles with LinQ in Asp.Net Core. This is my function:

```<code>public async Task<ApiResult<PagedResult<UserViewModel>>> GetUserPaging(PagingRequestBase request)
{
    if(request==null) return new ApiErrorResult<PagedResult<UserViewModel>>("Invalid request");
    var query= await userManager.Users.Skip((request.PageIndex-1)*request.PageSize)
    .Take(request.PageSize)
    .Select(async x => new UserViewModel{
        UserName=x.UserName,
        Dob=x.Dob,
        Email=x.Email,
        FirstName=x.FirstName,
        LastName=x.LastName,
        Roles=await userManager.GetRolesAsync(x)
    }).ToListAsync();
}
</code>```

I want to use async keyword inside Select method in order to use: await userManager.GetRolesAsync(x) but intellisense warning me:

Async lambda expressions cannot be converted to expression trees.

Thanks for yours help ^^

答:
I can suggest you 2 solutions.
The first one is so dividing the two steps. First, get the users, and then get the roles. I think the problem could be that EF can't convert the async code to the expression tree and then convert it to SQL. So making it by separate ensures you that the second step is linq to object request (not linq to SQL). The problem with this solution is that you are making to much requests to the Database. It is the N + 1 problem.

public async Task<ApiResult<PagedResult<UserViewModel>>> GetUserPaging(PagingRequestBase request)
{
    if(request==null) return new ApiErrorResult<PagedResult<UserViewModel>>("Invalid request");
    var users = await userManager.Users.Skip((request.PageIndex-1)*request.PageSize)
    .Take(request.PageSize)
    .ToListAsync();

    var query = users.Select(async x => new UserViewModel{
        UserName=x.UserName,
        Dob=x.Dob,
        Email=x.Email,
        FirstName=x.FirstName,
        LastName=x.LastName,
        Roles=await userManager.GetRolesAsync(x)
    })
}
```

<p>So, this points us to the second approach. And it is making the request directly to the EF Database Context, and making the joining explicitly: </p>

<pre class="lang-cs prettyprint-override"><code>            YourfDbContext t = null;  // this is only for pointing it

            var x = from usr in t.Users
                    join userRole in t.UserRoles on usr.Id equals userRole.UserId
                    join role in t.Roles on userRole.RoleId equals role.Id into roles
                    select new {
                        User = usr,
                        Roles = roles
                    };
</code>```

This solution only makes one DB request and get all the data you want.

Body:
I had a problem when select user roles with LinQ in Asp.Net Core. This is my function:

public async Task<ApiResult<PagedResult<UserViewModel>>> GetUserPaging(PagingRequestBase request)
{
    if(request==null) return new ApiErrorResult<PagedResult<UserViewModel>>("Invalid request");
    var query= await userManager.Users.Skip((request.PageIndex-1)*request.PageSize)
    .Take(request.PageSize)
    .Select(async x => new UserViewModel{
        UserName=x.UserName,
        Dob=x.Dob,
        Email=x.Email,
        FirstName=x.FirstName,
        LastName=x.LastName,
        Roles=await userManager.GetRolesAsync(x)
    }).ToListAsync();
}

I want to use async keyword inside Select method in order to use: await userManager.GetRolesAsync(x) but intellisense warning me:

Async lambda expressions cannot be converted to expression trees.

Thanks for yours help ^^

Body:
I can suggest you 2 solutions.
The first one is so dividing the two steps. First, get the users, and then get the roles. I think the problem could be that EF can't convert the async code to the expression tree and then convert it to SQL. So making it by separate ensures you that the second step is linq to object request (not linq to SQL). The problem with this solution is that you are making to much requests to the Database. It is the N + 1 problem.

public async Task<ApiResult<PagedResult<UserViewModel>>> GetUserPaging(PagingRequestBase request)
{
    if(request==null) return new ApiErrorResult<PagedResult<UserViewModel>>("Invalid request");
    var users = await userManager.Users.Skip((request.PageIndex-1)*request.PageSize)
    .Take(request.PageSize)
    .ToListAsync();

    var query = users.Select(async x => new UserViewModel{
        UserName=x.UserName,
        Dob=x.Dob,
        Email=x.Email,
        FirstName=x.FirstName,
        LastName=x.LastName,
        Roles=await userManager.GetRolesAsync(x)
    })
}

So, this points us to the second approach. And it is making the request directly to the EF Database Context, and making the joining explicitly:

            YourfDbContext t = null;  // this is only for pointing it

            var x = from usr in t.Users
                    join userRole in t.UserRoles on usr.Id equals userRole.UserId
                    join role in t.Roles on userRole.RoleId equals role.Id into roles
                    select new {
                        User = usr,
                        Roles = roles
                    };

This solution only makes one DB request and get all the data you want.


问:
Expected ResolvedDependencyResult but found DefaultUnresolvedDependencyResult when trying to sync
I am using Android Studio 3.6.1 and Gradle 6.3-all. I tried to sync my project and got the following error:

Expected org.gradle.api.artifacts.result.ResolvedDependencyResult but
  found
  org.gradle.api.internal.artifacts.result.DefaultUnresolvedDependencyResult

No idea how to fix this.

答: Ok, Some how I got working, by running the following command: watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache, also removed the .gradle & .idea folders and some .iml files and reopend the project.</p>


问:
IE 6 problems... help?
http://tendonaid.com/

That's the website.

The top and bottom navigation seem to be off in IE 6. What can I do to fix that?

答:
Per Ben's suggestion of using John Resig' shiv is a valid use of getting content to use the same css styling in IE6. But a more relaible way is to use IE specific conditional statements, this will make sure that browsers with javascript disabled will still render properly.

In Head

```<code> <!--[if IE 6]>
    <link rel="stylesheet" type="text/css" href="style-ie6.css" />
 <![endif]-->
</code>```

Body Code

```<code> <!--[if IE 6]>
    <div class="footer">
 <![endif]-->
      <footer>.......</footer>
 <!--[if IE 6]>
    </div>
 <![endif]-->
</code>```

You will only need the styling for the additional classes in the style-ie6.css

OwnerDisplayName: Maddy Osman

Title: IE 6 problems... help?

Body:
Per Ben's suggestion of using John Resig' shiv is a valid use of getting content to use the same css styling in IE6. But a more relaible way is to use IE specific conditional statements, this will make sure that browsers with javascript disabled will still render properly.

In Head

 <!--[if IE 6]>
    <link rel="stylesheet" type="text/css" href="style-ie6.css" />
 <![endif]-->

Body Code

 <!--[if IE 6]>
    <div class="footer">
 <![endif]-->
      <footer>.......</footer>
 <!--[if IE 6]>
    </div>
 <![endif]-->

You will only need the styling for the additional classes in the style-ie6.css


问:
Delimited file "|" with paragraph text including line breaks spanning multiple lines
I have a large TXT dataset that is delimited by | but there is a field that allows for paragraph text, which contains line breaks and blank lines. All lines that are not part of the paragraph text start with AA|. When I try to import into R via readr these values become NA because it doesn't follow the structure

Is there a way to use sed or awk to take a line if it doesn't start with AA| then to append it to the prior line that does with a space?

Input:

```<code>AA|5904060|9001084471200270|9000263372600200|Result Comment:
No (1, 3) Beta-D-Glucan detected.

This assay does not detect certain fungi, including
Cryptococcus species, which produce very low levels of (1,
3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia,
Mucor and Rhizopus), which are not known to produce BDG.
Additionally, the yeast phase of Blastomyces dermatitidis
produces little BDG and may not be detected by this assay.
|North Building|0|0
</code>```

Goal Output:

```<code>AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected.  This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0
</code>```

答:
Try:

#!/bin/bash
awk '
  /^AA\|/ { if (r) print r; r = $0; next }
  { r = r " " $0 }
  END { print r }
' input
```

<p>If you want to avoid redundant spaces, you may add <code>gsub (/  /, " ", r)</code> in the code above, as follows:</p>

<pre class="lang-sh prettyprint-override"><code>awk '
  /^AA\|/ { if (r) print r; r = $0; next }
  { r = r " " $0; gsub (/  /, " ", r) }
  END { print r }
' input
</code>```

Body:
I have a large TXT dataset that is delimited by | but there is a field that allows for paragraph text, which contains line breaks and blank lines. All lines that are not part of the paragraph text start with AA|. When I try to import into R via readr these values become NA because it doesn't follow the structure

Is there a way to use sed or awk to take a line if it doesn't start with AA| then to append it to the prior line that does with a space?

Input:

AA|5904060|9001084471200270|9000263372600200|Result Comment:
No (1, 3) Beta-D-Glucan detected.

This assay does not detect certain fungi, including
Cryptococcus species, which produce very low levels of (1,
3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia,
Mucor and Rhizopus), which are not known to produce BDG.
Additionally, the yeast phase of Blastomyces dermatitidis
produces little BDG and may not be detected by this assay.
|North Building|0|0

Goal Output:

AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected.  This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0

Body:
Try:

#!/bin/bash
awk '
  /^AA\|/ { if (r) print r; r = $0; next }
  { r = r " " $0 }
  END { print r }
' input

If you want to avoid redundant spaces, you may add gsub (/  /, " ", r) in the code above, as follows:

awk '
  /^AA\|/ { if (r) print r; r = $0; next }
  { r = r " " $0; gsub (/  /, " ", r) }
  END { print r }
' input


问:
Using dispose() when using StatefulBuilder in a StatelessWidget
I am using a StatefulBuilder widget to update my values and it all works fine.

```<code>StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
   return Mywidget();
});
</code>```

Since this widget is in a Tab view, when I scroll to the next tab, I get the below exception in console.

```<code>E/flutter ( 7147): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: Unhandled exception:
E/flutter ( 7147): setState() called after dispose(): _StatefulBuilderState#09a22(lifecycle state: defunct, not mounted)
E/flutter ( 7147): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 7147): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 7147): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1097:9)
E/flutter ( 7147): #1      State.setState (package:flutter/src/widgets/framework.dart:1123:6)
E/flutter ( 7147): #2      ImageItem.actionColumn.<anonymous closure>.<anonymous closure> (package:silkthread/widgets/image_item.dart:197:19)
E/flutter ( 7147): #3      _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter ( 7147): #4      _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter ( 7147): #5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter ( 7147): #6      Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter ( 7147): #7      Future._complete (dart:async/future_impl.dart:476:7)
E/flutter ( 7147): #8      _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 7147): #9      _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter ( 7147): #10     _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter ( 7147): #11     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter ( 7147): #12     Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter ( 7147): #13     Future._complete (dart:async/future_impl.dart:476:7)
E/flutter ( 7147): #14     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 7147): #15     _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async/runtime/libasync_patch.dart:33:20)
E/flutter ( 7147): #16     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 7147): #17     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
</code>```

Since the page which has StatefulBuilder widget is a StatelessWidget, I can't call dispose() method.

So while using StatefulBuilder how can I avoid this exception?

Edit:
I am trying something same as mentioned in the article https://medium.com/flutter-community/stateful-widgets-be-gone-stateful-builder-a67f139725a0.

```<code>class ImageItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

      return StatefulBuilder(
           builder: (BuildContext context, StateSetter setState) {
               setState(() {
                 likesCount = post.likesCount;
               });

              return ActionChip(label: Text(likesCount);
      });
  }
}
</code>```

答:
create and implement your own StatefulBuilder, add dispose method, like this:

```<code>import 'package:flutter/material.dart';

typedef Disposer = void Function();

class MyStatefulBuilder extends StatefulWidget {
  const MyStatefulBuilder({
    Key key,
    @required this.builder,
    @required this.dispose,
  }) : assert(builder != null),
        super(key: key);

  final StatefulWidgetBuilder builder;
  final Disposer dispose;

  @override
  _MyStatefulBuilderState createState() => _MyStatefulBuilderState();
}

class _MyStatefulBuilderState extends State<MyStatefulBuilder> {
  @override
  Widget build(BuildContext context) => widget.builder(context, setState);

  @override
  void dispose() {
    super.dispose();
    widget.dispose();
  }
}
</code>```

use it like this:

```<code>return AlertDialog(
        title: Text('Hello, world.'),
        content: MyStatefulBuilder(
          dispose: () {
            print('dispose!!!!!!!!!!!!');
          },
          builder: (BuildContext context, StateSetter setState) {
            return Container();
          }
    )
);
</code>```

Body:
I am using a StatefulBuilder widget to update my values and it all works fine.

StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
   return Mywidget();
});

Since this widget is in a Tab view, when I scroll to the next tab, I get the below exception in console.

E/flutter ( 7147): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: Unhandled exception:
E/flutter ( 7147): setState() called after dispose(): _StatefulBuilderState#09a22(lifecycle state: defunct, not mounted)
E/flutter ( 7147): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 7147): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 7147): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1097:9)
E/flutter ( 7147): #1      State.setState (package:flutter/src/widgets/framework.dart:1123:6)
E/flutter ( 7147): #2      ImageItem.actionColumn.<anonymous closure>.<anonymous closure> (package:silkthread/widgets/image_item.dart:197:19)
E/flutter ( 7147): #3      _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter ( 7147): #4      _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter ( 7147): #5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter ( 7147): #6      Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter ( 7147): #7      Future._complete (dart:async/future_impl.dart:476:7)
E/flutter ( 7147): #8      _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 7147): #9      _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter ( 7147): #10     _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter ( 7147): #11     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter ( 7147): #12     Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter ( 7147): #13     Future._complete (dart:async/future_impl.dart:476:7)
E/flutter ( 7147): #14     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 7147): #15     _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async/runtime/libasync_patch.dart:33:20)
E/flutter ( 7147): #16     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 7147): #17     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

Since the page which has StatefulBuilder widget is a StatelessWidget, I can't call dispose() method.

So while using StatefulBuilder how can I avoid this exception?

Edit:
I am trying something same as mentioned in the article https://medium.com/flutter-community/stateful-widgets-be-gone-stateful-builder-a67f139725a0.

class ImageItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

      return StatefulBuilder(
           builder: (BuildContext context, StateSetter setState) {
               setState(() {
                 likesCount = post.likesCount;
               });

              return ActionChip(label: Text(likesCount);
      });
  }
}

Body:
create and implement your own StatefulBuilder, add dispose method, like this:

import 'package:flutter/material.dart';

typedef Disposer = void Function();

class MyStatefulBuilder extends StatefulWidget {
  const MyStatefulBuilder({
    Key key,
    @required this.builder,
    @required this.dispose,
  }) : assert(builder != null),
        super(key: key);

  final StatefulWidgetBuilder builder;
  final Disposer dispose;

  @override
  _MyStatefulBuilderState createState() => _MyStatefulBuilderState();
}

class _MyStatefulBuilderState extends State<MyStatefulBuilder> {
  @override
  Widget build(BuildContext context) => widget.builder(context, setState);

  @override
  void dispose() {
    super.dispose();
    widget.dispose();
  }
}

use it like this:

return AlertDialog(
        title: Text('Hello, world.'),
        content: MyStatefulBuilder(
          dispose: () {
            print('dispose!!!!!!!!!!!!');
          },
          builder: (BuildContext context, StateSetter setState) {
            return Container();
          }
    )
);


问:
java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1."
and so my code is

```<code>public static void main(String[] args) {
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)
</code>```

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"

答:
You have an exception in your second loop. you try to call List2[20]. List2 only have 0 to 19 index available and you are trying to access 20th element which is not available.

```<code>List1[L1]= List2[L2]*L2;
</code>```

Try like this.

```<code>List1[L1]= List2[L1]*L2;
</code>```

complete code.

```<code>public static void main(String[] args) {
    int List1[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
    int List2[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
    int L1 = 0;
    int L2 = 0;

    for (L2 = 0; L2 < List2.length; L2++) {
        List2[L2] = (int) (100 * Math.random());
        System.out.print(" " + List2[L2]);
    } // end of list2 for loop

    System.out.println("");
    System.out.println(List1.length + " " + List2.length);

    for (L1 = 0; L1 < List1.length; L1++) {
        List1[L1] = List2[L1] * L2;
        System.out.print(" " + List1[L1]);
    } // end of list1 for loop
}
</code>```

Body:
Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1."
and so my code is

public static void main(String[] args) {
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"

Body:
You have an exception in your second loop. you try to call List2[20]. List2 only have 0 to 19 index available and you are trying to access 20th element which is not available.

List1[L1]= List2[L2]*L2;

Try like this.

List1[L1]= List2[L1]*L2;

complete code.

public static void main(String[] args) {
    int List1[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
    int List2[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
    int L1 = 0;
    int L2 = 0;

    for (L2 = 0; L2 < List2.length; L2++) {
        List2[L2] = (int) (100 * Math.random());
        System.out.print(" " + List2[L2]);
    } // end of list2 for loop

    System.out.println("");
    System.out.println(List1.length + " " + List2.length);

    for (L1 = 0; L1 < List1.length; L1++) {
        List1[L1] = List2[L1] * L2;
        System.out.print(" " + List1[L1]);
    } // end of list1 for loop
}


问:
intelliJ idea java certificate
I installed SSL certificate for Jira to Java via keytool. Actually i am using playframework 2 for development and if I use play terminal to compile and run project, everything is fine. The problem appears when I want to use debugger from IntelliJ idea. Project in IDE has set same java as SDK in project setting, but it has not accept the installed certificate. Can somebody help with this?</p>

答:
Go to File -> Settings -> Tools -> Server Certificates , and check the box "Accept non-trusted Certificates Automatically". That might solve your problem.
Also check your jdk version. I had to change to 1.8.0_192 on my Intellij.</p>

Title: intelliJ idea java certificate


问:
Android In App Updates - Not able to detect the update in AppUpdateInfo
Some log statements are thrown when we use,

```<code>Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
</code>```

```<code>2019-06-13 18:30:40.556 28375-28375/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : requestUpdateInfo(<"package name here">)
2019-06-13 18:30:40.556 28375-28584/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : Initiate binding to the service.
2019-06-13 18:30:40.560 28375-28375/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : ServiceConnectionImpl.onServiceConnected(ComponentInfo{com.android.vending/com.google.android.finsky.installservice.DevTriggeredUpdateService})
2019-06-13 18:30:40.560 28375-28584/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : linkToDeath
2019-06-13 18:30:40.564 28375-28389/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] OnRequestInstallCallback : onRequestInfo
2019-06-13 18:30:40.564 28375-28584/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : Unbind from service.
</code>```

I've made sure -

My signing keys are the same as uploaded in play store, as I can sign in facebook and other auths methods + I've verified myself.

The Google play google shows in My apps and games tab, with an UPDATE button showing up.

Application ID is the same

I've downloaded from the Play Google numberous times.

I've tried in the Internal Test track and a closed beta release

EDIT:
Also I've tried to run the app from adb install, or trying to install from google play and after that deploying aab on the play google.

答:
It could be also that your Android distro doesn't support in app updates
I'm debugging on a phone running Android GO
and when debugging , the following line was faiing as It's not supported on the Android system
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -></p>

Body:
Some log statements are thrown when we use,

Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {

2019-06-13 18:30:40.556 28375-28375/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : requestUpdateInfo(<"package name here">)
2019-06-13 18:30:40.556 28375-28584/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : Initiate binding to the service.
2019-06-13 18:30:40.560 28375-28375/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : ServiceConnectionImpl.onServiceConnected(ComponentInfo{com.android.vending/com.google.android.finsky.installservice.DevTriggeredUpdateService})
2019-06-13 18:30:40.560 28375-28584/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : linkToDeath
2019-06-13 18:30:40.564 28375-28389/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] OnRequestInstallCallback : onRequestInfo
2019-06-13 18:30:40.564 28375-28584/com.marsplay.debug I/PlayCore: UID: [10312]  PID: [28375] AppUpdateService : Unbind from service.

I've made sure -

My signing keys are the same as uploaded in play store, as I can sign in facebook and other auths methods + I've verified myself.

The Google play google shows in My apps and games tab, with an UPDATE button showing up.

Application ID is the same

I've downloaded from the Play Google numberous times.

I've tried in the Internal Test track and a closed beta release

EDIT:
Also I've tried to run the app from adb install, or trying to install from google play and after that deploying aab on the play google.


问:
Error when passing a laravel route as a props in VueJS
I want to use the blade syntax route() in a vue js component so i thought i should use something like this :

```<code><nav-bar
:user="{{ json_encode(Auth::user()) }}"
:authPath= "{{ route('auth') }}">

</nav-bar>
</code>```

but an error apear in the console :
app.js:86258 [Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

What did i do wrong?

答:
Your {{ route('auth') }} is eventually gonna return something like http://127.0.0.1:8000/auth --> This is a string NOT an expression.

Simply remove the : like this authPath="{{ route('auth') }}"

Body:
I want to use the blade syntax route() in a vue js component so i thought i should use something like this :

but an error apear in the console :
app.js:86258 [Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

What did i do wrong?


问:
XCode needs to be installed every time to detect iOS devices! Why? Any Solution?
XCode needs to be installed on every start up to detect iOS devices. Otherwise devices didn't  get detect. Why is it so? What to do? Any solutions?</p>

答: Have you tried creating a new user on the system to see if it has the same issue?  Perhaps there is a bad preference file somewhere.</p>


问:
PDO and binding multiple value sets during insert
Using PDO in PHP, when having to insert multiple rows into a table at once, I've used sql that looks something like this:

```<code>INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce');
</code>```

As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.

So my question is this: how do I do this in PHP if I want to be able to bind my values to a statement like I do in single statement:

```<code>$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
    "firstname"=>$firstName,
    "lastName"=>$lastName));
</code>```

So my question is: Is there any way to bind in a multi-insert statement? Something like:

```<code>INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
</code>```

答:
Just create your query text wtih ? placeholders as:

```<code>INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)
</code>```

And execute it. Sample code can be:

```<code>$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)'];  // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);
</code>```

Body:
Using PDO in PHP, when having to insert multiple rows into a table at once, I've used sql that looks something like this:

INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce');

As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.

So my question is this: how do I do this in PHP if I want to be able to bind my values to a statement like I do in single statement:

$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
    "firstname"=>$firstName,
    "lastName"=>$lastName));

So my question is: Is there any way to bind in a multi-insert statement? Something like:

INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));

Body:
Just create your query text wtih ? placeholders as:

INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)

And execute it. Sample code can be:

$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)'];  // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);


问:
Python netcdf grid_longitude
Normally when I work with files the coordinates are in lon and lat, but in this case they are in 'grid_longitude'

```<code>import xarray as xr
dataset = xr.open_dataset(r'C:\Users\eg\Desktop\nec\sfcan20120101a20121231_rot_mask.nc')
dataset

<xarray.Dataset>
Dimensions:        (height: 1, rlat: 240, rlon: 280, time: 366)
Coordinates:
* rlon           (rlon) float64 -5.0 -4.95 -4.9 -4.85 ... 8.8 8.85 8.9 8.95
* rlat           (rlat) float64 -6.45 -6.4 -6.35 -6.3 ... 5.35 5.4 5.45 5.5
* height         (height) float64 0.0
* time           (time) datetime64[ns] 2012-01-01T06:00:00 ... 2012-12- 31T06:00:00
Data variables:
rotated_pole   |S1 ...
precipitation  (time, height, rlat, rlon) float32 ...
lon            (rlat, rlon) float32 ...
lat            (rlat, rlon) float32 ...
Attributes:
title:        AEMET High-resolution (0.05 deg) daily gridded precipitatio...
institution:  Agencia Estatal de Meteorologia (AEMET, www.aemet.es)
references:   Peral, C., Navascu�s, B., Ramos, P. Available at: http://ww...
history:      Creation year 2017
Conventions:  CF-1.7
version:      1.0
</code>```

Someone knows how to turn it to degrees east and degrees north?, thanks

```<code> <xarray.DataArray 'rlon' (rlon: 280)>
 array([-5.  , -4.95, -4.9 , ...,  8.85,  8.9 ,  8.95])
 Coordinates:
  * rlon     (rlon) float64 -5.0 -4.95 -4.9 -4.85 -4.8 ... 8.8 8.85 8.9 8.95
 Attributes:
long_name:      longitude in rotated pole grid
units:          degrees
standard_name:  grid_longitude
axis:           X

<xarray.DataArray 'lon' (rlat: 240, rlon: 280)>
 array([[-11.988, -11.928, -11.868, ...,   4.566,   4.625,   4.684],
   [-11.992, -11.932, -11.872, ...,   4.573,   4.633,   4.692],
   [-11.996, -11.936, -11.876, ...,   4.581,   4.64 ,   4.699],
   ...,
   [-13.136, -13.065, -12.994, ...,   6.57 ,   6.64 ,   6.71 ],
   [-13.142, -13.071, -13.   , ...,   6.58 ,   6.65 ,   6.72 ],
   [-13.148, -13.077, -13.006, ...,   6.59 ,   6.661,   6.731]],
  dtype=float32)
  Coordinates:
  * rlon     (rlon) float64 -5.0 -4.95 -4.9 -4.85 -4.8 ... 8.8 8.85 8.9 8.95
  * rlat     (rlat) float64 -6.45 -6.4 -6.35 -6.3 -6.25 ... 5.35 5.4 5.45 5.5
 Attributes:
long_name:  longitude
units:      degrees_east
</code>```

That you can see they are completely different

答:
The data will derive from a numerical model in which the poles of the model's coordinate system differ from the earth's true poles.  This is typically done when running limited area models, in order to keep the poles as far away as possible from the area that is being modelled.  This allows the model's resolution to be roughly uniform over the model domain, as the coordinate system is then approximately cartesian and avoids issues where the meridians converge close to the poles.

In order to allow you to geolocate the other fields in the file properly, the CF Conventions mandate that the true location of each point in the model's grid is stored in the file alongside the data arrays, by means of 2-dimensional data variables containing the true longitude and latitude, which in this file have been called lon and lat.

To be completely certain that this is what lon and lat variables contain, you should in principle look at their attributes, and in particular any standard_name or long_name variable attributes, although given their names and the fact that a rotated pole is in use, it is obvious in this case that this is what they contain.

For more information, see http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html#grid-mappings-and-projections  (This link is for version 1.7 of the CF conventions, because that is what is in the data file.)

Title: Python netcdf grid_longitude

Body:
Normally when I work with files the coordinates are in lon and lat, but in this case they are in 'grid_longitude'

import xarray as xr
dataset = xr.open_dataset(r'C:\Users\eg\Desktop\nec\sfcan20120101a20121231_rot_mask.nc')
dataset

<xarray.Dataset>
Dimensions:        (height: 1, rlat: 240, rlon: 280, time: 366)
Coordinates:
* rlon           (rlon) float64 -5.0 -4.95 -4.9 -4.85 ... 8.8 8.85 8.9 8.95
* rlat           (rlat) float64 -6.45 -6.4 -6.35 -6.3 ... 5.35 5.4 5.45 5.5
* height         (height) float64 0.0
* time           (time) datetime64[ns] 2012-01-01T06:00:00 ... 2012-12- 31T06:00:00
Data variables:
rotated_pole   |S1 ...
precipitation  (time, height, rlat, rlon) float32 ...
lon            (rlat, rlon) float32 ...
lat            (rlat, rlon) float32 ...
Attributes:
title:        AEMET High-resolution (0.05 deg) daily gridded precipitatio...
institution:  Agencia Estatal de Meteorologia (AEMET, www.aemet.es)
references:   Peral, C., Navascu�s, B., Ramos, P. Available at: http://ww...
history:      Creation year 2017
Conventions:  CF-1.7
version:      1.0

Someone knows how to turn it to degrees east and degrees north?, thanks

 <xarray.DataArray 'rlon' (rlon: 280)>
 array([-5.  , -4.95, -4.9 , ...,  8.85,  8.9 ,  8.95])
 Coordinates:
  * rlon     (rlon) float64 -5.0 -4.95 -4.9 -4.85 -4.8 ... 8.8 8.85 8.9 8.95
 Attributes:
long_name:      longitude in rotated pole grid
units:          degrees
standard_name:  grid_longitude
axis:           X

<xarray.DataArray 'lon' (rlat: 240, rlon: 280)>
 array([[-11.988, -11.928, -11.868, ...,   4.566,   4.625,   4.684],
   [-11.992, -11.932, -11.872, ...,   4.573,   4.633,   4.692],
   [-11.996, -11.936, -11.876, ...,   4.581,   4.64 ,   4.699],
   ...,
   [-13.136, -13.065, -12.994, ...,   6.57 ,   6.64 ,   6.71 ],
   [-13.142, -13.071, -13.   , ...,   6.58 ,   6.65 ,   6.72 ],
   [-13.148, -13.077, -13.006, ...,   6.59 ,   6.661,   6.731]],
  dtype=float32)
  Coordinates:
  * rlon     (rlon) float64 -5.0 -4.95 -4.9 -4.85 -4.8 ... 8.8 8.85 8.9 8.95
  * rlat     (rlat) float64 -6.45 -6.4 -6.35 -6.3 -6.25 ... 5.35 5.4 5.45 5.5
 Attributes:
long_name:  longitude
units:      degrees_east

That you can see they are completely different


问:
how I can do on release input if empty fill with value using javascript
I have this input field is given below. when we click on the input field it clear field but 1 issue if the user does not enter any value it remains empty I want on release empty input it refills with old input value value="{{ $p->price }}" how I can do that?

```<code><input style="width: 70px;" onfocus="this.value=''" type="text" value="{{ $p->price }}" class="form-control" {{ Auth::user()->role < 3 ? '' : 'readonly' }} />
</code>```

答:
Two similar methods - one inline and the other as external event handlers. The basic gist is to capture a reference to the original value and store in a variable, reassign this value when the element loses focus if nothing has been entered into the field

var value;
var input=document.querySelector('input[name="bob"]');

input.onfocus=function(e){
  value=this.value;
  this.value='';
}
input.onblur=function(){
  if( this.value=='' )this.value=value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input name='boo' type="text" value="apple" class="form-control" onfocus='tmp=this.value;this.value=""' onblur='if(this.value=="")this.value=tmp' />
<input name='bob' type="text" value="banana" class="form-control" /></code>```

Body:
I have this input field is given below. when we click on the input field it clear field but 1 issue if the user does not enter any value it remains empty I want on release empty input it refills with old input value value="{{ $p->price }}" how I can do that?

<input style="width: 70px;" onfocus="this.value=''" type="text" value="{{ $p->price }}" class="form-control" {{ Auth::user()->role < 3 ? '' : 'readonly' }} />

Body:
Two similar methods - one inline and the other as external event handlers. The basic gist is to capture a reference to the original value and store in a variable, reassign this value when the element loses focus if nothing has been entered into the field

var value;
var input=document.querySelector('input[name="bob"]');

input.onfocus=function(e){
  value=this.value;
  this.value='';
}
input.onblur=function(){
  if( this.value=='' )this.value=value;
}

<input name='boo' type="text" value="apple" class="form-control" onfocus='tmp=this.value;this.value=""' onblur='if(this.value=="")this.value=tmp' />
<input name='bob' type="text" value="banana" class="form-control" />


问:
Js escape special characters
I've always escaped non-ASCII characters (such as à, ñ, é) as HTML entities (à, &entilde;, é), even if I'm using charset UTF-8 (just for text editor support and semplicity).

My problem is that I keep all the text in external PHP files for a multi-language purpose.

The problem comes when I have to escape strings which have to be alerted:

This <button onclick="alert('àèìòù')">Click me</button> outputs this: àèìòù,

while this  outputs this: &agrave ;&egrave ;&igrave ;&ograve ;&ugrave ;.

Which is the reason for it?

Since I want to escape characters in the second example too, how could I do that in a way supported by both examples?

答:
Those escaped chars are only readable by HTML.

A quick and dirty way if you want to handle them in the JS code (with JQuery though) is by adding them to an element and reading the output, otherwise if you just want to display your output somewhere in the page, it's super easy :)

See both examples below:

var myString = "àèìòù";

var escaped = $('<textarea />').html(myString).text();
alert(escaped);

document.getElementById("myElement").innerHTML = myString;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myElement">a</span></code>```

Title: Js escape special characters

Body:
Those escaped chars are only readable by HTML.

A quick and dirty way if you want to handle them in the JS code (with JQuery though) is by adding them to an element and reading the output, otherwise if you just want to display your output somewhere in the page, it's super easy :)

See both examples below:

var myString = "&agrave;&egrave;&igrave;&ograve;&ugrave;";

var escaped = $('<textarea />').html(myString).text();
alert(escaped);

document.getElementById("myElement").innerHTML = myString;

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myElement">a</span>


问:
Shorthand Directory Paths in Codes
i know this may be a simple question but your advise would be much appreciated.

I've never fully understood shorthand directory. Looking at the image;

QUESTION

Could one explain what ../../hoc/Aux refers to. In the
BurgerBuilder.js file - Is this referring to, existing out onto the folder
'BurgerBuilder', then existing out onto the 'containers' folder, then
existing out onto the 'src' folder? should this then be
.../../hoc/Aux with 3 dots, instead of ../../hoc/Aux?

And what does the 2 dots ..**/../**hoc/Aux in-between refer to? looking at
the image, is this referring to skipping the 'components' and
'containers' folder to get to the 'hoc' folder?

I know it's a simple question which i am yet to understand so if you kindly direct me to the right source to learn more would appreciate it. Thank you

答:
Let's just work through it step by step. </p>

```<code>// Path of burger file
src/containers/BurgerBuilder/BurgerBuilder.js

// ../
src/containers/BurgerBuilder/

// ../../
src/containers/

// ../../hoc
src/containers/hoc

// ../../Aux
src/containers/hoc/Aux.js
</code>```

Title: Shorthand Directory Paths in Codes

Body:
Let's just work through it step by step.

// Path of burger file
src/containers/BurgerBuilder/BurgerBuilder.js

// ../
src/containers/BurgerBuilder/

// ../../
src/containers/

// ../../hoc
src/containers/hoc

// ../../Aux
src/containers/hoc/Aux.js


问:
How to install Sensu client without installing Sensu server?
I am trying to install a Sensu client without the server.

According to the documentation:

"The Sensu Core package installs several processes including sensu-server, sensu-api, and sensu-client."

However after adding the repository, I was only able to locate the aggragate sensu package and could not locate or install sensu-client.

I noticed a ticket on github stating it was not possible however that was 2 years ago so maybe things have changed?

Is it possible to install Sensu server without having to install Redis, RabbitMQ and Sensu server?

答: It's not possible with sensu core. But you can install it using  the new product from sensu, sensu go which has sensu backend (replaces sensu server) and sensu agent (replaces sensu client) allows to install only sensu agent on your infrastructure.</p>