问:
Bitmap Rotate not working for 1Bpp but ok for 32BppRGB
```<code>  public Bitmap Rotate1BppIndexedImage(Bitmap SourceBitmap)
    {
        int originalWidth = SourceBitmap.Width;
        int originalHeight = SourceBitmap.Height;

        Bitmap rotatedBitmap = new Bitmap(SourceBitmap.Height, SourceBitmap.Width, SourceBitmap.PixelFormat);
        BitmapData rotatedData = rotatedBitmap.LockBits(new Rectangle(0, 0, rotatedBitmap.Width, rotatedBitmap.Height), ImageLockMode.WriteOnly, SourceBitmap.PixelFormat);

        BitmapData SourceBitmapData = SourceBitmap.LockBits(new Rectangle(0, 0, originalWidth, originalHeight), ImageLockMode.ReadOnly, SourceBitmap.PixelFormat);

        int newWidthMinusOne = rotatedBitmap.Width-1;
        int newWidth = rotatedBitmap.Width;

        unsafe
        {
           for (int y=0; y< originalHeight; y++)
            {
                int destinationX = newWidthMinusOne - y;
                for(int x =0; x<originalWidth; x++)
                {
                    bool Pixel;
                    Pixel = GetIndexedPixel(x, y, SourceBitmapData);

                    int DestinationPixel_X = x + y * originalWidth;
                    int DestinationPixel_Y = destinationX + x * newWidth;

                    SetIndexedPixel(DestinationPixel_X, DestinationPixel_Y, rotatedData, Pixel);
                }
            }
            SourceBitmap.UnlockBits(SourceBitmapData);
            rotatedBitmap.UnlockBits(rotatedData);
            rotatedBitmap.SetResolution(SourceBitmap.HorizontalResolution, SourceBitmap.VerticalResolution);
        }
        return rotatedBitmap;
    }
    private unsafe void SetIndexedPixel(int x, int y, BitmapData bmd, bool pixel)
    {
        byte* p = (byte*)bmd.Scan0.ToPointer();
        int index = y * bmd.Stride + (x >> 3);
        byte mask = (byte)(0x80 >> (x & 0x7));

        if (pixel)
            p[index] |= mask;
        else
            p[index] &= (byte)(mask ^ 0xff);
    }
    protected unsafe bool GetIndexedPixel(int x, int y, BitmapData bmd)
    {
        byte* p = (byte*)bmd.Scan0.ToPointer();
        int index = y * bmd.Stride + (x >> 3);
        byte mask = (byte)(0x80 >> (x & 0x7));
        return ((p[index] & mask)!=0);
    }`
</code>```

This code is working find for 32Bpprgb but not working for 1bppIndexed file. I am trying to rotate 1Bpp image but not working.
It says AccessViolation @ this line => rotatedPointer[destinationPosition] = originalPointer[sourcePosition];
Thanks in advance for help.
My image Size is 18144 X 46800 1Bpp indexed Bitmap image.

答:
Here is your first problem: int bytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(originalBitmap.PixelFormat)/32; You are never using the result of that call. And it is 1 for 32BppRGB and 0 for 1Bpp (dividing 1 by 32 yields 0).

Your crash is because width/height are in pixels, while your pointer size is 4. rotatedPointer[1] would point to pixels(!) 32 to 63 of a row. You can't address a single bit that way.

You basically have to rewrite this method completely to support 1Bpp, as you need to do a lot of bit-mangling to get that working.

Body:
  public Bitmap Rotate1BppIndexedImage(Bitmap SourceBitmap)
    {
        int originalWidth = SourceBitmap.Width;
        int originalHeight = SourceBitmap.Height;

        Bitmap rotatedBitmap = new Bitmap(SourceBitmap.Height, SourceBitmap.Width, SourceBitmap.PixelFormat);
        BitmapData rotatedData = rotatedBitmap.LockBits(new Rectangle(0, 0, rotatedBitmap.Width, rotatedBitmap.Height), ImageLockMode.WriteOnly, SourceBitmap.PixelFormat);

        BitmapData SourceBitmapData = SourceBitmap.LockBits(new Rectangle(0, 0, originalWidth, originalHeight), ImageLockMode.ReadOnly, SourceBitmap.PixelFormat);

        int newWidthMinusOne = rotatedBitmap.Width-1;
        int newWidth = rotatedBitmap.Width;

        unsafe
        {
           for (int y=0; y< originalHeight; y++)
            {
                int destinationX = newWidthMinusOne - y;
                for(int x =0; x<originalWidth; x++)
                {
                    bool Pixel;
                    Pixel = GetIndexedPixel(x, y, SourceBitmapData);

                    int DestinationPixel_X = x + y * originalWidth;
                    int DestinationPixel_Y = destinationX + x * newWidth;

                    SetIndexedPixel(DestinationPixel_X, DestinationPixel_Y, rotatedData, Pixel);
                }
            }
            SourceBitmap.UnlockBits(SourceBitmapData);
            rotatedBitmap.UnlockBits(rotatedData);
            rotatedBitmap.SetResolution(SourceBitmap.HorizontalResolution, SourceBitmap.VerticalResolution);
        }
        return rotatedBitmap;
    }
    private unsafe void SetIndexedPixel(int x, int y, BitmapData bmd, bool pixel)
    {
        byte* p = (byte*)bmd.Scan0.ToPointer();
        int index = y * bmd.Stride + (x >> 3);
        byte mask = (byte)(0x80 >> (x & 0x7));

        if (pixel)
            p[index] |= mask;
        else
            p[index] &= (byte)(mask ^ 0xff);
    }
    protected unsafe bool GetIndexedPixel(int x, int y, BitmapData bmd)
    {
        byte* p = (byte*)bmd.Scan0.ToPointer();
        int index = y * bmd.Stride + (x >> 3);
        byte mask = (byte)(0x80 >> (x & 0x7));
        return ((p[index] & mask)!=0);
    }`

This code is working find for 32Bpprgb but not working for 1bppIndexed file. I am trying to rotate 1Bpp image but not working.
It says AccessViolation @ this line => rotatedPointer[destinationPosition] = originalPointer[sourcePosition];
Thanks in advance for help.
My image Size is 18144 X 46800 1Bpp indexed Bitmap image.


来源: stackexchange

问:
Counting number of words in C#
I'm trying to count the number of words from a rich textbox in C# the code that I have below only works if it is a single line. How do I do this without relying on regex or any other special functions. </p>

```<code>string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";

foreach(string av in split_text)
{
    if (av == "")
    {
        space_count++;
    }
    else
    {
        new_text = new_text  + av + ",";
    }
}

new_text = new_text.TrimEnd(',');
split_text = new_text.Split(',');
MessageBox.Show(split_text.Length.ToString ());
</code>```

答:
```<code>using System.Collections;
using System;
class Program{
public static void Main(string[] args){
        //Enter the value of n
        int n = Convert.ToInt32(Console.ReadLine());
        string[] s = new string[n];
        ArrayList arr = new ArrayList();
        //enter the elements
        for(int i=0;i<n;i++){
            s[i] = Console.ReadLine();
        }
        string str = "";
        //Filter out duplicate values and store in arr
        foreach(string i in s){

            if(str.Contains(i)){

                }else{
                    arr.Add(i);
                }
                str += i;
        }
        //Count the string with arr and s variables
        foreach(string i in arr){
            int count = 0;
            foreach(string j in s){
                if(i.Equals(j)){
                    count++;
                }
            }
            Console.WriteLine(i+" - "+count);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Counting number of words in C#

Body:
I'm trying to count the number of words from a rich textbox in C# the code that I have below only works if it is a single line. How do I do this without relying on regex or any other special functions.

string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";

foreach(string av in split_text)
{
    if (av == "")
    {
        space_count++;
    }
    else
    {
        new_text = new_text  + av + ",";
    }
}

new_text = new_text.TrimEnd(',');
split_text = new_text.Split(',');
MessageBox.Show(split_text.Length.ToString ());

ContentLicense: CC BY-SA 4.0


问:
Traceback (most recent call last) OSerror and font not found
enter image description herei will run python script with kivy and kivymd but this problem appears, how to solve it?  I already installed the kivy library and kivymd still looks like this...

from kivy.app import App
from kivy.uix.button import Button

class TestApp(App):
def build(self):
return Button(text='Hello World')

TestApp().run()

Traceback (most last): File "d:/Python/main python/main.py", line 2, in  from kivy.uix.label import Label File "C:\Users\andihasan AppData\Local\Programs\  Python\Python38-32\lib\site-packages\kivy\uix\labe 1.py", line 286, in  from kivy.core.text import Label as Corelabel, DEFAULT_FONT File "C:\Users\andihasan AppData  \Local\Programs \Python\Python38-32\lib\site-packages\kivy\core\tex t_init_-py", line 1013, in  Label.register(DEFAULT_FONT, *default_font_paths) File "C: \Users\  andihasanAppData\Local\Programs \Python\Python38-32\lib\site-packages\kivy\coreltex t_init_-py", line 315, in register raise IOError('File {e} not found'.format(font_type)) OSError:  File data/fonts/Roboto-Regular.ttf not found

答:
OSError: File data/fonts/Roboto-Regular.ttf not found.

This line is the cause of your error.
if you're trying to use custom fonts in your kivymd project, you need to have the font file. that is the .ttf file
and to use the font without having to put the full directory, you need to register the font with the following lines.

first import label base

```<code>from kivy.core.text import LabelBase
</code>```

then register the font with an easier name to refer to.

```<code>if __name__ ==  "__main__":
    LabelBase.register(name="RobotoReg", fn_regular="{full_path_to}/Roboto-Regular.ttf")
</code>```

you can then use it in your .kv file like so:

```<code>MDLabel:
    text: "Text to test if font name works"
    size_hint_x: 1
    pos_hint: {"center_x":.5, "center_y": .5}
    font_name: "RobotoReg"
    font_style: "Caption"
    halign: "center"
