问:
opam init fails to verify certificate
On a completely fresh ubuntu 18.04 VM I tried to install opam:

```<code>$ wget https://github.com/ocaml/opam/releases/download/2.1.0/opam-2.1.0-x86_64-linux
$ mv opam-2.1.0-x86_64-linux opam
$ chmod 777 opam
$ ./opam init
</code>```

And here is the error I got

```<code><><> Fetching repository information ><><><><><><><><><><><><><><><><><><><><><>
[ERROR] Could not update repository "default": OpamDownload.Download_fail(_,
        "Download command failed: \"/usr/bin/wget --content-disposition -t 3 -O
        /tmp/opam-5936-f23d09/index.tar.gz.part -U opam/2.1.0 --
        https://opam.ocaml.org/index.tar.gz\" exited with code 5 \"ERROR:
        cannot verify opam.ocaml.org's certificate, issued by
        \226\128\152CN=Zscaler Intermediate Root CA (zscaler.net) (t)\\\\
        ,OU=Zscaler Inc.,O=Zscaler Inc.,ST=California,C=US\226\128\153:\"")
[ERROR] Initial download of repository failed.
</code>```

How should I solve this?

答:
I ran into the same issue and I found a workaround on the OCaml forum: here. (Credits to UnixJunkie)

You can run:

```<code>opam init github git+https://github.com/ocaml/opam-repository.git
</code>```

This should avoid the certificate issues. This worked for me.

I tried to fix the certificate issues using this answer as well. You could try doing that, but it seems complicated when the workaround is to simply point it to the github repo directly.

Update

The reason opam init failed for me was because curl was installed with snap on my system.
Try to run opam init -verbose and that could reveal more about why you ran into an error.
In my case I needed to install other things with opam and it kept failing every time. So snap uninstall curl and then sudo apt install curl fixed things. (Was only able to figure this out with the help from my professor)

Title: opam init fails to verify certificate

Body:
On a completely fresh ubuntu 18.04 VM I tried to install opam:

$ wget https://github.com/ocaml/opam/releases/download/2.1.0/opam-2.1.0-x86_64-linux
$ mv opam-2.1.0-x86_64-linux opam
$ chmod 777 opam
$ ./opam init

And here is the error I got

<><> Fetching repository information ><><><><><><><><><><><><><><><><><><><><><>
[ERROR] Could not update repository "default": OpamDownload.Download_fail(_,
        "Download command failed: \"/usr/bin/wget --content-disposition -t 3 -O
        /tmp/opam-5936-f23d09/index.tar.gz.part -U opam/2.1.0 --
        https://opam.ocaml.org/index.tar.gz\" exited with code 5 \"ERROR:
        cannot verify opam.ocaml.org's certificate, issued by
        \226\128\152CN=Zscaler Intermediate Root CA (zscaler.net) (t)\\\\
        ,OU=Zscaler Inc.,O=Zscaler Inc.,ST=California,C=US\226\128\153:\"")
[ERROR] Initial download of repository failed.

How should I solve this?

Body:
I ran into the same issue and I found a workaround on the OCaml forum: here. (Credits to UnixJunkie)

You can run:

opam init github git+https://github.com/ocaml/opam-repository.git

This should avoid the certificate issues. This worked for me.

I tried to fix the certificate issues using this answer as well. You could try doing that, but it seems complicated when the workaround is to simply point it to the github repo directly.

Update

The reason opam init failed for me was because curl was installed with snap on my system.
Try to run opam init -verbose and that could reveal more about why you ran into an error.
In my case I needed to install other things with opam and it kept failing every time. So snap uninstall curl and then sudo apt install curl fixed things. (Was only able to figure this out with the help from my professor)


来源: stackexchange

问:
wget with big data file straight to s3
I'm using wget to pipe straight from a www.backblaze.com url to S3 with the following command:

```<code>> wget -qO- '<url>' | aws s3 cp - s3://<bucket>/{data_file}
</code>```

The  is to a file, which can be anywhere from 10 to 20Gb in size. I've ran the process a couple of times with a Python script with the following:

```<code>os.system('wget -qO- '<url>' | aws s3 cp - s3://<bucket>/{data_file}')
</code>```

When the process is complete I don't receive any errors, however the files in my s3 bucket are only ~4 or 5Gb in size, suggesting the entire file wasn't either read or written to the pipe.

I'm not sure what the problem is here. Has anyone had experience using wget to pipe big data files?

答:
```<code>os.system('wget -qO- '<url>' | aws s3 cp - s3://<bucket>/{data_file}')
</code>```

Please note that there is general movement in python from using os.system to using subprocess built-in module. os module docs claims that os.system

This is implemented by calling the Standard C function system(), and
has the same limitations.

I am not Standard C function system()-ninja so I am unable to say if there is do not use | ramfication from above, but anyway I would suggest replacing os.system using subprocess built-in module, which seems to be general movement among python developers. See Replacing shell pipeline in subprocess docs for example of piping.

ContentLicense: CC BY-SA 4.0

Title: wget with big data file straight to s3

Body:
I'm using wget to pipe straight from a www.backblaze.com url to S3 with the following command:

> wget -qO- '<url>' | aws s3 cp - s3://<bucket>/{data_file}

The  is to a file, which can be anywhere from 10 to 20Gb in size. I've ran the process a couple of times with a Python script with the following:

os.system('wget -qO- '<url>' | aws s3 cp - s3://<bucket>/{data_file}')

When the process is complete I don't receive any errors, however the files in my s3 bucket are only ~4 or 5Gb in size, suggesting the entire file wasn't either read or written to the pipe.

I'm not sure what the problem is here. Has anyone had experience using wget to pipe big data files?

Body:
os.system('wget -qO- '<url>' | aws s3 cp - s3://<bucket>/{data_file}')

Please note that there is general movement in python from using os.system to using subprocess built-in module. os module docs claims that os.system

This is implemented by calling the Standard C function system(), and
has the same limitations.

I am not Standard C function system()-ninja so I am unable to say if there is do not use | ramfication from above, but anyway I would suggest replacing os.system using subprocess built-in module, which seems to be general movement among python developers. See Replacing shell pipeline in subprocess docs for example of piping.


问:
Laravel Livewire Typed property must not be accessed before initialization on form submission
New to livewire, and trying to convert an existing form to a livewire component.

When I submit the form, I'm getting this error:

Typed property App\Http\Livewire\LocationInfo::$location must not be accessed before initialization

I'm not sure how to make this work, or what I'm doing wrong. I was expecting that the save() method would know about $this->location, but maybe I'm misunderstanding something. Can't seem to find anything different in the docs from what I'm doing. I've also looked through other questions with the same error and not finding an answer.

I can move the Log statement to the mount method or the render method and it will log the correct info. I don't understand why it's not available to the save() method.

Here's my livewire component:

```<code>class LocationInfo extends Component
{

    public Object $states;
    public Location $location;

    protected $rules = [
        'location.name'          => ['required', 'string', 'max:150'],
        ...
    ];

    public function mount(Location $location)
    {
        $this->location = $location;
        $this->states = USState::all();
    }

    public function render()
    {
        return view('livewire.location-info');
    }

    public function save()
    {
        Log::debug($this->location);
    }
}
</code>```

and here's my form:

```<code><div class="modal fade" id="location_info_modal" tabindex="-1" aria-labelledby="location_info_modal" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form wire:submit.prevent="save" class="" id="location_info_form" method="POST" action="/locations/{{ $location->id }}">
            <div class="modal-content">
                <div class="modal-header d-flex justify-content-between">
                    <div id="modal_header" class="d-flex justify-content-start align-items-center">
                        <h5 class="modal-title pe-3">Edit Location Info</h5>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="btn-close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        @csrf
                        <div class="mb-3 col-md-8">
                            <label for="name" class="form-label">Location Name</label>
                            <input wire:model="location.name" type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ $location->name ?? '' }}" data-inputmask-regex="[A-Za-z0-9#.,''-() &]+">
                            @error('location.name') <span class="error">{{ $message }}</span> @enderror
                        </div>

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary save_btn" id="location_info_save" disabled>Save</button>
                </div>
            </div>
        </form>
    </div>
</div>
</code>```

and here's my route:

```<code>Route::post('/locations/{id}', [LocationInfo::class, 'save'])
    ->middleware('auth');
</code>```

答:
I had this error before to me it was the typed property try to remove it like:

```<code>public $location;

public function mount(Location $location)
{
    $this->location = $location;
}
</code>```

or remove the one in the mount:

```<code>public Location $location;

public function mount()
{
    $this->location = new Location();
}
</code>```

Body:
New to livewire, and trying to convert an existing form to a livewire component.

When I submit the form, I'm getting this error:

Typed property App\Http\Livewire\LocationInfo::$location must not be accessed before initialization

I'm not sure how to make this work, or what I'm doing wrong. I was expecting that the save() method would know about $this->location, but maybe I'm misunderstanding something. Can't seem to find anything different in the docs from what I'm doing. I've also looked through other questions with the same error and not finding an answer.

I can move the Log statement to the mount method or the render method and it will log the correct info. I don't understand why it's not available to the save() method.

