问:
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to boolean
I have big problem. Runing the app using Android Emulator works good, but when I put the app on a real phone i get this error :

```<code>java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to boolean (found in field 'imp')
</code>```

My Firebase data is OK, 'imp' field is a boolean in the database, so what I'm retrieving  is a boolean from databae and storing it in a boolean var. How can it say that I receive a Long when the data is sent from Firebase as a Boolean?

Why is this happening only with a real phone?

Now I really don't understand why in Android Emulator works fine and installing the app in a real phone gives me this error.

This is my adapptor who is handling the data:

```<code>public class modelNoutati  {

String name;
String cont;
Date data;
Boolean imp;

public modelNoutati(){ }

public modelNoutati(String cont, Date data, Boolean imp, String name) {
    this.name = name;
    this.cont = cont;
    this.data = data;
    this.imp = imp;
}

public String getName() {return name;}

public void setName(String name) {this.name = name;}

public Date getData() {return data;}

public void setData(Date data) {this.data = data;}

public String getCont() {return cont;}

public void setCont (String cont) {this.cont = cont; }

public Boolean getImp () {return imp;}

public void setImp (Boolean imp) {this.imp = imp;}
</code>```

I get the issue here on doc.getDocument().toObject(modelNoutati.class)

```<code>for (DocumentChange doc : documentSnapshots.getDocumentChanges()){

                if(doc.getType() == DocumentChange.Type.ADDED) {

                    modelNoutati newsInt = doc.getDocument().toObject(modelNoutati.class);
                    newsL.add(newsInt);

                    newsAdaptor.notifyDataSetChanged();
</code>```

Logcat:

```<code>Process: projects.nv.umcstudent, PID: 14354
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to boolean (found in field 'imp')
    at com.google.android.gms.internal.zzeym.zzc(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym.zzb(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym$zza.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.firebase.firestore.DocumentSnapshot.toObject(Unknown Source)
    at com.google.firebase.firestore.QueryDocumentSnapshot.toObject(Unknown Source)
    at projects.nv.umcstudent.News$1.onEvent(News.java:70)
    at projects.nv.umcstudent.News$1.onEvent(News.java:57)
    at com.google.firebase.firestore.zzi.onEvent(Unknown Source)
    at com.google.android.gms.internal.zzeyn.zza(Unknown Source)
    at com.google.android.gms.internal.zzeyo.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6692)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

答:
Check your Database, if your data type is accurate then follow these two methods.As you said that this problem only occurs on a real device so there is no problem with the data type ,it is accurate.

I was facing this same problem,this problem can be solved by two methods:

1.Removing the entire collection and then adding the data back again.I tried this and I don't recommend this method,because adding the data back requires lot of effort especially if you are working with tons of data.

2.Uninstall the app and then re-install it.If you tried the first method and it did not help this this will definitely work.It's the easiest of the two method and does not require that much effort.

For me, the second method worked but for some the first might work.
Use the second method.It is easy and does not require that much effort.

Body:
I have big problem. Runing the app using Android Emulator works good, but when I put the app on a real phone i get this error :

java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to boolean (found in field 'imp')

My Firebase data is OK, 'imp' field is a boolean in the database, so what I'm retrieving  is a boolean from databae and storing it in a boolean var. How can it say that I receive a Long when the data is sent from Firebase as a Boolean?

Why is this happening only with a real phone?

Now I really don't understand why in Android Emulator works fine and installing the app in a real phone gives me this error.

This is my adapptor who is handling the data:

public class modelNoutati  {

String name;
String cont;
Date data;
Boolean imp;

public modelNoutati(){ }

public modelNoutati(String cont, Date data, Boolean imp, String name) {
    this.name = name;
    this.cont = cont;
    this.data = data;
    this.imp = imp;
}

public String getName() {return name;}

public void setName(String name) {this.name = name;}

public Date getData() {return data;}

public void setData(Date data) {this.data = data;}

public String getCont() {return cont;}

public void setCont (String cont) {this.cont = cont; }

public Boolean getImp () {return imp;}

public void setImp (Boolean imp) {this.imp = imp;}

I get the issue here on doc.getDocument().toObject(modelNoutati.class)

for (DocumentChange doc : documentSnapshots.getDocumentChanges()){

                if(doc.getType() == DocumentChange.Type.ADDED) {

                    modelNoutati newsInt = doc.getDocument().toObject(modelNoutati.class);
                    newsL.add(newsInt);

                    newsAdaptor.notifyDataSetChanged();

Logcat:

Process: projects.nv.umcstudent, PID: 14354
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to boolean (found in field 'imp')
    at com.google.android.gms.internal.zzeym.zzc(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym.zzb(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym$zza.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.android.gms.internal.zzeym.zza(Unknown Source)
    at com.google.firebase.firestore.DocumentSnapshot.toObject(Unknown Source)
    at com.google.firebase.firestore.QueryDocumentSnapshot.toObject(Unknown Source)
    at projects.nv.umcstudent.News$1.onEvent(News.java:70)
    at projects.nv.umcstudent.News$1.onEvent(News.java:57)
    at com.google.firebase.firestore.zzi.onEvent(Unknown Source)
    at com.google.android.gms.internal.zzeyn.zza(Unknown Source)
    at com.google.android.gms.internal.zzeyo.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6692)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)


来源: stackexchange

问:
How to make selection style in UITableViewCell
I created Xib file for my uitableviewcell in the attributed inspector i choose SelectionStyle default, but it didn't help me. So and i added accessory type .detailDisclosureButton.
So when i tapped on a cell , My cell doesn't highlighted gray color, only disclosurebutton does

答:
Maybe you can try this one,

```<code>extension CWScoreBoardViewController: UITableViewDelegate {

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      tableView.deselectRow(at: indexPath, animated: true)
  }

}
</code>```

or you can try this,

```<code>extension CWScoreBoardViewController: UITableViewDataSource {

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "CWUsersTableViewCell", for: indexPath) as! CWUsersTableViewCell

      cell.selectionStyle = .none

      return cell
  }
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
Maybe you can try this one,

extension CWScoreBoardViewController: UITableViewDelegate {

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      tableView.deselectRow(at: indexPath, animated: true)
  }

}

or you can try this,

extension CWScoreBoardViewController: UITableViewDataSource {

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "CWUsersTableViewCell", for: indexPath) as! CWUsersTableViewCell

      cell.selectionStyle = .none

      return cell
  }

}


问:
Updating an LGBM model with new data
I want to use additional data to 'update' an already trained Light Gradient Boosting Model (LGBM). Is there a way to do that?

I am looking for an approach that uses the Skealrn API and thus can be used in a pipeline.

答:
An LGBM model in python can be fitted both with the original model API and with the Sklearn API.
I couldn't find any examples of using the Sklearn API for continuous learning.
Regardless of that, you can fit a model either way and it is compatible with the .train() function from the original API.
It can be saved with save_model() or with joblib.dump().

This does not affect its compatibility with Python Pileline() - it is perfectly compatible.

Title: Updating an LGBM model with new data


问:
Bootstrap 4: fix contents bottom inside container
I have an app wrapped around a
, in which I have an editor and a few buttons, which I always want to be shown at the bottom, something like so:

  // some content....

  // this should be shown always at the bottom!

```

I have tried changing the min-height, and height properties of html, body and container to be 100% and added important to this rules, but that doesnt make my div container stretch any more downwards. When I use the "fixed-bottom" bootstrap class, the #bottom div stretches horizontally over the container boundaries, which makes the layout completely ugly.

any suggestions? :)

答:
Wrap your "submit-form" with another container or use col-* for positioning.

For example:

```<code><div class="container">
  <!-- some content.... -->

  <!-- this should be shown always at the bottom! -->
  <div id="bottom" class="container fixed-bottom submit-form">
    <div id="editor"></div>
    <div class="btn btn-grp" ></div>
  </div>
</div>
</code>```

Manipulate your div size by col-* class (bootstrap grid contains 12 columns, so below  div will cover 4 columns of screen size)  :

```<code><div class="container">
  <!-- some content.... -->

  <!-- this should be shown always at the bottom! -->
  <div id="bottom" class="col-4 fixed-bottom submit-form">
    <div id="editor"></div>
    <div class="btn btn-grp" ></div>
  </div>
</div>
</code>```

After that this form will be aligned to the left side of the screen.

Use d-flex for positioning your bootstrap column:

```<code>  <div class="container">
      <!-- some content.... -->

      <!-- this should be shown always at the bottom! -->
     <div class="d-flex justify-content-center fixed-bottom">
        <div id="bottom" class="col-4 submit-form">
         <div id="editor"></div>
        <div class="btn btn-grp" ></div>
  </div>
     </div>
   </div>
