问:
How to add User and Admin navigation separate in angular
I want to separate admin and user navigation in angular project just like e-commerce website. But children route is not working for dashboard or user. When i click on reports route inside dashboard its give error.
here is my code for this

app/app-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './admin/dashboard.component';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'dashboard', component: DashboardComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

app/app.component.html

```<code><router-outlet></router-outlet>
</code>```

Admin/admin.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { AdminRoutingModule } from './admin-routing.module';
import { OrderComponent } from './components/order/order.component';
import { ProductComponent } from './components/product/product.component';
import { CustomerComponent } from './components/customer/customer.component';
import { ReportComponent } from './components/report/report.component';

@NgModule({
  declarations: [OrderComponent, ProductComponent, CustomerComponent, ReportComponent],
  imports: [
    CommonModule,
    AdminRoutingModule
  ]
})
export class AdminModule { }
</code>```

Admin/admin-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ReportComponent } from './components/report/report.component';

const routes: Routes = [
  {path: 'reports', component: ReportComponent}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }
</code>```

Admin/dashboard.components.html

```<code><h1>Dashboard</h1>
<li class="nav-item">
    <a class="nav-link" [routerLink]="['/reports']" routerLinkActive="router-link-active" >
      <span data-feather="bar-chart-2"></span>
      Reports
    </a>
  </li>
<router-outlet></router-outlet>
</code>```

Admin/components/report/report.components.html

```<code><p>report works!</p>
</code>```

But when i'm trying to access this route its gives error

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'reports'

答:
I think it will be clearer if you use children attribute of routes in AppRoutingModule like following:

I used layout component but you can use your modules.

I implemented for one of my projects. you can take a look at  on my github

```<code>const routes: Routes = [
  {
    path: "login", component: AuthlayoutComponent, children: [
      { path: "", component: LoginComponent }
    ]
  },
  {
    path: "admin", component: AdminlayoutComponent, children: [
      { path: 'home', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
      { path: 'report', component: ReportComponent, canActivate: [AuthGuard] }
    ]
  },
  {
    path: "user", component: UserlayoutComponent, children: [
      { path: 'home', component: UserHomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
      { path: 'report', component: UserReportComponent, canActivate: [AuthGuard] }
    ]
  },
  {
    path: '**', component: AuthlayoutComponent, children: [
      { path: "", component: LoginComponent }
    ]
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

Body:
I want to separate admin and user navigation in angular project just like e-commerce website. But children route is not working for dashboard or user. When i click on reports route inside dashboard its give error.
here is my code for this

app/app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './admin/dashboard.component';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'dashboard', component: DashboardComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app/app.component.html

<router-outlet></router-outlet>

Admin/admin.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { AdminRoutingModule } from './admin-routing.module';
import { OrderComponent } from './components/order/order.component';
import { ProductComponent } from './components/product/product.component';
import { CustomerComponent } from './components/customer/customer.component';
import { ReportComponent } from './components/report/report.component';

@NgModule({
  declarations: [OrderComponent, ProductComponent, CustomerComponent, ReportComponent],
  imports: [
    CommonModule,
    AdminRoutingModule
  ]
})
export class AdminModule { }

Admin/admin-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ReportComponent } from './components/report/report.component';

const routes: Routes = [
  {path: 'reports', component: ReportComponent}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }

Admin/dashboard.components.html

Dashboard

      Reports

<router-outlet></router-outlet>

Admin/components/report/report.components.html

report works!

But when i'm trying to access this route its gives error

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'reports'

Body:
I think it will be clearer if you use children attribute of routes in AppRoutingModule like following:

I used layout component but you can use your modules.

I implemented for one of my projects. you can take a look at  on my github

const routes: Routes = [
  {
    path: "login", component: AuthlayoutComponent, children: [
      { path: "", component: LoginComponent }
    ]
  },
  {
    path: "admin", component: AdminlayoutComponent, children: [
      { path: 'home', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
      { path: 'report', component: ReportComponent, canActivate: [AuthGuard] }
    ]
  },
  {
    path: "user", component: UserlayoutComponent, children: [
      { path: 'home', component: UserHomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
      { path: 'report', component: UserReportComponent, canActivate: [AuthGuard] }
    ]
  },
  {
    path: '**', component: AuthlayoutComponent, children: [
      { path: "", component: LoginComponent }
    ]
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


来源: stackexchange

问:
Finding if a property inside a list inside a list doesnt contain a specific string
I have a huge product database im working with threw a api

The API returns a Product those Products have MetaData which are stuff like minQuantities Maxes ect

Now I noticed some products dont have "variation_maximum_allowed_quantity" or " maximum_allowed_quantity"

So for every Product I have to look threw That Products meta data to so something like

```<code> foreach (var item in VarProduct)
 {
   foreach (var metaItem in item.meta_data)
    {

    }

 }
</code>```

The issue is meta_data have Key's Id's and value's I need to check against every key inside of every meta_data inside of every Product if that makes sense? Im wrecking my brain atm, Anyone know how I can check against all of those to see if those 2 Strings are missing? I need to be able to do something like

```<code>if(mdDoesntcontain)
{
 //This means stock is Unlimiteed so need to set a value for stock
   item.stockquantity = 9999999; (or int.maxValue())
}

</code>```

Little tricky Posting this as a Block but:

```<code>
-item.meta_data count = w.e
 -[0]
   -base
     -id = 101231
     -key = "min_max_rules"
     -value = "no"

 -[1]
   -base
     -id = 123131
     -key = "variation_minimum_allowed_quantity"
     -value = ""(this means 1 usually)