Here's my livewire component:

class LocationInfo extends Component
{

    public Object $states;
    public Location $location;

    protected $rules = [
        'location.name'          => ['required', 'string', 'max:150'],
        ...
    ];

    public function mount(Location $location)
    {
        $this->location = $location;
        $this->states = USState::all();
    }

    public function render()
    {
        return view('livewire.location-info');
    }

    public function save()
    {
        Log::debug($this->location);
    }
}

and here's my form:

        <form wire:submit.prevent="save" class="" id="location_info_form" method="POST" action="/locations/{{ $location->id }}">

Edit Location Info

                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="btn-close"></button>

                        @csrf

                            Location Name
                            <input wire:model="location.name" type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ $location->name ?? '' }}" data-inputmask-regex="[A-Za-z0-9#.,''-() &]+">
                            @error('location.name') {{ $message }} @enderror

                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary save_btn" id="location_info_save" disabled>Save</button>

        </form>

and here's my route:

Route::post('/locations/{id}', [LocationInfo::class, 'save'])
    ->middleware('auth');

Body:
I had this error before to me it was the typed property try to remove it like:

public $location;

public function mount(Location $location)
{
    $this->location = $location;
}

or remove the one in the mount:

public Location $location;

public function mount()
{
    $this->location = new Location();
}


问:
Disable DPI awareness for WPF application
Good day!

I've been working on a WPF app for some time now (as a learning experience and oh boy it was a learning experience) and it's finally ready for release. Release means installing it on my HTPC where it will be used to browse my movie collection.

I designed it on my PC which runs 1920*1080 but at the normal DPI setting, while the HTPC/TV is running at the same resolution but a higher DPI setting for obvious reasons.

The problem is my app goes bonkers on the HTPC, messing up pretty much everything as far as visuals go. I know this is due to bad design (mea culpa), but since it's an application that will only be used by me I'm looking for an quick fix, not a full redesign. I read it would be possible to stop the app from being DPI aware by adding the following to AssemblyInfo.cs:

```<code>[assembly: System.Windows.Media.DisableDpiAwareness]
</code>```

However, it doesn't seem to have any effect and the behavior of the app remains the same.

Could anyone point me in the right direction?

Thank you,
Johan

答:
In my case, changing high DPI settings of my exe helped. Example below. I choose 'Application' in combobox.

Read more about it here

ContentLicense: CC BY-SA 3.0

Body:
Good day!

I've been working on a WPF app for some time now (as a learning experience and oh boy it was a learning experience) and it's finally ready for release. Release means installing it on my HTPC where it will be used to browse my movie collection.

I designed it on my PC which runs 1920*1080 but at the normal DPI setting, while the HTPC/TV is running at the same resolution but a higher DPI setting for obvious reasons.

The problem is my app goes bonkers on the HTPC, messing up pretty much everything as far as visuals go. I know this is due to bad design (mea culpa), but since it's an application that will only be used by me I'm looking for an quick fix, not a full redesign. I read it would be possible to stop the app from being DPI aware by adding the following to AssemblyInfo.cs:

[assembly: System.Windows.Media.DisableDpiAwareness]

However, it doesn't seem to have any effect and the behavior of the app remains the same.

Could anyone point me in the right direction?

Thank you,
Johan


问:
simple yes or no checkbox for forms
I have inserted a checkbox in my form.

My code:

```<code><input type="checkbox" id="checkbox" name="checkbox" value="1"/>

if($checkbox = ($_POST['checkbox']) == '1')
        {
            $checkbox = "si";
        }
        else
        {
            $checkbox = "no";
        }
</code>```

I would like that if the checkbox is checked i receive "yes" otherwise "no".
Thanks.

答:
```<code>$request['checkbox_name'] = $request['checkbox_name'] == null ? 'N' : 'Y'; //for default value
</code>```

Title: simple yes or no checkbox for forms

Body:
I have inserted a checkbox in my form.

My code:

<input type="checkbox" id="checkbox" name="checkbox" value="1"/>

if($checkbox = ($_POST['checkbox']) == '1')
        {
            $checkbox = "si";
        }
        else
        {
            $checkbox = "no";
        }

I would like that if the checkbox is checked i receive "yes" otherwise "no".
Thanks.


问:
Geting some fields of class to JSON
How to get JSON, which contains only Name and Flags?

```<code>  TUser = class
  private
    FName:  string;
    FFlags: UInt32;
    FFields: UInt32;
    FCreated: TDateTime;
  public
    property Name: string read FName write FName;
    property Flags: UInt32 read FFlags write FFlags;
    property Fields: UInt32 read FFields write FFields;
    property Created: TDateTime read FCreated write FCreated;
    constructor Create;
  end;
</code>```

Usually is used all fields of this class:

```<code>var
  User: TUser
  sJson: string;

sJson := User.AsJson;
</code>```

but sometimes I needed a JSON with Name and Flags fields only.
Currently, to get such JSON I use such code:

```<code>var
  User: TUser
  usr: ISuperObject;
  sJson: string;

usr := SO(User.AsJson);
usr.Remove('Fields');
usr.Remove('Created');
sJson := usr.AsJSON;
</code>```

But I think is not optimal code (actually in real code I have 15 fields and need to remove 12). How to do that faster?

Updated (another method):

May be this will be more faster and useful for my purpose?

```<code>usr := SO('');
usr.S['Name']  := User.Name;
usr.I['Flags'] := User.Flags;
sJson := usr.AsJSON;
</code>```

答:
Thanks to the @NasreddineGalfout I'm found that is it possible with Neon JSON library. With INeonConfiguration I can select public or published or protected (or any combination) property fields that should be serialized. And is it what I need. Moreover deserializing with Neon is 2x much faster than with XSuperObject.</p>
```<code>type
  TUser = class
  private
    FName:  string;
    FFlags: UInt32;
    FFields: UInt32;
    FCreated: TDateTime;
  public
    property Name: string read FName write FName;
    property Flags: UInt32 read FFlags write FFlags;
  published
    property Fields: UInt32 read FFields write FFields;
    property Created: TDateTime read FCreated write FCreated;
    constructor Create;
  end;

function MyToJson(User: TUser): string;
var
  Config: INeonConfiguration;
  LJSON: TJSONValue;
  LWriter: TNeonSerializerJSON;
begin
  Config := TNeonConfiguration.Default.SetVisibility([mvPublic{, mvPublished}]);
  LWriter := TNeonSerializerJSON.Create(Config);
  try
    LJSON := LWriter.ObjectToJSON(User);
    try
      Result := TJSONUtils.ToJSON(LJSON);
    finally
      LJSON.Free;
    end;
  finally
    LWriter.Free;
  end;
end;

procedure MyFromJson(var User: TUser; const AJson: string);
var
  Config: INeonConfiguration;
  LJSON: TJSONValue;
  LReader: TNeonDeserializerJSON;
begin
  LJSON := TJSONObject.ParseJSONValue(AJson);
  if not Assigned(LJSON) then
    Exit;
  Config := TNeonConfiguration.Default.SetVisibility([mvPublic{, mvPublished}]);
  try
    LReader := TNeonDeserializerJSON.Create(Config);
    try
      LReader.JSONToObject(User, LJSON);
    finally
      LReader.Free;
    end;
  finally
    LJSON.Free;
  end;
end;
</code>```

Title: Geting some fields of class to JSON

Body:
How to get JSON, which contains only Name and Flags?

  TUser = class
  private
    FName:  string;
    FFlags: UInt32;
    FFields: UInt32;
    FCreated: TDateTime;
  public
    property Name: string read FName write FName;
    property Flags: UInt32 read FFlags write FFlags;
    property Fields: UInt32 read FFields write FFields;
    property Created: TDateTime read FCreated write FCreated;
    constructor Create;
  end;

Usually is used all fields of this class:

var
  User: TUser
  sJson: string;

sJson := User.AsJson;

but sometimes I needed a JSON with Name and Flags fields only.
Currently, to get such JSON I use such code:

var
  User: TUser
  usr: ISuperObject;
  sJson: string;

usr := SO(User.AsJson);
usr.Remove('Fields');
usr.Remove('Created');
sJson := usr.AsJSON;

But I think is not optimal code (actually in real code I have 15 fields and need to remove 12). How to do that faster?

Updated (another method):

May be this will be more faster and useful for my purpose?

usr := SO('');
usr.S['Name']  := User.Name;
usr.I['Flags'] := User.Flags;
sJson := usr.AsJSON;

Body:
Thanks to the @NasreddineGalfout I'm found that is it possible with Neon JSON library. With INeonConfiguration I can select public or published or protected (or any combination) property fields that should be serialized. And is it what I need. Moreover deserializing with Neon is 2x much faster than with XSuperObject.

type
  TUser = class
  private
    FName:  string;
    FFlags: UInt32;
    FFields: UInt32;
    FCreated: TDateTime;
  public
    property Name: string read FName write FName;
    property Flags: UInt32 read FFlags write FFlags;
  published
    property Fields: UInt32 read FFields write FFields;
    property Created: TDateTime read FCreated write FCreated;
    constructor Create;
  end;

function MyToJson(User: TUser): string;
var
  Config: INeonConfiguration;
  LJSON: TJSONValue;
  LWriter: TNeonSerializerJSON;
begin
  Config := TNeonConfiguration.Default.SetVisibility([mvPublic{, mvPublished}]);
  LWriter := TNeonSerializerJSON.Create(Config);
  try
    LJSON := LWriter.ObjectToJSON(User);
    try
      Result := TJSONUtils.ToJSON(LJSON);
    finally
      LJSON.Free;
    end;
  finally
    LWriter.Free;
  end;
end;

procedure MyFromJson(var User: TUser; const AJson: string);
var
  Config: INeonConfiguration;
  LJSON: TJSONValue;
  LReader: TNeonDeserializerJSON;
begin
  LJSON := TJSONObject.ParseJSONValue(AJson);
  if not Assigned(LJSON) then
    Exit;
  Config := TNeonConfiguration.Default.SetVisibility([mvPublic{, mvPublished}]);
  try
    LReader := TNeonDeserializerJSON.Create(Config);
    try
      LReader.JSONToObject(User, LJSON);
    finally
      LReader.Free;
    end;
  finally
    LJSON.Free;
  end;
end;


问:
is .agg() element-wise on a series?
If we were to take the following series:

```<code>s = pd.Series([20, 21, 12],
              index=['London', 'New York', 'Helsinki'])

London      20
New York    21
Helsinki    12
</code>```

This makes me believe it operates element-wise on a series:

```<code>s.agg('{}_Test'.format)

London      20_Test
New York    21_Test
Helsinki    12_Test
</code>```

But it can also produce scalar results on the series as well, which is well documented.

```<code>s.agg(np.sum)

53
</code>```

I believe .agg() is supposed to work very similar to apply, but can receive multiple functions at once.

If we did s.apply(np.sum), since it is element-wise wouldn't do anything.

My question is, is .agg() element-wise when not aggregating, and when doing an aggregation, not element-wise?

(in s.agg(lambda x: x) x would be a series I believe, but not always.)

答:
Whether the Series.agg() method works element-wise depends on the
function you pass to it. According to the pandas documentation

Actually it also depends on the content of Series!

```<code>ser_n = pd.Series([111.0, 222.0, 333.0])
ser_s = pd.Series(['abc', 'qrt', 'xyz'])
max(ser_n)      # 333.0
max(ser_s)      # xyz
ser_n.agg(max)  # 333.0
ser_s.agg(max)  # xyz
</code>```

But if you pass your own function .agg() behavior differs when dtype is string:

```<code>ser_n.agg(lambda s: max(s))     # 333.0
ser_s.agg(lambda s: max(s))     # Series: [0]:'c'  [1]:'t' [2]:'z'
</code>```

Also:

```<code>','.join(ser_s)         # 'abc,qrt,xyz'
ser_s.agg(','.join)     # Series: [0]:'a,b,c' [1]:'q,r,t' [2]:'x,y,z'
</code>```

Look closely what is happened inside the calls:

```<code>def func(s):
    print('---call:---')
    print(s, type(s))
    return max(s)
print('---result:---\n', ser_n.agg(func), '\n')
print('---result:---\n', ser_s.agg(func), '\n')

---call:---
111.0 <class 'float'>
---call:---
0    111.0
1    222.0
2    333.0
dtype: float64 <class 'pandas.core.series.Series'>
---result:---
 333.0

---call:---
abc <class 'str'>
---call:---
qrt <class 'str'>
---call:---
xyz <class 'str'>
---result:---
0    c
1    t
2    z
dtype: object
</code>```

It's like the first call tests type of data. If it's numerical - second call accept the whole Series. If it's a string - then continues element wise.
Very strange an undocumented behavior!

Title: is .agg() element-wise on a series?

Body:
If we were to take the following series:

s = pd.Series([20, 21, 12],
              index=['London', 'New York', 'Helsinki'])

London      20
New York    21
Helsinki    12

This makes me believe it operates element-wise on a series:

s.agg('{}_Test'.format)

London      20_Test
New York    21_Test
Helsinki    12_Test

But it can also produce scalar results on the series as well, which is well documented.

s.agg(np.sum)

53

I believe .agg() is supposed to work very similar to apply, but can receive multiple functions at once.

If we did s.apply(np.sum), since it is element-wise wouldn't do anything.

My question is, is .agg() element-wise when not aggregating, and when doing an aggregation, not element-wise?

(in s.agg(lambda x: x) x would be a series I believe, but not always.)

Body:
Whether the Series.agg() method works element-wise depends on the
function you pass to it. According to the pandas documentation

Actually it also depends on the content of Series!

ser_n = pd.Series([111.0, 222.0, 333.0])
ser_s = pd.Series(['abc', 'qrt', 'xyz'])
max(ser_n)      # 333.0
max(ser_s)      # xyz
ser_n.agg(max)  # 333.0
ser_s.agg(max)  # xyz

But if you pass your own function .agg() behavior differs when dtype is string:

ser_n.agg(lambda s: max(s))     # 333.0
ser_s.agg(lambda s: max(s))     # Series: [0]:'c'  [1]:'t' [2]:'z'

Also:

','.join(ser_s)         # 'abc,qrt,xyz'
ser_s.agg(','.join)     # Series: [0]:'a,b,c' [1]:'q,r,t' [2]:'x,y,z'

Look closely what is happened inside the calls:

def func(s):
    print('---call:---')
    print(s, type(s))
    return max(s)
print('---result:---\n', ser_n.agg(func), '\n')
print('---result:---\n', ser_s.agg(func), '\n')

---call:---
111.0 <class 'float'>
---call:---
0    111.0
1    222.0
2    333.0
dtype: float64 <class 'pandas.core.series.Series'>
---result:---
 333.0

---call:---
abc <class 'str'>
---call:---
qrt <class 'str'>
---call:---
xyz <class 'str'>
---result:---
0    c
1    t
2    z
dtype: object

It's like the first call tests type of data. If it's numerical - second call accept the whole Series. If it's a string - then continues element wise.
Very strange an undocumented behavior!


问:
Display errors with PDFViewer on Android
Getting PDFViewer to work. Now I have black blocks on the pages. Looks like a rendering problem.

PDFView pdfView = findViewById(R.id.pdfView);
File pdfFile = new File(getExternalFilesDir(null)+ "/Download/", "/epaper.pdf");
pdfView.fromFile(pdfFile).enableSwipe(true).swipeHorizontal(true).enableAnnotationRendering(true).load();
```

In Emulator it all works fine. I tried bestQuality(true), but nothing changed.

My Phone: Xiaomi Mi 9 (if it helps)

答:
I found the solution on this.

DarkMode needed to be deactivated in themes.xml:

<item name="android:forceDarkAllowed">false</item>

Only using:

```<code>AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
</code>```

did not work.

Body:
Getting PDFViewer to work. Now I have black blocks on the pages. Looks like a rendering problem.

PDFView pdfView = findViewById(R.id.pdfView);
File pdfFile = new File(getExternalFilesDir(null)+ "/Download/", "/epaper.pdf");
pdfView.fromFile(pdfFile).enableSwipe(true).swipeHorizontal(true).enableAnnotationRendering(true).load();

In Emulator it all works fine. I tried bestQuality(true), but nothing changed.

My Phone: Xiaomi Mi 9 (if it helps)

Body:
I found the solution on this.

DarkMode needed to be deactivated in themes.xml:

<item name="android:forceDarkAllowed">false</item>

Only using:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

did not work.


问:
Symfony 2: setting form attributes in Form Class
I have this form class, in my Symfony 2 project. Everything works fine, but I don't know where to set up form tag attributes.

```<code>namespace Forms\FormsBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', 'email', array(
                'label' => 'Enter Username',
                'attr'  => array(
                    'class' => 'form-control',
                    'placeholder'   => 'Username',
                    'data-trigger'  => 'change',
                    'data-required' => 'true',
                    'data-type'     => 'email',
                )
            ))
            ->add('password', 'password', array(
                'label' => 'Enter Password',
                'attr'  => array(
                    'class' => 'form-control',
                    'placeholder' => 'Password',
                    'data-trigger'  => 'change',
                    'data-required' => 'true',
                    'data-type'     => 'password'
                    )
            ))
            ->add('send', 'submit', array(
                'attr'  => array(
                    'class' => 'btn btn-primary',
                    'placeholder' => 'Send'
                    )
            ));
    }