</code>```

If you want to create responsive web site, you should read something about bootstrap grid system and use col-md-*, col-sm-* etc. instead of col-*:

https://getbootstrap.com/docs/4.0/layout/grid/

Body:
I have an app wrapped around a
, in which I have an editor and a few buttons, which I always want to be shown at the bottom, something like so:

  // some content....

  // this should be shown always at the bottom!

I have tried changing the min-height, and height properties of html, body and container to be 100% and added important to this rules, but that doesnt make my div container stretch any more downwards. When I use the "fixed-bottom" bootstrap class, the #bottom div stretches horizontally over the container boundaries, which makes the layout completely ugly.

any suggestions? :)

Body:
Wrap your "submit-form" with another container or use col-* for positioning.

For example:

<div class="container">
  <!-- some content.... -->

  <!-- this should be shown always at the bottom! -->
  <div id="bottom" class="container fixed-bottom submit-form">
    <div id="editor"></div>
    <div class="btn btn-grp" ></div>
  </div>
</div>

Manipulate your div size by col-* class (bootstrap grid contains 12 columns, so below  div will cover 4 columns of screen size)  :

<div class="container">
  <!-- some content.... -->

  <!-- this should be shown always at the bottom! -->
  <div id="bottom" class="col-4 fixed-bottom submit-form">
    <div id="editor"></div>
    <div class="btn btn-grp" ></div>
  </div>
</div>

After that this form will be aligned to the left side of the screen.

Use d-flex for positioning your bootstrap column:

  <div class="container">
      <!-- some content.... -->

      <!-- this should be shown always at the bottom! -->
     <div class="d-flex justify-content-center fixed-bottom">
        <div id="bottom" class="col-4 submit-form">
         <div id="editor"></div>
        <div class="btn btn-grp" ></div>
  </div>
     </div>
   </div>

If you want to create responsive web site, you should read something about bootstrap grid system and use col-md-*, col-sm-* etc. instead of col-*:

https://getbootstrap.com/docs/4.0/layout/grid/


问:
How to integrate PayPal with Zend Framework
I am new in Zend Framework and i need to integrate paypal. I don't know how to integrate
PayPal with Zend Framework. Any URL or sample code will be good for us.

Please Help...

Thanks In advance.

答: Dude, if those links get too complex, or you just want to use the NVP API instead of SOAP, try my two-part tutorial about leveraging the Zend Framework to use the PayPal Express Checkout and PayPal Payments Pro API.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How do I center nav items after the navbar got resized by a larger image?
I added a logo to the navbar and it made the navbar a bit larger..
you can replace the img source to any image you want, the effect is the same
I tried to nest the element below in a
, which I saw on the docs at the flexbox section but has no effect.

```<code><div class="container-fluid">
        <ul class="nav  justify-content-around bg-warning nav-tabs " >
            <img src="logo.png" style="height: 60px;">
            <li class="nav-item ">
                <a class="nav-link  text-success " href="#">Home</a>
            </li>
            <li class="nav-item ">
                <a class="nav-link text-success" href="#">News</a>
            </li>
            <li class="nav-item ">
                <a class="nav-link text-success" href="#">Items</a>
            </li>
            <li class="nav-item ">
                <a href="#" class=" text-danger nav-link">Affiliate</a>
            </li>
        </ul>
    </div>
</code>```

答:
I added d-flex and align-items-center to the nav class. This will solve your problem. I don't know where you're trying to add this, but it's got to be here for what you want. Because you want to center the elements in ul.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

      Home

      News

      Items

      Affiliate

```

Body:
I added a logo to the navbar and it made the navbar a bit larger..
you can replace the img source to any image you want, the effect is the same
I tried to nest the element below in a
, which I saw on the docs at the flexbox section but has no effect.

                Home

                News

                Items

                Affiliate

Body:
I added d-flex and align-items-center to the nav class. This will solve your problem. I don't know where you're trying to add this, but it's got to be here for what you want. Because you want to center the elements in ul.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<div class="container-fluid">
  <ul class="nav  justify-content-around bg-warning nav-tabs d-flex align-items-center ">
    <img src="https://www.bidolubaski.com/sites/default/files/u61150/google-logo.jpg" style="height: 60px;">
    <li class="nav-item ">
      <a class="nav-link  text-success " href="#">Home</a>
    </li>
    <li class="nav-item ">
      <a class="nav-link text-success" href="#">News</a>
    </li>
    <li class="nav-item ">
      <a class="nav-link text-success" href="#">Items</a>
    </li>
    <li class="nav-item ">
      <a href="#" class=" text-danger nav-link">Affiliate</a>
    </li>
  </ul>
</div>


问:
Athena partition locations
I can view all the partitions on my table using

```<code>show partitions my_table
</code>```

and I can see the location of a partition by using

```<code>describe formatted my_table partition (partition_col='value')
</code>```

but I have a lot of partitions, and don't want to have to parse the output of describe formatted if it can be avoided.

Is there a way to get all partitions and their locations, in a single query?

答:
Using boto3 (as of version 1.12.9) the following is returning the complete list:

glue_client = boto3.client("glue")
glue_paginator = glue_client.get_paginator("get_partitions")
pages_iter = glue_paginator.paginate(
    DatabaseName=db_name, TableName=table_name
)
res = []
for page in pages_iter:
    for partition in page["Partitions"]:
        res.append(
            {
                "Values": partition["Values"],
                "Location": partition["StorageDescriptor"]["Location"],
            }
        )
```

Title: Athena partition locations

Body:
I can view all the partitions on my table using

show partitions my_table

and I can see the location of a partition by using

describe formatted my_table partition (partition_col='value')

but I have a lot of partitions, and don't want to have to parse the output of describe formatted if it can be avoided.

Is there a way to get all partitions and their locations, in a single query?


问:
How to toggle (show/hide) element in Angular 4?
This is my html element:

```<code><ng-container>
    <span *ngIf="row.messageText && row.messageText.length >= 30 && expanded">{{row.messageText.substr(0, 25)}}
        <span>more</span>
    </span>
</ng-container>
</code>```

It shows part of a message when row.messageText.length is greater than 30. I need the first span to show the entire message (by using row.messageText.substr()) after clicking the more span. I think that there is a solution by using (click)="toggle()" and setting some true/false values.

Do you have any ideas?

答:
```<code> <div class="top5" *ngFor="let feedback of topFeedbacks; index as i" >
      <ng-container>
        <div style="margin-left: 5%;">
              <span *ngIf="feedback && feedback.length < 80"><i class="fas fa-comment-dots"></i>  {{feedback}}</span>
              <span *ngIf="feedback && feedback.length >= 80 && !expanded[i]"> <i class="fas fa-comment-dots"></i>  {{feedback.substr(0, 75)}}</span>
              <span *ngIf="feedback && feedback.length >= 80 && expanded[i]"><i class="fas fa-comment-dots"></i>  {{feedback.substr(0, feedback.length)}}</span>
              <label> </label>
              <a  *ngIf="feedback && feedback.length >= 80" class="toggle-button" (click)="toggle(i)">{{expanded[i]?' ...Show less':' ...Show more'}}</a>
        </div>
    </ng-container>
</d
iv>
</code>```

Body:
This is my html element:

<ng-container>
    = 30 && expanded">{{row.messageText.substr(0, 25)}}
        more

</ng-container>

It shows part of a message when row.messageText.length is greater than 30. I need the first span to show the entire message (by using row.messageText.substr()) after clicking the more span. I think that there is a solution by using (click)="toggle()" and setting some true/false values.

Do you have any ideas?

Body:
 <div class="top5" *ngFor="let feedback of topFeedbacks; index as i" >
      <ng-container>
        <div style="margin-left: 5%;">
              <span *ngIf="feedback && feedback.length < 80"><i class="fas fa-comment-dots"></i>&nbsp;&nbsp;{{feedback}}</span>
              <span *ngIf="feedback && feedback.length >= 80 && !expanded[i]"> <i class="fas fa-comment-dots"></i>&nbsp;&nbsp;{{feedback.substr(0, 75)}}</span>
              <span *ngIf="feedback && feedback.length >= 80 && expanded[i]"><i class="fas fa-comment-dots"></i>&nbsp;&nbsp;{{feedback.substr(0, feedback.length)}}</span>
              <label>&nbsp;</label>
              <a  *ngIf="feedback && feedback.length >= 80" class="toggle-button" (click)="toggle(i)">{{expanded[i]?' ...Show less':' ...Show more'}}</a>
        </div>
    </ng-container>
</d
iv>


问:
Formal algorithms for edit buffer memory allocation
I'm writing a Roslyn-driven C# editor. Roslyn syntax verification requires me to submit the entire edit buffer of a C# source file for analysis every time a keystroke is pressed. The buffer has to be a snapshot, so I can't wrap the actual live edit buffers.

The current algorithm, waiting for the "Never Optimize" rule to expire: Allocate a fresh char[] array every keystroke, and serialize the editor text into the array, pay no attention to what the actual operation was.

Surprisingly, the performance isn't terrible. But I'm worried about thrashing the garbage collector with large allocations in large projects. Imagine allocating a 2MB buffer every keystroke while editing a large C# file. That can't be good in the long term.

I know from an inside source that Visual Studio uses some sort of "binary tree" data structure to submit incremental updates. But the sources for that part of Visual Studio aren't available.

I imagine an algorithm something along the lines of: split the entire edit buffer up into manageably small pieces. A change to the document will either insert, delete or replace one or more characters every time a key is pressed. So instead of allocating a fresh buffer, use a strategy that splits and patches in changes; then wrap the entire data structure with a an interfaces that presents the fragments as a contiguous sequential block. Instead of allocating massive large-object structures, that are going to force a Gen2 CG, allocate little tiny blocks to effect the patch.

And presumably some strategy for coalescing, maybe on a lowest-priority thread.

I could go at it adhoc, but I can't help thinking there must be some formal algorithm to deal with this problem.

Anyone? (A pair of swapped buffers, I suppose. But still...)

答:
Relevant algorithms: splay trees, red-black trees.

The following article describes the implementation used by visual studio

https://code.visualstudio.com/blogs/2018/03/23/text-buffer-reimplementation

A red-black tree containing buffers that can be split into pieces, with a caveat that their piece buffers eventually fragment because they make no attempt to consolidate.

The implementation is.... ferociously difficult and I have grave concerns about correctness. :-) Modifying the already toxicly difficult red-black tree algorithm to be text-position based is.... really really hard.

I'm currently wondering whether O(n) insertion complexity is so terrible given that I'm going to immediately turn around and feed the result to a C# parser that is optimistically O(n log(n)) for processing.


问:
File I/O Uninitialised Variable Problem - C Program
I have the following code and when I try to run it, I get the following warning:

warning: variable 'myfile' is uninitialized when used here [-Wuninitialized]
myfile = fetch_file(myfile, argc, argv);

note: initialize the variable 'myfile' to silence this warning
FILE *myfile;

I have been trying to find out how to fix the warning but haven't been successful.

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

#define LINE_SIZE 300

FILE * fetch_file(FILE *myfile, int argc, char *argv[1])
{
  if (argc == 1)
  {
    printf("Error, not enough commandline arguments.");
    exit(0);
  }

  myfile = fopen (argv[1], "r");

  if (myfile == NULL)
  {
    printf("\nNo file named %s was found.", argv[1]);
    exit(0);
  }

  else
  {
    printf("%s was successfully opened", argv[1]);
  }

  return myfile;
}

void print_file(FILE *the_file, char *line, int size)
{
  int count = 0;

  while (fgets(line, size, the_file) != NULL)
  {
    printf("%s", line);
    count++;
  }
  fclose(the_file);

  printf("\nThere are %d lines\n", count);
}

int main (int argc, char *argv[])
{
  FILE *myfile;
  char line[LINE_SIZE];

  myfile = fetch_file(--> myfile <-- , argc, argv); <----------- (warning)
  print_file(myfile, line, LINE_SIZE);

  return 0;
}
</code>```