</code>```

Body:
OSError: File data/fonts/Roboto-Regular.ttf not found.

This line is the cause of your error.
if you're trying to use custom fonts in your kivymd project, you need to have the font file. that is the .ttf file
and to use the font without having to put the full directory, you need to register the font with the following lines.

first import label base

from kivy.core.text import LabelBase

then register the font with an easier name to refer to.

if __name__ ==  "__main__":
    LabelBase.register(name="RobotoReg", fn_regular="{full_path_to}/Roboto-Regular.ttf")

you can then use it in your .kv file like so:

MDLabel:
    text: "Text to test if font name works"
    size_hint_x: 1
    pos_hint: {"center_x":.5, "center_y": .5}
    font_name: "RobotoReg"
    font_style: "Caption"
    halign: "center"


问:
How to create a new text file on button click
Here is my problem:

I am developing a windows application

I am converting an image into text format, and saving it into a system location.

This is my code:

```<code>if (!System.IO.Directory.Exists("D:\\SaveImageOutPutFolder"))
{
    System.IO.Directory.CreateDirectory("D:\\SaveImageOutPutFolder");
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] +@"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("folder created and image output saved");
}
else
{
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + @"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}
</code>```

The problem is that it is not creating a new text file every time the button is clicked. It is writing to the same file. I want to create to a new txt file for every click.

Can anyboy help in this, and give me some sample code?

答:
Assuming you know the file name of the original image file and have it available in a string variable (PathOfOriginalImageFile) try

```<code>doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" +
Path.GetFileNameWithoutExtension (PathOfOriginalImageFile) + ".txt",
Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
</code>```

IF you need different filenames even when the original filename is identical then try

```<code>doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" +
Path.GetFileNameWithoutExtension (PathOfOriginalImageFile) + "-" +
Guid.NewGuid.ToString() ".txt",
Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
</code>```

Body:
Here is my problem:

I am developing a windows application

I am converting an image into text format, and saving it into a system location.

This is my code:

if (!System.IO.Directory.Exists("D:\\SaveImageOutPutFolder"))
{
    System.IO.Directory.CreateDirectory("D:\\SaveImageOutPutFolder");
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] +@"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("folder created and image output saved");
}
else
{
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + @"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}

The problem is that it is not creating a new text file every time the button is clicked. It is writing to the same file. I want to create to a new txt file for every click.

Can anyboy help in this, and give me some sample code?

Body:
Assuming you know the file name of the original image file and have it available in a string variable (PathOfOriginalImageFile) try

doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" +
Path.GetFileNameWithoutExtension (PathOfOriginalImageFile) + ".txt",
Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);

IF you need different filenames even when the original filename is identical then try

doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + "\\" +
Path.GetFileNameWithoutExtension (PathOfOriginalImageFile) + "-" +
Guid.NewGuid.ToString() ".txt",
Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);


问:
Got an Ng0901 error when using routerLink
This week i ran into the NG0901 Error (Yeah no message than this error)
I don't know why because as it seems it's due to a RouterLink that is not correctly functionning.

To sum up the application, it's an order manager for bakery. All it was remaining is the parameter page to modify add or delete client, warehouse etc etc.

So i create a first page witch is call params and this page have button with routerLink element to 4 other page.

Here is my html code of the params page:

```<code>    <ion-header>
  <ion-toolbar>
    <ion-title>P.I.C 2.0 - Paramétre</ion-title>
    <ion-back-button slot="start" color="primary" defaultHref="home"></ion-back-button>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <table>
    <tr>
      <td><ion-button> <a routerLink="params-client">Client</a></ion-button></td>
      <td><ion-button routerLink="./params_depot">Depot</ion-button></td>
      <!--<td><ion-button  routerLink="../depot">Feuille depot</ion-button></td>-->
    </tr>
    <tr>

      <td><ion-button routerLink="params-boul">Produit Boulangerie</ion-button></td>
      <td><ion-button routerLink="params_pat">Produit Patisserie</ion-button></td>
      <!--<td><ion-button routerLink="../params">Paramètre</ion-button></td>-->
    </tr>
  </table>
</ion-content>
</code>```

And to this link is the behavior that is unusual of the ion-button and routerLink

Also here is my ng --version

ng --version

Here is also the StackTrace :

```<code>ERROR Error: Uncaught (in promise): Error: NG0901
Error: NG0901
    at e.find (main.js:1:604380)
    at C.ngDoCheck (main.js:1:468239)
    at Xa (main.js:1:501521)
    at cs (main.js:1:501322)
    at xi (main.js:1:501042)
    at $i (main.js:1:524323)
    at sy (main.js:1:531388)
    at Vv (main.js:1:525062)
    at $i (main.js:1:525073)
    at Hv (main.js:1:525433)
    at fe (polyfills.js:1:137971)
    at fe (polyfills.js:1:137482)
    at polyfills.js:1:138833
    at S.invokeTask (polyfills.js:1:128604)
    at Object.onInvokeTask (main.js:1:583005)
    at S.invokeTask (polyfills.js:1:128525)
    at S.runTask (polyfills.js:1:123644)
    at P (polyfills.js:1:130949)
    at S.invokeTask [as invoke] (polyfills.js:1:129774)
    at x (polyfills.js:1:142703)
zm @ main.js:1
</code>```

And i also add the typescript and the html page where the routerLink is pointing at:

```<code>import { Component, OnInit } from '@angular/core';
import {HttpRequestService} from "../../http-request.service";

@Component({
  selector: 'app-params-client',
  templateUrl: './params-client.page.html',
  styleUrls: ['./params-client.page.scss'],
})
export class ParamsClientPage implements OnInit {
  public client:any = {}
  constructor(private http: HttpRequestService) {
    this.http.get_client_all((data) => {
      this.client = data;
    });
  }

  ngOnInit() {
  }

}

<ion-header>
  <ion-toolbar>
    <ion-title>P.I.C 2.0 - Parémetre Client </ion-title>
    <ion-back-button slot="start" color="primary" defaultHref="params" ></ion-back-button>
  </ion-toolbar>
</ion-header>

<ion-content>

<ion-grid>
  <ion-row>
    <ion-col>Id</ion-col>
    <ion-col>Nom</ion-col>
    <ion-col>Lieu</ion-col>
    <ion-col>Téléphone</ion-col>
    <ion-col>Modifier</ion-col>
    <ion-col>Supprimer</ion-col>
  </ion-row>

  <ion-row *ngFor="let c of client">
    <ion-col>{{c.id_client}}</ion-col>
    <ion-col>{{c.name}}</ion-col>
    <ion-col>{{c.lieu}}</ion-col>
    <ion-col>{{c.tel}}</ion-col>
    <ion-col>
      <ion-button>Modifier</ion-button>
    </ion-col>
    <ion-col>
      <ion-button>Supprimer</ion-button>
    </ion-col>
  </ion-row>

</ion-grid>

</ion-content>
</code>```

答:
The issue seems to be because of below property initialization code:

public client:any = {}
```

client is defined as an object and not an array and hence you will get an error during *ngFor="let c of client".

NgFor only supports binding to Iterables such as Arrays. If you expect data received from the HTTP call to be an array, then you should not initialize client with empty object {}. Either you can assign [] or have no assignment at all.

If client is truly an object, then you should use KeyValuePipe to iterate over an object.

Transforms Object or Map into an array of key value pairs.

Body:
This week i ran into the NG0901 Error (Yeah no message than this error)
I don't know why because as it seems it's due to a RouterLink that is not correctly functionning.

To sum up the application, it's an order manager for bakery. All it was remaining is the parameter page to modify add or delete client, warehouse etc etc.

So i create a first page witch is call params and this page have button with routerLink element to 4 other page.

Here is my html code of the params page:

    <ion-header>
  <ion-toolbar>
    <ion-title>P.I.C 2.0 - Paramétre</ion-title>
    <ion-back-button slot="start" color="primary" defaultHref="home"></ion-back-button>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">

      <ion-button> Client</ion-button>
      <ion-button routerLink="./params_depot">Depot</ion-button>

      <ion-button routerLink="params-boul">Produit Boulangerie</ion-button>
      <ion-button routerLink="params_pat">Produit Patisserie</ion-button>

</ion-content>

And to this link is the behavior that is unusual of the ion-button and routerLink

Also here is my ng --version

ng --version

Here is also the StackTrace :

ERROR Error: Uncaught (in promise): Error: NG0901
Error: NG0901
    at e.find (main.js:1:604380)
    at C.ngDoCheck (main.js:1:468239)
    at Xa (main.js:1:501521)
    at cs (main.js:1:501322)
    at xi (main.js:1:501042)
    at $i (main.js:1:524323)
    at sy (main.js:1:531388)
    at Vv (main.js:1:525062)
    at $i (main.js:1:525073)
    at Hv (main.js:1:525433)
    at fe (polyfills.js:1:137971)
    at fe (polyfills.js:1:137482)
    at polyfills.js:1:138833
    at S.invokeTask (polyfills.js:1:128604)
    at Object.onInvokeTask (main.js:1:583005)
    at S.invokeTask (polyfills.js:1:128525)
    at S.runTask (polyfills.js:1:123644)
    at P (polyfills.js:1:130949)
    at S.invokeTask [as invoke] (polyfills.js:1:129774)
    at x (polyfills.js:1:142703)
zm @ main.js:1

And i also add the typescript and the html page where the routerLink is pointing at:

import { Component, OnInit } from '@angular/core';
import {HttpRequestService} from "../../http-request.service";

@Component({
  selector: 'app-params-client',
  templateUrl: './params-client.page.html',
  styleUrls: ['./params-client.page.scss'],
})
export class ParamsClientPage implements OnInit {
  public client:any = {}
  constructor(private http: HttpRequestService) {
    this.http.get_client_all((data) => {
      this.client = data;
    });
  }

  ngOnInit() {
  }

}

<ion-header>
  <ion-toolbar>
    <ion-title>P.I.C 2.0 - Parémetre Client </ion-title>
    <ion-back-button slot="start" color="primary" defaultHref="params" ></ion-back-button>
  </ion-toolbar>
</ion-header>

<ion-content>

<ion-grid>
  <ion-row>
    <ion-col>Id</ion-col>
    <ion-col>Nom</ion-col>
    <ion-col>Lieu</ion-col>
    <ion-col>Téléphone</ion-col>
    <ion-col>Modifier</ion-col>
    <ion-col>Supprimer</ion-col>
  </ion-row>

  <ion-row *ngFor="let c of client">
    <ion-col>{{c.id_client}}</ion-col>
    <ion-col>{{c.name}}</ion-col>
    <ion-col>{{c.lieu}}</ion-col>
    <ion-col>{{c.tel}}</ion-col>
    <ion-col>
      <ion-button>Modifier</ion-button>
    </ion-col>
    <ion-col>
      <ion-button>Supprimer</ion-button>
    </ion-col>
  </ion-row>

</ion-grid>

</ion-content>

Body:
The issue seems to be because of below property initialization code:

public client:any = {}

client is defined as an object and not an array and hence you will get an error during *ngFor="let c of client".

NgFor only supports binding to Iterables such as Arrays. If you expect data received from the HTTP call to be an array, then you should not initialize client with empty object {}. Either you can assign [] or have no assignment at all.

If client is truly an object, then you should use KeyValuePipe to iterate over an object.

Transforms Object or Map into an array of key value pairs.


问:
Spark How to add value in a Hashmap from RDD?
I have below Data frame

```<code>val df = phDF.groupBy("name").agg(collect_list("message").as("Messages"))
</code>```

I got below output

```<code>+-----------+--------------------+
|name       |Messages            |
+-----------+--------------------+
|     Test1 |['A','B','C']       |
|     Test2 |['A','B','C','D']   |
|     Test3 |['A','B']           |
+-----------+--------------------+
</code>```

Now I want to add above name (as a Key) and Message (as a value) into a Hashmap.

I have used below approach to convert it into RDD but not getting any clue

```<code>var m = scala.collection.mutable.Map[String, String]()
val rdd = df.rdd.map(_.mkString("##"))
val rdd1 = rdd.map(s=>s.split("##"))
val rdd2 = rdd1.map(ele=>m.put(ele(0),ele(1)))
print(m)   // Output:- HashMap()
</code>```

As above when I try to print hashMap then I am getting blank

Does anyone can help me how could I store this value in HashMap as below like?

Map("Test1" -> "['A','B','C']" ,"Test2" -> "['A','B','C','D']","Test3" -> "['A','B']")

答:
Given your initial data:

```<code>val df = Seq(
  ("test1", Seq("A", "B", "C")),
  ("test2", Seq("A", "B", "C", "D")),
).toDF("name", "Messages")
</code>```

You can convert it into a map with the map_from_entries method:

```<code>val asMapDf = df.select(
  map_from_entries(
    array(
      struct("name", "Messages")
    )
  )
)
</code>```

Note you create an array of struct items with two columns. Each entry in the array becomes an entry in the map. This gives you:

```<code>+-----------------------+
|map                    |
+-----------------------+
|{test1 -> [A, B, C]}   |
|{test2 -> [A, B, C, D]}|
+-----------------------+
</code>```

Body:
I have below Data frame

val df = phDF.groupBy("name").agg(collect_list("message").as("Messages"))

I got below output

+-----------+--------------------+
|name       |Messages            |
+-----------+--------------------+
|     Test1 |['A','B','C']       |
|     Test2 |['A','B','C','D']   |
|     Test3 |['A','B']           |
+-----------+--------------------+

Now I want to add above name (as a Key) and Message (as a value) into a Hashmap.

I have used below approach to convert it into RDD but not getting any clue

var m = scala.collection.mutable.Map[String, String]()
val rdd = df.rdd.map(_.mkString("##"))
val rdd1 = rdd.map(s=>s.split("##"))
val rdd2 = rdd1.map(ele=>m.put(ele(0),ele(1)))
print(m)   // Output:- HashMap()

As above when I try to print hashMap then I am getting blank

Does anyone can help me how could I store this value in HashMap as below like?

Map("Test1" -> "['A','B','C']" ,"Test2" -> "['A','B','C','D']","Test3" -> "['A','B']")

Body:
Given your initial data:

val df = Seq(
  ("test1", Seq("A", "B", "C")),
  ("test2", Seq("A", "B", "C", "D")),
).toDF("name", "Messages")

You can convert it into a map with the map_from_entries method:

val asMapDf = df.select(
  map_from_entries(
    array(
      struct("name", "Messages")
    )
  )
)

Note you create an array of struct items with two columns. Each entry in the array becomes an entry in the map. This gives you:

+-----------------------+
|map                    |
+-----------------------+
|{test1 -> [A, B, C]}   |
|{test2 -> [A, B, C, D]}|
+-----------------------+


问:
Convert List<Integer> to JSON in Java
How can I convert a List object in Java to a JSON object?

For example, how can I convert this:

```<code>List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...
</code>```

To this JSON:

```<code>{
    "List" : [1, 2, ...]
}
</code>```

Thank you!

答:
If you need to convert to String use the  com.fasterxml.jackson.databind.ObjectMapper

Ex:

```<code>        List<Integer> myList = new ArrayList<>();
        myList.add(1);
        myList.add(2);

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(myList);
            System.out.println("result = " + json);
            //System.out.println(json);
        } catch (JsonProcessingException e) {
            //
        }
</code>```

Title: Convert List<Integer> to JSON in Java

Body:
How can I convert a List object in Java to a JSON object?

For example, how can I convert this:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...

To this JSON:

{
    "List" : [1, 2, ...]
}

Thank you!

Body:
If you need to convert to String use the  com.fasterxml.jackson.databind.ObjectMapper

Ex:

        List<Integer> myList = new ArrayList<>();
        myList.add(1);
        myList.add(2);

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(myList);
            System.out.println("result = " + json);
            //System.out.println(json);
        } catch (JsonProcessingException e) {
            //
        }