public function getName()
    {
        return 'registration';
    }

}
</code>```

Does anyone know if, it's possible to set attributes of form here? E.g. class="something" data-something="true"

Thank you very much for any advice

答:
You can add html attributes to the <form> element in the configureOptions method of your formType:

class FoobarType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'attr' => ['data-test' => 'hello'],
        ]);
    }
}
```

Body:
I have this form class, in my Symfony 2 project. Everything works fine, but I don't know where to set up form tag attributes.

namespace Forms\FormsBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', 'email', array(
                'label' => 'Enter Username',
                'attr'  => array(
                    'class' => 'form-control',
                    'placeholder'   => 'Username',
                    'data-trigger'  => 'change',
                    'data-required' => 'true',
                    'data-type'     => 'email',
                )
            ))
            ->add('password', 'password', array(
                'label' => 'Enter Password',
                'attr'  => array(
                    'class' => 'form-control',
                    'placeholder' => 'Password',
                    'data-trigger'  => 'change',
                    'data-required' => 'true',
                    'data-type'     => 'password'
                    )
            ))
            ->add('send', 'submit', array(
                'attr'  => array(
                    'class' => 'btn btn-primary',
                    'placeholder' => 'Send'
                    )
            ));
    }

public function getName()
    {
        return 'registration';
    }

}