Ps: I'm fairly new to asking questions on this website, so if there is any way I can improve my questions and code, feel free to criticise me...

答:
You want this:

```<code>FILE *fetch_file(int argc, char *argv[1])
{
  if (argc == 1)
  {
    printf("Error, not enough commandline arguments.");
    exit(0);
  }

  FILE *myfile = fopen (argv[1], "r");
  ...
}

int main (int argc, char *argv[])
{
  FILE *myfile;
  char line[LINE_SIZE];

  myfile = fetch_file(argc, argv);
  ...
}
</code>```

It is pointless to pass the myfile parameter to fetch_file.

The reason for the warning is that you pass an uninitialized value to a function:

This simple code reproduces this exact problem:

```<code>int foo(int bar)
{
    bar = 2;
    return bar * 2;
}

int main (int argc, char *argv[])
{
  int kwork;   // kwork is not initialized
  foo(kwork);  // here you pass an uninitialized value
               // which the foo function cannot use in a useful manner
}
</code>```

Body:
I have the following code and when I try to run it, I get the following warning:

warning: variable 'myfile' is uninitialized when used here [-Wuninitialized]
myfile = fetch_file(myfile, argc, argv);

note: initialize the variable 'myfile' to silence this warning
FILE *myfile;

I have been trying to find out how to fix the warning but haven't been successful.

#include <stdio.h>
#include <stdlib.h>

#define LINE_SIZE 300

FILE * fetch_file(FILE *myfile, int argc, char *argv[1])
{
  if (argc == 1)
  {
    printf("Error, not enough commandline arguments.");
    exit(0);
  }

  myfile = fopen (argv[1], "r");

  if (myfile == NULL)
  {
    printf("\nNo file named %s was found.", argv[1]);
    exit(0);
  }

  else
  {
    printf("%s was successfully opened", argv[1]);
  }

  return myfile;
}

void print_file(FILE *the_file, char *line, int size)
{
  int count = 0;

  while (fgets(line, size, the_file) != NULL)
  {
    printf("%s", line);
    count++;
  }
  fclose(the_file);

  printf("\nThere are %d lines\n", count);
}

int main (int argc, char *argv[])
{
  FILE *myfile;
  char line[LINE_SIZE];

  myfile = fetch_file(--> myfile <-- , argc, argv); <----------- (warning)
  print_file(myfile, line, LINE_SIZE);

  return 0;
}

Ps: I'm fairly new to asking questions on this website, so if there is any way I can improve my questions and code, feel free to criticise me...

Body:
You want this:

FILE *fetch_file(int argc, char *argv[1])
{
  if (argc == 1)
  {
    printf("Error, not enough commandline arguments.");
    exit(0);
  }

  FILE *myfile = fopen (argv[1], "r");
  ...
}

int main (int argc, char *argv[])
{
  FILE *myfile;
  char line[LINE_SIZE];

  myfile = fetch_file(argc, argv);
  ...
}

It is pointless to pass the myfile parameter to fetch_file.

The reason for the warning is that you pass an uninitialized value to a function:

This simple code reproduces this exact problem:

int foo(int bar)
{
    bar = 2;
    return bar * 2;
}

int main (int argc, char *argv[])
{
  int kwork;   // kwork is not initialized
  foo(kwork);  // here you pass an uninitialized value
               // which the foo function cannot use in a useful manner
}


问:
MSSQL Sql tuning advisor - in mysql
In Microsoft SQL Server; there is a 'SQL Tuning Advisor' where you can feed it a query and it will analyze it and offer you suggestions on indexing. Is there something like this for mysql that I can use from phpmyadmin?</p>

答: Add EXPLAIN to the front of a SELECT statement and run it from the Query tab. It will tell you which indexes it plans to use. You then need to make a judgement call if you can create a better index for it.</p>

Title: MSSQL Sql tuning advisor - in mysql


问:
Perl: match against a large array
Say I have $sentence = "The quick brown fox jumps over the lazy dog" and an array @targets = qw(brown red black lazy quick);.

The goal is to find out all words in @targets that contains in the $sentence, in this case, it's this three words: brown lazy quick.

Note: The @targets array could be very large, like there could be 10,000 elements in it. And there could be 10,000 $sentences to deal with.

Is there an efficient and elegant way to do it?

答:
Here is an example using Regexp::Assemble:

```<code>use feature qw(say);
use strict;
use warnings;
use Regexp::Assemble;

my $str = "The quick brown fox jumps over the lazy dog";
my @targets = qw(brown lazy quick);
my $ra = Regexp::Assemble->new;
$ra->add($_) for @targets;
my $regex = $ra->re;
my @matches = $str =~ /($regex)/g;
say for @matches;  # optionally add List::Util::uniq if you want the list
                     to be unique
</code>```

Output:

```<code>quick
brown
lazy
</code>```

Title: Perl: match against a large array

Body:
Here is an example using Regexp::Assemble:

use feature qw(say);
use strict;
use warnings;
use Regexp::Assemble;

my $str = "The quick brown fox jumps over the lazy dog";
my @targets = qw(brown lazy quick);
my $ra = Regexp::Assemble->new;
$ra->add($_) for @targets;
my $regex = $ra->re;
my @matches = $str =~ /($regex)/g;
say for @matches;  # optionally add List::Util::uniq if you want the list
                     to be unique

Output:

quick
brown
lazy


问:
Coloring subsets in PCA biplot
I am working on a gene expression data frame called expression. My samples belong to different subgroups, indicated in the colname (i.e. all samples that contain "adk" in their colname belong to the same subgroup)

```<code>       adk1  adk2  bas1  bas2  bas3  non1  ...
gene1   1.1   1.3   2.2   2.3   2.8   1.6
gene2   2.5   2.3   4.1   4.6   4.2   1.9
gene3   1.6   1.8   0.5   0.4   0.9   2.2
...
</code>```

I already defined subsets using

```<code>adk <- expression[grepl('adk', names(expression))]
</code>```

I then did a PCA on this data set using

```<code>pca = prcomp (t(expression), center = F, scale= F)
</code>```

I now want to plot the PCs I got from the PCA against each other in a PCA biplot. For this, I want all samples that belong to the same subgroup to have the same color (so e.g. all "adk" samples should be green, all "bas" samples should be red and all "non" samples should be blue). I tried to use the color argument of the autoplot function from ggfortify, but I wansn't able to make it use my defined subsets.

I would be glad if someone could help me with this! Thanks :)

Edit: I'd like to give you an example of what I want to do, using the USArrests dataset:

```<code>head(USArrests)
           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7

## Doing a PCA on the USArrests dataset

US.pca = prcomp(t(USArrests), center = F, scale = F)

## Now I can create a PCA biplot of PC1 and PC2 using the autoplot function (since I have ggfortify installed)

biplot1 = autoplot(US.pca,data=t(USArrests), x=1, y=2)
</code>```

I want all samples that contain an "e" in their colname (in this case "Murder" and "Rape") to be the same color. The "UrbanPop" and the "Assault" sample should be an individual color as well. I hope this makes things a little clearer :)

P.S. I run R in the latest version of RStudio on Windows 10

答:
Welcome to SO!
What about something like this, using ggbiplot package:

```<code># PCA
pca <- prcomp (t(expressions), center = F, scale= F)
# first you get the vector of the names
# gr <- substr(rownames(t(expressions)),1,3)
# EDIT
gr <-gsub(".*(adk|bas|non).*$", "\\1",rownames(t(expressions)), ignore.case = TRUE)

library(ggbiplot)
# plot it
ggbiplot(pca, groups = gr)+
  scale_color_manual(values=c("green", "red"," blue")) +
  theme_light()
</code>```

EDIT

If you're using R 4.0.0, you'd install the package following this two lines:

```<code>library(devtools)
install_github("vqv/ggbiplot", force = TRUE)
</code>```

With data:

```<code>expressions <- read.table(    text = "adk1  adk2  bas1  bas2  bas3  non1
                               gene1   1.1   1.3   2.2   2.3   2.8   1.6
                               gene2   2.5   2.3   4.1   4.6   4.2   1.9
                               gene3   1.6   1.8   0.5   0.4   0.9   2.2", header = T )
</code>```

Title: Coloring subsets in PCA biplot

Body:
I am working on a gene expression data frame called expression. My samples belong to different subgroups, indicated in the colname (i.e. all samples that contain "adk" in their colname belong to the same subgroup)

       adk1  adk2  bas1  bas2  bas3  non1  ...
gene1   1.1   1.3   2.2   2.3   2.8   1.6
gene2   2.5   2.3   4.1   4.6   4.2   1.9
gene3   1.6   1.8   0.5   0.4   0.9   2.2
...

I already defined subsets using

adk <- expression[grepl('adk', names(expression))]

I then did a PCA on this data set using

pca = prcomp (t(expression), center = F, scale= F)

I now want to plot the PCs I got from the PCA against each other in a PCA biplot. For this, I want all samples that belong to the same subgroup to have the same color (so e.g. all "adk" samples should be green, all "bas" samples should be red and all "non" samples should be blue). I tried to use the color argument of the autoplot function from ggfortify, but I wansn't able to make it use my defined subsets.