</code>```

```<code>public class MetaData
{
    private object preValue;

    [DataMember (EmitDefaultValue = false)]
    public int? id {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public string key {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public object value {
        get;
        set;
    }
</code>```

答:
You could use linq Any operation:</p>

```<code>foreach (var item in VarProduct)
{
    if (!item.meta_data.Any(m => m.key.Equals("variation_maximum_allowed_quantity")
        || m.key.Equals("maximum_allowed_quantity")))
    {
        item.stockQuantity = int.MaxValue;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a huge product database im working with threw a api

The API returns a Product those Products have MetaData which are stuff like minQuantities Maxes ect

Now I noticed some products dont have "variation_maximum_allowed_quantity" or " maximum_allowed_quantity"

So for every Product I have to look threw That Products meta data to so something like

 foreach (var item in VarProduct)
 {
   foreach (var metaItem in item.meta_data)
    {

    }

 }

The issue is meta_data have Key's Id's and value's I need to check against every key inside of every meta_data inside of every Product if that makes sense? Im wrecking my brain atm, Anyone know how I can check against all of those to see if those 2 Strings are missing? I need to be able to do something like

if(mdDoesntcontain)
{
 //This means stock is Unlimiteed so need to set a value for stock
   item.stockquantity = 9999999; (or int.maxValue())
}

Little tricky Posting this as a Block but:

-item.meta_data count = w.e
 -[0]
   -base
     -id = 101231
     -key = "min_max_rules"
     -value = "no"

 -[1]
   -base
     -id = 123131
     -key = "variation_minimum_allowed_quantity"
     -value = ""(this means 1 usually)

public class MetaData
{
    private object preValue;

    [DataMember (EmitDefaultValue = false)]
    public int? id {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public string key {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public object value {
        get;
        set;
    }

Body:
You could use linq Any operation:

foreach (var item in VarProduct)
{
    if (!item.meta_data.Any(m => m.key.Equals("variation_maximum_allowed_quantity")
        || m.key.Equals("maximum_allowed_quantity")))
    {
        item.stockQuantity = int.MaxValue;
    }
}


问:
How to get the value of the last assert statement?
Is there an easy way to get the value of the last assert as boolean so I can avoid asking for it twice?

Example:

```<code>assert 1 == 2
status = ???? # how can i get the boolean value of the previous assert
</code>```

I do not want just as i want the nice reporting feature of assert in pytest

```<code>test = 1 == 2
assert test
</code>```

答:
Try this way:

```<code>def f(test):
  try:
    assert test
  except AssertionError:
    return False
</code>```

You could do:

```<code>f( 1 == 2)
</code>```

Body:
Is there an easy way to get the value of the last assert as boolean so I can avoid asking for it twice?

Example:

assert 1 == 2
status = ???? # how can i get the boolean value of the previous assert

I do not want just as i want the nice reporting feature of assert in pytest

test = 1 == 2
assert test

Body:
Try this way:

def f(test):
  try:
    assert test
  except AssertionError:
    return False

You could do:

f( 1 == 2)


问:
Error when submitting app to iTunes: "Application executable is missing a required architecture"
please i need some help.

I got this message in Organiser when trying to submit my app to iTunes connect: "iPhone/iPod Touch; application executable is missing a required architecture. At least one of the following architecture(s) must be present: armv6 ". There is no problem when building for on a iPhone or simulator.

I use xcode 4

Thank for any help:

答: Check the project build settings "Architectures".  You're likely building with "Optimized armv7" instead of "Standard armv6, armv7".  Your iPhone (3GS or 4) can handle armv7 but I think some of the older devices you may be targeting once you get to iTunes (iPhone 2G/3G, iPod 1G/2G) can't and require armv6.</p>

ContentLicense: CC BY-SA 3.0


问:
How to deal with double quotes in conditional formatting's formula
I was having a look at this question, and in order to help, I wrote a conditional formatting rule, based on this formula:

```<code>="ABS(B3-A3)>=1,5" // the double-quotes are automatically added by Excel
</code>```

This, however, seems not to work, although the formula seems to be correct (in the cell at the right, I asked whether this was true and I got a positive result, as you can see (WAAR is Dutch for true)):

I'm not interested in the final solution, I just want to know how I can debug such a situation: apparantly the formula is true, but still the conditional formatting is not applied. This might mean that:

Something is wrong with the language settings.

Something is wrong with the dot/comma decimal separator.

Something else is wrong with the formula (absolute references, relative references, ...)

How can I, step by step, evaluate the formula, entered in a conditional formatting configuration, in order to see what might be wrong?

Thanks in advance

答: Remove the "" at the beginning and end of your formula. Should do the trick.</p>

Body:
I was having a look at this question, and in order to help, I wrote a conditional formatting rule, based on this formula:

="ABS(B3-A3)>=1,5" // the double-quotes are automatically added by Excel

This, however, seems not to work, although the formula seems to be correct (in the cell at the right, I asked whether this was true and I got a positive result, as you can see (WAAR is Dutch for true)):

I'm not interested in the final solution, I just want to know how I can debug such a situation: apparantly the formula is true, but still the conditional formatting is not applied. This might mean that:

Something is wrong with the language settings.

Something is wrong with the dot/comma decimal separator.

Something else is wrong with the formula (absolute references, relative references, ...)

How can I, step by step, evaluate the formula, entered in a conditional formatting configuration, in order to see what might be wrong?

Thanks in advance


问:
JavaScript not working in Firefox, Chrome - works in IE, Edge
I made this script, that will put a filter on an images. But it only seems to work in Internet explore and in Microsoft Edge.

Can someone maybe guide me in the right direction, to get it working in Google chrome and Firefox?

```<code><html>
<style>
h1 { font-size:2rem; }
p { font-size:1rem; }
canvas { display:block; margin:15px; }
button { margin:15px; }
img { display:block;}
</style>
<script>
function filter() {

  //canvas settings
    var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  var img = document.getElementById("picture");

  //matches the image size to the canvas
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;

  //overfører billedet til canvas
  context.drawImage(img,0,0);

  //Loads data from the image   var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  var data = imageData.data;

  //Runs all the pixel
  for (var i = 0; i < data.length; i += 4) {

    //fetch the RGB values from the pixels
    var red = data[i];
    var green = data[i + 1];
    var blue = data[i + 2];
    // på pladsen i+3 sidder alpha (gennemsigtigheden)

    //FILTER START

        //puts the avarage for red green and blue
        imageData.data[i] = Math.round(red*0.5);
        imageData.data[i+1] = Math.round(green*0.5);
        imageData.data[i+2] = Math.round(blue*0.5);

    }

  // overrides the original image on the canvas
  context.putImageData(imageData, 0, 0);

}

</script>
<body>

  <div align="center">

      <h1>Use a filter</h1>

            <button onclick="filter()">Use filter</button>

      <img src="https://videnskab.dk/files/article_media/golden_gate_bridge.jpg" id='picture'>
       <canvas id="canvas"></div>

  </div>
</body>
</html>
</code>```

答:
This is a crossorigin problem caused by running the webpage from the filesystem. To get round this, try running the page from a webserver, ensuring that the image is served from the same origin, or is served with the relevant CORS headers. Without this, getImageData will fail.

Running through a webserver should get you going again. I use https://fenixwebserver.com/ , a mini desktop webserver that you can point at local folders and start a static file web-server.

Body:
I made this script, that will put a filter on an images. But it only seems to work in Internet explore and in Microsoft Edge.

Can someone maybe guide me in the right direction, to get it working in Google chrome and Firefox?

Use a filter

            <button onclick="filter()">Use filter</button>

       <canvas id="canvas">


问:
Add revocation information to signature using iText7
I am producing Long Term signature. I am trying to add revocation information (Crls, OCSP Responses, Certificate Chain) to the signature as an unsigned attributes but the revocation information is not been embedded in the final signature.
Following is the code snippet:

```<code>        Stream outputStream = new MemoryStream();

        List<byte[]> ocspCollection = new List<byte[]>();
        List<byte[]> crlCollection = new List<byte[]>();
        List<byte[]> certsCollection = new List<byte[]>();

        Stream readerStream = new MemoryStream(signedDocument);
        PdfReader pdfReader = new PdfReader(readerStream);
        PdfSigner pdfSigner = new PdfSigner(pdfReader, outputStream, new StampingProperties().UseAppendMode());

        LtvVerification ltvVerification = new LtvVerification(pdfSigner.GetDocument());

        X509Chain chain = new X509Chain();
        chain.Build(signerCertificate);

        foreach (X509ChainElement item in chain.ChainElements)
        {
            byte[] certBytes = item.Certificate.Export(X509ContentType.Cert);
            certsCollection.Add(certBytes);
        }

        foreach (byte[] ocsp in revocationInfo.OCSPResponses)
        {
            ocspCollection.Add(ocsp);
        }

        foreach (byte[] crlBytes in revocationInfo.CRLs)
        {
            crlCollection.Add(crlBytes);
        }

        bool revocationInfoAdded = ltvVerification.AddVerification(signingRequest.FieldName, ocspCollection, crlCollection, certsCollection);
</code>```

ltvVerification.AddVerification() method returns true in response.

Please find the signed document from below link:
https://1drv.ms/b/s!AvIgyv7xAxxoihGn9aFbe9TQSps4?e=eKPdn8

Any help in this regard is highly appreciated.
Regards

答:
Some working code

You used a PdfSigner (which only makes sense when also applying a signature or document time stamp but you provided only the already signed file) and have some variables I do not have here. Thus, I essentially wrote an example based on a mere PdfDocument and your shared files without those extra variables:

```<code>using (PdfReader pdfReader = new PdfReader("LTV Doc-Revocation Info Issue.pdf"))
using (PdfWriter pdfWriter = new PdfWriter("LTV Doc-Revocation Info Issue-WithRevocation.pdf"))
using (PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter, new StampingProperties().UseAppendMode()))
{
    List<byte[]> ocspCollection = new List<byte[]>();
    List<byte[]> crlCollection = new List<byte[]>();
    List<byte[]> certsCollection = new List<byte[]>();
    ocspCollection.Add(File.ReadAllBytes(@"Ocsp"));
    crlCollection.Add(File.ReadAllBytes(@"Crl.crl"));

    LtvVerification ltvVerification = new LtvVerification(pdfDocument);
    ltvVerification.AddVerification("SH_SIGNATURE_532546", ocspCollection, crlCollection, certsCollection);
    ltvVerification.Merge();
}
</code>```

Inspecting the result one sees:

In particular the provided OCSP response and the provided CRL are embedded in the PDF, so the iText LtvVerification class does its job.

Possible issues in your project

First of all your say:

I am trying to add revocation information (Crls, OCSP Responses, Certificate Chain) to the signature as an unsigned attributes

This already indicates a mismatch: You use the LtvVerification class, and so do I in the working code above. This class does not change the embedded CMS containers. It does not add the revocation information to the unsigned attributes of the embedded CMS container but instead to the DSS (Document Security Store) structure of the PDF.

Embedding revocation data as unsigned attributes of the embedded CMS signature container actually is not possible in an interoperable way: You either use the signed adbe-revocationInfoArchival attribute in the CMS container or the DSS outside of the CMS container.

(Some validators accept revocation data embedded CAdES-style in the unsigned attributes but strictly speaking that is forbidden in PAdES and not interoperable in PDF 2.0.)

So if you actually want to embed the revocation data in the CMS container, provide them to the PdfSigner signing method of your choice, they all explicitly or implicitly accept revocation data to embed,

```<code>public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain,
    ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
    int estimatedSize, PdfSigner.CryptoStandard sigtype)

public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain,
    ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
    int estimatedSize, PdfSigner.CryptoStandard sigtype, SignaturePolicyInfo signaturePolicy)

public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain,
    ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
    int estimatedSize, PdfSigner.CryptoStandard sigtype, SignaturePolicyIdentifier signaturePolicy)
</code>```

or

```<code>public virtual void SignExternalContainer(IExternalSignatureContainer externalSignatureContainer,
    int estimatedSize)
</code>```

The former three explicitly accept CRL and OCSP clients (which can be implemented to provide pre-existing CRLs and OCSPs) while the latter gets the full CMS container from the given IExternalSignatureContainer implementation, so in that implementation you can add any information to it you want.

Body:
I am producing Long Term signature. I am trying to add revocation information (Crls, OCSP Responses, Certificate Chain) to the signature as an unsigned attributes but the revocation information is not been embedded in the final signature.
Following is the code snippet:

        Stream outputStream = new MemoryStream();

        List<byte[]> ocspCollection = new List<byte[]>();
        List<byte[]> crlCollection = new List<byte[]>();
        List<byte[]> certsCollection = new List<byte[]>();

        Stream readerStream = new MemoryStream(signedDocument);
        PdfReader pdfReader = new PdfReader(readerStream);
        PdfSigner pdfSigner = new PdfSigner(pdfReader, outputStream, new StampingProperties().UseAppendMode());

        LtvVerification ltvVerification = new LtvVerification(pdfSigner.GetDocument());

        X509Chain chain = new X509Chain();
        chain.Build(signerCertificate);

        foreach (X509ChainElement item in chain.ChainElements)
        {
            byte[] certBytes = item.Certificate.Export(X509ContentType.Cert);
            certsCollection.Add(certBytes);
        }

        foreach (byte[] ocsp in revocationInfo.OCSPResponses)
        {
            ocspCollection.Add(ocsp);
        }

        foreach (byte[] crlBytes in revocationInfo.CRLs)
        {
            crlCollection.Add(crlBytes);
        }

        bool revocationInfoAdded = ltvVerification.AddVerification(signingRequest.FieldName, ocspCollection, crlCollection, certsCollection);

ltvVerification.AddVerification() method returns true in response.

Please find the signed document from below link:
https://1drv.ms/b/s!AvIgyv7xAxxoihGn9aFbe9TQSps4?e=eKPdn8

Any help in this regard is highly appreciated.
Regards

Body:
Some working code

You used a PdfSigner (which only makes sense when also applying a signature or document time stamp but you provided only the already signed file) and have some variables I do not have here. Thus, I essentially wrote an example based on a mere PdfDocument and your shared files without those extra variables:

using (PdfReader pdfReader = new PdfReader("LTV Doc-Revocation Info Issue.pdf"))
using (PdfWriter pdfWriter = new PdfWriter("LTV Doc-Revocation Info Issue-WithRevocation.pdf"))
using (PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter, new StampingProperties().UseAppendMode()))
{
    List<byte[]> ocspCollection = new List<byte[]>();
    List<byte[]> crlCollection = new List<byte[]>();
    List<byte[]> certsCollection = new List<byte[]>();
    ocspCollection.Add(File.ReadAllBytes(@"Ocsp"));
    crlCollection.Add(File.ReadAllBytes(@"Crl.crl"));

    LtvVerification ltvVerification = new LtvVerification(pdfDocument);
    ltvVerification.AddVerification("SH_SIGNATURE_532546", ocspCollection, crlCollection, certsCollection);
    ltvVerification.Merge();
}

Inspecting the result one sees:

In particular the provided OCSP response and the provided CRL are embedded in the PDF, so the iText LtvVerification class does its job.

Possible issues in your project

First of all your say:

I am trying to add revocation information (Crls, OCSP Responses, Certificate Chain) to the signature as an unsigned attributes

This already indicates a mismatch: You use the LtvVerification class, and so do I in the working code above. This class does not change the embedded CMS containers. It does not add the revocation information to the unsigned attributes of the embedded CMS container but instead to the DSS (Document Security Store) structure of the PDF.

Embedding revocation data as unsigned attributes of the embedded CMS signature container actually is not possible in an interoperable way: You either use the signed adbe-revocationInfoArchival attribute in the CMS container or the DSS outside of the CMS container.

(Some validators accept revocation data embedded CAdES-style in the unsigned attributes but strictly speaking that is forbidden in PAdES and not interoperable in PDF 2.0.)

So if you actually want to embed the revocation data in the CMS container, provide them to the PdfSigner signing method of your choice, they all explicitly or implicitly accept revocation data to embed,

public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain,
    ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
    int estimatedSize, PdfSigner.CryptoStandard sigtype)

public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain,
    ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
    int estimatedSize, PdfSigner.CryptoStandard sigtype, SignaturePolicyInfo signaturePolicy)

public virtual void SignDetached(IExternalSignature externalSignature, X509Certificate[] chain,
    ICollection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
    int estimatedSize, PdfSigner.CryptoStandard sigtype, SignaturePolicyIdentifier signaturePolicy)

or

public virtual void SignExternalContainer(IExternalSignatureContainer externalSignatureContainer,
    int estimatedSize)

The former three explicitly accept CRL and OCSP clients (which can be implemented to provide pre-existing CRLs and OCSPs) while the latter gets the full CMS container from the given IExternalSignatureContainer implementation, so in that implementation you can add any information to it you want.


问:
How to group and aggregate in pandas
I have df like this.
this value is projected values so that many columns exist.

```<code>Customer seg value0  value1
A         a   10      60
A         b   20      50
A         c   30      40
B         a   40      30
B         b   50      20
B         c   60      10
</code>```

I would like to calculate value by referring to seg columns.

a-b-c ( a minus b minus c)

in each customers

```<code>customer value0 value1
A        -40     -30
B        -70      0
</code>```

How can I calculate each values by grouping customers.

df.groupby(customer)

Thanks

答:
Another approach : Use numpy subtract, combined with reduce:

```<code>(df.groupby('Customer')
   .agg(value0=('value0',np.subtract.reduce),
        value1=('value1',np.subtract.reduce))
 )

          value0    value1
Customer
A          -40  -30
B          -70  0
</code>```

numpy reduce

numpy subtract

Title: How to group and aggregate in pandas

Body:
I have df like this.
this value is projected values so that many columns exist.

Customer seg value0  value1
A         a   10      60
A         b   20      50
A         c   30      40
B         a   40      30
B         b   50      20
B         c   60      10

I would like to calculate value by referring to seg columns.

a-b-c ( a minus b minus c)

in each customers

customer value0 value1
A        -40     -30
B        -70      0

How can I calculate each values by grouping customers.

df.groupby(customer)

Thanks

Body:
Another approach : Use numpy subtract, combined with reduce:

(df.groupby('Customer')
   .agg(value0=('value0',np.subtract.reduce),
        value1=('value1',np.subtract.reduce))
 )

          value0    value1
Customer
A          -40  -30
B          -70  0

numpy reduce

numpy subtract


问:
Spring Data Hibernate: N+1 problem and pagination
TL;DR -- I cannot find a way to solve the N+1 problem while doing pagination at the same time.

My Entities:

```<code>@Entity
public class Invoice {

    @Id
    @JsonView(InvoiceView.ShortView.class)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

// other stuff

    @OneToMany(targetEntity = InvoiceItem.class)
    @JoinColumn(name = "invoice")
    private List<InvoiceItem> items;
}

@Entity
public class InvoiceItem {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

// other stuff
}

</code>```

My repository:

```<code>    @EntityGraph(attributePaths = {"vendor","items"})
    @Query(value = "select i from Invoice i where i.status=:status")
    Page<Invoice> getInvoicesWithItemsByStatus(@Param("status") Status status, Pageable pageSpec);
</code>```

or

```<code>        @Query(value = "select i from Invoice i join fetch i.items join fetch i.vendor where i.status=:status",
            countQuery = "select count(i) from Invoice i where i.status=:status")
    Page<Invoice> getInvoicesWithItemsByStatus(@Param("status") Status status, Pageable pageSpec);
</code>```

Both of these produce this Hibernate warning:

```<code>HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!
</code>```

and they do just that: fetch everything and give back the page requested. Every time a new page is requested, naturally.

答:
Your problem and how to solve it is described in this article by Vlad Mihalcea

https://vladmihalcea.com/fix-hibernate-hhh000104-entity-fetch-pagination-warning-message/

Basically, you would need to write a native query.

Body:
TL;DR -- I cannot find a way to solve the N+1 problem while doing pagination at the same time.

My Entities:

@Entity
public class Invoice {

    @Id
    @JsonView(InvoiceView.ShortView.class)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

// other stuff

    @OneToMany(targetEntity = InvoiceItem.class)
    @JoinColumn(name = "invoice")
    private List<InvoiceItem> items;
}

@Entity
public class InvoiceItem {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

// other stuff
}

My repository:

    @EntityGraph(attributePaths = {"vendor","items"})
    @Query(value = "select i from Invoice i where i.status=:status")
    Page<Invoice> getInvoicesWithItemsByStatus(@Param("status") Status status, Pageable pageSpec);

or

        @Query(value = "select i from Invoice i join fetch i.items join fetch i.vendor where i.status=:status",
            countQuery = "select count(i) from Invoice i where i.status=:status")
    Page<Invoice> getInvoicesWithItemsByStatus(@Param("status") Status status, Pageable pageSpec);

Both of these produce this Hibernate warning:

HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!

and they do just that: fetch everything and give back the page requested. Every time a new page is requested, naturally.


问:
Configuring nginx to server assets files in angular
I'm getting data from assets folder. On my local machine, I'm able to get the data with this url:

http://localhost:4200/assets/data.json

But when I deploy my app using docker in a VM, I'm getting an HTTP 404 error.

The HTTP request:

```<code>http://192.168.xxx.xxx:22/assets/data.json
</code>```

Error:

```<code><html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.17.7</center>
</body>
</code>```

Here's my docker file

```<code>FROM node:alpine AS builder

WORKDIR /app
COPY . .
FROM nginx:alpine

COPY --from=builder /app/dist/proj/* /usr/share/nginx/html/
</code>```

I figured out that I should also add an nginx config file  like in this example

I would like how to configue in my case nginx to serve asset files

答:
I have found the solution.

My issue is that I was the * in /app/dist/proj/* , the command copy all files in the same directory level  in my case in html instead of keeping files in a subdirectory assets

I removed *and that worked fine

Body:
I'm getting data from assets folder. On my local machine, I'm able to get the data with this url:

http://localhost:4200/assets/data.json

But when I deploy my app using docker in a VM, I'm getting an HTTP 404 error.

The HTTP request:

http://192.168.xxx.xxx:22/assets/data.json

Error:

<title>404 Not Found</title>

404 Not Found

nginx/1.17.7

Here's my docker file

FROM node:alpine AS builder

WORKDIR /app
COPY . .
FROM nginx:alpine

COPY --from=builder /app/dist/proj/* /usr/share/nginx/html/

I figured out that I should also add an nginx config file  like in this example

I would like how to configue in my case nginx to serve asset files


问:
App works on Debug mode, but not work on Release mode
I have an application and now I'm going to release it.
I've created an apk file, and installed it but when I send login request to the server, It returns null..

Weird thing is that when I launch my application with debug build, It works fine. The problem happens on release mode only. So I thought the problem is from proguard after reading this article

Here's what I've done so far.

Added all proguard rules that is needed. (Retrofit, Okhttp3, Glide) - Not worked.

Create an apk with [Build apk(s)] in Build menu and test it - Worked but it is debug.

Any help would be appreciated...

This is my build.gradle file.

```<code>defaultConfig {
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:recyclerview-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:design:$rootProject.supportLibraryVersion"
    implementation "com.android.support:cardview-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:gridlayout-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:animated-vector-drawable:$rootProject.supportLibraryVersion"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.2'
    implementation 'com.squareup:otto:1.3.8'
    implementation 'com.github.nisrulz:recyclerviewhelper:26.0.0'
    implementation 'jp.wasabeef:recyclerview-animators:2.2.7'
    implementation 'com.github.ittianyu:BottomNavigationViewEx:1.2.4'
    implementation 'com.blankj:utilcode:1.9.6'
    implementation 'com.github.bumptech.glide:glide:4.3.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
    implementation 'com.j256.ormlite:ormlite-core:5.0'
    implementation 'com.j256.ormlite:ormlite-android:5.0'
    implementation 'io.github.luizgrp.sectionedrecyclerviewadapter:sectionedrecyclerviewadapter:1.1.3'
    implementation 'com.akexorcist:RoundCornerProgressBar:2.0.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
    implementation 'com.daimajia.easing:library:2.0@aar'
    implementation 'com.daimajia.androidanimations:library:2.3@aar'
    implementation files('libs/opencsv-3.8.jar')
    implementation('tk.zielony:carbon:0.15.0.1') {
        exclude group: 'com.android.support', module: 'animated-vector-drawable'
        exclude group: 'com.android.support', module: 'gridlayout-v7'
    }
    implementation 'com.github.QuadFlask:colorpicker:0.0.13'
    implementation 'com.android.support:multidex:1.0.2'
    implementation 'com.fasterxml.jackson.core:jackson-core:2.7.3'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
    implementation 'com.liulishuo.filedownloader:library:1.6.9'
    implementation 'org.jsoup:jsoup:1.11.2'
    implementation project(':typekit')
    implementation 'com.loopj.android:android-async-http:1.4.9'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    compile('com.crashlytics.sdk.android:crashlytics:2.9.0@aar') {
        transitive = true;
    }
}
</code>```

And here is my proguard-rules.pro file.

```<code>-dontwarn com.google.android.gms.common.GooglePlayServicesUtil

-ignorewarnings
-keep class * {
    public private *;
}
# Retrofit
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain service method parameters.
-keepclassmembernames,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}
# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
# OkHttp 3
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.

# Glide

-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}
</code>```

答:
I added the below line in gradle.properties and it worked smoothly after that.

```<code>android.enableR8 = false
</code>```

Body:
I have an application and now I'm going to release it.
I've created an apk file, and installed it but when I send login request to the server, It returns null..

Weird thing is that when I launch my application with debug build, It works fine. The problem happens on release mode only. So I thought the problem is from proguard after reading this article

Here's what I've done so far.

Added all proguard rules that is needed. (Retrofit, Okhttp3, Glide) - Not worked.

Create an apk with [Build apk(s)] in Build menu and test it - Worked but it is debug.

Any help would be appreciated...

This is my build.gradle file.

defaultConfig {
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:recyclerview-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:design:$rootProject.supportLibraryVersion"
    implementation "com.android.support:cardview-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:gridlayout-v7:$rootProject.supportLibraryVersion"
    implementation "com.android.support:animated-vector-drawable:$rootProject.supportLibraryVersion"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.2'
    implementation 'com.squareup:otto:1.3.8'
    implementation 'com.github.nisrulz:recyclerviewhelper:26.0.0'
    implementation 'jp.wasabeef:recyclerview-animators:2.2.7'
    implementation 'com.github.ittianyu:BottomNavigationViewEx:1.2.4'
    implementation 'com.blankj:utilcode:1.9.6'
    implementation 'com.github.bumptech.glide:glide:4.3.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
    implementation 'com.j256.ormlite:ormlite-core:5.0'
    implementation 'com.j256.ormlite:ormlite-android:5.0'
    implementation 'io.github.luizgrp.sectionedrecyclerviewadapter:sectionedrecyclerviewadapter:1.1.3'
    implementation 'com.akexorcist:RoundCornerProgressBar:2.0.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
    implementation 'com.daimajia.easing:library:2.0@aar'
    implementation 'com.daimajia.androidanimations:library:2.3@aar'
    implementation files('libs/opencsv-3.8.jar')
    implementation('tk.zielony:carbon:0.15.0.1') {
        exclude group: 'com.android.support', module: 'animated-vector-drawable'
        exclude group: 'com.android.support', module: 'gridlayout-v7'
    }
    implementation 'com.github.QuadFlask:colorpicker:0.0.13'
    implementation 'com.android.support:multidex:1.0.2'
    implementation 'com.fasterxml.jackson.core:jackson-core:2.7.3'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
    implementation 'com.liulishuo.filedownloader:library:1.6.9'
    implementation 'org.jsoup:jsoup:1.11.2'
    implementation project(':typekit')
    implementation 'com.loopj.android:android-async-http:1.4.9'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    compile('com.crashlytics.sdk.android:crashlytics:2.9.0@aar') {
        transitive = true;
    }
}

And here is my proguard-rules.pro file.

-dontwarn com.google.android.gms.common.GooglePlayServicesUtil

-ignorewarnings
-keep class * {
    public private *;
}
# Retrofit
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain service method parameters.
-keepclassmembernames,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}
# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
# OkHttp 3
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.

# Glide

-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

Body:
I added the below line in gradle.properties and it worked smoothly after that.

android.enableR8 = false


问:
AFNetworking 3.0 multipart/form-data API call without file gives error
I am attaching the screenshot of Postman

Using postman I am getting successful response. But I am not able to get same response using AFNetworking library. Following is my sample code.

```<code>- (void)updateActivityQuantity:(NSDictionary *)quantityDic{
    NSString *strURL = [NSString stringWithFormat:@"%@/%@", MAINTAIN_BASEURL,JobDetailCommonURL];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    NSURLSessionTask *task = [manager POST:strURL parameters:quantityDic constructingBodyWithBlock:nil  progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"responseObject = %@", responseObject);
    } failure:^(NSURLSessionTask *task, NSError *error) {
        NSLog(@"error = %@", error);
    }];

    if (!task) {
        NSLog(@"Creation of task failed.");
    }
}
</code>```

How can I successful response using AFNetworking?

答:
You should not serialize your request manager for JSON. You can serialize your manager for multipart form-data like this

```<code>[manager.requestSerializer setValue:@"multipart/form-data; boundary=something" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
</code>```

And you need to serialize & encode your 'events' key's value as string if you didn't do it earlier like bellow, since it's a JSON object and add it to your quantityDic dictionary.

```<code>NSDictionary *events = @[@{@"event_time": @"564545454", ....}];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
</code>```

Body:
I am attaching the screenshot of Postman

Using postman I am getting successful response. But I am not able to get same response using AFNetworking library. Following is my sample code.

- (void)updateActivityQuantity:(NSDictionary *)quantityDic{
    NSString *strURL = [NSString stringWithFormat:@"%@/%@", MAINTAIN_BASEURL,JobDetailCommonURL];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    NSURLSessionTask *task = [manager POST:strURL parameters:quantityDic constructingBodyWithBlock:nil  progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"responseObject = %@", responseObject);
    } failure:^(NSURLSessionTask *task, NSError *error) {
        NSLog(@"error = %@", error);
    }];

    if (!task) {
        NSLog(@"Creation of task failed.");
    }
}

How can I successful response using AFNetworking?

Body:
You should not serialize your request manager for JSON. You can serialize your manager for multipart form-data like this

[manager.requestSerializer setValue:@"multipart/form-data; boundary=something" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];

And you need to serialize & encode your 'events' key's value as string if you didn't do it earlier like bellow, since it's a JSON object and add it to your quantityDic dictionary.

NSDictionary *events = @[@{@"event_time": @"564545454", ....}];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


问:
CPP how to escape a quotation mark
I'm in the process of making code from 1991 work on Ubuntu 19.

I've got this file I need to run through CPP where I am forced to use the -traditional option.

```<code>#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6
Trade types = "+ITEM_WEAPON+ITEM_FIREWEAPON+"
</code>```

I want the line to become

```<code>Trade types = "+5+6+"
</code>```

This worked just fine in 1991-1997 ;-) It seems cpp for obvious reasons no longer parse between quotation marks.

I've tried to escape the quotes using the backslash character e.g.

```<code>Trade types = \""+ITEM_WEAPON+ITEM_FIREWEAPON+\""
</code>```

But still haven't found a good solution.

For clarity this is not a C program, instead we simply used cpp to expand various macros into a structured text file which was later run through a parser.

The closest I have come (with -traditional flag) to something that almost works is this:

```<code>#define WI 1
#define WJ 2

#define T(a,b) Trade types = "+a+b+"
T(1,2)
T(WI,WJ)
</code>```

Which outputs:

```<code>Trade types = "+1+2+"
Trade types = "+WI+WJ+"
</code>```

So the pre-processor does substitute the arguments between the quotes but does not expand the parametized macro.

答:
With more macros you can do that:

```<code>#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

#define MAKESTRING2(s) #s
#define MAKESTRING(s) MAKESTRING2(s)

Trade types = "+" MAKESTRING(ITEM_WEAPON) "+" MAKESTRING(ITEM_FIREWEAPON) "+";
</code>```

But I also would try avoiding macros:

```<code>#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

const std::string types = "+" + std::to_string(ITEM_WEAPON) +  "+" + std::to_string(ITEM_FIREWEAPON) + "+";
</code>```

Or even better:

```<code>constexpr int ITEM_WEAPON = 5;
constexpr int ITEM_FIREWEAPON = 6;

const std::string types = "+" + std::to_string(ITEM_WEAPON) +  "+" + std::to_string(ITEM_FIREWEAPON) + "+";
</code>```

Title: CPP how to escape a quotation mark

Body:
I'm in the process of making code from 1991 work on Ubuntu 19.

I've got this file I need to run through CPP where I am forced to use the -traditional option.

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6
Trade types = "+ITEM_WEAPON+ITEM_FIREWEAPON+"

I want the line to become

Trade types = "+5+6+"

This worked just fine in 1991-1997 ;-) It seems cpp for obvious reasons no longer parse between quotation marks.

I've tried to escape the quotes using the backslash character e.g.

Trade types = \""+ITEM_WEAPON+ITEM_FIREWEAPON+\""

But still haven't found a good solution.

For clarity this is not a C program, instead we simply used cpp to expand various macros into a structured text file which was later run through a parser.

The closest I have come (with -traditional flag) to something that almost works is this:

#define WI 1
#define WJ 2

#define T(a,b) Trade types = "+a+b+"
T(1,2)
T(WI,WJ)

Which outputs:

Trade types = "+1+2+"
Trade types = "+WI+WJ+"

So the pre-processor does substitute the arguments between the quotes but does not expand the parametized macro.

Body:
With more macros you can do that:

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

#define MAKESTRING2(s) #s
#define MAKESTRING(s) MAKESTRING2(s)

Trade types = "+" MAKESTRING(ITEM_WEAPON) "+" MAKESTRING(ITEM_FIREWEAPON) "+";

But I also would try avoiding macros:

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

const std::string types = "+" + std::to_string(ITEM_WEAPON) +  "+" + std::to_string(ITEM_FIREWEAPON) + "+";

Or even better:

constexpr int ITEM_WEAPON = 5;
constexpr int ITEM_FIREWEAPON = 6;

const std::string types = "+" + std::to_string(ITEM_WEAPON) +  "+" + std::to_string(ITEM_FIREWEAPON) + "+";


问:
Ruby on Rails server setup
I'm trying to deploy ROR application to Ubuntu server(EC2).
I'm using following versions:

Ruby : 2.4.0p0

Rails : 4.2.8

Bundler : 1.17.3

*For some reason my colleague has created a gemset instead of normal setup.

gem env is:

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.8
  - RUBY VERSION: 2.4.0 (2016-12-24 patchlevel 0) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
  - USER INSTALLATION DIRECTORY: /home/ubuntu/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin/ruby
  - EXECUTABLE DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
  - SPEC CACHE DIRECTORY: /home/ubuntu/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global/bin
     - /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin
     - /home/ubuntu/.rvm/bin
     - /home/ubuntu/bin
     - /home/ubuntu/.local/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin

</code>```

I did the setup of nginx and passenger and set the root paths.

nginx version: nginx/1.17.3

Phusion Passenger : 6.0.4

I believe there is nothing wrong with nginx and passenger's settings but I'm getting following error:
The Phusion Passenger application server tried to start the web application. But the application itself (and not Passenger) encountered an internal error.

Error details:

```<code>cannot load such file -- bundler/setup (LoadError)
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'
</code>```

The stdout/stderr output of the subprocess so far is:

```<code> [passenger_native_support.so] trying to compile for the current user (nobody) and Ruby interpreter...
     (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
     Warning: compilation didn't succeed. To learn why, read this file:
     /tmp/passenger_native_support-18gfm98.log
 [passenger_native_support.so] finding downloads for the current Ruby interpreter...
     (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
     Could not download https://github.com/phusion/passenger/releases/download/release-6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://oss-binaries.phusionpassenger.com/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://s3.amazonaws.com/phusion-passenger/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 403 Forbidden
 [passenger_native_support.so] will not be used (can't compile or download)
  --> Passenger will still operate normally.
Error: The application encountered the following error: cannot load such file -- bundler/setup (LoadError)
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'
</code>```

Does anybody has any idea?

答:
Most probably the point is in that you're setting up and testing rvm/ruby under ubuntu user, but nginx server is running under some other user (which does not have rvm configured, at least in the session in which the daemon runs)

RVM has ability to create a wrapper, that will set correct paths and gemset (if needed):

rvm alias create ruby_for_my_app ruby-2.4.0@myrepo
```

and then use /home/ubuntu/.rvm/wrappers/ruby_for_my_app/ruby in passenger_ruby nginx config directive (remember to reload it after changing)

Title: Ruby on Rails server setup

Body:
I'm trying to deploy ROR application to Ubuntu server(EC2).
I'm using following versions:

Ruby : 2.4.0p0

Rails : 4.2.8

Bundler : 1.17.3

*For some reason my colleague has created a gemset instead of normal setup.

gem env is:

RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.8
  - RUBY VERSION: 2.4.0 (2016-12-24 patchlevel 0) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
  - USER INSTALLATION DIRECTORY: /home/ubuntu/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin/ruby
  - EXECUTABLE DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
  - SPEC CACHE DIRECTORY: /home/ubuntu/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global/bin
     - /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin
     - /home/ubuntu/.rvm/bin
     - /home/ubuntu/bin
     - /home/ubuntu/.local/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin

I did the setup of nginx and passenger and set the root paths.

nginx version: nginx/1.17.3

Phusion Passenger : 6.0.4

I believe there is nothing wrong with nginx and passenger's settings but I'm getting following error:
The Phusion Passenger application server tried to start the web application. But the application itself (and not Passenger) encountered an internal error.

Error details:

cannot load such file -- bundler/setup (LoadError)
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `'

The stdout/stderr output of the subprocess so far is:

 [passenger_native_support.so] trying to compile for the current user (nobody) and Ruby interpreter...
     (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
     Warning: compilation didn't succeed. To learn why, read this file:
     /tmp/passenger_native_support-18gfm98.log
 [passenger_native_support.so] finding downloads for the current Ruby interpreter...
     (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
     Could not download https://github.com/phusion/passenger/releases/download/release-6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://oss-binaries.phusionpassenger.com/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://s3.amazonaws.com/phusion-passenger/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 403 Forbidden
 [passenger_native_support.so] will not be used (can't compile or download)
  --> Passenger will still operate normally.
Error: The application encountered the following error: cannot load such file -- bundler/setup (LoadError)
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `'

Does anybody has any idea?

Body:
Most probably the point is in that you're setting up and testing rvm/ruby under ubuntu user, but nginx server is running under some other user (which does not have rvm configured, at least in the session in which the daemon runs)

RVM has ability to create a wrapper, that will set correct paths and gemset (if needed):

rvm alias create ruby_for_my_app ruby-2.4.0@myrepo

and then use /home/ubuntu/.rvm/wrappers/ruby_for_my_app/ruby in passenger_ruby nginx config directive (remember to reload it after changing)


问:
How to handle error for response Type blob in HttpRequest
I am calling an http request using httpClient and using response Type as 'blob' but the problem is when it goes in error block the response type remains 'blob'.This is causing problem with my error handling.

```<code>this.httpClient.get('http://m502126:3000/reports/perdate', {
observe: 'body',
responseType: 'blob',
params: new HttpParams().set('START_DATE', startDate)
 .set('END_DATE', endDate)
 .set('MIXER', mixer)
 .set('ATTACH', 'true')

 }).subscribe(data => {
 console.log(data);
},
error => {
 console.log(error);

}

)
</code>```

the problem is i am setting request type as'blob' and type of error is any . So when error comes and goes in error block the response type remains 'blob'.
How to handle this ?

答:
If you're usung RxJS you can use something like this:

```<code>catchError((response: HttpErrorResponse) => {
  return !!this.isBlobError(response) ? this.parseErrorBlob(response) : throwError(response);
})
</code>```

and after that you can chain other catchError and do your stuff.

Here are the methods:

```<code>isBlobError(err: any) {
  return err instanceof HttpErrorResponse && err.error instanceof Blob && err.error.type === 'application/json';
}

parseErrorBlob(err: HttpErrorResponse): Observable<any> {
  const reader: FileReader = new FileReader();
  const obs = new Observable((observer: any) => {
    reader.onloadend = (e) => {
      observer.error(new HttpErrorResponse({
        ...err,
        error: JSON.parse(reader.result as string),
      }));
      observer.complete();
    };
  });
  reader.readAsText(err.error);
  return obs;
}
</code>```

Body:
I am calling an http request using httpClient and using response Type as 'blob' but the problem is when it goes in error block the response type remains 'blob'.This is causing problem with my error handling.

this.httpClient.get('http://m502126:3000/reports/perdate', {
observe: 'body',
responseType: 'blob',
params: new HttpParams().set('START_DATE', startDate)
 .set('END_DATE', endDate)
 .set('MIXER', mixer)
 .set('ATTACH', 'true')

 }).subscribe(data => {
 console.log(data);
},
error => {
 console.log(error);

}

)

the problem is i am setting request type as'blob' and type of error is any . So when error comes and goes in error block the response type remains 'blob'.
How to handle this ?

Body:
If you're usung RxJS you can use something like this:

catchError((response: HttpErrorResponse) => {
  return !!this.isBlobError(response) ? this.parseErrorBlob(response) : throwError(response);
})

and after that you can chain other catchError and do your stuff.

Here are the methods:

isBlobError(err: any) {
  return err instanceof HttpErrorResponse && err.error instanceof Blob && err.error.type === 'application/json';
}

parseErrorBlob(err: HttpErrorResponse): Observable<any> {
  const reader: FileReader = new FileReader();
  const obs = new Observable((observer: any) => {
    reader.onloadend = (e) => {
      observer.error(new HttpErrorResponse({
        ...err,
        error: JSON.parse(reader.result as string),
      }));
      observer.complete();
    };
  });
  reader.readAsText(err.error);
  return obs;
}


答:
Select the whole range (for the example A2:B5)

Add in conditional formatting formula =ABS($B3-$A3)>=1.5

Result:

Title: How to deal with double quotes in conditional formatting's formula

Body:
I was having a look at this question, and in order to help, I wrote a conditional formatting rule, based on this formula:

="ABS(B3-A3)>=1,5" // the double-quotes are automatically added by Excel

This, however, seems not to work, although the formula seems to be correct (in the cell at the right, I asked whether this was true and I got a positive result, as you can see (WAAR is Dutch for true)):

I'm not interested in the final solution, I just want to know how I can debug such a situation: apparantly the formula is true, but still the conditional formatting is not applied. This might mean that:

Something is wrong with the language settings.

Something is wrong with the dot/comma decimal separator.

Something else is wrong with the formula (absolute references, relative references, ...)

How can I, step by step, evaluate the formula, entered in a conditional formatting configuration, in order to see what might be wrong?

Thanks in advance


答:
I think you want:</p>

```<code>select x.*,
       sum (case when prev_ld > log_date - interval '24 hour'
                 then 0 else 1
            end) over (partition by unique_customer_id
                       order by log_date
                       rows unbounded preceding
                      )  as customer_trxn_cnt
from (select x.*,
             lag(log_date, 1) over (partition by unique_customer_id order by log_date) as prev_ld
      from x
     ) x
order by unique_customer_id, log_date;
</code>```

Title: Partitioning customer id on timestamp based on date differences

Body:
I want to get a rank/row_number for each customer but keep the rank the same if subsequent transactions are made within 24 hours.

This is what I've tried to do:

with x as (
    select 214142446 as unique_customer_id, 19331177 as transaction_id, to_timestamp('26/04/2017 11:28:01', 'DD/MM/YYYY HH24:MI:SS') as log_date union all
    select 214142446, 1193324450, to_timestamp('26/04/2017  12:29:50', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1193327391, to_timestamp('26/04/2017  12:42:17', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1194753492, to_timestamp('03/05/2017  14:56:33', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1198679862, to_timestamp('23/05/2017  11:11:46', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1198893043, to_timestamp('24/05/2017  11:23:33', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1198948574, to_timestamp('24/05/2017  16:12:35', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1198952915, to_timestamp('24/05/2017  17:04:10', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1200182526, to_timestamp('30/05/2017  14:23:43', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1202206887, to_timestamp('07/06/2017  14:19:33', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1202163318, to_timestamp('08/06/2017  13:04:01', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1203934169, to_timestamp('14/06/2017  17:08:58', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1205508321, to_timestamp('20/06/2017  13:05:00', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1205541102, to_timestamp('20/06/2017  14:35:41', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1205562693, to_timestamp('20/06/2017  15:58:01', 'DD/MM/YYYY HH24:MI:SS') union all
    select 214142446, 1206273894, to_timestamp('23/06/2017  10:18:45', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1231603750, to_timestamp('06/10/2017  13:47:20', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1231697368, to_timestamp('07/10/2017  12:34:08', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1231699273, to_timestamp('07/10/2017  12:46:01', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1231699882, to_timestamp('07/10/2017  12:52:28', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1231975996, to_timestamp('09/10/2017  20:06:47', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232073502, to_timestamp('10/10/2017  17:05:06', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232074795, to_timestamp('10/10/2017  17:15:16', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232250513, to_timestamp('12/10/2017  09:15:41', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232251114, to_timestamp('12/10/2017  09:21:43', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232371321, to_timestamp('13/10/2017  11:50:36', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232391230, to_timestamp('13/10/2017  15:07:00', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232392844, to_timestamp('13/10/2017  15:23:44', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232450858, to_timestamp('14/10/2017  08:43:02', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232451164, to_timestamp('14/10/2017  08:51:17', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232755473, to_timestamp('17/10/2017  09:11:38', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 1232766588, to_timestamp('17/10/2017  11:15:38', 'DD/MM/YYYY HH24:MI:SS') union all
    select 2115686902, 232989319, to_timestamp('19/10/2017  13:42:25', 'DD/MM/YYYY HH24:MI:SS')
)
select *
    , sum (case when hour_diff > 24 then 1 else 0 end)
     over (partition by unique_customer_id order by log_date rows unbounded preceding) + 1 as customer_trxn_cnt
from (
    select *
    , datediff(hour, lag(log_date, 1) over (partition by unique_customer_id order by log_date)::timestamp, log_date::timestamp) as hour_diff
    from x
    )
order by unique_customer_id, log_date
;

The problem with this is that it only considers the previous transaction log_date when determining whether or not to keep the rank the same. I'm looking for the output to group transactions made within 24 hours of each other and assign the same rank to them:

unique_customer_id|booking_id|to_timestamp       |customer_trxn_cnt|
------------------|----------|-------------------|-----------------|
           4142446|  19331177|2017-04-26 12:28:01|                1|
           4142446|  19332445|2017-04-26 13:29:50|                1|
           4142446|  19332739|2017-04-26 13:42:17|                1|
           4142446|  19475349|2017-05-03 15:56:33|                2|
           4142446|  19867986|2017-05-23 12:11:46|                3|
           4142446|  19889304|2017-05-24 12:23:33|                4|
           4142446|  19894857|2017-05-24 17:12:35|                4|
           4142446|  19895291|2017-05-24 18:04:10|                4|
           4142446|  20018252|2017-05-30 15:23:43|                5|
           4142446|  20220688|2017-06-07 15:19:33|                6|
           4142446|  20216331|2017-06-08 14:04:01|                6|
           4142446|  20393416|2017-06-14 18:08:58|                7|
           4142446|  20550832|2017-06-20 14:05:00|                8|
           4142446|  20554110|2017-06-20 15:35:41|                8|
           4142446|  20556269|2017-06-20 16:58:01|                8|
           4142446|  20627389|2017-06-23 11:18:45|                9|
          15686902|  23160370|2017-10-06 14:47:20|                1|
          15686902|  23169738|2017-10-07 13:34:08|                1|
          15686902|  23169923|2017-10-07 13:46:01|                1|
          15686902|  23169982|2017-10-07 13:52:28|                1|
          15686902|  23197596|2017-10-09 21:06:47|                2|
          15686902|  23207352|2017-10-10 18:05:06|                2|
          15686902|  23207475|2017-10-10 18:15:16|                3|
          15686902|  23225053|2017-10-12 10:15:41|                4|
          15686902|  23225114|2017-10-12 10:21:43|                4|
          15686902|  23237131|2017-10-13 12:50:36|                5|
          15686902|  23239120|2017-10-13 16:07:00|                5|
          15686902|  23239284|2017-10-13 16:23:44|                5|
          15686902|  23245088|2017-10-14 09:43:02|                6|
          15686902|  23245114|2017-10-14 09:51:17|                6|
          15686902|  23275543|2017-10-17 10:11:38|                7|
          15686902|  23276658|2017-10-17 12:15:38|                7|
          15686902|  23298931|2017-10-19 14:42:25|                8|

Was thinking a cumulative sum of hour_diff resetting when it reaches over 24 and then doing a row_number() against that?
Any help would be much appreciated.

Body:
I think you want:

select x.*,
       sum (case when prev_ld > log_date - interval '24 hour'
                 then 0 else 1
            end) over (partition by unique_customer_id
                       order by log_date
                       rows unbounded preceding
                      )  as customer_trxn_cnt
from (select x.*,
             lag(log_date, 1) over (partition by unique_customer_id order by log_date) as prev_ld
      from x
     ) x
order by unique_customer_id, log_date;


问:
Can you use CSS to mirror/flip text?
Is it possible to use CSS/CSS3 to mirror text?

Specifically, I have this scissors char “✂” (✂) that I'd like to display pointing left and not right.

答:
That works fine with font icons like 's7 stroke icons' and 'font-awesome':

```<code>.mirror {
  display: inline-block;
  transform: scaleX(-1);
}
</code>```

And then on target element:

```<code><button>
  <span class="s7-back mirror"></span>
  <span>Next</span>
</button>
</code>```

Title: Can you use CSS to mirror/flip text?

Body:
That works fine with font icons like 's7 stroke icons' and 'font-awesome':

.mirror {
  display: inline-block;
  transform: scaleX(-1);
}

And then on target element:

<button>
  <span class="s7-back mirror"></span>
  <span>Next</span>
</button>


问:
Injecting jQuery css via a bookmarklet
This will be a very dummy question, but... I want to add some css styles to a page, when browsing it, simply by clicking on a bookmarklet. It will save me some time :)

For instance, this code works :

```<code>javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ) );
</code>```

But how come this one doesnt? It returns to me an error because of ";" before the second jquery.

```<code>javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ); jQuery( ".fancybox-close").css({ "display":"none"}); );
</code>```

Any idea of how to adapt it, in order to add styles to more than 1 element?
Thanks !

答:
Replace ';' to ',' working good tested. Hope this help you.  </p>

```<code>javascript:void(  jQuery( ".fancybox-overlay-fixed").css("background-color","black" ), jQuery( ".fancybox-close").css({ "display":"none"}) );
</code>```

Title: Injecting jQuery css via a bookmarklet

Body:
This will be a very dummy question, but... I want to add some css styles to a page, when browsing it, simply by clicking on a bookmarklet. It will save me some time :)

For instance, this code works :

javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ) );

But how come this one doesnt? It returns to me an error because of ";" before the second jquery.

javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ); jQuery( ".fancybox-close").css({ "display":"none"}); );

Any idea of how to adapt it, in order to add styles to more than 1 element?
Thanks !

Body:
Replace ';' to ',' working good tested. Hope this help you.

javascript:void(  jQuery( ".fancybox-overlay-fixed").css("background-color","black" ), jQuery( ".fancybox-close").css({ "display":"none"}) );


问:
User authentication in Elasticsearch query using python
I'm using elastisearch using Python. My code looks somewhat like this:-

```<code>from elasticsearch import Elasticsearch

if __name__ == '__main__':
    index="IndexPosition"
    es=Elasticsearch(['https://localhost:8080'])
    res = es.search(index='{0}'.format(index), doc_type="log",size=1000, from_=0, body={ "query": {
    "match": {

        ...Match condition
      }
    }
  }})
</code>```

Now, due to changes in architecture user authentication has been added in the elasticsearch.Let's assume username-user and password-pass.How do I pass the username and password in the query..?

答:
you can connect the elasticsearch with below Host url config</p>

```<code>es = Elasticsearch(hosts="http://user:pass@localhost:9200/")
</code>```

Body:
I'm using elastisearch using Python. My code looks somewhat like this:-

from elasticsearch import Elasticsearch

if __name__ == '__main__':
    index="IndexPosition"
    es=Elasticsearch(['https://localhost:8080'])
    res = es.search(index='{0}'.format(index), doc_type="log",size=1000, from_=0, body={ "query": {
    "match": {

        ...Match condition
      }
    }
  }})

Now, due to changes in architecture user authentication has been added in the elasticsearch.Let's assume username-user and password-pass.How do I pass the username and password in the query..?

Body:
you can connect the elasticsearch with below Host url config

es = Elasticsearch(hosts="http://user:pass@localhost:9200/")


问:
Download List of Car Pictures based on a list of their names
I want to download a list of car pictures based on an excel list of car make model name.

I can do that manually by taping the car model in google and save or copy the url of the first picture in google result. But I have like 800 car model names and this is time consuming.

How can I do it ?
Thanks

答:
Here is a function that you can use in R. You'll first need to install.packages("rvest") and install.packages("httr")

```<code>library(rvest)
library(httr)

get_first_google_image <- function(car_name)
{
  site <- "https://www.google.com"
  query <- paste0(site, "/search?q=", url_escape(car_name))

  image_page <- read_html(query)                          %>%
    html_nodes(xpath = "//a[contains(text(), 'Images')]") %>%
    html_attr("href")

  paste0(site, image_page)             %>%
    read_html(image_page)              %>%
    html_nodes("img")                  %>%
    html_attr("src")                   %>%
    {grep("gstatic", ., value = TRUE)} %>%
    `[`(1)                             %>%
    httr::GET()                        %>%
    httr::content("raw")               %>%
    writeBin(paste0("~/", car_name, ".jpg"))
}
</code>```

To use it, you just do

```<code>get_first_google_image("Mazda MX5")
</code>```

It will then save the first hit from the Google image search as a jpeg to your home directory.

If you want to get all your car names into R, just select and copy the column in Excel then in R do

```<code>car_names <- readClipboard()
</code>```

Then you can do

```<code>for(i in seq_along(car_names) get_first_google_image(car_names[i])
</code>```

This might take quite a long time to run.

Body:
Here is a function that you can use in R. You'll first need to install.packages("rvest") and install.packages("httr")

library(rvest)
library(httr)

get_first_google_image <- function(car_name)
{
  site <- "https://www.google.com"
  query <- paste0(site, "/search?q=", url_escape(car_name))

  image_page <- read_html(query)                          %>%
    html_nodes(xpath = "//a[contains(text(), 'Images')]") %>%
    html_attr("href")

  paste0(site, image_page)             %>%
    read_html(image_page)              %>%
    html_nodes("img")                  %>%
    html_attr("src")                   %>%
    {grep("gstatic", ., value = TRUE)} %>%
    `[`(1)                             %>%
    httr::GET()                        %>%
    httr::content("raw")               %>%
    writeBin(paste0("~/", car_name, ".jpg"))
}

To use it, you just do

get_first_google_image("Mazda MX5")

It will then save the first hit from the Google image search as a jpeg to your home directory.

If you want to get all your car names into R, just select and copy the column in Excel then in R do

car_names <- readClipboard()

Then you can do

for(i in seq_along(car_names) get_first_google_image(car_names[i])

This might take quite a long time to run.


问:
word is not found in dictionary must not be considered
I am implementing an lstm model where I have already trained my model with a dataset. When I am using my new dataset to predict the output, I am having errors because some words that are in my new dataset are not present in trained model. Is there any method to perform so that is the word is not found, it does not consider it?

Actually the words from the train model are saved in a dictionary as shown in my codes below:

```<code>df = pd.read_csv('C:/Users/User/Desktop/Coding/lstm emotion recognition/emotion.data/emotion.data')

#Preparing data for model traininng
#Tokenization-Since the data is already tokenized and lowecased, we just need to split the words
input_sentences = [text.split(" ") for text in df["text"].values.tolist()]
labels = df["emotions"].values.tolist()

#creating vocabulary(word index)
#Initialize word2id and label2id dictionaries that will be used to encode words and labels
word2id = dict() #creating the dictionary named word2id
label2id = dict() #creating a dictionary named label2id

max_words = 0 #maximum number of words in a sentence

#construction of word2id
for sentence in input_sentences:
    for word in sentence:
        #Add words to word2id if not exist
        if word not in word2id:
            word2id[word] = len(word2id)
    #If length of the sentence is greater than max_words, update max_words
    if len(sentence) > max_words:
        max_words = len(sentence)

#Construction of label2id and id2label dictionaries
label2id = {l: i for i, l in enumerate(set(labels))}
id2label = {v: k for k, v in label2id.items()}

from keras.models import load_model

model = load_model('modelsave2.py')
print(model)

import keras
model_with_attentions = keras.Model(inputs=model.input,
                                    output=[model.output,
                                              model.get_layer('attention_vec').output])
#File I/O Open function for read data from JSON File
with open('C:/Users/User/Desktop/Coding/parsehubjsonfileeg/all.json', encoding='utf8') as file_object:
        # store file data in object
        data = json.load(file_object)

        # dictionary for element which you want to keep
        new_data = {'selection1': []}
        print(new_data)
        # copy item from old data to new data if it has 'reviews'
        for item in data['selection1']:
            if 'reviews' in item:
                new_data['selection1'].append(item)
                print(item['reviews'])
                print('--')

        # save in file
        with open('output.json', 'w') as f:
            json.dump(new_data, f)
selection1 = data['selection1']

for item in selection1:
    name = item['name']
    print ('>>>>>>>>>>>>>>>>>> ', name)
    CommentID = item['reviews']
    for com in CommentID:
      comment = com['review'].lower()  # converting all to lowercase
      result = re.sub(r'\d+', '', comment)  # remove numbers
      results = (result.translate(
          str.maketrans('', '', string.punctuation))).strip()  # remove punctuations and white spaces
      comments = remove_stopwords(results)
      print('>>>>>>',comments)
    encoded_samples = [[word2id[word] for word in comments]]

      # Padding
      encoded_samples = keras.preprocessing.sequence.pad_sequences(encoded_samples, maxlen=max_words)

      # Make predictions
      label_probs, attentions = model_with_attentions.predict(encoded_samples)
      label_probs = {id2label[_id]: prob for (label, _id), prob in zip(label2id.items(), label_probs[0])}

      # Get word attentions using attenion vector
      print(label_probs)
      print(max(label_probs))
</code>```

my output is:

```<code>>>>>>> ['amazing', 'stay', 'nights', 'cleanliness', 'room', 'faultless']
{'fear': 0.26750156, 'love': 0.0044763167, 'joy': 0.06064613, 'surprise': 0.32365623, 'sadness': 0.03203068, 'anger': 0.31168908}
surprise
>>>>>> ['good', 'time', 'food', 'good']
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/Dissertation/loadandresult.py", line 96, in <module>
    encoded_samples = [[word2id[word] for word in comments]]
  File "C:/Users/User/PycharmProjects/Dissertation/loadandresult.py", line 96, in <listcomp>
    encoded_samples = [[word2id[word] for word in comments]]
KeyError: 'everydaythe'

</code>```

the error is because the word 'everydaythe' is not found my my trained dataset,..What should i do to correct this? please help me guys. please

答:
You can add a the following condition inside the list comprehension:

```<code>encoded_samples = [[word2id[word] for word in comments if word in word2id.keys()]]
</code>```

This one will only add the words in comments that are already present in the keys of the dictionary.

Edit:

When you're dealing with dictionaries, and facing a situation where you're trying to access a key which you're not sure exists for every dictionary, you can use get(). This method allows you to query a dictionary for a key, and if it doesn't exist, it will return a default value which you can choose, like in the code below:

```<code>my_dict = {'id': 0, 'reviews': 4.5}
your_dict = {'id': 1}

# If I just specify the key, the default return value is None
your_dict.get('reviews')

# However, I can specify the return value
your_dict.get('reviews', default=4.0)
</code>```

Body:
I am implementing an lstm model where I have already trained my model with a dataset. When I am using my new dataset to predict the output, I am having errors because some words that are in my new dataset are not present in trained model. Is there any method to perform so that is the word is not found, it does not consider it?

Actually the words from the train model are saved in a dictionary as shown in my codes below:

df = pd.read_csv('C:/Users/User/Desktop/Coding/lstm emotion recognition/emotion.data/emotion.data')

#Preparing data for model traininng
#Tokenization-Since the data is already tokenized and lowecased, we just need to split the words
input_sentences = [text.split(" ") for text in df["text"].values.tolist()]
labels = df["emotions"].values.tolist()

#creating vocabulary(word index)
#Initialize word2id and label2id dictionaries that will be used to encode words and labels
word2id = dict() #creating the dictionary named word2id
label2id = dict() #creating a dictionary named label2id

max_words = 0 #maximum number of words in a sentence

#construction of word2id
for sentence in input_sentences:
    for word in sentence:
        #Add words to word2id if not exist
        if word not in word2id:
            word2id[word] = len(word2id)
    #If length of the sentence is greater than max_words, update max_words
    if len(sentence) > max_words:
        max_words = len(sentence)

#Construction of label2id and id2label dictionaries
label2id = {l: i for i, l in enumerate(set(labels))}
id2label = {v: k for k, v in label2id.items()}

from keras.models import load_model

model = load_model('modelsave2.py')
print(model)

import keras
model_with_attentions = keras.Model(inputs=model.input,
                                    output=[model.output,
                                              model.get_layer('attention_vec').output])
#File I/O Open function for read data from JSON File
with open('C:/Users/User/Desktop/Coding/parsehubjsonfileeg/all.json', encoding='utf8') as file_object:
        # store file data in object
        data = json.load(file_object)

        # dictionary for element which you want to keep
        new_data = {'selection1': []}
        print(new_data)
        # copy item from old data to new data if it has 'reviews'
        for item in data['selection1']:
            if 'reviews' in item:
                new_data['selection1'].append(item)
                print(item['reviews'])
                print('--')

        # save in file
        with open('output.json', 'w') as f:
            json.dump(new_data, f)
selection1 = data['selection1']

for item in selection1:
    name = item['name']
    print ('>>>>>>>>>>>>>>>>>> ', name)
    CommentID = item['reviews']
    for com in CommentID:
      comment = com['review'].lower()  # converting all to lowercase
      result = re.sub(r'\d+', '', comment)  # remove numbers
      results = (result.translate(
          str.maketrans('', '', string.punctuation))).strip()  # remove punctuations and white spaces
      comments = remove_stopwords(results)
      print('>>>>>>',comments)
    encoded_samples = [[word2id[word] for word in comments]]

      # Padding
      encoded_samples = keras.preprocessing.sequence.pad_sequences(encoded_samples, maxlen=max_words)

      # Make predictions
      label_probs, attentions = model_with_attentions.predict(encoded_samples)
      label_probs = {id2label[_id]: prob for (label, _id), prob in zip(label2id.items(), label_probs[0])}

      # Get word attentions using attenion vector
      print(label_probs)
      print(max(label_probs))

my output is:

>>>>>> ['amazing', 'stay', 'nights', 'cleanliness', 'room', 'faultless']
{'fear': 0.26750156, 'love': 0.0044763167, 'joy': 0.06064613, 'surprise': 0.32365623, 'sadness': 0.03203068, 'anger': 0.31168908}
surprise
>>>>>> ['good', 'time', 'food', 'good']
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/Dissertation/loadandresult.py", line 96, in <module>
    encoded_samples = [[word2id[word] for word in comments]]
  File "C:/Users/User/PycharmProjects/Dissertation/loadandresult.py", line 96, in <listcomp>
    encoded_samples = [[word2id[word] for word in comments]]
KeyError: 'everydaythe'

the error is because the word 'everydaythe' is not found my my trained dataset,..What should i do to correct this? please help me guys. please

Body:
You can add a the following condition inside the list comprehension:

encoded_samples = [[word2id[word] for word in comments if word in word2id.keys()]]

This one will only add the words in comments that are already present in the keys of the dictionary.

Edit:

When you're dealing with dictionaries, and facing a situation where you're trying to access a key which you're not sure exists for every dictionary, you can use get(). This method allows you to query a dictionary for a key, and if it doesn't exist, it will return a default value which you can choose, like in the code below:

my_dict = {'id': 0, 'reviews': 4.5}
your_dict = {'id': 1}

# If I just specify the key, the default return value is None
your_dict.get('reviews')

# However, I can specify the return value
your_dict.get('reviews', default=4.0)


问:
How to copy all website with selenium in Python?
I used webdriver, because I need to make to copy the site after authentication.

```<code>from selenium import webdriver
import myconnutils
import re
from time import sleep

connection = myconnutils.getConnection()

#use Chrome
driver = webdriver.Chrome("/Users/User/Documents/sender/chromedriver")

#enter to site
driver.get("https://example.com/en/account")
driver.find_element_by_id("user").send_keys("userlogin")
driver.find_element_by_id("password").send_keys("passwordinput")
driver.find_element_by_id("submit").click()
</code>```

What is next? How to copy all page with css, js, images?

答:
Eventually try using Selenium with BeautifulSoup. You should be able to get the source code like this:

```<code>example_soup = BeautifulSoup(driver.page_source, 'html.parser')
</code>```

Eventually this blog post also helps.

Body:
I used webdriver, because I need to make to copy the site after authentication.

from selenium import webdriver
import myconnutils
import re
from time import sleep

connection = myconnutils.getConnection()

#use Chrome
driver = webdriver.Chrome("/Users/User/Documents/sender/chromedriver")

#enter to site
driver.get("https://example.com/en/account")
driver.find_element_by_id("user").send_keys("userlogin")
driver.find_element_by_id("password").send_keys("passwordinput")
driver.find_element_by_id("submit").click()

What is next? How to copy all page with css, js, images?

Body:
Eventually try using Selenium with BeautifulSoup. You should be able to get the source code like this:

example_soup = BeautifulSoup(driver.page_source, 'html.parser')

Eventually this blog post also helps.