Does anyone know if, it's possible to set attributes of form here? E.g. class="something" data-something="true"

Thank you very much for any advice


问:
How to properly define destructor
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

```<code>class1::~class1(void) {

}
</code>```

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico

答:
First you should try to allocate your objects on the stack:

```<code>Object obj;
</code>```

so you don't have to worry about memory allocation. The disadvantage is that the object life is limited to the current scope.

If that's not good for you, you should consider using smart pointers. If that's not an option use new / delete to create / destroy your objects. But you have to be careful, every new should lead to a delete at some point in time..

Title: How to properly define destructor

Body:
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

class1::~class1(void) {

}

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico

Body:
First you should try to allocate your objects on the stack:

Object obj;

so you don't have to worry about memory allocation. The disadvantage is that the object life is limited to the current scope.

If that's not good for you, you should consider using smart pointers. If that's not an option use new / delete to create / destroy your objects. But you have to be careful, every new should lead to a delete at some point in time..


问:
Why is the Button Null?
I'm receiving a NullPointerException. It says that the button is null which makes no sense. The full error code and my code is listed below.

```<code>package com.example.effectslikerotation;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Scene;

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    private Button blurButton, rotateButton, scaleButton;
    private Rotate rotate;
    private double angle;
    Object buttonClicked;
    Object buttonText;

    @Override
    public void start(Stage stage) throws IOException {
        Button rotateButton = new Button();
        Button blurButton = new Button();
        Button scaleButton = new Button();

        angle = 0.0;

        rotateButton.setOnAction(this);
        blurButton.setOnAction(this);
        scaleButton.setOnAction(this);

        rotateButton.setText("Rotate");
        blurButton.setText("Blur");
        scaleButton.setText("Scale");

        Label reflect = new Label("I'm a reflection of you.");

        FlowPane FProot = new FlowPane();
        Scene scene = new Scene(FProot, 600, 500);
        FProot.setAlignment(Pos.CENTER);
        FProot.getChildren().addAll(rotateButton, blurButton, scaleButton, reflect);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();

        //rotateButton.getTransforms().add(rotate);

    }

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void handle(ActionEvent e) {
        Object buttonClicked = e.getSource();

        if (rotateButton.isPressed()) { //
            System.out.println("Rotate button clicked"); //not sure why this doesnt print out.

        }
        if (buttonClicked.equals(blurButton)) { //
            System.out.println("Rotate button clicked"); //not sure why this doesnt print out.
        }
        if (buttonClicked.equals(scaleButton)) { //
            System.out.println("Rotate button clicked"); //not sure why this doesnt print out.
        }

}}
</code>```

Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.scene.control.Button.isPressed()" because "this.rotateButton" is null
at com.example.effectslikerotation/com.example.effectslikerotation.HelloApplication.handle(HelloApplication.java:73)
at com.example.effectslikerotation/com.example.effectslikerotation.HelloApplication.handle(HelloApplication.java:20)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8792)
at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3897)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1878)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2623)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:557)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:943)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
at java.base/java.lang.Thread.run(Thread.java:833)

答:
You define these fields:

```<code>private Button blurButton, rotateButton, scaleButton;
</code>```

but never assign anything to them.

```<code>Button rotateButton = new Button();
Button blurButton = new Button();
Button scaleButton = new Button();
</code>```

By adding Button in front of these assignments it means you're creating new variables.

To fix this just remove Button:

```<code>rotateButton = new Button();
blurButton = new Button();
scaleButton = new Button();
</code>```

Title: Why is the Button Null?

Body:
I'm receiving a NullPointerException. It says that the button is null which makes no sense. The full error code and my code is listed below.

package com.example.effectslikerotation;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Scene;

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    private Button blurButton, rotateButton, scaleButton;
    private Rotate rotate;
    private double angle;
    Object buttonClicked;
    Object buttonText;

    @Override
    public void start(Stage stage) throws IOException {
        Button rotateButton = new Button();
        Button blurButton = new Button();
        Button scaleButton = new Button();

        angle = 0.0;

        rotateButton.setOnAction(this);
        blurButton.setOnAction(this);
        scaleButton.setOnAction(this);

        rotateButton.setText("Rotate");
        blurButton.setText("Blur");
        scaleButton.setText("Scale");

        Label reflect = new Label("I'm a reflection of you.");

        FlowPane FProot = new FlowPane();
        Scene scene = new Scene(FProot, 600, 500);
        FProot.setAlignment(Pos.CENTER);
        FProot.getChildren().addAll(rotateButton, blurButton, scaleButton, reflect);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();

        //rotateButton.getTransforms().add(rotate);

    }

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void handle(ActionEvent e) {
        Object buttonClicked = e.getSource();

        if (rotateButton.isPressed()) { //
            System.out.println("Rotate button clicked"); //not sure why this doesnt print out.

        }
        if (buttonClicked.equals(blurButton)) { //
            System.out.println("Rotate button clicked"); //not sure why this doesnt print out.
        }
        if (buttonClicked.equals(scaleButton)) { //
            System.out.println("Rotate button clicked"); //not sure why this doesnt print out.
        }

}}

Application Thread" java.lang.NullPointerException: Cannot invoke "javafx.scene.control.Button.isPressed()" because "this.rotateButton" is null
at com.example.effectslikerotation/com.example.effectslikerotation.HelloApplication.handle(HelloApplication.java:73)
at com.example.effectslikerotation/com.example.effectslikerotation.HelloApplication.handle(HelloApplication.java:20)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8792)
at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3897)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1878)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2623)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:557)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:943)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
at java.base/java.lang.Thread.run(Thread.java:833)

Body:
You define these fields:

private Button blurButton, rotateButton, scaleButton;

but never assign anything to them.

Button rotateButton = new Button();
Button blurButton = new Button();
Button scaleButton = new Button();

By adding Button in front of these assignments it means you're creating new variables.

To fix this just remove Button:

rotateButton = new Button();
blurButton = new Button();
scaleButton = new Button();


问:
Getting NULL / empty data when running fetch(URL) with useEffect() in React client
I have built a NodeJS server that reliably supports an API

```<code>http://localhost:5000/record/gopa
</code>```

that returns a well formed JSON string

```<code>{"pid":
  {
   "ck":"F1965121910:265.522.5788.37",
   "name":"gopa",
   "cID":"MVOE9BW5ZZOC"
   }
}
</code>```

I have built a ReactJS client to received this JSON output and convert it into a string for subsequent processing as follows:

```<code>import React, { useEffect, useState } from "react";
import { useParams } from "react-router";

export default function Detail52() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');

 useEffect(() => {
   async function getData() {
   //const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
   const response = await fetch(`http://localhost:5000/record/gopa}`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     window.alert(JSON.stringify(dbdata));
     setData(dbdata);
     //setData('fake data')
   }
   getData();
   return;
 },[dbdata]);

 return (
   <div>
     <h3>Detail 52</h3>
       <p>{dbdata}</p>
       <p>{JSON.stringify(dbdata)}</p>
   </div>
 );

}
</code>```

When this executes, I get NULL value in dbdata and a empty string when I convert the JSON output into a string.

I was initially under the impression that the ${params.id.toString()} was not being passed correctly, so for the time being I have hardcoded the parameter and the effect is the same.

I have tested this by placing an alert after dbdata is fetched and it shows null

To complete the testing, I have also placed a 'fake data' using the setData() functions and this fake data is correctly reflected in the final output.

So, I think, the problem is not with the setData() but with an empty string being returned.

I have been struggling with this for quite some time and I think that I have localised the problem. Would be very grateful if someone can help me sort this out.

答:
First I think you inserted the wrong URL since you have a bracket at the end of it:

```<code>const response = await fetch(`http://localhost:5000/record/gopa}`);
//Instead of
const response = await fetch(`http://localhost:5000/record/gopa`);
</code>```

I saw that you are awaiting twice your object:

The first after the fetch:

```<code>const response = await fetch(`http://localhost:5000/record/gopa}`);
</code>```

The second (that seems unnecessary):

```<code>const dbdata = await response.json();
// How it should be:
const dbdata = response.json();
</code>```

Can you please log us the content of the response, to understand if this is the issue or if the problem comes from another part of your code? I will edit the post if that's the case

Body:
I have built a NodeJS server that reliably supports an API

http://localhost:5000/record/gopa

that returns a well formed JSON string

{"pid":
  {
   "ck":"F1965121910:265.522.5788.37",
   "name":"gopa",
   "cID":"MVOE9BW5ZZOC"
   }
}

I have built a ReactJS client to received this JSON output and convert it into a string for subsequent processing as follows:

import React, { useEffect, useState } from "react";
import { useParams } from "react-router";

export default function Detail52() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');

 useEffect(() => {
   async function getData() {
   //const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
   const response = await fetch(`http://localhost:5000/record/gopa}`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     window.alert(JSON.stringify(dbdata));
     setData(dbdata);
     //setData('fake data')
   }
   getData();
   return;
 },[dbdata]);

 return (

Detail 52

{dbdata}

{JSON.stringify(dbdata)}

 );

}