I would be glad if someone could help me with this! Thanks :)

Edit: I'd like to give you an example of what I want to do, using the USArrests dataset:

head(USArrests)
           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7

## Doing a PCA on the USArrests dataset

US.pca = prcomp(t(USArrests), center = F, scale = F)

## Now I can create a PCA biplot of PC1 and PC2 using the autoplot function (since I have ggfortify installed)

biplot1 = autoplot(US.pca,data=t(USArrests), x=1, y=2)

I want all samples that contain an "e" in their colname (in this case "Murder" and "Rape") to be the same color. The "UrbanPop" and the "Assault" sample should be an individual color as well. I hope this makes things a little clearer :)

P.S. I run R in the latest version of RStudio on Windows 10

Body:
Welcome to SO!
What about something like this, using ggbiplot package:

# PCA
pca <- prcomp (t(expressions), center = F, scale= F)
# first you get the vector of the names
# gr <- substr(rownames(t(expressions)),1,3)
# EDIT
gr <-gsub(".*(adk|bas|non).*$", "\\1",rownames(t(expressions)), ignore.case = TRUE)

library(ggbiplot)
# plot it
ggbiplot(pca, groups = gr)+
  scale_color_manual(values=c("green", "red"," blue")) +
  theme_light()

EDIT

If you're using R 4.0.0, you'd install the package following this two lines:

library(devtools)
install_github("vqv/ggbiplot", force = TRUE)

With data:

expressions <- read.table(    text = "adk1  adk2  bas1  bas2  bas3  non1
                               gene1   1.1   1.3   2.2   2.3   2.8   1.6
                               gene2   2.5   2.3   4.1   4.6   4.2   1.9
                               gene3   1.6   1.8   0.5   0.4   0.9   2.2", header = T )


问:
Swift PromiseKit. Do GET requests multiple times one by one. Pyramid of doom with PromiseKit
I am doing multiple GET requests to the URL, it returns me some JSON data, which I decode into the class. From this class I extract attribute - id: Int, this id is part of a URL which I build to make another GET Request.

In other words:
JSON fetched from URL -> JSON Decoded -> id extracted -> new url built -> JSON fetched from new URL -> JSON Decoded... and this process is repeated n times.

What I have for now is just the same pyramid of doom, but using PromiseKit notation:

```<code>
        func fetch_analysis_dataTask(url: String) -> Promise<(data: Data, response: URLResponse)> {
            let urlRequest = APIConnect.urlRequest(endPoint: url, method: .GET, data: nil)
            return URLSession.shared.dataTask(.promise, with: urlRequest).validate()
        }

        let expectation = self.expectation(description: "Async call")
        let urlRequest = APIConnect.urlRequest(endPoint: "test?patient_id=3730", method: .GET, data: nil)

        firstly {
            URLSession.shared.dataTask(.promise, with: urlRequest).validate()
        }.map {
            try JSONDecoder().decode([TestWrapper].self, from: $0.data)
        }.done { testWrappers in
            var tests = [Test]()
            for testWrapper in testWrappers {
                if testWrapper.test != nil {
                    tests.append(testWrapper.test!)
                }
            }

            let testID = tests.first!.id!
            let urlRequest = APIConnect.urlRequest(endPoint: "analysis/" + String(testID), method: .GET, data: nil)

            firstly {
                URLSession.shared.dataTask(.promise, with: urlRequest).validate()
            }.map {
                try JSONSerialization.jsonObject(with: $0.data, options: .allowFragments)
            }.done { data in
                XCTAssert(data != nil)
                expectation.fulfill()
            }.catch { error in
                print(error)
                XCTAssert(false)
                expectation.fulfill()
            }
        }

        waitForExpectations(timeout: 20)
    }
</code>```

However I do not see the way how to do it, but I am sure there is, or?

答:
If you use then instead of done you can return a promise and it will continue the chain. Something like this:

```<code>let expectation = self.expectation(description: "Async call")
let urlRequest = APIConnect.urlRequest(endPoint: "test?patient_id=3730", method: .GET, data: nil)

firstly {
    URLSession.shared.dataTask(.promise, with: urlRequest).validate()
}.map {
    try JSONDecoder().decode([TestWrapper].self, from: $0.data)
}.then { testWrappers in
    var tests = [Test]()
    for testWrapper in testWrappers {
        if testWrapper.test != nil {
            tests.append(testWrapper.test!)
        }
    }

    let testID = tests.first!.id!
    let urlRequest = APIConnect.urlRequest(endPoint: "analysis/" + String(testID), method: .GET, data: nil)
    return URLSession.shared.dataTask(.promise, with: urlRequest).validate()
}.map {
    try JSONSerialization.jsonObject(with: $0.data, options: .allowFragments)
}.done { data in
    XCTAssert(data != nil)
    expectation.fulfill()
}.catch { error in
    print(error)
    XCTAssert(false)
    expectation.fulfill()
}

waitForExpectations(timeout: 20)
</code>```

PS. I've had the compiler getting confused with complex chains. Annotating the return values could help, but what I usually end up doing is trying to make all map, then, ensure, etc. calls have a single statement, which might mean using more maps.

Body:
I am doing multiple GET requests to the URL, it returns me some JSON data, which I decode into the class. From this class I extract attribute - id: Int, this id is part of a URL which I build to make another GET Request.

In other words:
JSON fetched from URL -> JSON Decoded -> id extracted -> new url built -> JSON fetched from new URL -> JSON Decoded... and this process is repeated n times.

What I have for now is just the same pyramid of doom, but using PromiseKit notation:

        func fetch_analysis_dataTask(url: String) -> Promise<(data: Data, response: URLResponse)> {
            let urlRequest = APIConnect.urlRequest(endPoint: url, method: .GET, data: nil)
            return URLSession.shared.dataTask(.promise, with: urlRequest).validate()
        }

        let expectation = self.expectation(description: "Async call")
        let urlRequest = APIConnect.urlRequest(endPoint: "test?patient_id=3730", method: .GET, data: nil)

        firstly {
            URLSession.shared.dataTask(.promise, with: urlRequest).validate()
        }.map {
            try JSONDecoder().decode([TestWrapper].self, from: $0.data)
        }.done { testWrappers in
            var tests = [Test]()
            for testWrapper in testWrappers {
                if testWrapper.test != nil {
                    tests.append(testWrapper.test!)
                }
            }

            let testID = tests.first!.id!
            let urlRequest = APIConnect.urlRequest(endPoint: "analysis/" + String(testID), method: .GET, data: nil)

            firstly {
                URLSession.shared.dataTask(.promise, with: urlRequest).validate()
            }.map {
                try JSONSerialization.jsonObject(with: $0.data, options: .allowFragments)
            }.done { data in
                XCTAssert(data != nil)
                expectation.fulfill()
            }.catch { error in
                print(error)
                XCTAssert(false)
                expectation.fulfill()
            }
        }

        waitForExpectations(timeout: 20)
    }

However I do not see the way how to do it, but I am sure there is, or?

Body:
If you use then instead of done you can return a promise and it will continue the chain. Something like this:

let expectation = self.expectation(description: "Async call")
let urlRequest = APIConnect.urlRequest(endPoint: "test?patient_id=3730", method: .GET, data: nil)

firstly {
    URLSession.shared.dataTask(.promise, with: urlRequest).validate()
}.map {
    try JSONDecoder().decode([TestWrapper].self, from: $0.data)
}.then { testWrappers in
    var tests = [Test]()
    for testWrapper in testWrappers {
        if testWrapper.test != nil {
            tests.append(testWrapper.test!)
        }
    }

    let testID = tests.first!.id!
    let urlRequest = APIConnect.urlRequest(endPoint: "analysis/" + String(testID), method: .GET, data: nil)
    return URLSession.shared.dataTask(.promise, with: urlRequest).validate()
}.map {
    try JSONSerialization.jsonObject(with: $0.data, options: .allowFragments)
}.done { data in
    XCTAssert(data != nil)
    expectation.fulfill()
}.catch { error in
    print(error)
    XCTAssert(false)
    expectation.fulfill()
}

waitForExpectations(timeout: 20)

PS. I've had the compiler getting confused with complex chains. Annotating the return values could help, but what I usually end up doing is trying to make all map, then, ensure, etc. calls have a single statement, which might mean using more maps.


问:
Can't block AspiegelBot in htaccess or robots.txt
I have issues with AspiegelBot crawling one of the sites on a server, this results in a lot of cores getting used up. I've been trying to block the bot in both in the sites htaccess with no sucess. The bot still constantly appears in my access.log

```<code>114.119.165.232 - - [20/Apr/2020:07:38:40 +0200] "GET /tillbehor.html?size=98%2C422%2C423%2C1129%2C1378 HTTP/1.1" 301 296 "-" "Mozilla/5.0 (Linux; Android 7.0;) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; AspiegelBot)"
</code>```

Here is some of what I've tried:

htaccess

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^.(Mb2345Browser|AspiegelBot|LieBaoFast|MicroMessenger|zh-CN|Kinza|Mb2345Browser).$ [NC]
RewriteRule .* - [F,L]
</code>```

robots.txt

```<code>User-agent: *
Allow: /
Disallow: */shopby

#######################################
################ PAGES ################
#######################################

Disallow: /privacy-policy-cookie-restriction-mode/
Disallow: /terms/

#######################################
############# Block Bots ##############
#######################################

 User-agent: MJ12bot
 Disallow: /
 User-agent: SemrushBot
 Disallow: /
 User-agent: SemrushBot-SA
 Disallow: /
 User-agent: rogerbot
 Disallow:/
 User-agent: dotbot
 Disallow:/
 User-agent: AhrefsBot
 Disallow: /
 User-agent: Alexibot
 Disallow: /
 User-agent: SurveyBot
 Disallow: /
 User-agent: Xenu's
 Disallow: /
 User-agent: Xenu's Link Sleuth 1.1c
 Disallow: /
 User-agent: AspiegelBot
 Disallow: /