问:
how to change the columns in a dataframe into lists?
I have data formatted as a dataframe.

```<code>a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- cbind(a1,a2,b1,b2,c)
</code>```

I would like to change "abc" into two lists.

```<code>list <- list()
list[[1]] <- cbind(a1,a2,c)
list[[2]] <- cbind(b2,b2,c)
</code>```

thanks in advance!

答:
Not enough details have been shared about the logic of creation of two lists but I am going to assume you want to split them based on the names. So all the columns with "a" in them are in one list and all the columns with "b" in another one. One column ("c") is constant in both the lists.

Here is a base R way using split.default -

```<code>exclude_cols <- c(5) #"c"

list_df <- lapply(split.default(abc[-exclude_cols],
                 sub('\\d+', '', names(abc)[-exclude_cols])), function(x) {
  cbind(x, abc[exclude_cols])
})

list_df
#$a
#  a1 a2 c
#1  1  2 g
#2  2  4 h
33  3  6 i
#4  4  7 j
#5  5  8 k

#$b
#  b1 b2 c
#1  2  3 g
#2  5  1 h
#3  8  2 i
#4  1  5 j
#5  2  6 k
</code>```

sub is used to remove numbers from the column name and is used as grouping variable in split.default.

```<code>sub('\\d+', '', names(abc)[-exclude_cols])
#[1] "a" "a" "b" "b"
</code>```

data

```<code>a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- data.frame(a1,a2,b1,b2,c)
</code>```

Body:
I have data formatted as a dataframe.

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- cbind(a1,a2,b1,b2,c)

I would like to change "abc" into two lists.

list <- list()
list[[1]] <- cbind(a1,a2,c)
list[[2]] <- cbind(b2,b2,c)

thanks in advance!

Body:
Not enough details have been shared about the logic of creation of two lists but I am going to assume you want to split them based on the names. So all the columns with "a" in them are in one list and all the columns with "b" in another one. One column ("c") is constant in both the lists.

Here is a base R way using split.default -

exclude_cols <- c(5) #"c"

list_df <- lapply(split.default(abc[-exclude_cols],
                 sub('\\d+', '', names(abc)[-exclude_cols])), function(x) {
  cbind(x, abc[exclude_cols])
})

list_df
#$a
#  a1 a2 c
#1  1  2 g
#2  2  4 h
33  3  6 i
#4  4  7 j
#5  5  8 k

#$b
#  b1 b2 c
#1  2  3 g
#2  5  1 h
#3  8  2 i
#4  1  5 j
#5  2  6 k

sub is used to remove numbers from the column name and is used as grouping variable in split.default.

sub('\\d+', '', names(abc)[-exclude_cols])
#[1] "a" "a" "b" "b"

data

a1 <- c(1,2,3,4,5)
a2 <- c(2,4,6,7,8)
b1 <- c(2,5,8,1,2)
b2 <- c(3,1,2,5,6)
c  <- c("g","h","i","j","k")
abc <- data.frame(a1,a2,b1,b2,c)


问:
How to get MVC ActionLink Full Path in Jquery
I am trying to set the class on the selected menu anchor based on the URL. I have below actionlinks

```<code>@Html.ActionLink("Home","Index","Home" new {type="new task"},null)
@Html.ActionLink("Home","Index")
</code>```

I need to get its fullpath in Jquery to change the selected link based on the url as given below

```<code>$("a").each(function () {
 if (location.indexOf($(this).prop('href')) != -1) {
                          $(this).addClass('mlnkactive').siblings().removeClass('mlnkactive');
                        $(this).parent().addClass('mlnkactive').siblings().removeClass('mlnkactive');
});
</code>```

The problem is that when i get href of the links using $(this).prop('href') , both of the above Home links have the same href.So both of the Anchors are selected and I am unable to set the class on the selected Link based on URL.

Thanks,

答:
Why don't you add a css class to the selected link server side (in the ActionLink)?

```<code><div id="menulinks">
    @Html.ActionLink("Home","Index","Home" new {type="new task"}, new { @class = "mlnkactive" })
    @Html.ActionLink("Home","Index")
</div>
</code>```

And then remove the class and add it to the new selected link client side? Like this:

```<code>$('#menulinks a').click(function(){
    $('#menulinks a').removeClass('mlnkactive');
    $(this).addClass('mlnkactive');
}
</code>```

Body:
I am trying to set the class on the selected menu anchor based on the URL. I have below actionlinks

@Html.ActionLink("Home","Index","Home" new {type="new task"},null)
@Html.ActionLink("Home","Index")

I need to get its fullpath in Jquery to change the selected link based on the url as given below