When this executes, I get NULL value in dbdata and a empty string when I convert the JSON output into a string.

I was initially under the impression that the ${params.id.toString()} was not being passed correctly, so for the time being I have hardcoded the parameter and the effect is the same.

I have tested this by placing an alert after dbdata is fetched and it shows null

To complete the testing, I have also placed a 'fake data' using the setData() functions and this fake data is correctly reflected in the final output.

So, I think, the problem is not with the setData() but with an empty string being returned.

I have been struggling with this for quite some time and I think that I have localised the problem. Would be very grateful if someone can help me sort this out.

Body:
First I think you inserted the wrong URL since you have a bracket at the end of it:

const response = await fetch(`http://localhost:5000/record/gopa}`);
//Instead of
const response = await fetch(`http://localhost:5000/record/gopa`);

I saw that you are awaiting twice your object:

The first after the fetch:

const response = await fetch(`http://localhost:5000/record/gopa}`);

The second (that seems unnecessary):

const dbdata = await response.json();
// How it should be:
const dbdata = response.json();

Can you please log us the content of the response, to understand if this is the issue or if the problem comes from another part of your code? I will edit the post if that's the case


问:
When is postgres database created?
Let's say I'm running pg_ctl init or initdb to initialise cluster.
When is the exact moment the default database inside this cluster is created?

In the initdb procedure?

After I run the server?

After the first connection to the database?

答:
Quote from the manual

Creating a database cluster consists of creating the directories in which the database data will live, generating the shared catalog tables (tables that belong to the whole cluster rather than to any particular database), and creating the template1 and postgres databases.

(emphasis mine)

So it's created when you run initdb

Title: When is postgres database created?


问:
Build input file cannot be found on Xcode13.1
Question for Building

I'm using m1 mac machine.
I trying to run my app no my device.
But somehow an error message appeared saying, "Build input files cannot be found".

Detailed:

```<code>CopySwiftLibs /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app (in target 'finwork' from project 'finwork')
    cd /Users/evanlu/Desktop/rebackup/finwork
    export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export DEVELOPER_DIR\=/Applications/Xcode.app/Contents/Developer
    export SDKROOT\=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.0.sdk
    builtin-swiftStdLibTool --copy --verbose --sign 22FE53F897AFEB6A2955A6C7BCB17C806EDD894A --scan-executable /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/finwork --scan-folder /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/Frameworks --scan-folder /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/PlugIns --scan-folder /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/Pods_finwork.framework --platform iphoneos --toolchain /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain --destination /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/Frameworks --strip-bitcode --strip-bitcode-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/bitcode_strip --emit-dependency-info /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Intermediates.noindex/finwork.build/Debug-iphoneos/finwork.build/SwiftStdLibToolInputDependencies.dep --filter-for-swift-os

error: Build input file cannot be found: '/Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/finwork' (in target 'finwork' from project 'finwork')
</code>```

And when I using Simulator. It can’t find my pod plugin.

```<code>/Users/evanlu/Desktop/rebackup/finwork/finwork/Database/FirestoreDatabase.swift:9:8: No such module 'FirebaseCore'

</code>```

These are what I have been tried.

1.Clear build folder.

2.Re-install and Update podfile.

3.Check Compile Source make sure there’s not no red or grayed out files.

4.Check I didn’t using legacy build system.

5.Tracking the path

(/Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/finwork).

It say "finwork.app is damaged and can’t be opened" and I check brew inside, there's no finwork file inside.

6.I try to changing Build Settings to EXCLUDED_ARCHS = arm64 ,ONLY_ACTIVE_ARCH:YES It still unworkable.

Here’s my podfile:

```<code># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'finwork' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!
  #use_modular_headers!
  #use_frameworks! :linkage => :static
    pod 'GoogleMaps'

    pod 'SwiftyStarRatingView'

    pod 'Firebase/Analytics'
    pod 'Firebase/Auth'
    pod 'Firebase/Storage'
    pod 'FirebaseUI/Storage'
    #pod 'FirebaseUI'
    #pod 'FirebaseUI', '>= 10.0.2'
    #pod 'GoogleSignIn'
    pod 'Firebase/Database'
    pod 'Firebase/Firestore'
    pod 'FirebaseFirestoreSwift'

    #pod 'BoringSSL-GRPC', '= 0.0.3', :modular_headers => false
    #pod 'gRPC-Core', '= 1.21.0', :modular_headers => false
    pod 'SideMenu'

    #pod 'FBSDKLoginKit'

    post_install do |installer|
    installer.pods_project.build_configurations.each do |config|
        config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
    end
    end
end
</code>```

Complement:

The Simulator was work in the beginning but device not.

When I running on my iPhone it show me Command PhaseScriptExecution failed with a nonzero exit code.

So I changing my build setting including set EXCLUDED_ARCHS = arm64
、Deleted VALID_ARCHS、
tried to set up ONLY_ACTIVE_ARCH to yes and no (neither of them working).
Then it return me No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=arm64, VALID_ARCHS=arm64 arm64e i386 x86_64, EXCLUDED_ARCHS=( arm64 )).
After this I keep my build setting ONLY_ACTIVE_ARCH = NO , EXCLUDED_ARCHS = arm64 and Clear build folder + Re-install podfile.
It started say Library not loaded: @rpath/FBLPromises.framework/FBLPromises.
To solve this I change the developer account.
And then It trun me into this position.

Build settings :

Any suggest will be helpful, Or on less tell me how did I massacred my Project.
Thank you for taking your time！

Update :
I just Clear build folder a few times and running by Simulator now it also showing me Build input file cannot be found.
But Weirdly, I didn’t do anything to solve No such module 'FirebaseCore'

答:
Do you want to try the same method as the image below?

Build Settings -> Architectures -> Excluded Architectures, arm64.

I don't know if it'll help, but I hope it'll be solved.

Body:
Question for Building

I'm using m1 mac machine.
I trying to run my app no my device.
But somehow an error message appeared saying, "Build input files cannot be found".

Detailed:

CopySwiftLibs /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app (in target 'finwork' from project 'finwork')
    cd /Users/evanlu/Desktop/rebackup/finwork
    export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export DEVELOPER_DIR\=/Applications/Xcode.app/Contents/Developer
    export SDKROOT\=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.0.sdk
    builtin-swiftStdLibTool --copy --verbose --sign 22FE53F897AFEB6A2955A6C7BCB17C806EDD894A --scan-executable /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/finwork --scan-folder /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/Frameworks --scan-folder /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/PlugIns --scan-folder /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/Pods_finwork.framework --platform iphoneos --toolchain /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain --destination /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/Frameworks --strip-bitcode --strip-bitcode-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/bitcode_strip --emit-dependency-info /Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Intermediates.noindex/finwork.build/Debug-iphoneos/finwork.build/SwiftStdLibToolInputDependencies.dep --filter-for-swift-os

error: Build input file cannot be found: '/Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/finwork' (in target 'finwork' from project 'finwork')

And when I using Simulator. It can’t find my pod plugin.

/Users/evanlu/Desktop/rebackup/finwork/finwork/Database/FirestoreDatabase.swift:9:8: No such module 'FirebaseCore'

These are what I have been tried.

1.Clear build folder.

2.Re-install and Update podfile.

3.Check Compile Source make sure there’s not no red or grayed out files.

4.Check I didn’t using legacy build system.

5.Tracking the path

(/Users/evanlu/Library/Developer/Xcode/DerivedData/finwork-dbwrwhkrmlwsysdijoivlfbkytnc/Build/Products/Debug-iphoneos/finwork.app/finwork).

It say "finwork.app is damaged and can’t be opened" and I check brew inside, there's no finwork file inside.

6.I try to changing Build Settings to EXCLUDED_ARCHS = arm64 ,ONLY_ACTIVE_ARCH:YES It still unworkable.

Here’s my podfile:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'finwork' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!
  #use_modular_headers!
  #use_frameworks! :linkage => :static
    pod 'GoogleMaps'

    pod 'SwiftyStarRatingView'

    pod 'Firebase/Analytics'
    pod 'Firebase/Auth'
    pod 'Firebase/Storage'
    pod 'FirebaseUI/Storage'
    #pod 'FirebaseUI'
    #pod 'FirebaseUI', '>= 10.0.2'
    #pod 'GoogleSignIn'
    pod 'Firebase/Database'
    pod 'Firebase/Firestore'
    pod 'FirebaseFirestoreSwift'

    #pod 'BoringSSL-GRPC', '= 0.0.3', :modular_headers => false
    #pod 'gRPC-Core', '= 1.21.0', :modular_headers => false
    pod 'SideMenu'

    #pod 'FBSDKLoginKit'

    post_install do |installer|
    installer.pods_project.build_configurations.each do |config|
        config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
    end
    end