</code>```

Am I missing something or writing something incorrectly? Ï'm kinda at a loss here.

答:
I posted this as a comment but seeing as it's what solved this for me I will add it as an answer.
I managed to get the bot blocked by blocking the starting IP sequence in the htaccess file. It might not be optimal way to do it but it worked.

Deny from 114.119.0.0/16

Body:
I have issues with AspiegelBot crawling one of the sites on a server, this results in a lot of cores getting used up. I've been trying to block the bot in both in the sites htaccess with no sucess. The bot still constantly appears in my access.log

114.119.165.232 - - [20/Apr/2020:07:38:40 +0200] "GET /tillbehor.html?size=98%2C422%2C423%2C1129%2C1378 HTTP/1.1" 301 296 "-" "Mozilla/5.0 (Linux; Android 7.0;) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; AspiegelBot)"

Here is some of what I've tried:

htaccess

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^.(Mb2345Browser|AspiegelBot|LieBaoFast|MicroMessenger|zh-CN|Kinza|Mb2345Browser).$ [NC]
RewriteRule .* - [F,L]

robots.txt

User-agent: *
Allow: /
Disallow: */shopby

#######################################
################ PAGES ################
#######################################

Disallow: /privacy-policy-cookie-restriction-mode/
Disallow: /terms/

#######################################
############# Block Bots ##############
#######################################

 User-agent: MJ12bot
 Disallow: /
 User-agent: SemrushBot
 Disallow: /
 User-agent: SemrushBot-SA
 Disallow: /
 User-agent: rogerbot
 Disallow:/
 User-agent: dotbot
 Disallow:/
 User-agent: AhrefsBot
 Disallow: /
 User-agent: Alexibot
 Disallow: /
 User-agent: SurveyBot
 Disallow: /
 User-agent: Xenu's
 Disallow: /
 User-agent: Xenu's Link Sleuth 1.1c
 Disallow: /
 User-agent: AspiegelBot
 Disallow: /

Am I missing something or writing something incorrectly? Ï'm kinda at a loss here.


问:
Does dart support operator overloading? (not to be confused with overriding)
This sounds like an exact duplicate of: Does dart support operator overloading

But the name is misleading, the question is about how to override existing operators (the == operator).

As far as I understand, overloading a function means having multiple implementations that vary only in their parameters, but not in the name of the function:

```<code>int max(int a, int b);
double max(double a, double b);
</code>```

By contrast, overriding means rewriting an existing implementation. Since the original function is replaced, there are no name clashes. This is common in OOP where you extend a base class and override its methods.

The docs say that there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

Would it be possible to write the following code:

```<code>class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}
</code>```

答:
In geometry.dart there is the following lines :

  /// Unary negation operator.
  ///
  /// Returns an offset with the coordinates negated.
  ///
  /// If the [Offset] represents an arrow on a plane, this operator returns the
  /// same arrow but pointing in the reverse direction.
  Offset operator -() => Offset(-dx, -dy);

After some research it appears that `-` operator can be used with 0 or 1 parameter, which allows it to be defined twice.

  /// Binary subtraction operator.
  ///
  /// Returns an offset whose [dx] value is the left-hand-side operand's [dx]
  /// minus the right-hand-side operand's [dx] and whose [dy] value is the
  /// left-hand-side operand's [dy] minus the right-hand-side operand's [dy].
  ///
  /// See also [translate].
  Offset operator -(Offset other) => Offset(dx - other.dx, dy - other.dy);

```

This is only due to the fact that - operator can be defined with 0 or 1 parameters.

Body:
This sounds like an exact duplicate of: Does dart support operator overloading

But the name is misleading, the question is about how to override existing operators (the == operator).

As far as I understand, overloading a function means having multiple implementations that vary only in their parameters, but not in the name of the function:

int max(int a, int b);
double max(double a, double b);

By contrast, overriding means rewriting an existing implementation. Since the original function is replaced, there are no name clashes. This is common in OOP where you extend a base class and override its methods.

The docs say that there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

Would it be possible to write the following code:

class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}

Body:
In geometry.dart there is the following lines :

  /// Unary negation operator.
  ///
  /// Returns an offset with the coordinates negated.
  ///
  /// If the [Offset] represents an arrow on a plane, this operator returns the
  /// same arrow but pointing in the reverse direction.
  Offset operator -() => Offset(-dx, -dy);

After some research it appears that `-` operator can be used with 0 or 1 parameter, which allows it to be defined twice.

  /// Binary subtraction operator.
  ///
  /// Returns an offset whose [dx] value is the left-hand-side operand's [dx]
  /// minus the right-hand-side operand's [dx] and whose [dy] value is the
  /// left-hand-side operand's [dy] minus the right-hand-side operand's [dy].
  ///
  /// See also [translate].
  Offset operator -(Offset other) => Offset(dx - other.dx, dy - other.dy);

This is only due to the fact that - operator can be defined with 0 or 1 parameters.


问:
How to group by without duplication - Apache Pig
I need to find the order value (unit price multiplied by quantity of products).  However, my results show duplication of order_id. How can i remove the duplication such that i get the order_id followed by order value? Any help is appreciated! Thanks!

Code:

```<code>orderdetails = load '/user/bigdata/order_detail.tbl' using PigStorage('|') as

(ORDER_ID:int,PRODUCT_ID:int,CUSTOMER_ID:int,SALESPERSON_ID:int,UNIT_PRICE:float,QUANTITY:int,DISCOUNT:float);

ordervalue = FOREACH orderdetails GENERATE ORDER_ID, UNIT_PRICE*QUANTITY as VALUE;

order_filter = FILTER ordervalue BY (ORDER_ID > 10269) AND (ORDER_ID < 10280);

groupOrder = GROUP order_filter BY (ORDER_ID);

groupOrdersum = FOREACH groupOrder GENERATE (order_filter.ORDER_ID),SUM(order_filter.VALUE) as ORDERVALUE;

dump groupOrdersum;
</code>```

Results

```<code>({(10270),(10270)},1376.0) ({(10271)},48.0) ({(10272),(10272),(10272)},1455.9999694824219) ({(10273),(10273),(10273),(10273),(10273)},2142.399932861328) ({(10274),(10274)},538.5999908447266) ({(10275),(10275)},307.1999969482422) ({(10276),(10276)},420.0) ({(10277),(10277)},1200.8000183105469) ({(10278),(10278),(10278),(10278)},1488.7999877929688) ({(10279)},468.0)
</code>```

答:
I think you need to change the:

```<code>groupOrdersum = FOREACH groupOrder GENERATE (order_filter.ORDER_ID),SUM(order_filter.VALUE) as ORDERVALUE;
</code>```

to

```<code>groupOrdersum = FOREACH groupOrder GENERATE
    group AS ORDERID,
    SUM(order_filter.VALUE) as ORDERVALUE;
</code>```

I think right now you're generating the grouped bag of order ids (i.e the value) and not the actual key.

Body:
I need to find the order value (unit price multiplied by quantity of products).  However, my results show duplication of order_id. How can i remove the duplication such that i get the order_id followed by order value? Any help is appreciated! Thanks!

Code:

orderdetails = load '/user/bigdata/order_detail.tbl' using PigStorage('|') as

(ORDER_ID:int,PRODUCT_ID:int,CUSTOMER_ID:int,SALESPERSON_ID:int,UNIT_PRICE:float,QUANTITY:int,DISCOUNT:float);

ordervalue = FOREACH orderdetails GENERATE ORDER_ID, UNIT_PRICE*QUANTITY as VALUE;

order_filter = FILTER ordervalue BY (ORDER_ID > 10269) AND (ORDER_ID < 10280);

groupOrder = GROUP order_filter BY (ORDER_ID);

groupOrdersum = FOREACH groupOrder GENERATE (order_filter.ORDER_ID),SUM(order_filter.VALUE) as ORDERVALUE;

dump groupOrdersum;

Results

({(10270),(10270)},1376.0) ({(10271)},48.0) ({(10272),(10272),(10272)},1455.9999694824219) ({(10273),(10273),(10273),(10273),(10273)},2142.399932861328) ({(10274),(10274)},538.5999908447266) ({(10275),(10275)},307.1999969482422) ({(10276),(10276)},420.0) ({(10277),(10277)},1200.8000183105469) ({(10278),(10278),(10278),(10278)},1488.7999877929688) ({(10279)},468.0)

Body:
I think you need to change the:

groupOrdersum = FOREACH groupOrder GENERATE (order_filter.ORDER_ID),SUM(order_filter.VALUE) as ORDERVALUE;

to

groupOrdersum = FOREACH groupOrder GENERATE
    group AS ORDERID,
    SUM(order_filter.VALUE) as ORDERVALUE;

I think right now you're generating the grouped bag of order ids (i.e the value) and not the actual key.


问:
Redirect www.domain.com/uk to www.domain.co.uk/uk
I'm no .htaccess expert, but I've tried a few different things to redirect a domain to no avail.

I've got a UK and US domain...some US pages have uk extension, and need to be pointed to the proper UK domain:

www.domain.com/uk needs to be rewritten to www.domain.co.uk/uk

Ex. If someone types in www.domain.com/uk/about it will be rewritten as www.domain.co.uk/uk/about

Edit: Paths with /uk should be rewritten

So www.domain.com/uk and www.domain.co.uk should be rewritten to www.domain.co.uk/uk/

答:
You can try something like this:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule (.*) http://www.domain.co.uk/$1 [L,R=301]
</code>```

The important point is to use a RewriteCondition that works on the HTTP Host header. Simply speaking, if a RewriteCond is placed before a normal RewriteRule then the rule is only used if the the condition matches.

The code excerpt above redirects all requests from the .COM to the .CO.UK domain, so if you only need to redirect certain directory, then you need to adjust the rule accordingly, e.g.:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$
RewriteRule uk(.*) http://www.domain.co.uk/uk$1 [L,R=301]
</code>```