$("a").each(function () {
 if (location.indexOf($(this).prop('href')) != -1) {
                          $(this).addClass('mlnkactive').siblings().removeClass('mlnkactive');
                        $(this).parent().addClass('mlnkactive').siblings().removeClass('mlnkactive');
});

The problem is that when i get href of the links using $(this).prop('href') , both of the above Home links have the same href.So both of the Anchors are selected and I am unable to set the class on the selected Link based on URL.

Thanks,

Body:
Why don't you add a css class to the selected link server side (in the ActionLink)?

<div id="menulinks">
    @Html.ActionLink("Home","Index","Home" new {type="new task"}, new { @class = "mlnkactive" })
    @Html.ActionLink("Home","Index")
</div>

And then remove the class and add it to the new selected link client side? Like this:

$('#menulinks a').click(function(){
    $('#menulinks a').removeClass('mlnkactive');
    $(this).addClass('mlnkactive');
}


问:
Python3: Heap memory not getting released when expected
I have a class that has a cache implemented as a dict for numpy arrays, which can occupy GBs of data.

```<code>class WorkOperations(object):
    def __init__(self):
        self.data_cache: Dict[str, Dict[str, Tuple[np.ndarray, np.ndarray]]] = {}

    def get_data(key):
        if key not in data_cache:
            add_data(key)
        return self.data_cache[key]

    def add_data(key)
        result = run_heavy_calculation(key)
        self.data_cache[key] = result
</code>```

I am testing the code with this function  -

```<code>import gc

def perform_operations()
    work_operations = WorkOperations()

    # input_keys gives a list of keys to process
    for keys in input_keys():
        data = work_operations.get_data(key)
        do_some_operation(data)

    del work_operations

perform_operations()
gc.collect()

</code>```

The result of run_heavy_calculation is heavy in memory and soon data_cache grows and occupies memory in GBs (which is expected).

But memory does not get released even after perform_operations() is done. I tried adding del work_operations and invoking gc.collect() but that did not help either. I checked memory of the process after several hours, but the memory was still not freed up.

If I don't use caching (data_cache) at all (at the cost of latency), memory never goes high.

I am wondering what is it that is taking memory. I tried running tracemalloc, but it just showed lines occupying memory in KBs. I also took a memory dump with gdb by looking at memory address from process pmap and /proc/<pid>/smaps, but that is really long and even with hexeditor I couldn't figure out much.

I am measuring memory used by the process using top command and looking at RES. I also tried outputting memory in the end from within python process as well with -

```<code>import psutils
import gc
import logging

GIGABYTE = 1024.0 * 1024.0 * 1024.0

perform_operations()
gc.collect()

memory_full_info = psutil.Process().memory_full_info()
logging.info(f"process memory after running the process {memory_full_info.uss / GIGABYTE}")
</code>```

答:
Could not reproduce on Ubuntu  with this :

import itertools
import time
import os
from typing import Dict, Tuple

import numpy as np
import psutil  # installed with pip

process = psutil.Process(os.getpid())

SIZE = 10**7

def run_heavy_calculation(key):
    array1 = np.zeros(SIZE)
    array2 = np.zeros(SIZE)
    # Linux use "virtual memory", which means that the memory required for the arrays was allocated, but will not
    # be actually deducted until we use them, so we write some 1 into them
    # cf: https://stackoverflow.com/q/29516888/11384184
    for i in range(0, SIZE, 1000):
        array1[i] = 1
        array2[i] = 1
    return {key: (array1, array2)}

class WorkOperations(object):
    def __init__(self):
        self.data_cache: Dict[str, Dict[str, Tuple[np.ndarray, np.ndarray]]] = {}

    def get_data(self, key):
        if key not in self.data_cache:
            self.add_data(key)
        return self.data_cache[key]

    def add_data(self, key):
        result = run_heavy_calculation(key)
        self.data_cache[key] = result

def perform_operations(input_keys):
    work_operations = WorkOperations()

    for key in input_keys():
        data = work_operations.get_data(key)
        time.sleep(0.2)
        print(key, process.memory_info().rss / 10**9)

    del work_operations

perform_operations(lambda: map(str, itertools.product("abcdefgh", "0123456789")))  # dummy keys
print("after operations", process.memory_info().rss / 10**9)
input("pause")
```
```('a', '0') 0.113106944
('a', '1') 0.195014656
('a', '2') 0.276926464
...
('h', '7') 6.421118976
('h', '8') 6.503030784
('h', '9') 6.584942592
after operations 0.031363072
pause
```
<p>It climbed up to using 6,5 Go of RAM, then returned from the function and all of it was released.</p>
<p>You can add a finalizer (<code>__del__</code>) to the class <code>WorkOperations</code> :</p>
<pre class="lang-py prettyprint-override"><code>    def __del__(self):
        print("deleted")
</code>```

I see it printed between the last operation's print and the one after.

Although it does not guarantee that this will always be the case (cf this question), it strongly indicates that everything is working as intended : event without the del, the functions returns (hence the scope is lost), so the reference count for work_operations gets to 0, and then gets GC'ed.

It can be checked with sys.getrefcount too :

    print(sys.getrefcount(work_operations) - 1)  # see https://stackoverflow.com/a/510417/11384184
    del work_operations
```

which for me print 1.

Please provide a Minimal Reproducible Example and info on your system.

Body:
I have a class that has a cache implemented as a dict for numpy arrays, which can occupy GBs of data.

class WorkOperations(object):
    def __init__(self):
        self.data_cache: Dict[str, Dict[str, Tuple[np.ndarray, np.ndarray]]] = {}

    def get_data(key):
        if key not in data_cache:
            add_data(key)
        return self.data_cache[key]

    def add_data(key)
        result = run_heavy_calculation(key)
        self.data_cache[key] = result

I am testing the code with this function  -

import gc

def perform_operations()
    work_operations = WorkOperations()

    # input_keys gives a list of keys to process
    for keys in input_keys():
        data = work_operations.get_data(key)
        do_some_operation(data)

    del work_operations

perform_operations()
gc.collect()

The result of run_heavy_calculation is heavy in memory and soon data_cache grows and occupies memory in GBs (which is expected).

But memory does not get released even after perform_operations() is done. I tried adding del work_operations and invoking gc.collect() but that did not help either. I checked memory of the process after several hours, but the memory was still not freed up.

If I don't use caching (data_cache) at all (at the cost of latency), memory never goes high.

I am wondering what is it that is taking memory. I tried running tracemalloc, but it just showed lines occupying memory in KBs. I also took a memory dump with gdb by looking at memory address from process pmap and /proc/<pid>/smaps, but that is really long and even with hexeditor I couldn't figure out much.

I am measuring memory used by the process using top command and looking at RES. I also tried outputting memory in the end from within python process as well with -

import psutils
import gc
import logging

GIGABYTE = 1024.0 * 1024.0 * 1024.0

perform_operations()
gc.collect()

memory_full_info = psutil.Process().memory_full_info()
logging.info(f"process memory after running the process {memory_full_info.uss / GIGABYTE}")

Body:
Could not reproduce on Ubuntu  with this :

import itertools
import time
import os
from typing import Dict, Tuple

import numpy as np
import psutil  # installed with pip

process = psutil.Process(os.getpid())

SIZE = 10**7

def run_heavy_calculation(key):
    array1 = np.zeros(SIZE)
    array2 = np.zeros(SIZE)
    # Linux use "virtual memory", which means that the memory required for the arrays was allocated, but will not
    # be actually deducted until we use them, so we write some 1 into them
    # cf: https://stackoverflow.com/q/29516888/11384184
    for i in range(0, SIZE, 1000):
        array1[i] = 1
        array2[i] = 1
    return {key: (array1, array2)}

class WorkOperations(object):
    def __init__(self):
        self.data_cache: Dict[str, Dict[str, Tuple[np.ndarray, np.ndarray]]] = {}

    def get_data(self, key):
        if key not in self.data_cache:
            self.add_data(key)
        return self.data_cache[key]

    def add_data(self, key):
        result = run_heavy_calculation(key)
        self.data_cache[key] = result

def perform_operations(input_keys):
    work_operations = WorkOperations()

    for key in input_keys():
        data = work_operations.get_data(key)
        time.sleep(0.2)
        print(key, process.memory_info().rss / 10**9)

    del work_operations

perform_operations(lambda: map(str, itertools.product("abcdefgh", "0123456789")))  # dummy keys
print("after operations", process.memory_info().rss / 10**9)
input("pause")

('a', '0') 0.113106944
('a', '1') 0.195014656
('a', '2') 0.276926464
...
('h', '7') 6.421118976
('h', '8') 6.503030784
('h', '9') 6.584942592
after operations 0.031363072
pause

It climbed up to using 6,5 Go of RAM, then returned from the function and all of it was released.

You can add a finalizer (__del__) to the class WorkOperations :

    def __del__(self):
        print("deleted")

I see it printed between the last operation's print and the one after.

Although it does not guarantee that this will always be the case (cf this question), it strongly indicates that everything is working as intended : event without the del, the functions returns (hence the scope is lost), so the reference count for work_operations gets to 0, and then gets GC'ed.

It can be checked with sys.getrefcount too :

    print(sys.getrefcount(work_operations) - 1)  # see https://stackoverflow.com/a/510417/11384184
    del work_operations

which for me print 1.

Please provide a Minimal Reproducible Example and info on your system.


问:
Laravel 8 Dynamic Model Factories?
I'm trying to create a package that allows for specifying model factory definitions inside of the model class itself.

For example:

```<code>class User extends Authenticatable
{
    use LaravelUIModel, Notifiable;

    protected $hidden = ['password', 'remember_token'];
    protected $casts = ['email_verified_at' => 'datetime'];

    public function definition(Generator $faker)
    {
        return [
            'name' => $faker->name,
            'email' => $faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}
</code>```

So I created a trait called LaravelUIModel, where I'm trying to specify a dynamic newFactory:

```<code>trait LaravelUIModel
{
    use HasFactory;

    protected static function newFactory()
    {
        $factory = new Factory;
        $factory->setModel(static::class);

        return $factory->new();
    }
}
</code>```

Now, the $model factory properted is protected, so I made my own Factory class to extend the Eloquent Factory class, which should allow me to change it:

```<code>class Factory extends EloquentFactory
{
    public function setModel($model)
    {
        $this->model = $model;
    }

    public function definition()
    {
        return app($this->model)->definition($this->faker);
    }
}
</code>```

I keep getting this error:

```<code>Class "App\" not found
</code>```

It's like it isn't recognizing that I've set the model name at all, because when I print $this->model it shows me App\Models\User.

How do I set the factory $model dynamically like this so I can specify definitions in the model class, WITHOUT making a new factory file per model?

答:
i got this working by creating this trait:

use Faker\Generator;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Factories\HasFactory;

trait HasNewFactory
{
    use HasFactory;

    protected static function newFactory()
    {
        $factory = new class extends Factory
        {
            public static $definition;

            public function definition()
            {
                $definition = static::$definition;

                return $definition($this->faker);
            }
        };

        $factory::guessModelNamesUsing(function () {
            return get_called_class();
        });

        $factory::$definition = function (Generator $faker) {
            return (new static)->definition($faker);
        };

        return $factory;
    }
}
```
<p>Now in my model, instead of using <code>HasFactory</code>, I use this <code>HasNewFactory</code> trait:</p>
<pre class="lang-php prettyprint-override"><code>use Diontron\Lucid\Traits\HasNewFactory;
use Faker\Generator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;

class MyModel extends Model
{
    use HasNewFactory;

    public function definition(Generator $faker)
    {
        return [
            'name' => $faker->name(),
        ];
    }
}
</code>```

Title: Laravel 8 Dynamic Model Factories?

Body:
I'm trying to create a package that allows for specifying model factory definitions inside of the model class itself.

For example:

class User extends Authenticatable
{
    use LaravelUIModel, Notifiable;

    protected $hidden = ['password', 'remember_token'];
    protected $casts = ['email_verified_at' => 'datetime'];

    public function definition(Generator $faker)
    {
        return [
            'name' => $faker->name,
            'email' => $faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

So I created a trait called LaravelUIModel, where I'm trying to specify a dynamic newFactory:

trait LaravelUIModel
{
    use HasFactory;

    protected static function newFactory()
    {
        $factory = new Factory;
        $factory->setModel(static::class);

        return $factory->new();
    }
}

Now, the $model factory properted is protected, so I made my own Factory class to extend the Eloquent Factory class, which should allow me to change it:

class Factory extends EloquentFactory
{
    public function setModel($model)
    {
        $this->model = $model;
    }

    public function definition()
    {
        return app($this->model)->definition($this->faker);
    }
}

I keep getting this error:

Class "App\" not found

It's like it isn't recognizing that I've set the model name at all, because when I print $this->model it shows me App\Models\User.

How do I set the factory $model dynamically like this so I can specify definitions in the model class, WITHOUT making a new factory file per model?

Body:
i got this working by creating this trait:

use Faker\Generator;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Factories\HasFactory;

trait HasNewFactory
{
    use HasFactory;

    protected static function newFactory()
    {
        $factory = new class extends Factory
        {
            public static $definition;

            public function definition()
            {
                $definition = static::$definition;

                return $definition($this->faker);
            }
        };

        $factory::guessModelNamesUsing(function () {
            return get_called_class();
        });

        $factory::$definition = function (Generator $faker) {
            return (new static)->definition($faker);
        };

        return $factory;
    }
}

Now in my model, instead of using HasFactory, I use this HasNewFactory trait:

use Diontron\Lucid\Traits\HasNewFactory;
use Faker\Generator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;

class MyModel extends Model
{
    use HasNewFactory;

    public function definition(Generator $faker)
    {
        return [
            'name' => $faker->name(),
        ];
    }
}


问:
Can't convert a char to string using standard Linq methods?
I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";

            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}
```

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'.
I tried changing "Value" to a var type, but that didn't work either.ch

答:
You don't need to check the existence of the characters in the string by using Contains method. The count will give you valid result EVEN if there are no instances of the character you are searching. PF the simplest implementation.

```<code>string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
char charToFind = '(';
int bCount = bracketList.Count(x => x == charToFind);
</code>```

Remember, string is a character array.

Body:
I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";

            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'.
I tried changing "Value" to a var type, but that didn't work either.ch

Body:
You don't need to check the existence of the characters in the string by using Contains method. The count will give you valid result EVEN if there are no instances of the character you are searching. PF the simplest implementation.

string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
char charToFind = '(';
int bCount = bracketList.Count(x => x == charToFind);

Remember, string is a character array.


问:
Anyone know where in Active Directory schema the Email Address Policies are kept?
For reasons that aren't important in this question, I cannot use the ECP or the Exchange Shell to get the email address policies. I will be using standard PowerShell. I do know the name of the on-prem Exchange Server, but it's totally impossible for me to use any remote connection or plugin to ascertain something that's really easy to get with a mouse.

I'm sure somewhere tucked away in the schema are the email address policies, and with it the default policy assigned.

Does anyone know where this would be? I can't for the life of me find it using ADSIEdit, and can't think of something unique as a search term for PowerShell.

Thank you

答:
Found it

CanonicalName : domain.local/Configuration/Services/Microsoft Exchange/ Domain Exchange/Recipient Policies/

And for PowerShell users:

```<code>$configurationNamingContext = ( Get-ADRootDSE ).ConfigurationNamingContext
$msConfig = "CN=Microsoft Exchange,CN=Services,$configurationNamingContext"

$defaultPolicy = Get-ADObject -Filter 'objectClass -eq "msExchRecipientPolicy"' -SearchBase $(
        $msConfig ) -Properties *
</code>```

Body:
Found it

CanonicalName : domain.local/Configuration/Services/Microsoft Exchange/ Domain Exchange/Recipient Policies/

And for PowerShell users:

$configurationNamingContext = ( Get-ADRootDSE ).ConfigurationNamingContext
$msConfig = "CN=Microsoft Exchange,CN=Services,$configurationNamingContext"

$defaultPolicy = Get-ADObject -Filter 'objectClass -eq "msExchRecipientPolicy"' -SearchBase $(
        $msConfig ) -Properties *


问:
How to submit form data to a external URL using C# in my .NET Core 5 application?
I need to send form data to an external URI and get the response which is a page redirect.  I've written the code to do this but the remote server isn't accepting it, the reasons are not specified.  If I create the form in a HTML page and submit it from there, it works perfectly.

Here is the form I need to submit:

```<code><form action="https://someurl.com/make" method=POST>
    <input type="hidden" name="test" value="42">
    <input type="hidden" name="version" value="123">
    <input type=submit value="Send">
</form>
</code>```

So, to send this form data to someurl.com instead of the user having to do it, I tried to use a WebClient because I'm posting to an external URL for this, I also use string interpolation for values that are passed when this is called.

```<code>public async Task<string> Send_Version(string versionNumber = "0")
{
    try
    {
        string html = $"test=42&version={versionNumber}";

        using (WebClient webclient = new())
        {
            webclient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            string pagesource = webclient.UploadString("www.someurl.com/make", html);

            return pagesource.ToString();
            }
        }
        catch (Exception ex)
        {
            errorString = $"Error";
            return errorString;
        }
    }
</code>```

As you can see I use the WebClient so that is disposes correctly, I add a Content-Type and then I UploadString via the web client with both the URL and my data html.

The remote server doesn't like this way of doing it but my question is, does this look accurate for posting form data to a remote url with c# or have I missed something critical?

答:
I have tried your C# code with one of my APIs, and it's working fine. The only finding is:

If it works

```<code><form action="https://someurl.com/make" method=POST>
</code>```

Then try keeping the URL the same as used in HTML

```<code>string pagesource = webclient.UploadString("https://someurl.com/make", HTML);
</code>```

Also, if it is not the URL issue, then please share the exception details.

Body:
I need to send form data to an external URI and get the response which is a page redirect.  I've written the code to do this but the remote server isn't accepting it, the reasons are not specified.  If I create the form in a HTML page and submit it from there, it works perfectly.

Here is the form I need to submit:

<form action="https://someurl.com/make" method=POST>
    <input type="hidden" name="test" value="42">
    <input type="hidden" name="version" value="123">
    <input type=submit value="Send">
</form>

So, to send this form data to someurl.com instead of the user having to do it, I tried to use a WebClient because I'm posting to an external URL for this, I also use string interpolation for values that are passed when this is called.

public async Task<string> Send_Version(string versionNumber = "0")
{
    try
    {
        string html = $"test=42&version={versionNumber}";

        using (WebClient webclient = new())
        {
            webclient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            string pagesource = webclient.UploadString("www.someurl.com/make", html);

            return pagesource.ToString();
            }
        }
        catch (Exception ex)
        {
            errorString = $"Error";
            return errorString;
        }
    }

As you can see I use the WebClient so that is disposes correctly, I add a Content-Type and then I UploadString via the web client with both the URL and my data html.

The remote server doesn't like this way of doing it but my question is, does this look accurate for posting form data to a remote url with c# or have I missed something critical?

Body:
I have tried your C# code with one of my APIs, and it's working fine. The only finding is:

If it works

<form action="https://someurl.com/make" method=POST>

Then try keeping the URL the same as used in HTML

string pagesource = webclient.UploadString("https://someurl.com/make", HTML);

Also, if it is not the URL issue, then please share the exception details.


问:
Using attr to set css variable inline that work with CSP
I was thinking how I can use css variables without using inline styles. I thought that I can use this:

[data-color] {
    --color: attr(data-color color, green);
}
* {
    color: var(--color, blue);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-color="red">hello</div></code>```

It seems that attr work only in pseudo selectors (and probably only on content: property), but MDN attr page says:

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

There is even demo but it don't work in Chrome on Linux, so it's of no use to me. It even don't work in Firefox on Linux.

Is there any other way to use css variables without inline styles and without writing dynamic   and nonce?

答:
For everyone who still want to manage CSS variable on HTML you can do it like that:

* {
    color: var(--color, blue);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="--color: red">hello</div>
<div>hello</div></code>```

Body:
I was thinking how I can use css variables without using inline styles. I thought that I can use this:

[data-color] {
    --color: attr(data-color color, green);
}
* {
    color: var(--color, blue);
}

hello

It seems that attr work only in pseudo selectors (and probably only on content: property), but MDN attr page says:

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

There is even demo but it don't work in Chrome on Linux, so it's of no use to me. It even don't work in Firefox on Linux.

Is there any other way to use css variables without inline styles and without writing dynamic   and nonce?

Body:
For everyone who still want to manage CSS variable on HTML you can do it like that:

* {
    color: var(--color, blue);
}

<div style="--color: red">hello</div>
<div>hello</div>


问:
Fetch API Not displaying Images properly - TV Show Website
I'm a beginner when it comes to coding and the biggest issue I have is to understand WHY something doesn't work (how to diagnose an error). I tried to combine what I learned from Colt Steele on Udemy with fetch API and so far, I've managed to make it work to list the NAMES of the movies when you search, but when I try to display the IMAGES, they seem to not work and it seems like it's trying to load them from my PC rather than from the TVMaze API. Here's my code:

function searchShow(query) {
    const url = `https://api.tvmaze.com/search/shows?q=${query}`;
    fetch(url)
        .then(response => response.json())
        .then((jsonData) => {
            const resultsNames = jsonData.map(element => element.show.name);
            const resultsImages = jsonData.map(e => e.show.image);
            console.log(resultsNames);
            renderResults(resultsNames);
            console.log(resultsImages);
            renderImages(resultsImages);
            document.getElementById("errorMessage").innerHTML = "";
        })
        .catch((error) => {
            document.getElementById("errorMessage").innerHTML = error;
        })
}

function renderResults(resultsNames) {
    const list = document.getElementById("resultsList");
    list.innerHTML = "";
    resultsNames.forEach(result => {
        const element = document.createElement("li");
        element.innerText = result;
        list.appendChild(element);

    });
}

function renderImages(resultsImages) {
    const list2 = document.getElementById("imagesDisplay");
    list2.innerHTML = "";
    resultsImages.forEach(result => {
        const imgShow = document.createElement("IMG");
        imgShow.src = result;
        list2.appendChild(imgShow);
    })
}

let searchTimeoutToken = 0;

window.onload = () => {
    const searchFieldElement = document.getElementById("searchField")
    searchFieldElement.onkeyup = (event) => {
        clearTimeout(searchTimeoutToken);
        searchTimeoutToken = setTimeout(() => {
            searchShow(searchFieldElement.value);
        }, 250);

    };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TV Show</title>

</head>

<body>
    <h1>TV Search</h1>
    <input type="text" id="searchField" placeholder="Search a TV Show...">
    <ul id="resultsList"></ul>
    <ul id="imagesDisplay"></ul>
    <div id=" errorMessage">
    </div>

    <script src="script.js"></script>
</body>

</html></code>```

Can you please help me understand why is this not working and also, how can I make it display in a list like this:

-Name of the show
-Image of the show
-2nd name of the 2nd show
-2nd image of the 2nd show
etc.

Thank you in advance!

答:
If you look at your images, you will see the src as [object Object] instead of the url to your image. You need to access the property of your object, in this case there's a few to choose from that represent different sized images.

I've modified your snippet to get what you want.

function searchShow(query) {
  const url = `https://api.tvmaze.com/search/shows?q=${query}`;
  fetch(url)
    .then(response => response.json())
    .then((jsonData) => {
      let shows = jsonData.map(element => element.show);
      renderShows(shows);
      document.getElementById("errorMessage").innerHTML = "";
    })
    .catch((error) => {
      document.getElementById("errorMessage").innerHTML = error;
    })
}

function renderShows(shows) {
  const list = document.getElementById("resultsList");
  list.innerHTML = "";
  shows.forEach(show => {
    const element = document.createElement("li");
    const img = document.createElement("img");
    const text = document.createElement("span");

    img.src = show.image.original;
    text.innerText = show.name;

    element.appendChild(text);
    element.appendChild(img);

    list.appendChild(element);

  });
}

let searchTimeoutToken = 0;

window.onload = () => {
  const searchFieldElement = document.getElementById("searchField")
  searchFieldElement.onkeyup = (event) => {
    clearTimeout(searchTimeoutToken);
    searchTimeoutToken = setTimeout(() => {
      searchShow(searchFieldElement.value);
    }, 250);

  };
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  max-width: 100px;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>TV Show</title>

TV Search

  <input type="text" id="searchField" placeholder="Search a TV Show...">

```

Body:
I'm a beginner when it comes to coding and the biggest issue I have is to understand WHY something doesn't work (how to diagnose an error). I tried to combine what I learned from Colt Steele on Udemy with fetch API and so far, I've managed to make it work to list the NAMES of the movies when you search, but when I try to display the IMAGES, they seem to not work and it seems like it's trying to load them from my PC rather than from the TVMaze API. Here's my code:

function searchShow(query) {
    const url = `https://api.tvmaze.com/search/shows?q=${query}`;
    fetch(url)
        .then(response => response.json())
        .then((jsonData) => {
            const resultsNames = jsonData.map(element => element.show.name);
            const resultsImages = jsonData.map(e => e.show.image);
            console.log(resultsNames);
            renderResults(resultsNames);
            console.log(resultsImages);
            renderImages(resultsImages);
            document.getElementById("errorMessage").innerHTML = "";
        })
        .catch((error) => {
            document.getElementById("errorMessage").innerHTML = error;
        })
}

function renderResults(resultsNames) {
    const list = document.getElementById("resultsList");
    list.innerHTML = "";
    resultsNames.forEach(result => {
        const element = document.createElement("li");
        element.innerText = result;
        list.appendChild(element);

    });
}

function renderImages(resultsImages) {
    const list2 = document.getElementById("imagesDisplay");
    list2.innerHTML = "";
    resultsImages.forEach(result => {
        const imgShow = document.createElement("IMG");
        imgShow.src = result;
        list2.appendChild(imgShow);
    })
}

let searchTimeoutToken = 0;

window.onload = () => {
    const searchFieldElement = document.getElementById("searchField")
    searchFieldElement.onkeyup = (event) => {
        clearTimeout(searchTimeoutToken);
        searchTimeoutToken = setTimeout(() => {
            searchShow(searchFieldElement.value);
        }, 250);

    };
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TV Show</title>

TV Search

    <input type="text" id="searchField" placeholder="Search a TV Show...">

Can you please help me understand why is this not working and also, how can I make it display in a list like this:

-Name of the show
-Image of the show
-2nd name of the 2nd show
-2nd image of the 2nd show
etc.

Thank you in advance!

Body:
If you look at your images, you will see the src as [object Object] instead of the url to your image. You need to access the property of your object, in this case there's a few to choose from that represent different sized images.

I've modified your snippet to get what you want.

function searchShow(query) {
  const url = `https://api.tvmaze.com/search/shows?q=${query}`;
  fetch(url)
    .then(response => response.json())
    .then((jsonData) => {
      let shows = jsonData.map(element => element.show);
      renderShows(shows);
      document.getElementById("errorMessage").innerHTML = "";
    })
    .catch((error) => {
      document.getElementById("errorMessage").innerHTML = error;
    })
}

function renderShows(shows) {
  const list = document.getElementById("resultsList");
  list.innerHTML = "";
  shows.forEach(show => {
    const element = document.createElement("li");
    const img = document.createElement("img");
    const text = document.createElement("span");

    img.src = show.image.original;
    text.innerText = show.name;

    element.appendChild(text);
    element.appendChild(img);

    list.appendChild(element);

  });
}

let searchTimeoutToken = 0;

window.onload = () => {
  const searchFieldElement = document.getElementById("searchField")
  searchFieldElement.onkeyup = (event) => {
    clearTimeout(searchTimeoutToken);
    searchTimeoutToken = setTimeout(() => {
      searchShow(searchFieldElement.value);
    }, 250);

  };
}

img {
  max-width: 100px;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>TV Show</title>

</head>

<body>
  <h1>TV Search</h1>
  <input type="text" id="searchField" placeholder="Search a TV Show...">
  <ul id="resultsList"></ul>
  <ul id="imagesDisplay"></ul>
  <div id="errorMessage">
  </div>

  <script src="script.js"></script>
</body>

</html>


问:
How to make the character jump but only to a certain height and then come back down to ground level?
I am currently trying to work on a small project for my programming module and I am still very much a beginner since it's just the first semester. I want to make my character jump when I press the Up-arrow key but only to a certain height and then come back down, I can't figure out how to do this, for now when I press the arrow key, the character keeps going up if I keep holding it down and stops otherwise in mid-air. this is the link for my code in the online editor since I can't post all the code down here GP 3A. The part below is where I am having trouble.</p>
```<code>    if (isLeft == true)
    {
        gameChar_x -= 5
    }
    if (isRight == true)
    {
        gameChar_x += 5
    }
    if (isJumping == true)
    {
        gameChar_y -= 5
    }
    // if (gameChar_y == gameChar_y - 5)
    // {
    //  gameChar_y += 5
    // }
    // if (isPlummeting == true)
    // {
    //  gameChar_y += 10
    // }

}

function keyPressed()
{
    // if statements to control the animation of the character when
    // keys are pressed.

    //open up the console to see how these work
    // console.log("keyPressed: " + key);
    // console.log("keyPressed: " + keyCode);
    if (keyCode == 37)
    {
        isLeft = true
    }
    else if (keyCode == 39)
    {
        isRight = true
    }
    else if (keyCode == 38)
    {
        isJumping = true
    }
}

function keyReleased()
{
    // if statements to control the animation of the character when
    // keys are released.

    // console.log("keyReleased: " + key);
    // console.log("keyReleased: " + keyCode);
    if (keyCode == 37)
    {
        isLeft = false
    }
    else if (keyCode == 39)
    {
        isRight = false
    }
    else if (keyCode == 38)
    {
        isJumping = false
    }
}
</code>```

答:
```<code>var jumping = false;
var gravity = 1;

var rectangle = {
    x: 20,
    y: 0,
    vx: 10, // X velocity
    vy: 5, // Y velocity  velocity = acceleration

    size: 80
};

var ground = {
    x: 0,
    y: 600-rectangle.size,
    width: 600
};

function setup() {
    createCanvas(600, 600);
}

function draw () {
    background('#000000');

    // The Rectangle
    fill('red');
    rect(rectangle.x, rectangle.y, rectangle.size);

    // Physics
    rectangle.y += rectangle.vy; // contantly add y velocity
    rectangle.vy += gravity; // constantly add gravity to Y
    // Ground check
    if (rectangle.y > ground.y - 0 && rectangle.x <= ground.width) {
        rectangle.y = ground.y - 0;
        rectangle.vy = 0;
        jumping = false;
            }

  // Right
if (keyIsDown(RIGHT_ARROW)) {
    rectangle.x += rectangle.vx;
    }
// Left
if (keyIsDown(LEFT_ARROW)) {
    rectangle.x -= rectangle.vx;
    }

}

// THE JUMP
function keyPressed() {
    if (jumping === false && keyCode === UP_ARROW) {
        rectangle.vy -= 10;
        jumping = true;
        console.log(jumping);
    }

}
</code>```

Body:
I am currently trying to work on a small project for my programming module and I am still very much a beginner since it's just the first semester. I want to make my character jump when I press the Up-arrow key but only to a certain height and then come back down, I can't figure out how to do this, for now when I press the arrow key, the character keeps going up if I keep holding it down and stops otherwise in mid-air. this is the link for my code in the online editor since I can't post all the code down here GP 3A. The part below is where I am having trouble.

    if (isLeft == true)
    {
        gameChar_x -= 5
    }
    if (isRight == true)
    {
        gameChar_x += 5
    }
    if (isJumping == true)
    {
        gameChar_y -= 5
    }
    // if (gameChar_y == gameChar_y - 5)
    // {
    //  gameChar_y += 5
    // }
    // if (isPlummeting == true)
    // {
    //  gameChar_y += 10
    // }

}

function keyPressed()
{
    // if statements to control the animation of the character when
    // keys are pressed.

    //open up the console to see how these work
    // console.log("keyPressed: " + key);
    // console.log("keyPressed: " + keyCode);
    if (keyCode == 37)
    {
        isLeft = true
    }
    else if (keyCode == 39)
    {
        isRight = true
    }
    else if (keyCode == 38)
    {
        isJumping = true
    }
}

function keyReleased()
{
    // if statements to control the animation of the character when
    // keys are released.

    // console.log("keyReleased: " + key);
    // console.log("keyReleased: " + keyCode);
    if (keyCode == 37)
    {
        isLeft = false
    }
    else if (keyCode == 39)
    {
        isRight = false
    }
    else if (keyCode == 38)
    {
        isJumping = false
    }
}


问:
Which would be a quicker (and better) tool for querying data stored in the Parquet format - Spark SQL, Athena or ElasticSearch?
Am currently building an ETL pipeline, which outputs tables of data (order of ~100+ GBs) to a downstream interactive dashboard, which allows filtering the data dynamically (based on pre-defined & indexed filters).

Have zeroed in on using PySpark / Spark for the initial ETL phase.
Next, this processed data will be summarised (simple counts, averages, etc.) & then visualised in the interactive dashboard.

Towards the interactive querying part, I was wondering which tool might work best with my structured & transactional data (stored in Parquet format) -

Spark SQL (in memory dynamic querying)

AWS Athena (Serverless SQL querying, based on Presto)

Elastic Search (search engine)

Redis (Key Value DB)

Feel free to suggest alternative tools, if you know of a better option.

答: you can use amazon quicksight , it has spice to do the query.. and can do visualisation at the same time..</p>


问:
how to display jquery UI datepicker in vertical
I'm using the jquery datepicker and this is my code

```<code>$( "#appointment_date" ).datepicker({
    dateFormat:"yy-mm-dd",
    altField:"#datepicker",
    numberOfMonths:3,
    minDate:0,
});
</code>```

And this is the interface that I look in desktop view and mobile view
desktop view
mobile view

Is it possible to remain same for the datepicker ui in desktop view? I want to display the datepicker ui in vertical like this example in mobile view.

答:
Have a look at this blog post from Salman Arshad. They explain how to install and use the "Monkey-Patch".

Not sure what versions of jquery/jqueryui/jquerymobile you are using - but remember to check if these files are compatible with each other (js + css).

For example, don't have jquerymobile.css (v1.2) and use jquerymobile.js (v1.4)

These are the most recent releases that you can include in your head

```<code><link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</code>```

Body:
I'm using the jquery datepicker and this is my code

$( "#appointment_date" ).datepicker({
    dateFormat:"yy-mm-dd",
    altField:"#datepicker",
    numberOfMonths:3,
    minDate:0,
});

And this is the interface that I look in desktop view and mobile view
desktop view
mobile view

Is it possible to remain same for the datepicker ui in desktop view? I want to display the datepicker ui in vertical like this example in mobile view.

Body:
Have a look at this blog post from Salman Arshad. They explain how to install and use the "Monkey-Patch".

Not sure what versions of jquery/jqueryui/jquerymobile you are using - but remember to check if these files are compatible with each other (js + css).

For example, don't have jquerymobile.css (v1.2) and use jquerymobile.js (v1.4)

These are the most recent releases that you can include in your head

<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>


答:
If you want just to convert the list to json, you can use Gson:

```<code>List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);
</code>```

If you want that the key will be "List", you need to create a object with a member that call List and then convert it.

Title: Convert List<Integer> to JSON in Java

Body:
How can I convert a List object in Java to a JSON object?

For example, how can I convert this:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...

To this JSON:

{
    "List" : [1, 2, ...]
}

Thank you!

Body:
If you want just to convert the list to json, you can use Gson:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);

If you want that the key will be "List", you need to create a object with a member that call List and then convert it.


问:
Synchronizing with a GO waitgroup
Why is this a deadlock in example 1, and does not deadlock nor print anything in example 2 ?

Example 1.)

```<code>func main() {

    w := sync.WaitGroup{}
    w.Add(4)
    c := make(chan int)

    go func() { c <- 1; w.Done() }()
    go func() { c <- 2; w.Done() }()
    go func() { c <- 3; w.Done() }()

    go func() { println(len(c)); w.Done() }()

    w.Wait()
}
</code>```

Example 2.)

```<code>func main() {
    w := sync.WaitGroup{}
    w.Add(3)
    c := make(chan int)

    go func() { c <- 1; w.Done() }()
    go func() { c <- 2; w.Done() }()
    go func() { c <- 3; w.Done() }()

    go func() { w.Wait(); println(len(c)) }()
}
</code>```

答:
Your first example launches 3 goroutines, and each tries to send a value on the c unbuffered channel. Since no one receives from the channel, all these will block. So the main() waiting for them to complete, will also be blocked. All goroutines are blocked: deadlock.

In your second example the main() function "just" launches goroutines and does not do anything after that. And when the main goroutine finishes (when your main() function returns), your app ends as well, it does not wait for other non-main goroutines to finishes. For details, see No output from goroutine.

Title: Synchronizing with a GO waitgroup

Body:
Why is this a deadlock in example 1, and does not deadlock nor print anything in example 2 ?

Example 1.)

func main() {

    w := sync.WaitGroup{}
    w.Add(4)
    c := make(chan int)

    go func() { c <- 1; w.Done() }()
    go func() { c <- 2; w.Done() }()
    go func() { c <- 3; w.Done() }()

    go func() { println(len(c)); w.Done() }()

    w.Wait()
}

Example 2.)

func main() {
    w := sync.WaitGroup{}
    w.Add(3)
    c := make(chan int)

    go func() { c <- 1; w.Done() }()
    go func() { c <- 2; w.Done() }()
    go func() { c <- 3; w.Done() }()

    go func() { w.Wait(); println(len(c)) }()
}


问:
Is it possible to look at the output of the previous row of a PostgreSQL query?
This is the question: Is it possible to look at the outputs, what has been selected, from the previous row of a running SQL query in Postgres?

I know that lag exists to look at the inputs, the "from" of the query. I also know that a CTE, subquery or lateral join can solve most issues of this kind. But I think the problem I'm facing genuinely requires a peek at the output of the previous row. Why? Because the output of the current row depends on a constant from a lookup table and the value used too look up that constant is an aggregate of all the previous rows. And if that lookup returns the wrong constant all subsequent rows will be increasingly off from the expected value.

The whole rest of this text is a simplified example based on the problem I'm facing. It should be possible to input it to PostgreSQL 12 and above and play around. I'm terribly sorry that it is as complicated as it is, but I think it is the most simple I can make it while still retaining the core issue: lookup in lookup table based on an aggregate from all previous rows as well as the fact that the "inventory" that's being tracked is modeled as a series of transactions of two discrete types.

The database itself exists to keep track of multiple fish farms, or cages full of fish. Fish can be moved/transferred from between these farms and the farms are fed about daily. Why not just carry the aggregate as a field in the table? Because it should be possible to switch out the lookup table after the season is over, to adjust it to better match with reality.

```<code>-- A listing of all groups of fish ever grown.
create table farms (
    id             bigserial primary key,
    start          timestamp not null,
    stop           timestamp
);

insert into farms
    (id, start)
values (
    1, '2021-02-01T13:37'
);

-- A transfer of fish from one odling to another.
-- If the source is null the fish is transferred from another fishery outside our system.
-- If the destination is null the fish is being slaughtered, removed from the system.
create table transfers (
    source           bigint    references farms(id),
    destination      bigint    references farms(id),
    timestamp        timestamp not null default current_timestamp,
    total_weight_g   bigint    not null constraint positive_nonzero_total_weight_g check (total_weight_g > 0),
    average_weight_g bigint    not null constraint positive_nonzero_average_weight_g check (average_weight_g > 0),
    number_fish      bigint    generated always as (total_weight_g / average_weight_g) stored
);

insert into transfers
    (source, destination, timestamp, total_weight_g, average_weight_g)
values
    (null, 1, '2021-02-01T16:38',  5,   5),
    (null, 1, '2021-02-15T16:38',  500, 500);

-- Transactions of fish feed into a farm.
create table feedings (
    id             bigserial primary key,
    growth_table   bigint    not null,
    farm           bigint    not null references farms(id),
    amount_g       bigint    not null constraint positive_nonzero_amunt_g check (amount_g > 0),
    timestamp      timestamp not null
);

insert into feedings
    (farm, growth_table, amount_g, timestamp)
values
    (1, 1, 1,  '2021-02-02T13:37'),
    (1, 1, 1,  '2021-02-03T13:37'),
    (1, 1, 1,  '2021-02-04T13:37'),
    (1, 1, 1,  '2021-02-05T13:37'),
    (1, 1, 1,  '2021-02-06T13:37'),
    (1, 1, 1,  '2021-02-07T13:37');

create view combined_feed_and_transfer_history as
with transfer_history as (
  select timestamp, destination as farm, total_weight_g, average_weight_g, number_fish
    from transfers as deposits
   where deposits.destination = 1 -- TODO: This view only works for one farm, fix that.
  union all
  select timestamp, source as farm, -total_weight_g, -average_weight_g, -number_fish
    from transfers as withdrawals
   where withdrawals.source = 1
)
select timestamp, farm, total_weight_g, number_fish, average_weight_g, null as growth_table
from transfer_history
union all
select timestamp, farm, amount_g, 0 as number_fish, 0 as average_weight_g, growth_table
from feedings
order by timestamp;

-- Conversion tables from feed to gained weight.
create table growth_coefficients (
    growth_table                   bigserial        not null,
    average_weight_g               bigint           not null constraint positive_nonzero_weight                 check (average_weight_g     >  0),
    feed_conversion_rate           double precision not null constraint positive_foderkonverteringsfaktor       check (feed_conversion_rate >= 0),
    primary key(growth_table, average_weight_g)
);

insert into growth_coefficients
    (average_weight_g, feed_conversion_rate, growth_table)
values
    (5.00,0.10,1),
    (10.00,10.00,1),
    (20.00,1.30,1),
    (50.00,1.31,1),
    (100.00,1.32,1),
    (300.00,1.36,1),
    (600.00,1.42,1),
    (1000.00,1.50,1),
    (1500.00,1.60,1),
    (2000.00,1.70,1),
    (2500.00,1.80,1),
    (3000.00,1.90,1),
    (4000.00,2.10,1),
    (5000.00,2.30,1);

-- My current solution is a bad one. It does a CTE that sums over all events but does not account
-- for the feed conversion rate. That means that the average weight used too look up the feed
-- conversion rate will diverge more and more from reality the further into the season time goes.
-- This is why it is important to look at the output, the average weight, of the previous row.

-- We start by summing up all the transfer and feed events to get a rough average_weight_g.
with estimate as (
    select
        timestamp,
        farm,
        total_weight_g as transaction_size_g,
        growth_table,
        sum(total_weight_g) over (order by timestamp)                                              as sum_weight_g,
        sum(number_fish)    over (order by timestamp)                                              as sum_number_fish,
        sum(total_weight_g) over (order by timestamp) / sum(number_fish) over (order by timestamp) as average_weight_g
    from
        combined_feed_and_transfer_history
)
select
    timestamp,
    sum_number_fish,
    transaction_size_g as trans_g,
    sum_weight_g,
    closest_lookup_table_weight.average_weight_g as lookup_g,
    converted_weight_g as conv_g,
    sum(converted_weight_g) over (order by timestamp)                   as sum_conv_g,
    sum(converted_weight_g) over (order by timestamp) / sum_number_fish as sum_average_g
from
    estimate
    join lateral ( -- We then use this estimated_average_weight to look up the closest constant in the growth coefficient table.
      (select gc.average_weight_g - estimate.average_weight_g as diff, gc.average_weight_g from growth_coefficients gc where gc.average_weight_g >= estimate.average_weight_g order by gc.average_weight_g asc  limit 1)
        union all
        (select estimate.average_weight_g - gc.average_weight_g as diff, gc.average_weight_g from growth_coefficients gc where gc.average_weight_g <= estimate.average_weight_g order by gc.average_weight_g desc limit 1)
        order by diff
        limit 1
    ) as closest_lookup_table_weight
    on true
    join lateral ( -- If the historical event is a feeding we need to lookup the feed conversion rate.
        select case when growth_table is null then 1
                  else (select feed_conversion_rate
                        from   growth_coefficients gc
                        where  gc.growth_table     = growth_table
                        and    gc.average_weight_g = closest_lookup_table_weight.average_weight_g)
             end
    ) as growth_coefficient
    on true
    join lateral (
        select feed_conversion_rate * transaction_size_g as converted_weight_g
    ) as converted_weight_g
    on true;
</code>```

At the very bottom is my current "solution". With the above example data the sum_conv_g should end up being 5.6, but due to the aggregate being used as the lookup not accounting for the conversion rate the sum_conv_g ends up 45.2 instead.

One idea I had was if there perhaps something like query-local variables one could use to store the sum_average_g between rows? There's always the escape hatch of just querying out the transactions to my generic programming language Clojure and solving it there, but it would be neat if it could be solved entirely within the database.

答: You have to formulate a recursive subquery. I posted a simplified version of this question over at the DBA SE and got the answer there. The answer to that question can be found here and can be expanded to this more complicated question, though I would wager that no one will ever have the interest to do that.</p>

Body:
This is the question: Is it possible to look at the outputs, what has been selected, from the previous row of a running SQL query in Postgres?

I know that lag exists to look at the inputs, the "from" of the query. I also know that a CTE, subquery or lateral join can solve most issues of this kind. But I think the problem I'm facing genuinely requires a peek at the output of the previous row. Why? Because the output of the current row depends on a constant from a lookup table and the value used too look up that constant is an aggregate of all the previous rows. And if that lookup returns the wrong constant all subsequent rows will be increasingly off from the expected value.

The whole rest of this text is a simplified example based on the problem I'm facing. It should be possible to input it to PostgreSQL 12 and above and play around. I'm terribly sorry that it is as complicated as it is, but I think it is the most simple I can make it while still retaining the core issue: lookup in lookup table based on an aggregate from all previous rows as well as the fact that the "inventory" that's being tracked is modeled as a series of transactions of two discrete types.

The database itself exists to keep track of multiple fish farms, or cages full of fish. Fish can be moved/transferred from between these farms and the farms are fed about daily. Why not just carry the aggregate as a field in the table? Because it should be possible to switch out the lookup table after the season is over, to adjust it to better match with reality.

-- A listing of all groups of fish ever grown.
create table farms (
    id             bigserial primary key,
    start          timestamp not null,
    stop           timestamp
);

insert into farms
    (id, start)
values (
    1, '2021-02-01T13:37'
);

-- A transfer of fish from one odling to another.
-- If the source is null the fish is transferred from another fishery outside our system.
-- If the destination is null the fish is being slaughtered, removed from the system.
create table transfers (
    source           bigint    references farms(id),
    destination      bigint    references farms(id),
    timestamp        timestamp not null default current_timestamp,
    total_weight_g   bigint    not null constraint positive_nonzero_total_weight_g check (total_weight_g > 0),
    average_weight_g bigint    not null constraint positive_nonzero_average_weight_g check (average_weight_g > 0),
    number_fish      bigint    generated always as (total_weight_g / average_weight_g) stored
);

insert into transfers
    (source, destination, timestamp, total_weight_g, average_weight_g)
values
    (null, 1, '2021-02-01T16:38',  5,   5),
    (null, 1, '2021-02-15T16:38',  500, 500);

-- Transactions of fish feed into a farm.
create table feedings (
    id             bigserial primary key,
    growth_table   bigint    not null,
    farm           bigint    not null references farms(id),
    amount_g       bigint    not null constraint positive_nonzero_amunt_g check (amount_g > 0),
    timestamp      timestamp not null
);

insert into feedings
    (farm, growth_table, amount_g, timestamp)
values
    (1, 1, 1,  '2021-02-02T13:37'),
    (1, 1, 1,  '2021-02-03T13:37'),
    (1, 1, 1,  '2021-02-04T13:37'),
    (1, 1, 1,  '2021-02-05T13:37'),
    (1, 1, 1,  '2021-02-06T13:37'),
    (1, 1, 1,  '2021-02-07T13:37');

create view combined_feed_and_transfer_history as
with transfer_history as (
  select timestamp, destination as farm, total_weight_g, average_weight_g, number_fish
    from transfers as deposits
   where deposits.destination = 1 -- TODO: This view only works for one farm, fix that.
  union all
  select timestamp, source as farm, -total_weight_g, -average_weight_g, -number_fish
    from transfers as withdrawals
   where withdrawals.source = 1
)
select timestamp, farm, total_weight_g, number_fish, average_weight_g, null as growth_table
from transfer_history
union all
select timestamp, farm, amount_g, 0 as number_fish, 0 as average_weight_g, growth_table
from feedings
order by timestamp;

-- Conversion tables from feed to gained weight.
create table growth_coefficients (
    growth_table                   bigserial        not null,
    average_weight_g               bigint           not null constraint positive_nonzero_weight                 check (average_weight_g     >  0),
    feed_conversion_rate           double precision not null constraint positive_foderkonverteringsfaktor       check (feed_conversion_rate >= 0),
    primary key(growth_table, average_weight_g)
);

insert into growth_coefficients
    (average_weight_g, feed_conversion_rate, growth_table)
values
    (5.00,0.10,1),
    (10.00,10.00,1),
    (20.00,1.30,1),
    (50.00,1.31,1),
    (100.00,1.32,1),
    (300.00,1.36,1),
    (600.00,1.42,1),
    (1000.00,1.50,1),
    (1500.00,1.60,1),
    (2000.00,1.70,1),
    (2500.00,1.80,1),
    (3000.00,1.90,1),
    (4000.00,2.10,1),
    (5000.00,2.30,1);

-- My current solution is a bad one. It does a CTE that sums over all events but does not account
-- for the feed conversion rate. That means that the average weight used too look up the feed
-- conversion rate will diverge more and more from reality the further into the season time goes.
-- This is why it is important to look at the output, the average weight, of the previous row.

-- We start by summing up all the transfer and feed events to get a rough average_weight_g.
with estimate as (
    select
        timestamp,
        farm,
        total_weight_g as transaction_size_g,
        growth_table,
        sum(total_weight_g) over (order by timestamp)                                              as sum_weight_g,
        sum(number_fish)    over (order by timestamp)                                              as sum_number_fish,
        sum(total_weight_g) over (order by timestamp) / sum(number_fish) over (order by timestamp) as average_weight_g
    from
        combined_feed_and_transfer_history
)
select
    timestamp,
    sum_number_fish,
    transaction_size_g as trans_g,
    sum_weight_g,
    closest_lookup_table_weight.average_weight_g as lookup_g,
    converted_weight_g as conv_g,
    sum(converted_weight_g) over (order by timestamp)                   as sum_conv_g,
    sum(converted_weight_g) over (order by timestamp) / sum_number_fish as sum_average_g
from
    estimate
    join lateral ( -- We then use this estimated_average_weight to look up the closest constant in the growth coefficient table.
      (select gc.average_weight_g - estimate.average_weight_g as diff, gc.average_weight_g from growth_coefficients gc where gc.average_weight_g >= estimate.average_weight_g order by gc.average_weight_g asc  limit 1)
        union all
        (select estimate.average_weight_g - gc.average_weight_g as diff, gc.average_weight_g from growth_coefficients gc where gc.average_weight_g <= estimate.average_weight_g order by gc.average_weight_g desc limit 1)
        order by diff
        limit 1
    ) as closest_lookup_table_weight
    on true
    join lateral ( -- If the historical event is a feeding we need to lookup the feed conversion rate.
        select case when growth_table is null then 1
                  else (select feed_conversion_rate
                        from   growth_coefficients gc
                        where  gc.growth_table     = growth_table
                        and    gc.average_weight_g = closest_lookup_table_weight.average_weight_g)
             end
    ) as growth_coefficient
    on true
    join lateral (
        select feed_conversion_rate * transaction_size_g as converted_weight_g
    ) as converted_weight_g
    on true;

At the very bottom is my current "solution". With the above example data the sum_conv_g should end up being 5.6, but due to the aggregate being used as the lookup not accounting for the conversion rate the sum_conv_g ends up 45.2 instead.

One idea I had was if there perhaps something like query-local variables one could use to store the sum_average_g between rows? There's always the escape hatch of just querying out the transactions to my generic programming language Clojure and solving it there, but it would be neat if it could be solved entirely within the database.


问:
Python program to number rows
i have a file with data as such.

```<code>>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>3_DL_2021.1214
>4_DL_2021.1214
>4_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214
</code>```

now as you can see the data is not numbered properly and hence needs to be numbered.
what im aiming for is this:

```<code>>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>4_DL_2021.1214
>5_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214
>9_DL_2021.1214
</code>```

now the file has a lot of other stuff between these lines starting with > sign. i want only the > sign stuff affected.

could someone please help me out with this.
also there are 563 such lines so manually doing it is out of question.

答:
So, assuming input data file is "input.txt"

You can achieve what you want with this

```<code>import re

with open("input.txt", "r") as f:
    a = f.readlines()

regex = re.compile(r"^>\d+_DL_2021\.\d+\n$")

counter = 1

for i, line in enumerate(a):
    if regex.match(line):
        tokens = line.split("_")
        tokens[0] = f">{counter}"
        a[i] = "_".join(tokens)

        counter += 1

with open("input.txt", "w") as f:
    f.writelines(a)
</code>```

So what it does it searches for line with the regex ^>\d+_DL_2021\.\d+\n$, then splits it by _ and gets the first (0th) element and rewrites it, then counts up by 1 and continues the same thing, after all it just writes updated strings back to "input.txt"

Title: Python program to number rows

Body:
i have a file with data as such.

>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>3_DL_2021.1214
>4_DL_2021.1214
>4_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214

now as you can see the data is not numbered properly and hence needs to be numbered.
what im aiming for is this:

>1_DL_2021.1123
>2_DL_2021.1206
>3_DL_2021.1202
>4_DL_2021.1214
>5_DL_2021.1214
>6_DL_2021.1214
>7_DL_2021.1214
>8_DL_2021.1214
>9_DL_2021.1214

now the file has a lot of other stuff between these lines starting with > sign. i want only the > sign stuff affected.

could someone please help me out with this.
also there are 563 such lines so manually doing it is out of question.

Body:
So, assuming input data file is "input.txt"

You can achieve what you want with this

import re

with open("input.txt", "r") as f:
    a = f.readlines()

regex = re.compile(r"^>\d+_DL_2021\.\d+\n$")

counter = 1

for i, line in enumerate(a):
    if regex.match(line):
        tokens = line.split("_")
        tokens[0] = f">{counter}"
        a[i] = "_".join(tokens)

        counter += 1

with open("input.txt", "w") as f:
    f.writelines(a)

So what it does it searches for line with the regex ^>\d+_DL_2021\.\d+\n$, then splits it by _ and gets the first (0th) element and rewrites it, then counts up by 1 and continues the same thing, after all it just writes updated strings back to "input.txt"


答:
In the first example, the channels won't be able to send since there is no receiver on the other end of the unbuffered channel. The sent will block forever. And therefore the waitgroup will wait forever. This is a deadlock situation as your program is not able to continue at all.

In the second case, the same thing happens, but you wait in a separate goroutine. So the main function is able to continue. It's not a complete deadlock. In this case, the continuation means the program just exists.

Title: Synchronizing with a GO waitgroup