end

Complement:

The Simulator was work in the beginning but device not.

When I running on my iPhone it show me Command PhaseScriptExecution failed with a nonzero exit code.

So I changing my build setting including set EXCLUDED_ARCHS = arm64
、Deleted VALID_ARCHS、
tried to set up ONLY_ACTIVE_ARCH to yes and no (neither of them working).
Then it return me No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=arm64, VALID_ARCHS=arm64 arm64e i386 x86_64, EXCLUDED_ARCHS=( arm64 )).
After this I keep my build setting ONLY_ACTIVE_ARCH = NO , EXCLUDED_ARCHS = arm64 and Clear build folder + Re-install podfile.
It started say Library not loaded: @rpath/FBLPromises.framework/FBLPromises.
To solve this I change the developer account.
And then It trun me into this position.

Build settings :

Any suggest will be helpful, Or on less tell me how did I massacred my Project.
Thank you for taking your time！

Update :
I just Clear build folder a few times and running by Simulator now it also showing me Build input file cannot be found.
But Weirdly, I didn’t do anything to solve No such module 'FirebaseCore'


问:
Hidden Features of C#?
This came to my mind after I learned the following from this question:

```<code>where T : struct
</code>```

We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.

Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Here are the revealed features so far:

Keywords

yield by Michael Stum

var by Michael Stum

using() statement by kokos

readonly by kokos

as by Mike Stone

as / is by Ed Swangren

as / is (improved) by Rocketpants

default by deathofrats

global:: by pzycoman

using() blocks by AlexCuse

volatile by Jakub Šturc

extern alias by Jakub Šturc

Attributes

DefaultValueAttribute by Michael Stum

ObsoleteAttribute by DannySmurf

DebuggerDisplayAttribute by Stu

DebuggerBrowsable and DebuggerStepThrough by bdukes

ThreadStaticAttribute by marxidad

FlagsAttribute by Martin Clarke

ConditionalAttribute by AndrewBurns

Syntax

?? (coalesce nulls) operator by kokos

Number flaggings by Nick Berardi

where T:new by Lars Mæhlum

Implicit generics by Keith

One-parameter lambdas by Keith

Auto properties by Keith

Namespace aliases by Keith

Verbatim string literals with @ by Patrick

enum values by lfoust

@variablenames by marxidad

event operators by marxidad

Format string brackets by Portman

Property accessor accessibility modifiers by xanadont

Conditional (ternary) operator (?:) by JasonS

checked and unchecked operators by Binoj Antony

implicit and explicit operators by Flory

Language Features

Nullable types by Brad Barker

Anonymous types by Keith

__makeref __reftype __refvalue by Judah Himango

Object initializers by lomaxx

Format strings by David in Dakota

Extension Methods by marxidad

partial methods by Jon Erickson

Preprocessor directives by John Asbeck

DEBUG pre-processor directive by Robert Durgin

Operator overloading by SefBkn

Type inferrence by chakrit

Boolean operators taken to next level by Rob Gough

Pass value-type variable as interface without boxing by Roman Boiko

Programmatically determine declared variable type by Roman Boiko

Static Constructors by Chris

Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid

__arglist by Zac Bowling

Visual Studio Features

Select block of text in editor by Himadri

Snippets by DannySmurf

Framework

TransactionScope by KiwiBastard

DependantTransaction by KiwiBastard

Nullable<T> by IainMH

Mutex by Diago

System.IO.Path by ageektrapped

WeakReference by Juan Manuel

Methods and Properties

String.IsNullOrEmpty() method by KiwiBastard

List.ForEach() method by KiwiBastard

BeginInvoke(), EndInvoke() methods by Will Dean

Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo

GetValueOrDefault method by John Sheehan

Tips & Tricks

Nice method for event handlers by Andreas H.R. Nilsson

Uppercase comparisons by John

Access anonymous types without reflection by dp

A quick way to lazily instantiate collection properties by Will

JavaScript-like anonymous inline-functions by roosteronacid

Other

netmodules by kokos

LINQBridge by Duncan Smart

Parallel Extensions by Joel Coehoorn

答:
I quite enjoy implicit generic parameters on functions. For example, if you have:

```<code>public void DoStuff<T>(T value);
</code>```

Instead of calling it like this:

```<code>DoStuff<int>(5);
</code>```

You can:

```<code>DoStuff(5);
</code>```

And it'll work out the generic type from the parameter's type.

This doesn't work if you're calling the method through reflection.

I remember having some weird problems on Mono.

OwnerDisplayName: buyutec

Title: Hidden Features of C#?

Body:
This came to my mind after I learned the following from this question:

where T : struct

We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.

Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Here are the revealed features so far:

Keywords

yield by Michael Stum

var by Michael Stum

using() statement by kokos

readonly by kokos

as by Mike Stone

as / is by Ed Swangren

as / is (improved) by Rocketpants

default by deathofrats

global:: by pzycoman

using() blocks by AlexCuse

volatile by Jakub Šturc

extern alias by Jakub Šturc

Attributes

DefaultValueAttribute by Michael Stum

ObsoleteAttribute by DannySmurf

DebuggerDisplayAttribute by Stu

DebuggerBrowsable and DebuggerStepThrough by bdukes

ThreadStaticAttribute by marxidad

FlagsAttribute by Martin Clarke

ConditionalAttribute by AndrewBurns

Syntax

?? (coalesce nulls) operator by kokos

Number flaggings by Nick Berardi

where T:new by Lars Mæhlum

Implicit generics by Keith

One-parameter lambdas by Keith

Auto properties by Keith

Namespace aliases by Keith

Verbatim string literals with @ by Patrick

enum values by lfoust

@variablenames by marxidad

event operators by marxidad

Format string brackets by Portman

Property accessor accessibility modifiers by xanadont

Conditional (ternary) operator (?:) by JasonS

checked and unchecked operators by Binoj Antony

implicit and explicit operators by Flory

Language Features

Nullable types by Brad Barker

Anonymous types by Keith

__makeref __reftype __refvalue by Judah Himango

Object initializers by lomaxx

Format strings by David in Dakota

Extension Methods by marxidad

partial methods by Jon Erickson

Preprocessor directives by John Asbeck

DEBUG pre-processor directive by Robert Durgin

Operator overloading by SefBkn

Type inferrence by chakrit

Boolean operators taken to next level by Rob Gough

Pass value-type variable as interface without boxing by Roman Boiko

Programmatically determine declared variable type by Roman Boiko

Static Constructors by Chris

Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid

__arglist by Zac Bowling

Visual Studio Features

Select block of text in editor by Himadri

Snippets by DannySmurf

Framework

TransactionScope by KiwiBastard

DependantTransaction by KiwiBastard

Nullable<T> by IainMH

Mutex by Diago

System.IO.Path by ageektrapped

WeakReference by Juan Manuel

Methods and Properties

String.IsNullOrEmpty() method by KiwiBastard

List.ForEach() method by KiwiBastard

BeginInvoke(), EndInvoke() methods by Will Dean

Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo

GetValueOrDefault method by John Sheehan

Tips & Tricks

Nice method for event handlers by Andreas H.R. Nilsson

Uppercase comparisons by John

Access anonymous types without reflection by dp

A quick way to lazily instantiate collection properties by Will

JavaScript-like anonymous inline-functions by roosteronacid

Other

netmodules by kokos

LINQBridge by Duncan Smart

Parallel Extensions by Joel Coehoorn

LastEditorDisplayName: Binoj Antony

Body:
I quite enjoy implicit generic parameters on functions. For example, if you have:

public void DoStuff<T>(T value);

Instead of calling it like this:

DoStuff<int>(5);

You can:

DoStuff(5);

And it'll work out the generic type from the parameter's type.

This doesn't work if you're calling the method through reflection.

I remember having some weird problems on Mono.

OwnerDisplayName: pacaci

ContentLicense: CC BY-SA 2.5


问:
Quarkus discovering of JAXRS-Endpoints
I'am currently trying to understand the discovering of JAXRS-Endpoints in Quarkus. My assumption is that they are automatically discovered and there is no need to register them. In addition I tried to import Endpoints from an other module/jar File. It is working to out of the box.

But than I tried to understand the order of discovering endpoints.

I tried to overwrite a jar file provided endpoint in my application, but it is not working. Therfore in my opinion there is a potential security problem, if any third party module can overwrite my endpoints. Has anyone the same problems and can provide me informations how to think about this problem? (My only solution is to write an own extension which removes all endpoints an add only the ones I want to have, but I think this is against the idea)

Thanks in advance!

答:
Duplicate endpoint detection was added to RESTEasy Reactive in https://github.com/quarkusio/quarkus/pull/15037.

This means that from version 2.7.0.CR1 and on, Quarkus will fail the build if duplicate JAX-RS endpoints are defined (assuming you are using quarkus-resteasy-reactive).

Title: Quarkus discovering of JAXRS-Endpoints