Edit: I hope that this will work for you according to your edit.

The first rule rewrites http://www.domain.com/uk and http://www.domain.com/uk/anything to http://www.domain.co.uk/uk/anything.

The second rule rewrites http://www.domain.co.uk to http://www.domain.co.uk/uk/.

Edit 2: I changed the rule (modified the last one and added another one) to reflect the demand for rewrites on .co.uk/something. If the path starts with uk/ then it just passes through, otherwise it gets rewritten to uk/something.

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule uk($|/.*) http://www.domain.co.uk/uk$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$ [NC]
RewriteRule ^uk/(.*) - [PT,L]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$ [NC]
RewriteRule (.*) http://www.domain.co.uk/uk/$1 [L,R=301]
</code>```

Body:
You can try something like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule (.*) http://www.domain.co.uk/$1 [L,R=301]

The important point is to use a RewriteCondition that works on the HTTP Host header. Simply speaking, if a RewriteCond is placed before a normal RewriteRule then the rule is only used if the the condition matches.

The code excerpt above redirects all requests from the .COM to the .CO.UK domain, so if you only need to redirect certain directory, then you need to adjust the rule accordingly, e.g.:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$
RewriteRule uk(.*) http://www.domain.co.uk/uk$1 [L,R=301]

Edit: I hope that this will work for you according to your edit.

The first rule rewrites http://www.domain.com/uk and http://www.domain.com/uk/anything to http://www.domain.co.uk/uk/anything.

The second rule rewrites http://www.domain.co.uk to http://www.domain.co.uk/uk/.

Edit 2: I changed the rule (modified the last one and added another one) to reflect the demand for rewrites on .co.uk/something. If the path starts with uk/ then it just passes through, otherwise it gets rewritten to uk/something.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule uk($|/.*) http://www.domain.co.uk/uk$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$ [NC]
RewriteRule ^uk/(.*) - [PT,L]
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.co\.uk$ [NC]
RewriteRule (.*) http://www.domain.co.uk/uk/$1 [L,R=301]


问:
How do I use ValidateAntiForgeryToken in an HTTP GET request in ASP.NET Core?
Normally you use ValidateAntiForgeryToken with HttpPost, like this:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ...
</code>```

I want to use ValidateAntiForgeryToken without HttpPost so that I can pass the token in as a URL parameter. How can I do this? Will it just work without HttpPost, and if so, what's the name of the parameter?

答:
With ASP.NET Core 3.1 things seem to be a lot easier.

All you have to do is pass a "RequestVerificationToken" header in the AJAX-call:

```<code>let token = $('input[name="__RequestVerificationToken"]').val();
let headers = { "RequestVerificationToken": token };
$.ajax({ ..., type: 'GET', headers: headers, ... });
</code>```

For  POST-calls, the token can be passed via the object in the body (or the FormData) as a "__RequestVerificationToken" field:

```<code>let postData["__RequestVerificationToken"] = token;
$.ajax({ ..., type: 'POST', data: postData, ... });
</code>```

The method in the controller may be defined as follows:

```<code>[ValidateAntiForgeryToken]
public IActionResult GetNotifications()
{
    var notifications = _notificationService.GetNotifications();
    return Json(notifications);
}
</code>```

Make sure the AntiforgeryOptions.HeaderName and AntiforgeryOptions.FormFieldName are not modified, otherwise change the names above with the respective values.

Body:
Normally you use ValidateAntiForgeryToken with HttpPost, like this:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ...

I want to use ValidateAntiForgeryToken without HttpPost so that I can pass the token in as a URL parameter. How can I do this? Will it just work without HttpPost, and if so, what's the name of the parameter?

Body:
With ASP.NET Core 3.1 things seem to be a lot easier.

All you have to do is pass a "RequestVerificationToken" header in the AJAX-call:

let token = $('input[name="__RequestVerificationToken"]').val();
let headers = { "RequestVerificationToken": token };
$.ajax({ ..., type: 'GET', headers: headers, ... });

For  POST-calls, the token can be passed via the object in the body (or the FormData) as a "__RequestVerificationToken" field:

let postData["__RequestVerificationToken"] = token;
$.ajax({ ..., type: 'POST', data: postData, ... });

The method in the controller may be defined as follows:

[ValidateAntiForgeryToken]
public IActionResult GetNotifications()
{
    var notifications = _notificationService.GetNotifications();
    return Json(notifications);
}

Make sure the AntiforgeryOptions.HeaderName and AntiforgeryOptions.FormFieldName are not modified, otherwise change the names above with the respective values.


问:
Logistic Regression sklearn with categorical Output
i have to train a model with logistic Regression in sklearn. I saw everywhere that the outcome has to be binary but my label is good, bad or normal. I have 12 features and i don't know how can i deal with three Labels ? I am very thankful for every answer</p>

答:
You can use Multinomial Logistic Regression.
In python, you can modify your Logistic Regression code as:

LogisticRegression(multi_class='multinomial').fit(X_train,y_train)
```

You can see Logistic Regression documentation in Scikit-Learn for more details.

Body:
You can use Multinomial Logistic Regression.
In python, you can modify your Logistic Regression code as:

LogisticRegression(multi_class='multinomial').fit(X_train,y_train)

You can see Logistic Regression documentation in Scikit-Learn for more details.


问:
How to do both client side and server side validation?
I was creating a HTML form in which I was doing both client side and server side validation.I used the below code.

```<code><form action='logic.php' method='post' id='login'>
    <input type='text' placeholder='Enter name' name='name'>
    <input type='submit'>
</form>

// Jquery
$(document).ready(function(){

    function validate_name(input_id,error_id,msg="Name"){
        const x = document.getElementById(input_id).value;
        const y = document.getElementById(error_id);
        const pattern = /^[a-zA-Z]+$/
        if(x!==""){
            if(pattern.test(x) ){
                if(x.length<3 || x.length>10){
                    y.innerHTML = msg+' should be between 3 and 10 characters.'
                    return false;
                }
                else{
                    y.innerHTML = '';
                    return true;
                }
            }
            else{
                y.innerHTML = 'Should contain only alphabets.'
                return false;
            }
        }
        else{
            y.innerHTML = "Please Enter Your "+msg;
            return false;
        }
    }

    $('#login').submit(function(e){
        e.preventDefault();
        let name = validate_name('rollno','rerror');
        let subject_name = validate_select('subject_dropdown','serror');
        if(name === true & subject_name === true){
            window.location = 'controller/indexPage_logic.php';
        }
    })
});
</code>```

I may able to do client side validation but if the form is properly validated I can't able to access the input value using $_POST['name'] in server side PHP.I think this is due to window.location.Is there any better way to do both side validation?

答:
Your location change does a GET when you need a POST

Change to

```<code>$('#login').submit(function(e){
    e.preventDefault();
    let name = validate_name('rollno','rerror');
    let subject_name = validate_select('subject_dropdown','serror');
    if(name === true & subject_name === true){
        $.post('controller/indexPage_logic.php', {name:rollno}, function(response) { console.log(response)}); // do what you need to do when valid on the server too
    }
})
</code>```

Body:
I was creating a HTML form in which I was doing both client side and server side validation.I used the below code.

<form action='logic.php' method='post' id='login'>
    <input type='text' placeholder='Enter name' name='name'>
    <input type='submit'>
</form>

// Jquery
$(document).ready(function(){

    function validate_name(input_id,error_id,msg="Name"){
        const x = document.getElementById(input_id).value;
        const y = document.getElementById(error_id);
        const pattern = /^[a-zA-Z]+$/
        if(x!==""){
            if(pattern.test(x) ){
                if(x.length<3 || x.length>10){
                    y.innerHTML = msg+' should be between 3 and 10 characters.'
                    return false;
                }
                else{
                    y.innerHTML = '';
                    return true;
                }
            }
            else{
                y.innerHTML = 'Should contain only alphabets.'
                return false;
            }
        }
        else{
            y.innerHTML = "Please Enter Your "+msg;
            return false;
        }
    }

    $('#login').submit(function(e){
        e.preventDefault();
        let name = validate_name('rollno','rerror');
        let subject_name = validate_select('subject_dropdown','serror');
        if(name === true & subject_name === true){
            window.location = 'controller/indexPage_logic.php';
        }
    })
});

I may able to do client side validation but if the form is properly validated I can't able to access the input value using $_POST['name'] in server side PHP.I think this is due to window.location.Is there any better way to do both side validation?

Body:
Your location change does a GET when you need a POST

Change to

$('#login').submit(function(e){
    e.preventDefault();
    let name = validate_name('rollno','rerror');
    let subject_name = validate_select('subject_dropdown','serror');
    if(name === true & subject_name === true){
        $.post('controller/indexPage_logic.php', {name:rollno}, function(response) { console.log(response)}); // do what you need to do when valid on the server too
    }
})


问:
Convert/cast an stdClass object to another class
I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.

For instance something along the lines of:

```<code>//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;
</code>```

I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.

Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.

Cheers

答:
Convert it to an array, return the first element of that array, and set the return param to that class. Now you should get the autocomplete for that class as it will regconize it as that class instead of stdclass.</p>

```<code>/**
 * @return Order
 */
    public function test(){
    $db = new Database();

    $order = array();
    $result = $db->getConnection()->query("select * from `order` where productId in (select id from product where name = 'RTX 2070')");
    $data = $result->fetch_object("Order"); //returns stdClass
    array_push($order, $data);

    $db->close();
    return $order[0];
}
</code>```

Body:
I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.

For instance something along the lines of:

//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;

I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.

Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.

Cheers

Body:
Convert it to an array, return the first element of that array, and set the return param to that class. Now you should get the autocomplete for that class as it will regconize it as that class instead of stdclass.

/**
 * @return Order
 */
    public function test(){
    $db = new Database();

    $order = array();
    $result = $db->getConnection()->query("select * from `order` where productId in (select id from product where name = 'RTX 2070')");
    $data = $result->fetch_object("Order"); //returns stdClass
    array_push($order, $data);

    $db->close();
    return $order[0];
}


问:
Kibana visualization without time aggregation
I have data with the following format::

```<code>{
  timestamp: Date,
  x: number
}
</code>```

I want to display these values simply in a line, without any aggregation over x, but in Kibana it always requires me to select some kind of aggregation, like average.

答:
It is possible to create the line-chart that you request, but for Kibana to create an visualization, I'm afraid an aggregation would be necessary.

Kibana basis its visualization on buckets (Date, x-axis) and metrics (x, y-axis). Buckets are aggregations of documents over a specified search (almost 30 aggregation methods)
. Metrics are value(s) based on the documents contained in each bucket (almost 20 aggregation methods)
(https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html).

However, you could try to create buckets with 'date_histogram' for which the time interval is small enough so it contain one document. Then for the metric aggregation you could select min or max aggregation (Note: This assumes though that you timestamp is unique for each document).

Body:
I have data with the following format::

{
  timestamp: Date,
  x: number
}

I want to display these values simply in a line, without any aggregation over x, but in Kibana it always requires me to select some kind of aggregation, like average.


答:
Yep, you can definitely do that, but you'll need to check the type inside the single method since there can't be duplicate methods for one operator:</p>

```<code>class Matrix {
  int num = 0;
  Matrix(this.num);
  Matrix operator+(dynamic b) {
    if(b is int) {
      return Matrix(this.num + b);
    } else if(b is Matrix){
      return Matrix(this.num + b.num);
    }
  }
}

void main() {
  print((Matrix(5) + 6).num);

  print((Matrix(7) + Matrix(3)).num);
}
</code>```

Title: Does dart support operator overloading? (not to be confused with overriding)

Body:
Yep, you can definitely do that, but you'll need to check the type inside the single method since there can't be duplicate methods for one operator:

class Matrix {
  int num = 0;
  Matrix(this.num);
  Matrix operator+(dynamic b) {
    if(b is int) {
      return Matrix(this.num + b);
    } else if(b is Matrix){
      return Matrix(this.num + b.num);
    }
  }
}

void main() {
  print((Matrix(5) + 6).num);

  print((Matrix(7) + Matrix(3)).num);
}


问:
Rendering the content asynchronously in reactJS
Basically I have a set of dynamic tables that are being displayed based on the values passed. If there is an empty array passed, it should show No data found. In my case when I send data to the table, all the tables will show "No data found" first then followed by the actual table content. I am not sure what is causing this.

The data is loaded asynchronously , it shows no data found and then the actual content. I have added setInterval to show this asynchronous nature

Sandbox:https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js:0-1322

Can someone help me?

Parent

```<code>import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";

const d1 = [{ name: "test", age: "20" }, { name: "test1", age: "15" }];
const d2 = [{ area: "area", pin: "123" }, { area: "area1", pin: "1245" }];
const c1 = [
  { Header: "Name", accessor: "name" },
  { Header: "Age", accessor: "age" }
];
const c2 = [
  { Header: "Area", accessor: "area" },
  { Header: "Pin", accessor: "pin" }
];
const d3 = [];
const c3 = [];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data1: [],
      column1: [],
      data2: [],
      column2: [],
      data3: [],
      column3: []
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        data1: d1,
        column1: c1
      });
    }, 2000);
    setTimeout(() => {
      this.setState({
        data2: d2,
        column2: c2
      });
    }, 2500);
    this.setState({
      data3: d3,
      column3: c3
    });
  }

  render() {
    return (
      <>
        <DataGrid data={this.state.data1} columns={this.state.column1} />
        <DataGrid data={this.state.data2} columns={this.state.column2} />
        <DataGrid data={this.state.data3} columns={this.state.column3} />
      </>
    );
  }
}
</code>```

Child

```<code>import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  };

  formatData = () => {
    let arr = [];
    if (this.props.data && this.props.data.length > 0)
      arr = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    return arr;
  };

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = this.formatData();
    return (
      <>
        {showLink && (
          <button onClick={this.toggleState}>
            Show {showMore ? "Less" : "More"}
          </button>
        )}
        {data && data.length > 0 ? (
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
            minRows={0}
            NoDataComponent={() => null}
            loading={false}
          />
        ) : (
          "No data found"
        )}
      </>
    );
  }
}

</code>```

答:
Adding few points to the above answer.

The reason it was behaving in that way is not because of the asynchronous behavior but the  life-cycle nature of the React component.which in this case takes place as:

The DataGrid is rendered with initial state of data i.e empty[] array.

No data is shown because empty[] array is passed in this cycle.

Then you are setting the state in componentDidMount.

To show the effect Datagrid is again re rendered with actual data.

Body:
Basically I have a set of dynamic tables that are being displayed based on the values passed. If there is an empty array passed, it should show No data found. In my case when I send data to the table, all the tables will show "No data found" first then followed by the actual table content. I am not sure what is causing this.

The data is loaded asynchronously , it shows no data found and then the actual content. I have added setInterval to show this asynchronous nature

Sandbox:https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js:0-1322

Can someone help me?

Parent

import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";

const d1 = [{ name: "test", age: "20" }, { name: "test1", age: "15" }];
const d2 = [{ area: "area", pin: "123" }, { area: "area1", pin: "1245" }];
const c1 = [
  { Header: "Name", accessor: "name" },
  { Header: "Age", accessor: "age" }
];
const c2 = [
  { Header: "Area", accessor: "area" },
  { Header: "Pin", accessor: "pin" }
];
const d3 = [];
const c3 = [];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data1: [],
      column1: [],
      data2: [],
      column2: [],
      data3: [],
      column3: []
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        data1: d1,
        column1: c1
      });
    }, 2000);
    setTimeout(() => {
      this.setState({
        data2: d2,
        column2: c2
      });
    }, 2500);
    this.setState({
      data3: d3,
      column3: c3
    });
  }

  render() {
    return (
      <>
        <DataGrid data={this.state.data1} columns={this.state.column1} />
        <DataGrid data={this.state.data2} columns={this.state.column2} />
        <DataGrid data={this.state.data3} columns={this.state.column3} />
      </>
    );
  }
}

Child

import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  };

  formatData = () => {
    let arr = [];
    if (this.props.data && this.props.data.length > 0)
      arr = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    return arr;
  };

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = this.formatData();
    return (
      <>
        {showLink && (
          <button onClick={this.toggleState}>
            Show {showMore ? "Less" : "More"}
          </button>
        )}
        {data && data.length > 0 ? (
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
            minRows={0}
            NoDataComponent={() => null}
            loading={false}
          />
        ) : (
          "No data found"
        )}
      </>
    );
  }
}


问:
Python Dictionary How to create combinations of list items?
I have a dictionary which has value as a list.

```<code>thisdict = {  'G1' : [10,20],
              'G2' : [12,13]

}
</code>```

I want to create new dictionary with  all possible 4 combinations.

C1 :[10,12]

C2 :[10,13]

C3 :[20,12]

C4 :[20,13]

How do I create that ?

答:
As other stated, you can use itertools.product for this.

But you have just two lists, you can also just use two for loops:

```<code>> d = { f'C{i+1}': {'G1':g1e, 'G2':g2e}
      for i, (g1e, g2e) in
      enumerate((g1e, g2e) for g1e in thisdict['G1']
                           for g2e in thisdict['G2']) }
> d
{'C1': {'G1': 10, 'G2': 12},
 'C2': {'G1': 10, 'G2': 13},
 'C3': {'G1': 20, 'G2': 12},
 'C4': {'G1': 20, 'G2': 13}}
</code>```

NB: I used the format requested in the comment to another answer.

Body:
I have a dictionary which has value as a list.

thisdict = {  'G1' : [10,20],
              'G2' : [12,13]

}

I want to create new dictionary with  all possible 4 combinations.

C1 :[10,12]

C2 :[10,13]

C3 :[20,12]

C4 :[20,13]

How do I create that ?

Body:
As other stated, you can use itertools.product for this.

But you have just two lists, you can also just use two for loops:

> d = { f'C{i+1}': {'G1':g1e, 'G2':g2e}
      for i, (g1e, g2e) in
      enumerate((g1e, g2e) for g1e in thisdict['G1']
                           for g2e in thisdict['G2']) }
> d
{'C1': {'G1': 10, 'G2': 12},
 'C2': {'G1': 10, 'G2': 13},
 'C3': {'G1': 20, 'G2': 12},
 'C4': {'G1': 20, 'G2': 13}}

NB: I used the format requested in the comment to another answer.


问:
Materialized view to be refreshed only when the select query returns data in oracle
```<code>Create materialized view mv_testdata
BUILD IMMEDIATE
REFRESH FORCE
AS
SELECT * FROM VW_TESTDATA;
</code>```

I want the view to be refreshed weekly once and only when the data available in vw_testdata view. Trying with triggers also but it didn't work.

Is it possible to refresh mv only data available in view?

答:
If vw_testdata is an "ordinary" view, it is a stored query and contains no data. I presume your concern is that - if that query (at some time) fetches "nothing" and you refresh the materialized view, you'll lose data in the materialized view.

If that's so, create a stored procedure, e.g.

```<code>create or replace procedure p_refresh as
  l_cnt number;
begin
  select max(1)
    into l_cnt
    from vw_testdata
    where exists (select null from vw_testdata);

  if l_cnt = 1 then
     dbms_mview.refresh('mv_testdata');
  end if;