问:
'User' object has no attribute 'staffUser'
I customized the User Model Using Django One To One Field

My models.py

```<code>class StaffUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.ForeignKey(Dept, on_delete=models.RESTRICT)

    def __str__(self):
        return self.user.username
</code>```

When uploading a form, i want to get the department of the user

'My Views.py'

```<code>   def FileUploadForm(request, pk):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=False)
            u = User.objects.get(username=request.user)
            form.instance.username = u
            folder = Folder.objects.get(id=pk)
            department = u.staffUser.department
            form.save()
            messages.success(request, f'File Successfully uploaded to {folder} in {department}!')
            return redirect('home')
    else:
        form = UploadFileForm()

    context = {'pk':pk, 'form':form}
    return render(request, "pages/fileup_form.html", context)
</code>```

But it gives error
AttributeError at /file/new/1
'User' object has no attribute 'staffUser'

Please guys i need help

答:
Add related_name on your user field in StaffUser model

```<code>class StaffUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=staff_user)
    department = models.ForeignKey(Dept, on_delete=models.RESTRICT)

    def __str__(self):
        return self.user.username
</code>```

Now you will be able to access StaffUser by staff_user on User object

Body:
I customized the User Model Using Django One To One Field

My models.py

class StaffUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.ForeignKey(Dept, on_delete=models.RESTRICT)

    def __str__(self):
        return self.user.username

When uploading a form, i want to get the department of the user

'My Views.py'

   def FileUploadForm(request, pk):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=False)
            u = User.objects.get(username=request.user)
            form.instance.username = u
            folder = Folder.objects.get(id=pk)
            department = u.staffUser.department
            form.save()
            messages.success(request, f'File Successfully uploaded to {folder} in {department}!')
            return redirect('home')
    else:
        form = UploadFileForm()

    context = {'pk':pk, 'form':form}
    return render(request, "pages/fileup_form.html", context)

But it gives error
AttributeError at /file/new/1
'User' object has no attribute 'staffUser'

Please guys i need help

Body:
Add related_name on your user field in StaffUser model

class StaffUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=staff_user)
    department = models.ForeignKey(Dept, on_delete=models.RESTRICT)

    def __str__(self):
        return self.user.username

Now you will be able to access StaffUser by staff_user on User object


问:
Unique_ptr with custom deleter
Here is a MRE of my code:

```<code>#include <memory>

struct Deleter
{
    void operator() (A* a) {}
};

class A
{
    A(int a) {}
};

int main()
{
    std::unique_ptr<A, Deleter> unique = std::make_unique<A, Deleter>(5);
}
</code>```

I get this error:

```<code>error C2664: 'std::unique_ptr<A,std::default_delete<A>> std::make_unique<A,Deleter,0>(Deleter &&)': cannot convert argument 1 from 'int' to 'Deleter &&'
</code>```

How should I call A constructor with std::make_unique when I use a custom deleter like that?

答:
You cannot use std::make_unique with a custom deleter. You’ll need to use the regular constructor instead:

```<code>auto unique = std::unique_ptr<A, Deleter>(new A(5), Deleter());
</code>```

Of course this will still require you to fix the rest of your code: make the constructor of A public, and declare A before Deleter. And you’d need to replace new A(…) by the proper construction that matches the custom Deleter.

And it’s worth noting that this might leak memory if the Deleter constructor throws, so you need to make sure that it doesn’t do that.

Title: Unique_ptr with custom deleter

Body:
Here is a MRE of my code:

#include <memory>

struct Deleter
{
    void operator() (A* a) {}
};

class A
{
    A(int a) {}
};

int main()
{
    std::unique_ptr unique = std::make_unique(5);
}

I get this error:

error C2664: 'std::unique_ptr<A,std::default_delete> std::make_unique(Deleter &&)': cannot convert argument 1 from 'int' to 'Deleter &&'

How should I call A constructor with std::make_unique when I use a custom deleter like that?

Body:
You cannot use std::make_unique with a custom deleter. You’ll need to use the regular constructor instead:

auto unique = std::unique_ptr<A, Deleter>(new A(5), Deleter());

Of course this will still require you to fix the rest of your code: make the constructor of A public, and declare A before Deleter. And you’d need to replace new A(…) by the proper construction that matches the custom Deleter.

And it’s worth noting that this might leak memory if the Deleter constructor throws, so you need to make sure that it doesn’t do that.


问:
How to fire keyboard events in Javascript using onClick?
I have an existing function that gets called when KeyD is pressed.

I want to trigger an KeyD event (without actually pressing keyD on keyboard) as soon as I click on some button.

Is it possible in Javascript?

答:
yes, it is possible