end;
/
</code>```

It checks whether anything exists in vw_testadata; if so, it refreshes the materialized view.

Now schedule that procedure to be executed weekly.

Body:
Create materialized view mv_testdata
BUILD IMMEDIATE
REFRESH FORCE
AS
SELECT * FROM VW_TESTDATA;

I want the view to be refreshed weekly once and only when the data available in vw_testdata view. Trying with triggers also but it didn't work.

Is it possible to refresh mv only data available in view?

Body:
If vw_testdata is an "ordinary" view, it is a stored query and contains no data. I presume your concern is that - if that query (at some time) fetches "nothing" and you refresh the materialized view, you'll lose data in the materialized view.

If that's so, create a stored procedure, e.g.

create or replace procedure p_refresh as
  l_cnt number;
begin
  select max(1)
    into l_cnt
    from vw_testdata
    where exists (select null from vw_testdata);

  if l_cnt = 1 then
     dbms_mview.refresh('mv_testdata');
  end if;
end;
/

It checks whether anything exists in vw_testadata; if so, it refreshes the materialized view.

Now schedule that procedure to be executed weekly.


问:
Standard way to "clamp" a number between two values in Swift
Given:

```<code>let a = 4.2
let b = -1.3
let c = 6.4
</code>```

I want to know the simplest, Swiftiest way to clamp these values to a given range, say 0...5, such that:

```<code>a -> 4.2
b -> 0
c -> 5
</code>```

I know I can do the following:

```<code>let clamped = min(max(a, 0), 5)
</code>```

Or something like:

```<code>let clamped = (a < 0) ? 0 : ((a > 5) ? 5 : a)
</code>```

But I was wondering if there were any other ways to do this in Swift—in particular, I want to know (and document on SO, since there doesn't appear to be a question about clamping numbers in Swift) whether there is anything in the Swift standard library intended specifically for this purpose.

There may not be, and if so, that's also an answer I'll happily accept.

答:
Following up on @Fattie's answer and my comment, here's my suggestion for clarity:</p>
```<code>extension Comparable {
    func clamped(_ a: Self, _ b: Self) -> Self {
        min(max(self, a), b)
    }
}
</code>```

Body:
Given:

let a = 4.2
let b = -1.3
let c = 6.4

I want to know the simplest, Swiftiest way to clamp these values to a given range, say 0...5, such that:

a -> 4.2
b -> 0
c -> 5

I know I can do the following:

let clamped = min(max(a, 0), 5)

Or something like:

let clamped = (a < 0) ? 0 : ((a > 5) ? 5 : a)

But I was wondering if there were any other ways to do this in Swift—in particular, I want to know (and document on SO, since there doesn't appear to be a question about clamping numbers in Swift) whether there is anything in the Swift standard library intended specifically for this purpose.

There may not be, and if so, that's also an answer I'll happily accept.

Body:
Following up on @Fattie's answer and my comment, here's my suggestion for clarity:

extension Comparable {
    func clamped(_ a: Self, _ b: Self) -> Self {
        min(max(self, a), b)
    }
}


问:
How to export data from GCP Postgres sql to a csv file in GCS through AIRFLOW?
We are using GCP with Postgres sql. Need to export one table from postgres to a csv file in google cloud storage bucket but only through AIRFLOW.
Not sure whether API call / Operator can be used.
Please advise if possible with sample code.

Thanks
Raj.

答: What you're looking to do should be feasible with the PostgresToGCSOperator. Here you can find a usage example.</p>


问:
POWERSHELL: Simplest way to save string variable to csv file
I know a little bit of Bash scripting, but I am very new to PowerShell. When I execute below code using bash, everything is fine. But, when I use PowerShell, each entry per echo is saved only in a single cell in Excel. Why is it like this? How can I accomplish my objective in the simplest way?

```<code>echo "1,2,3" > file.csv
echo "A,B,C" >> file.csv
</code>```

UNDESIRED:

DESIRED:

I tried to Google it. But, in my understanding, they are converting the string type variables to something like PS Object and convert to CSV format. I tried it and it worked. But I had to force include a header.

```<code>New-Object -Type PSObject -Property @{
'X' = $A
'Y' = $B
'Z' = $C
} | Export-Csv 'C:\Temp\test.csv' -NoType
</code>```

When I also opened the csv file using notepad, every word has double quotation marks (which I don't prefer to have)

You see, that is way more complicated compared to Linux Scripting. Can someone teach me the simplest way to do what I want? Thank you very much!

答:
If in your system locale the ListSeparator character is NOT the comma, double-clicking a comma-delimited csv file will open Excel with all values in the same column.

I believe this is what happens here.

You can check by typing

```<code>[cultureinfo]::CurrentCulture.TextInfo.ListSeparator
</code>```

in PowerShell

To have Excel 'understand' a CSV when you double-click it, add -UseCulture switch to the cmdlet:

```<code>Export-Csv 'C:\Temp\test.csv' -UseCulture -NoTypeInformation
</code>```

As for the quotes around the values:

They are not always necessary, but sometimes essential, for instance if the value has leading or trailing space characters, or if the value contains the delimiter character itself.

Just leave them as-is, Excel knows how to handle that.

If you really can't resist on having a csv without quotes, please first have a look at the answers given here about that subject.

Edit

If you are absolutely sure all fields can do without quoting, you can do this:

```<code>$sep = [cultureinfo]::CurrentCulture.TextInfo.ListSeparator
"1,2,3", "A,B,C" -replace ',', $sep | Out-File -FilePath 'D:\Test\file.csv' -Encoding utf8
</code>```

Body:
I know a little bit of Bash scripting, but I am very new to PowerShell. When I execute below code using bash, everything is fine. But, when I use PowerShell, each entry per echo is saved only in a single cell in Excel. Why is it like this? How can I accomplish my objective in the simplest way?

echo "1,2,3" > file.csv
echo "A,B,C" >> file.csv

UNDESIRED:

DESIRED:

I tried to Google it. But, in my understanding, they are converting the string type variables to something like PS Object and convert to CSV format. I tried it and it worked. But I had to force include a header.

New-Object -Type PSObject -Property @{
'X' = $A
'Y' = $B
'Z' = $C
} | Export-Csv 'C:\Temp\test.csv' -NoType

When I also opened the csv file using notepad, every word has double quotation marks (which I don't prefer to have)

You see, that is way more complicated compared to Linux Scripting. Can someone teach me the simplest way to do what I want? Thank you very much!

Body:
If in your system locale the ListSeparator character is NOT the comma, double-clicking a comma-delimited csv file will open Excel with all values in the same column.

I believe this is what happens here.

You can check by typing

[cultureinfo]::CurrentCulture.TextInfo.ListSeparator

in PowerShell

To have Excel 'understand' a CSV when you double-click it, add -UseCulture switch to the cmdlet:

Export-Csv 'C:\Temp\test.csv' -UseCulture -NoTypeInformation

As for the quotes around the values:

They are not always necessary, but sometimes essential, for instance if the value has leading or trailing space characters, or if the value contains the delimiter character itself.

Just leave them as-is, Excel knows how to handle that.

If you really can't resist on having a csv without quotes, please first have a look at the answers given here about that subject.

Edit

If you are absolutely sure all fields can do without quoting, you can do this:

$sep = [cultureinfo]::CurrentCulture.TextInfo.ListSeparator
"1,2,3", "A,B,C" -replace ',', $sep | Out-File -FilePath 'D:\Test\file.csv' -Encoding utf8


问:
Apply UICollectionViewDelegateFlowLayout on specific Collection View in View Controller with multiple Collection Views
I am designing a screen where I have 3 Collectio Views.

```<code>@IBOutlet weak var colorCollectionView: UICollectionView!
@IBOutlet weak var sizesCollectionView: UICollectionView!
@IBOutlet weak var imgCollectionView: UICollectionView!
</code>```

I wanna apply some methods of UICollectionViewDelegateFlowLayout on just imgCollectionView.

```<code>extension ItemDetailVC: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if collectionView == imgCollectionView{
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == imgCollectionView{
            let size = collectionView.frame.size
            return CGSize(width: size.width, height: size.height)
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == imgCollectionView{
            return 0.0
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == imgCollectionView{
            return 0.0
        }
    }
}
</code>```

but I am having the errors for the missing return value.

答:
You can create custom UICollectionView to do this

Create custom CollectionView

public class ImageCollectionView: UICollectionView {

  override public func awakeFromNib() {
    super.awakeFromNib()

    self.delegate = self
  }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension ImageCollectionView: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size = collectionView.frame.size
        return CGSize(width: size.width, height: size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }
}
```

<hr>

<ul>
<li>Set your custom <code>CollectionView</code> in your <code>ItemDetailVC</code></li>
</ul>

<pre class="lang-swift prettyprint-override"><code>@IBOutlet weak var imgCollectionView: ImageCollectionView!
</code>```

NOTE: You don't need to set imgCollectionView.delegate in ItemDetailVC

Remove UICollectionViewDelegateFlowLayout functions from ItemDetailVC

Body:
I am designing a screen where I have 3 Collectio Views.

@IBOutlet weak var colorCollectionView: UICollectionView!
@IBOutlet weak var sizesCollectionView: UICollectionView!
@IBOutlet weak var imgCollectionView: UICollectionView!

I wanna apply some methods of UICollectionViewDelegateFlowLayout on just imgCollectionView.

extension ItemDetailVC: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if collectionView == imgCollectionView{
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == imgCollectionView{
            let size = collectionView.frame.size
            return CGSize(width: size.width, height: size.height)
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == imgCollectionView{
            return 0.0
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == imgCollectionView{
            return 0.0
        }
    }
}

but I am having the errors for the missing return value.

Body:
You can create custom UICollectionView to do this

Create custom CollectionView

public class ImageCollectionView: UICollectionView {

  override public func awakeFromNib() {
    super.awakeFromNib()

    self.delegate = self
  }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension ImageCollectionView: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size = collectionView.frame.size
        return CGSize(width: size.width, height: size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }
}

Set your custom CollectionView in your ItemDetailVC

@IBOutlet weak var imgCollectionView: ImageCollectionView!

NOTE: You don't need to set imgCollectionView.delegate in ItemDetailVC

Remove UICollectionViewDelegateFlowLayout functions from ItemDetailVC