button.addEventListener('click', function(){
    let keydown = new KeyboardEvent('keydown', {key: 'a', code: 'KeyA', keyCode: 65});
    element.dispatchEvent(keydown); // element is the one you want to trigger the event
});
```

the construction of KeyboardEvent please read https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent

Body:
yes, it is possible

button.addEventListener('click', function(){
    let keydown = new KeyboardEvent('keydown', {key: 'a', code: 'KeyA', keyCode: 65});
    element.dispatchEvent(keydown); // element is the one you want to trigger the event
});

the construction of KeyboardEvent please read https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent


问:
The 4.1.2 R version leads to some issues with ggplot
I have a list of df Measurements_l for which I used to work with lapply and a function containing ggplot to plot each list :

```<code>Measurements_l <- split(Measurements,list(Measurements$Sample.type,Measurements$Site), drop=TRUE)
      lapply(names(Measurements_l), function(i){
        ggplot(Measurements_l[[i]], aes(Date, Activity, group = Nuclides, col = as.factor(Nuclides))) +
          geom_line() +
          geom_point() +
          facet_grid(rows = vars(Locality)) +
          xlab("Date") +
          ylab(paste("Concentration in", Measurements_l[[ i ]]$Measuring.Unit[ 1 ])) +
          theme(legend.title=element_blank(),
          guides(col=guide_legend(ncol=1)) +
          ggsave(paste(i, ".png", sep = ""),  dpi = 600, width = 30, height = 22, units = "cm")
      })
      dev.off()
</code>```

With the latest R version (4.1.2), I got some issues :

```<code>Error in `ggplot_add()`:
! Can't add `ggsave(paste(i, ".png", sep = ""), dpi = 600, width = 30, height = 20, ` to a ggplot object.
* Can't add `    units = "cm")` to a ggplot object.
Run `rlang::last_error()` to see where the error occurred.
Called from: signal_abort(cnd, .file)
Browse[1]> dev.off()
Error during wrapup: cannot shut down device 1 (the null device)
Error: no more error handlers available (recursive errors?); invoking 'abort' restart
</code>```

ggsave  being included in my ggplot  function, I do not know how to tackle this issue. Any idea ? I do not want to rewrite all my functions in all my scripts because of this newer version.

Moreover, why is it no longer possible to use "cm" units to a ggplot object ?

REPRODUCIBLE EXAMPLE (leading to 4 graphs)

```<code>Measurements

Locality Sample Nuclides    Activity    Measuring Unit  Date
PARIS    MILK   I-131          1            BQ/L        2010
PARIS    MILK   I-131          2            BQ/L        2020
PARIS    WATER  I-131          3            BQ/L        2010
PARIS    WATER  I-131          4            BQ/L        2020
BRUSSELS MILK   I-131          5            BQ/L        2010
BRUSSELS MILK   I-131          6            BQ/L        2020
BRUSSELS WATER  I-131          7            BQ/L        2010
BRUSSELS WATER  I-131          8            BQ/L        2020

Measurements_l <- split(Measurements,list(Measurements$Sample,Measurements$Locality), drop=TRUE)
      lapply(names(Measurements_l), function(i){
        ggplot(Measurements_l[[i]], aes(Date, Activity, group = Nuclides, col = as.factor(Nuclides))) +
          geom_line() +
          geom_point() +
          facet_grid(rows = vars(Locality)) +
          ggsave(paste(i, ".png", sep = ""),  dpi = 600, width = 30, height = 22, units = "cm")
      })
      dev.off()
</code>```
```<code></code>```

答:
The following, which I had suggested in the comments, works for me:

library(ggplot2)

Measurements <- data.frame(
  Locality = rep(c("PARIS", "BRUSSELS"), each = 4),
  Sample   = rep(rep(c("MILK", "WATER"), each = 2), 2),
  Nuclides = "I-131",
  Activity = 1:8,
  Measuring_Unit = "BQ/L",
  Date     = rep(c(2010, 2020), 4)
)

Measurements_l <- split(Measurements,list(Measurements$Sample,Measurements$Locality), drop=TRUE)

lapply(names(Measurements_l), function(i){
  g <- ggplot(Measurements_l[[i]],
              aes(Date, Activity, group = Nuclides, col = as.factor(Nuclides))) +
    geom_line() +
    geom_point() +
    facet_grid(rows = vars(Locality))

  ggsave(paste(i, ".png", sep = ""), plot = g,
         dpi = 600, width = 30, height = 22, units = "cm")
})
```

It yields 4 plots with the names 'WATER.BRUSSELS.png', 'WATER.PARIS.png', 'MILK.BRUSSELS.png' and 'MILK.PARIS.png' in the working directory.

Body:
I have a list of df Measurements_l for which I used to work with lapply and a function containing ggplot to plot each list :

Measurements_l <- split(Measurements,list(Measurements$Sample.type,Measurements$Site), drop=TRUE)
      lapply(names(Measurements_l), function(i){
        ggplot(Measurements_l[[i]], aes(Date, Activity, group = Nuclides, col = as.factor(Nuclides))) +
          geom_line() +
          geom_point() +
          facet_grid(rows = vars(Locality)) +
          xlab("Date") +
          ylab(paste("Concentration in", Measurements_l[[ i ]]$Measuring.Unit[ 1 ])) +
          theme(legend.title=element_blank(),
          guides(col=guide_legend(ncol=1)) +
          ggsave(paste(i, ".png", sep = ""),  dpi = 600, width = 30, height = 22, units = "cm")
      })
      dev.off()

With the latest R version (4.1.2), I got some issues :

Error in `ggplot_add()`:
! Can't add `ggsave(paste(i, ".png", sep = ""), dpi = 600, width = 30, height = 20, ` to a ggplot object.
* Can't add `    units = "cm")` to a ggplot object.
Run `rlang::last_error()` to see where the error occurred.
Called from: signal_abort(cnd, .file)
Browse[1]> dev.off()
Error during wrapup: cannot shut down device 1 (the null device)
Error: no more error handlers available (recursive errors?); invoking 'abort' restart

ggsave  being included in my ggplot  function, I do not know how to tackle this issue. Any idea ? I do not want to rewrite all my functions in all my scripts because of this newer version.

Moreover, why is it no longer possible to use "cm" units to a ggplot object ?

REPRODUCIBLE EXAMPLE (leading to 4 graphs)

Measurements

Locality Sample Nuclides    Activity    Measuring Unit  Date
PARIS    MILK   I-131          1            BQ/L        2010
PARIS    MILK   I-131          2            BQ/L        2020
PARIS    WATER  I-131          3            BQ/L        2010
PARIS    WATER  I-131          4            BQ/L        2020
BRUSSELS MILK   I-131          5            BQ/L        2010
BRUSSELS MILK   I-131          6            BQ/L        2020
BRUSSELS WATER  I-131          7            BQ/L        2010
BRUSSELS WATER  I-131          8            BQ/L        2020

Measurements_l <- split(Measurements,list(Measurements$Sample,Measurements$Locality), drop=TRUE)
      lapply(names(Measurements_l), function(i){
        ggplot(Measurements_l[[i]], aes(Date, Activity, group = Nuclides, col = as.factor(Nuclides))) +
          geom_line() +
          geom_point() +
          facet_grid(rows = vars(Locality)) +
          ggsave(paste(i, ".png", sep = ""),  dpi = 600, width = 30, height = 22, units = "cm")
      })
      dev.off()

Body:
The following, which I had suggested in the comments, works for me:

library(ggplot2)

Measurements <- data.frame(
  Locality = rep(c("PARIS", "BRUSSELS"), each = 4),
  Sample   = rep(rep(c("MILK", "WATER"), each = 2), 2),
  Nuclides = "I-131",
  Activity = 1:8,
  Measuring_Unit = "BQ/L",
  Date     = rep(c(2010, 2020), 4)
)

Measurements_l <- split(Measurements,list(Measurements$Sample,Measurements$Locality), drop=TRUE)

lapply(names(Measurements_l), function(i){
  g <- ggplot(Measurements_l[[i]],
              aes(Date, Activity, group = Nuclides, col = as.factor(Nuclides))) +
    geom_line() +
    geom_point() +
    facet_grid(rows = vars(Locality))

  ggsave(paste(i, ".png", sep = ""), plot = g,
         dpi = 600, width = 30, height = 22, units = "cm")
})

It yields 4 plots with the names 'WATER.BRUSSELS.png', 'WATER.PARIS.png', 'MILK.BRUSSELS.png' and 'MILK.PARIS.png' in the working directory.


问:
url path with image variable in image source uri React Native
I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

```<code><FlatList
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}
renderItem={({item}) => {
   return (

    <Image
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    />

   )
}}
/>
</code>```

Thanks for the help

答:
Complete test code

```<code>import * as React from 'react';
import { Image, Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const data = [{ id: 1, user_image: 'cute-boy-standing-little-white-background-40214306.jpg' }, { id: 1, user_image: 'no image url.jpg' }]
  return (
    <View >
      <FlatList
        data={data}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => {
          let uriVar
          if (item.user_image) uriVar = `https://thumbs.dreamstime.com/b/${item.user_image}`
          return (<View>
            {uriVar != null ?
              <Image source={{ uri: uriVar }}

                style={styles.userImage}
              /> : null} </View>)
        }}
      />
      <Text style={styles.paragraph}>
        Hello
      </Text>

    </View>
  );
}

const styles = StyleSheet.create({
  userImage: {
    width: '150px',
    height: '150px',
    borderWidth: 1
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
</code>```

Body:
I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

<FlatList
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}
renderItem={({item}) => {
   return (

    <Image
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    />

   )
}}
/>

Thanks for the help

Body:
Complete test code

import * as React from 'react';
import { Image, Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const data = [{ id: 1, user_image: 'cute-boy-standing-little-white-background-40214306.jpg' }, { id: 1, user_image: 'no image url.jpg' }]
  return (
    <View >
      <FlatList
        data={data}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
        renderItem={({ item }) => {
          let uriVar
          if (item.user_image) uriVar = `https://thumbs.dreamstime.com/b/${item.user_image}`
          return (<View>
            {uriVar != null ?
              <Image source={{ uri: uriVar }}

                style={styles.userImage}
              /> : null} </View>)
        }}
      />
      <Text style={styles.paragraph}>
        Hello
      </Text>

    </View>
  );
}

const styles = StyleSheet.create({
  userImage: {
    width: '150px',
    height: '150px',
    borderWidth: 1
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});


问:
H2 Database - What does SELECTIVITY mean in ERROR messages
I'm using H2 for java unit tests.  When intentionally invoking an error by inserting a value that is too large I see 2 different responses from H2:

```<code> Value too long for column "MY_COLUMN VARCHAR(50)"
</code>```

and

```<code> Value too long for column "MY_COLUMN VARCHAR(50) SELECTIVITY 20"
</code>```

What I am trying to understand why and what "SELECTIVITY" means in this case.  Is there something I can do to get a consistent response I can assert on besides the obvious workarounds like using "StartsWith"?

答:
You might have figured it out by now, but I came across this question and others might come here, too:

SELECTIVITY is part of the column definition. From the H2 documentation:

The selectivity describes the 'uniqueness' of values in a column. A selectivity of 100 means each value appears only once, and a selectivity of 1 means the same value appears in many or most rows.

H2 can only use one index per table1, however, if multiple indices could be used for a query, then the selectivity decides which index is used.

So, in your case, it looks as if the column definition changes in between unit tests. This could be the case if, e.g, you have setup a memory database that is being recreated for each test.

1 The documentation here states one index per join, but if you don't have any joins it is just one index for the table

Body:
I'm using H2 for java unit tests.  When intentionally invoking an error by inserting a value that is too large I see 2 different responses from H2:

 Value too long for column "MY_COLUMN VARCHAR(50)"

and

 Value too long for column "MY_COLUMN VARCHAR(50) SELECTIVITY 20"

What I am trying to understand why and what "SELECTIVITY" means in this case.  Is there something I can do to get a consistent response I can assert on besides the obvious workarounds like using "StartsWith"?


问:
Redshift permission denied on Federated Table
I am trying to query a Federated Table in Redshift with a user different from the one who created the Federated Schema and Table.

Of course I get a

```<code>permission denied for relation my_federated_table
</code>```

so it is the case to grant the right permissions.

The syntax to create a Federated Schema is quite similar to the one used for External Schemas on S3 but when it comes to grant permission on the Federated Schema it is different.

So I tried

```<code>grant select on my_federated_schema.my_federated_table to my_user;
</code>```

But I get

```<code>[0A000] ERROR: Operation not supported on external tables
</code>```

Also I've been looking for documentation online around it but no luck.

Any ideas on how to grant access to a Federated Table?

答:
It was my mistake, eventually granting access to the Federated Schema as follows allows the user to run Federated Queries:</p>
```<code>grant usage on schema my_federated_schema to my_user;
</code>```

Body:
I am trying to query a Federated Table in Redshift with a user different from the one who created the Federated Schema and Table.

Of course I get a

permission denied for relation my_federated_table

so it is the case to grant the right permissions.

The syntax to create a Federated Schema is quite similar to the one used for External Schemas on S3 but when it comes to grant permission on the Federated Schema it is different.

So I tried

grant select on my_federated_schema.my_federated_table to my_user;

But I get

[0A000] ERROR: Operation not supported on external tables

Also I've been looking for documentation online around it but no luck.

Any ideas on how to grant access to a Federated Table?

Body:
It was my mistake, eventually granting access to the Federated Schema as follows allows the user to run Federated Queries:

grant usage on schema my_federated_schema to my_user;