问:
Add constraints to a UIViewController does not work
Simple question, but I don't get the answer of satisfaction.
So, I want to add some constraints to my added UIViewController via code.

Thank you so much :)

```<code>override func viewDidLoad() {

let imageLogoName = "pictureIsInAssets"
let imageLogo = UIImage(named: imageLogoName)
let imageLogoView = UIImageView(image: imageLogo!)

setImageContraints()
}

func setImageContraints(){

imageLogoView.translatesAutoresizingMaskIntoConstraints = false
imageLogoView.widthAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.heightAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageLogoView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
    }

</code>```

In the func setImageContraints:
Error: Use of unresolved identifier 'imageLogoView'

答:
You are using variable imageLogoView outside of it's visibility/life cycle scope. You should have an instance variable instead:

```<code>class SomeViewController {
    var imageLogoView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad() // <-- notice this

        let imageLogoName = "pictureIsInAssets"
        let imageLogo = UIImage(named: imageLogoName)
        self.imageLogoView = UIImageView(image: imageLogo!)

        setImageContraints()
    }
}
</code>```

or simpler:

```<code>class SomeViewController {
    let imageLogoView = UIImageView(image: UIImage(imageLiteralResourceName: "pictureIsInAssets"))

    override func viewDidLoad() {
        super.viewDidLoad() // <-- notice this

        setImageContraints()
    }
}
</code>```

And don't forget to add the image view to the view.

Body:
Simple question, but I don't get the answer of satisfaction.
So, I want to add some constraints to my added UIViewController via code.

Thank you so much :)

override func viewDidLoad() {

let imageLogoName = "pictureIsInAssets"
let imageLogo = UIImage(named: imageLogoName)
let imageLogoView = UIImageView(image: imageLogo!)

setImageContraints()
}

func setImageContraints(){

imageLogoView.translatesAutoresizingMaskIntoConstraints = false
imageLogoView.widthAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.heightAnchor.constraint(equalToConstant: 180).isActive = true
imageLogoView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageLogoView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
    }

In the func setImageContraints:
Error: Use of unresolved identifier 'imageLogoView'

Body:
You are using variable imageLogoView outside of it's visibility/life cycle scope. You should have an instance variable instead:

class SomeViewController {
    var imageLogoView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad() // <-- notice this

        let imageLogoName = "pictureIsInAssets"
        let imageLogo = UIImage(named: imageLogoName)
        self.imageLogoView = UIImageView(image: imageLogo!)

        setImageContraints()
    }
}

or simpler:

class SomeViewController {
    let imageLogoView = UIImageView(image: UIImage(imageLiteralResourceName: "pictureIsInAssets"))

    override func viewDidLoad() {
        super.viewDidLoad() // <-- notice this

        setImageContraints()
    }
}

And don't forget to add the image view to the view.


来源: stackexchange

问:
Executing unix shell commands using PHP
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

答:
You could start looking at the php manual:

System program execution

But like sdleihssirhc mentioned, watchout this IS very dangerous and you should NOT allow everything to be executed!

If you still want to do it, to get the output of the shell, just use

exec

The output of the shell will be passed in the second parameter.

E.g.:

```<code>exec('ls -la', $outputArray);
print_r($outputArray);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Executing unix shell commands using PHP

Body:
You could start looking at the php manual:

System program execution

But like sdleihssirhc mentioned, watchout this IS very dangerous and you should NOT allow everything to be executed!

If you still want to do it, to get the output of the shell, just use

exec

The output of the shell will be passed in the second parameter.

E.g.:

exec('ls -la', $outputArray);
print_r($outputArray);


问:
I have an exception in exception handling which is different?
in the last line when i was printed the message by using alias it was running fine .for example

```<code>except insufficient as i :
    print("exception is caught",i.msg)
</code>```

but when I did this

```<code>except insufficient :
    print("exception is caught",insufficient.msg)
</code>```

it was an error ..why???

```<code>```class insufficient(ZeroDivisionError):
    def __init__(self,arg):
            self.msg=arg
balance=5000
w=int(input("enter a number"))
try:
    if w>5000:
        raise insufficient("balance in the account is insufficient")
    balance=balance-w
    print("no exception and balance is=",balance)
except insufficient :
    print("exception is caught",insufficient.msg)```
</code>```

Error Log:-

```<code>Traceback (most recent call last):
  File "C:\Users\ahmod\AppData\Local\Programs\Python\Python37-32\hello.py", line 8, in <module>
    raise insufficient("balance in the account is insufficient")
insufficient: balance in the account is insufficient

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ahmod\AppData\Local\Programs\Python\Python37-32\hello.py", line 12, in <module>
    print("exception is caught",insufficient.msg)
AttributeError: type object 'insufficient' has no attribute 'msg'
</code>```

答:
When you do:

```<code>except insufficient as i:
</code>```

Whatever Exception is thrown by the code in the try block is assigned to the variable i and is made available in the except block. So if your try block throws an insufficient exception then that exception is assigned to i. Hence you can refer to i.msg.

But since msg is a object attribute in the class insufficient, insufficient.msg evaluates to nothing.

Lastly:

```<code>except insufficient:
</code>```

Does not make the thrown object available in the except block. insufficient here is merely a type identifier. So you can't access the msg attribute.

ContentLicense: CC BY-SA 4.0

Body:
in the last line when i was printed the message by using alias it was running fine .for example

except insufficient as i :
    print("exception is caught",i.msg)

but when I did this

except insufficient :
    print("exception is caught",insufficient.msg)

it was an error ..why???

```class insufficient(ZeroDivisionError):
    def __init__(self,arg):
            self.msg=arg
balance=5000
w=int(input("enter a number"))
try:
    if w>5000:
        raise insufficient("balance in the account is insufficient")
    balance=balance-w
    print("no exception and balance is=",balance)
except insufficient :
    print("exception is caught",insufficient.msg)```

Error Log:-

Traceback (most recent call last):
  File "C:\Users\ahmod\AppData\Local\Programs\Python\Python37-32\hello.py", line 8, in <module>
    raise insufficient("balance in the account is insufficient")
insufficient: balance in the account is insufficient

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ahmod\AppData\Local\Programs\Python\Python37-32\hello.py", line 12, in <module>
    print("exception is caught",insufficient.msg)
AttributeError: type object 'insufficient' has no attribute 'msg'

Body:
When you do:

except insufficient as i:

Whatever Exception is thrown by the code in the try block is assigned to the variable i and is made available in the except block. So if your try block throws an insufficient exception then that exception is assigned to i. Hence you can refer to i.msg.

But since msg is a object attribute in the class insufficient, insufficient.msg evaluates to nothing.

Lastly:

except insufficient:

Does not make the thrown object available in the except block. insufficient here is merely a type identifier. So you can't access the msg attribute.


问:
Kotlin, unresolved reference on everything in VSCode
I installed Kotlin plugins for VSCode and created Hello World file test.kt but VSCode shows errors (it could be compiled via command line)

答:
I had this issue when I had both the Kotlin Language by mathiasfrohlich and Kotlin by fwcd extensions installed. </p>

<p>Uninstalling Kotlin by fwcd resolved the problem in my case. </p>

Body:
I had this issue when I had both the Kotlin Language by mathiasfrohlich and Kotlin by fwcd extensions installed.

Uninstalling Kotlin by fwcd resolved the problem in my case.


答:
imageLogoView is no global variable.

You have to declare it like that:

```<code>class ViewController: UIViewController{
   let imageLogoView: UIImageView!

   override func viewDidLoad() {

   let imageLogoName = "pictureIsInAssets"
   let imageLogo = UIImage(named: imageLogoName)
   imageLogoView = UIImageView(image: imageLogo!)

   setImageContraints()
   }
}
</code>```

Title: Add constraints to a UIViewController does not work

Body:
imageLogoView is no global variable.

You have to declare it like that:

class ViewController: UIViewController{
   let imageLogoView: UIImageView!

   override func viewDidLoad() {

   let imageLogoName = "pictureIsInAssets"
   let imageLogo = UIImage(named: imageLogoName)
   imageLogoView = UIImageView(image: imageLogo!)

   setImageContraints()
   }
}


问:
Print out a selected number of a string problem
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

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

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }
</code>```

Ex. The user gives m=3 and a[50]=House . The program should print Hou .

答:
One problem is with a[50]=getchar(). This reads one character into the 50-th position in your buffer (which by the way is out of a's bounds). Trying using scanf instead.

symbolse(a[50],m) is also wrong. I'll let you figure out what the problem is.

One further hint is to print out the values of your input variables to ensure that you've read them correctly.

Body:
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

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

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }

Ex. The user gives m=3 and a[50]=House . The program should print Hou .


问:
Connecting to SSH using a bash script
I am trying to write a bash script to make things faster. Is it not possible to connect to the server with the code below in a bash script? I can't make it work, even though it works in the terminal.

```<code>#!/bin/bash -x
echo "Starting connection script"
sh -i /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com
</code>```

What I get when I run is a not found output for each line in the pem file,

```<code>$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: -----BEGIN: not found
$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: adsnaleAFemasdsdsdnds: not foundMadfdasfdasfnda;vonraada
...
</code>```

答:
Some debug is needed.

Please change:

ssh -i /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com

to:

```<code> #!/bin/bash -x
 echo "Starting connection script"
 ssh -vi /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com
</code>```

does it produce an idea about the reason ?

Title: Connecting to SSH using a bash script

Body:
I am trying to write a bash script to make things faster. Is it not possible to connect to the server with the code below in a bash script? I can't make it work, even though it works in the terminal.

#!/bin/bash -x
echo "Starting connection script"
sh -i /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com

What I get when I run is a not found output for each line in the pem file,

$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: -----BEGIN: not found
$ /home/EC2_KEY_HEHE.pem: 1: /home/EC2_KEY_HEHE.pem: adsnaleAFemasdsdsdnds: not foundMadfdasfdasfnda;vonraada
...

Body:
Some debug is needed.

Please change:

ssh -i /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com

to:

 #!/bin/bash -x
 echo "Starting connection script"
 ssh -vi /home/EC2_KEY_HEHE.pem ubuntu@ec2-IP.blabla.amazonaws.com

does it produce an idea about the reason ?


问:
Compress Image bytes in Xamarin.Android
How can be compress the image taken in Xamarin.Android using CameraSourcePreview, the byte in the method OnPictureTaken is too big.

答:
Here's one way to do it by converting the Bitmap to a compressed JPG file.  Also in this example is how to save the compressed JPG file to the picture gallery and make it immediately available through USB/Windows via an Android Media Scan.  Hope this helps!

```<code>    public void OnPictureTaken(byte[] data, Camera camera) {
        var bmp = BitmapFactory.DecodeByteArray(data, 0, data.Length);
        SaveBitmapAsJPEG(bmp, 75);
    }

    public void SaveBitmapAsJPEG(Bitmap pBitmap, int pnQuality = 85) {

        Java.IO.File jFolder = GetCreatePhotoAlbumStorageDir("MyPhotoAlbum");
        Java.IO.File jFile = new Java.IO.File(jFolder, $"Photo_{DateTime.Now.ToString("yyyyMMddHHmmss")}.jpg");

        // "/storage/emulated/0/Pictures/MyPhotoAlbum/Photo_20190526112410.jpg", which is the following via Windows/USB...
        // "Internal shared storage\Pictures\MyPhotoAlbum\Photo_20190526112410.jpg"

        using (var fs = new FileStream(jFile.AbsolutePath, FileMode.CreateNew)) {
            pBitmap.Compress(Bitmap.CompressFormat.Jpeg, pnQuality, fs);
        }

        SavePictureToGallery(jFile);

        Android.Util.Log.Info("MyApp", $"Picture saved using SaveBitmapAsJPEG() at {jFile.AbsolutePath}");

        // Request the media scanner to scan a file and add it to the media database (Make file visible/available through USB connection in Windows Explorer)
        var f = new Java.IO.File(jFile.AbsolutePath);
        var intent = new Intent(Intent.ActionMediaScannerScanFile);
        intent.SetData(Android.Net.Uri.FromFile(f));
        Application.Context.SendBroadcast(intent);
    }

    public Java.IO.File GetCreatePhotoAlbumStorageDir(string psAlbumName) {
        // Get the directory for the user's public pictures directory.  Will create if it doesn't exist.
        var dir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), psAlbumName);
        if (!dir.Exists())
            dir.Mkdirs();
        return dir;
    }

    private void SavePictureToGallery(Java.IO.File pFile) {
        var intent = new Intent(MediaStore.ActionImageCapture);
        intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(pFile));
        StartActivityForResult(intent, 0);
    }
</code>```

Note that you could change the format to PNG if desired by changing the "CompressFormat" to .Png, and naming the file accordingly.

Title: Compress Image bytes in Xamarin.Android

Body:
Here's one way to do it by converting the Bitmap to a compressed JPG file.  Also in this example is how to save the compressed JPG file to the picture gallery and make it immediately available through USB/Windows via an Android Media Scan.  Hope this helps!

    public void OnPictureTaken(byte[] data, Camera camera) {
        var bmp = BitmapFactory.DecodeByteArray(data, 0, data.Length);
        SaveBitmapAsJPEG(bmp, 75);
    }

    public void SaveBitmapAsJPEG(Bitmap pBitmap, int pnQuality = 85) {

        Java.IO.File jFolder = GetCreatePhotoAlbumStorageDir("MyPhotoAlbum");
        Java.IO.File jFile = new Java.IO.File(jFolder, $"Photo_{DateTime.Now.ToString("yyyyMMddHHmmss")}.jpg");

        // "/storage/emulated/0/Pictures/MyPhotoAlbum/Photo_20190526112410.jpg", which is the following via Windows/USB...
        // "Internal shared storage\Pictures\MyPhotoAlbum\Photo_20190526112410.jpg"

        using (var fs = new FileStream(jFile.AbsolutePath, FileMode.CreateNew)) {
            pBitmap.Compress(Bitmap.CompressFormat.Jpeg, pnQuality, fs);
        }

        SavePictureToGallery(jFile);

        Android.Util.Log.Info("MyApp", $"Picture saved using SaveBitmapAsJPEG() at {jFile.AbsolutePath}");

        // Request the media scanner to scan a file and add it to the media database (Make file visible/available through USB connection in Windows Explorer)
        var f = new Java.IO.File(jFile.AbsolutePath);
        var intent = new Intent(Intent.ActionMediaScannerScanFile);
        intent.SetData(Android.Net.Uri.FromFile(f));
        Application.Context.SendBroadcast(intent);
    }

    public Java.IO.File GetCreatePhotoAlbumStorageDir(string psAlbumName) {
        // Get the directory for the user's public pictures directory.  Will create if it doesn't exist.
        var dir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), psAlbumName);
        if (!dir.Exists())
            dir.Mkdirs();
        return dir;
    }

    private void SavePictureToGallery(Java.IO.File pFile) {
        var intent = new Intent(MediaStore.ActionImageCapture);
        intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(pFile));
        StartActivityForResult(intent, 0);
    }

Note that you could change the format to PNG if desired by changing the "CompressFormat" to .Png, and naming the file accordingly.


问:
Class 'App\Carbon\Carbon' not found Laravel 5
I recently run sudo composer update

Now on one of my pages, I kept getting

I did use

$now = Carbon\Carbon::now('America/New_York');

in line 792 on my Helper.php

My Helper.php located at app/Helper.php

How do I prevent this ?

This is what I have in my aliases

```<code>'aliases' => [

    'App'       => Illuminate\Support\Facades\App::class,
    'Artisan'   => Illuminate\Support\Facades\Artisan::class,
    'Auth'      => Illuminate\Support\Facades\Auth::class,
    'Blade'     => Illuminate\Support\Facades\Blade::class,
    'Bus'       => Illuminate\Support\Facades\Bus::class,
    'Cache'     => Illuminate\Support\Facades\Cache::class,
    'Config'    => Illuminate\Support\Facades\Config::class,
    'Cookie'    => Illuminate\Support\Facades\Cookie::class,
    'Crypt'     => Illuminate\Support\Facades\Crypt::class,
    'DB'        => Illuminate\Support\Facades\DB::class,
    'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
    'Event'     => Illuminate\Support\Facades\Event::class,
    'File'      => Illuminate\Support\Facades\File::class,
    'Gate'      => Illuminate\Support\Facades\Gate::class,
    'Hash'      => Illuminate\Support\Facades\Hash::class,
    'Input'     => Illuminate\Support\Facades\Input::class,
    'Inspiring' => Illuminate\Foundation\Inspiring::class,
    'Lang'      => Illuminate\Support\Facades\Lang::class,
    'Log'       => Illuminate\Support\Facades\Log::class,
    'Mail'      => Illuminate\Support\Facades\Mail::class,
    'Password'  => Illuminate\Support\Facades\Password::class,
    'Queue'     => Illuminate\Support\Facades\Queue::class,
    'Redirect'  => Illuminate\Support\Facades\Redirect::class,
    'Redis'     => Illuminate\Support\Facades\Redis::class,
    'Request'   => Illuminate\Support\Facades\Request::class,
    'Response'  => Illuminate\Support\Facades\Response::class,
    'Route'     => Illuminate\Support\Facades\Route::class,
    'Schema'    => Illuminate\Support\Facades\Schema::class,
    'Session'   => Illuminate\Support\Facades\Session::class,
    'Storage'   => Illuminate\Support\Facades\Storage::class,
    'URL'       => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,

    /*
     * Extra Alias ...
     */

    'Form'        => 'Illuminate\Html\FormFacade',
    'Html'        => 'Illuminate\Html\HtmlFacade',

    /*
     * Custom ...
     */

    'VSE'         => App\VSE::class,
    'Helper'      => App\Helper::class,
    'DateHelper'  => App\Helpers\DateHelper::class,
    'DD'          => App\Helpers\DD::class,
    'Facebook'    => SammyK\LaravelFacebookSdk\FacebookFacade::class,

],
</code>```

答:
Use Carbon:</p>

```<code>use Carbon\Carbon;
</code>```

Body:
I recently run sudo composer update

Now on one of my pages, I kept getting

I did use

$now = Carbon\Carbon::now('America/New_York');

in line 792 on my Helper.php

My Helper.php located at app/Helper.php

How do I prevent this ?

This is what I have in my aliases

'aliases' => [

    'App'       => Illuminate\Support\Facades\App::class,
    'Artisan'   => Illuminate\Support\Facades\Artisan::class,
    'Auth'      => Illuminate\Support\Facades\Auth::class,
    'Blade'     => Illuminate\Support\Facades\Blade::class,
    'Bus'       => Illuminate\Support\Facades\Bus::class,
    'Cache'     => Illuminate\Support\Facades\Cache::class,
    'Config'    => Illuminate\Support\Facades\Config::class,
    'Cookie'    => Illuminate\Support\Facades\Cookie::class,
    'Crypt'     => Illuminate\Support\Facades\Crypt::class,
    'DB'        => Illuminate\Support\Facades\DB::class,
    'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
    'Event'     => Illuminate\Support\Facades\Event::class,
    'File'      => Illuminate\Support\Facades\File::class,
    'Gate'      => Illuminate\Support\Facades\Gate::class,
    'Hash'      => Illuminate\Support\Facades\Hash::class,
    'Input'     => Illuminate\Support\Facades\Input::class,
    'Inspiring' => Illuminate\Foundation\Inspiring::class,
    'Lang'      => Illuminate\Support\Facades\Lang::class,
    'Log'       => Illuminate\Support\Facades\Log::class,
    'Mail'      => Illuminate\Support\Facades\Mail::class,
    'Password'  => Illuminate\Support\Facades\Password::class,
    'Queue'     => Illuminate\Support\Facades\Queue::class,
    'Redirect'  => Illuminate\Support\Facades\Redirect::class,
    'Redis'     => Illuminate\Support\Facades\Redis::class,
    'Request'   => Illuminate\Support\Facades\Request::class,
    'Response'  => Illuminate\Support\Facades\Response::class,
    'Route'     => Illuminate\Support\Facades\Route::class,
    'Schema'    => Illuminate\Support\Facades\Schema::class,
    'Session'   => Illuminate\Support\Facades\Session::class,
    'Storage'   => Illuminate\Support\Facades\Storage::class,
    'URL'       => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,

    /*
     * Extra Alias ...
     */

    'Form'        => 'Illuminate\Html\FormFacade',
    'Html'        => 'Illuminate\Html\HtmlFacade',

    /*
     * Custom ...
     */

    'VSE'         => App\VSE::class,
    'Helper'      => App\Helper::class,
    'DateHelper'  => App\Helpers\DateHelper::class,
    'DD'          => App\Helpers\DD::class,
    'Facebook'    => SammyK\LaravelFacebookSdk\FacebookFacade::class,

],

Body:
Use Carbon:

use Carbon\Carbon;


问:
Keras showing images from data generator
I am using image generator for keras like this:

```<code>val_generator = datagen.flow_from_directory(
        path+'/valid',
        target_size=(224, 224),
        batch_size=batch_size,)

x,y = val_generator.next()
for i in range(0,1):
    image = x[i]
    plt.imshow(image.transpose(2,1,0))
    plt.show()
</code>```

This shows wrong colors:

I have two questions.

How to fix the problem

How to get file names of the files (so that I can read it myself from something like matplotlib)

Edit : this is what my datagen looks like

```<code>datagen = ImageDataGenerator(
    rotation_range=3,
#     featurewise_std_normalization=True,
    fill_mode='nearest',
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True
)
</code>```

Edit 2 :

After following Marcin's answer :

```<code>image = 255 - image
</code>```

I get normal colors , but there are still some weird colors:

答:
```<code>from skimage import io

def imshow(image_RGB):
  io.imshow(image_RGB)
  io.show()

x,y = train_generator.next()

for i in range(0,11):
    image = x[i]
    imshow(image)
</code>```

It works for me.

Body:
I am using image generator for keras like this:

val_generator = datagen.flow_from_directory(
        path+'/valid',
        target_size=(224, 224),
        batch_size=batch_size,)

x,y = val_generator.next()
for i in range(0,1):
    image = x[i]
    plt.imshow(image.transpose(2,1,0))
    plt.show()

This shows wrong colors:

I have two questions.

How to fix the problem

How to get file names of the files (so that I can read it myself from something like matplotlib)

Edit : this is what my datagen looks like

datagen = ImageDataGenerator(
    rotation_range=3,
#     featurewise_std_normalization=True,
    fill_mode='nearest',
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True
)

Edit 2 :

After following Marcin's answer :

image = 255 - image

I get normal colors , but there are still some weird colors:

Body:
from skimage import io

def imshow(image_RGB):
  io.imshow(image_RGB)
  io.show()

x,y = train_generator.next()

for i in range(0,11):
    image = x[i]
    imshow(image)

It works for me.


问:
Creating a zoom function in D3
I have a function where that when a button is pressed (Several buttons the represent several animal types), that animal types SVG is updated with its corresponding data. I'm trying to replicate this zoom function but am having issues implementing it with my code. There are several SVGs that are used globally like this (one for each animal type):

```<code>let x = d3.scaleLinear()
  .domain([0, 1000])
  .range([ 0, width ]);

var xAxis = d3.axisBottom(x);

svgReptile.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

const yAxis = d3.scaleLinear()
  .domain([0, 220])
  .range([ height, 0])

svgReptile.append("g")
  .call(d3.axisLeft(yAxis))
</code>```

The function below is called when one of the animal buttons is pressed.

```<code> function update(animal, whatSVG, xAxis, yAxis, color) {

      const points = whatSVG
        .selectAll("circle")
        .data(data);

      points.enter()
        .append("circle")
        .attr("cx", function(d) {
          return xAxis(d.state);
        })
        .attr("cy", function(d) {
          return yAxis(d.percentage);
        })
        .merge(points)
        .attr("r", 3)
        .attr("cx", function(d) {
          return xAxis(d.decade)
        })
        .attr("cy", function(d) {
          return yAxis(d.count)
        })
        .style("fill", function (d) { return colour(d.animal) } );

      points.exit()
        .attr('r', 0)
        .remove();

    }
</code>```

Question:

How can I implement a zoom feature that expands the x-axis when zoomed (or anything similar) like the one linked above?

答:
I think you're looking for a 'brush zoom' from the last line of your question.

The following source code if from an example in a d3 graph gallery

The cross hair allows you to select an area to expand. If you follow the link there is a graph above it that is entitled "Zoom with axis" but it doesn't zoom in the way you've described, it just moves the axis, but doesn't enlarge the graph contents with it. Perhaps both will be useful!

Hope this helps

// set the dimensions and margins of the graph
var margin = {top: 10, right: 20, bottom: 20, left: 20},
    width = 500 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var Svg = d3.select("#brushZoom")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

  // Add X axis
  var x = d3.scaleLinear()
    .domain([4, 8])
    .range([ 0, width ]);
  var xAxis = Svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, 9])
    .range([ height, 0]);
  Svg.append("g")
    .call(d3.axisLeft(y));

  // Add a clipPath: everything out of this area won't be drawn.
  var clip = Svg.append("defs").append("svg:clipPath")
      .attr("id", "clip")
      .append("svg:rect")
      .attr("width", width )
      .attr("height", height )
      .attr("x", 0)
      .attr("y", 0);

  // Color scale: give me a specie name, I return a color
  var color = d3.scaleOrdinal()
    .domain(["setosa", "versicolor", "virginica" ])
    .range([ "#440154ff", "#21908dff", "#fde725ff"])

  // Add brushing
  var brush = d3.brushX()                 // Add the brush feature using the d3.brush function
      .extent( [ [0,0], [width,height] ] ) // initialise the brush area: start at 0,0 and finishes at width,height: it means I select the whole graph area
      .on("end", updateChart) // Each time the brush selection changes, trigger the 'updateChart' function

  // Create the scatter variable: where both the circles and the brush take place
  var scatter = Svg.append('g')
    .attr("clip-path", "url(#clip)")

  // Add circles
  scatter
    .selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
      .attr("cx", function (d) { return x(d.Sepal_Length); } )
      .attr("cy", function (d) { return y(d.Petal_Length); } )
      .attr("r", 8)
      .style("fill", function (d) { return color(d.Species) } )
      .style("opacity", 0.5)

  // Add the brushing
  scatter
    .append("g")
      .attr("class", "brush")
      .call(brush);

  // A function that set idleTimeOut to null
  var idleTimeout
  function idled() { idleTimeout = null; }

  // A function that update the chart for given boundaries
  function updateChart() {

    extent = d3.event.selection

    // If no selection, back to initial coordinate. Otherwise, update X axis domain
    if(!extent){
      if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a little bit
      x.domain([ 4,8])
    }else{
      x.domain([ x.invert(extent[0]), x.invert(extent[1]) ])
      scatter.select(".brush").call(brush.move, null) // This remove the grey brush area as soon as the selection has been done
    }

    // Update axis and circle position
    xAxis.transition().duration(1000).call(d3.axisBottom(x))
    scatter
      .selectAll("circle")
      .transition().duration(1000)
      .attr("cx", function (d) { return x(d.Sepal_Length); } )
      .attr("cy", function (d) { return y(d.Petal_Length); } )

    }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>

<div id="brushZoom"></div></code>```

Title: Creating a zoom function in D3

Body:
I have a function where that when a button is pressed (Several buttons the represent several animal types), that animal types SVG is updated with its corresponding data. I'm trying to replicate this zoom function but am having issues implementing it with my code. There are several SVGs that are used globally like this (one for each animal type):

let x = d3.scaleLinear()
  .domain([0, 1000])
  .range([ 0, width ]);

var xAxis = d3.axisBottom(x);

svgReptile.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

const yAxis = d3.scaleLinear()
  .domain([0, 220])
  .range([ height, 0])

svgReptile.append("g")
  .call(d3.axisLeft(yAxis))

The function below is called when one of the animal buttons is pressed.

 function update(animal, whatSVG, xAxis, yAxis, color) {

      const points = whatSVG
        .selectAll("circle")
        .data(data);

      points.enter()
        .append("circle")
        .attr("cx", function(d) {
          return xAxis(d.state);
        })
        .attr("cy", function(d) {
          return yAxis(d.percentage);
        })
        .merge(points)
        .attr("r", 3)
        .attr("cx", function(d) {
          return xAxis(d.decade)
        })
        .attr("cy", function(d) {
          return yAxis(d.count)
        })
        .style("fill", function (d) { return colour(d.animal) } );

      points.exit()
        .attr('r', 0)
        .remove();

    }

Question:

How can I implement a zoom feature that expands the x-axis when zoomed (or anything similar) like the one linked above?

Body:
I think you're looking for a 'brush zoom' from the last line of your question.

The following source code if from an example in a d3 graph gallery

The cross hair allows you to select an area to expand. If you follow the link there is a graph above it that is entitled "Zoom with axis" but it doesn't zoom in the way you've described, it just moves the axis, but doesn't enlarge the graph contents with it. Perhaps both will be useful!

Hope this helps

// set the dimensions and margins of the graph
var margin = {top: 10, right: 20, bottom: 20, left: 20},
    width = 500 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var Svg = d3.select("#brushZoom")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

  // Add X axis
  var x = d3.scaleLinear()
    .domain([4, 8])
    .range([ 0, width ]);
  var xAxis = Svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, 9])
    .range([ height, 0]);
  Svg.append("g")
    .call(d3.axisLeft(y));

  // Add a clipPath: everything out of this area won't be drawn.
  var clip = Svg.append("defs").append("svg:clipPath")
      .attr("id", "clip")
      .append("svg:rect")
      .attr("width", width )
      .attr("height", height )
      .attr("x", 0)
      .attr("y", 0);

  // Color scale: give me a specie name, I return a color
  var color = d3.scaleOrdinal()
    .domain(["setosa", "versicolor", "virginica" ])
    .range([ "#440154ff", "#21908dff", "#fde725ff"])

  // Add brushing
  var brush = d3.brushX()                 // Add the brush feature using the d3.brush function
      .extent( [ [0,0], [width,height] ] ) // initialise the brush area: start at 0,0 and finishes at width,height: it means I select the whole graph area
      .on("end", updateChart) // Each time the brush selection changes, trigger the 'updateChart' function

  // Create the scatter variable: where both the circles and the brush take place
  var scatter = Svg.append('g')
    .attr("clip-path", "url(#clip)")

  // Add circles
  scatter
    .selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
      .attr("cx", function (d) { return x(d.Sepal_Length); } )
      .attr("cy", function (d) { return y(d.Petal_Length); } )
      .attr("r", 8)
      .style("fill", function (d) { return color(d.Species) } )
      .style("opacity", 0.5)

  // Add the brushing
  scatter
    .append("g")
      .attr("class", "brush")
      .call(brush);

  // A function that set idleTimeOut to null
  var idleTimeout
  function idled() { idleTimeout = null; }

  // A function that update the chart for given boundaries
  function updateChart() {

    extent = d3.event.selection

    // If no selection, back to initial coordinate. Otherwise, update X axis domain
    if(!extent){
      if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a little bit
      x.domain([ 4,8])
    }else{
      x.domain([ x.invert(extent[0]), x.invert(extent[1]) ])
      scatter.select(".brush").call(brush.move, null) // This remove the grey brush area as soon as the selection has been done
    }

    // Update axis and circle position
    xAxis.transition().duration(1000).call(d3.axisBottom(x))
    scatter
      .selectAll("circle")
      .transition().duration(1000)
      .attr("cx", function (d) { return x(d.Sepal_Length); } )
      .attr("cy", function (d) { return y(d.Petal_Length); } )

    }

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>

<div id="brushZoom"></div>


问:
Is bit shifting O(1) or O(n)?
Are shift operations O(1) or O(n) ?

Does it make sense that computers generally require more operations to shift 31 places instead of shifting 1 place?

Or does it make sense the number of operations required for shifting is constant regardless of how many places we need to shift?

PS: wondering if hardware is an appropriate tag..

答:
As a concrete example, according to Table C-17. General Purpose Instructions of the Intel® 64 and IA-32 Architectures Optimization Reference Manual:

```<code>SAL/SAR/SHL/SHR reg, imm   1 cycle latency
SAL/SAR/SHL/SHR reg, cl    1.5 cycles latency
</code>```

So that's still a constant factor and O(1.5) = O(1). There may be simpler microarchitectures as outliers but in general, O(1).

Title: Is bit shifting O(1) or O(n)?

Body:
As a concrete example, according to Table C-17. General Purpose Instructions of the Intel® 64 and IA-32 Architectures Optimization Reference Manual:

SAL/SAR/SHL/SHR reg, imm   1 cycle latency
SAL/SAR/SHL/SHR reg, cl    1.5 cycles latency

So that's still a constant factor and O(1.5) = O(1). There may be simpler microarchitectures as outliers but in general, O(1).


问:
Completely hide products from unauthorized users in WooCommerce
I'm trying to remove a product/products completely from Users that are not logged in and if user is not specific role (e.g Verified Buyer).

I have been able to create a new role called Verified Buyer using the code below;

```<code>add_role(
    'verified_buyer',
    __( 'Verified Buyer', 'text-domain' ),
    array(
       'read'         => true,
        'edit_posts'   => false,
    )
);
//This Role is same role capability as the WooCommerce Customer role
</code>```

and i have as well added a checkbox to the WooCommerce Add New Product page using the code below

```<code>function hide_product_from_unathorised_users() {
  $args = array(
    'id' => '_hide_from_unauthorize_users',
    'label' => 'Hide Product from unauthorized users',
    'desc_tip' => true,
    'description' => __('Check this to hide this product from unauthorized users', 'text-domain')
  );
  woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'hide_product_from_unathorised_users' );

// Save Fields
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $hide_product_unathorised_users = isset( $_POST['_hide_from_unauthorize_users'] ) ? 'yes' : 'no';
        update_post_meta($post_id, '_hide_from_unauthorize_users', esc_attr( $hide_product_unathorised_users ));
}
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');
</code>```

Now that i have this two options (user role and a checkbox to know which product to hide) ... I want to Hide such product if the following conditions are met;

HIDE PRODUCT COMPLETELY (Even from search Queries) IF;

1. Checkbox is checked on product & User is not logged in

2. Checkbox is checked on product & User logged in & not Verified Buyer or admin Role

Like this

```<code>function hide_product_completely_conditionally() {

global $post;

$hide_product_checkbox = get_post_meta( $post->ID, '_hide_from_unauthorize_users', true )

$user = wp_get_current_user();
$authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
$admin_role = in_array( 'administrator', (array) $user->roles );

    if ( ($hide_product_checkbox == 'yes' && !is_user_loggedin()) || ($hide_product_checkbox == 'yes' && is_user_loggedin() && (!$authorized_user_role || !$admin_role) ) ) {

     //(...) HIDE SUCH PRODUCT COMPLETELY CODE THAT I'M NOT SURE HOW TO WRITE

    }
}
</code>```

Thanks for your help in advance.

答:
The following will code will filter products based on a your custom product field when users are not allowed (and will redirect them to shop page if they try to access manually to a protected product).

```<code>// Conditional function checking for authorized users
function is_authorized_user(){
    if ( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $caps = $user->allcaps;

        if ( ( isset($caps['edit_product']) && $caps['edit_product'] )
        || in_array( 'verified_buyer', $user->roles ) ) return true;
    }
    else return false;
}

// Filter product query (and search) from unauthorized users
add_filter( 'woocommerce_product_query_meta_query', 'only_authorized_users_meta_query', 10, 2 );
function only_authorized_users_meta_query( $meta_query, $query ) {
    // Hide specific products from unauthorized users
    if( ! is_authorized_user() && ! is_admin() ) {
        $meta_query['relation'] = 'OR';
        $meta_query[] = array(
            'key'     => '_hide_from_unauthorize_users',
            'value'   => 'no',
            'compare' => '='
        );
        $meta_query[] = array(
            'key'     => '_hide_from_unauthorize_users',
            'compare' => 'NOT EXISTS'
        );
    }
    return $meta_query;
}

// Security: Redirect unauthorized users if accessing prodtected products
add_action( 'template_redirect', 'only_authorized_users_redirect' );
function only_authorized_users_redirect() {
    // Specific products redirect for unauthorized users (to be sure)
    if( is_product() && ! is_authorized_user()
    && get_post_meta( get_the_id(), '_hide_from_unauthorize_users', true ) === 'yes' ) {
        wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
        exit;
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Instead of using an additional user role, you can:

1) Use use the WC_Customer is_paying_customer boolean property like:

```<code> if( WC()->customer->get_is_paying_customer() ) {
     // Is a playing customer
 } else {
     // NOT a playing customer
 }
</code>```

2) Or adding custom user meta as:

```<code> update_user_meta( get_current_user_id(), 'allowed_customer', '1' );
</code>```

Then you will check using:

```<code> if( get_user_meta( get_current_user_id(), 'allowed_customer', true ) ) {
     // Allowed customer
 } else {
     // NOT Allowed customer
 }
</code>```

Body:
I'm trying to remove a product/products completely from Users that are not logged in and if user is not specific role (e.g Verified Buyer).

I have been able to create a new role called Verified Buyer using the code below;

add_role(
    'verified_buyer',
    __( 'Verified Buyer', 'text-domain' ),
    array(
       'read'         => true,
        'edit_posts'   => false,
    )
);
//This Role is same role capability as the WooCommerce Customer role

and i have as well added a checkbox to the WooCommerce Add New Product page using the code below

function hide_product_from_unathorised_users() {
  $args = array(
    'id' => '_hide_from_unauthorize_users',
    'label' => 'Hide Product from unauthorized users',
    'desc_tip' => true,
    'description' => __('Check this to hide this product from unauthorized users', 'text-domain')
  );
  woocommerce_wp_checkbox( $args );
}

add_action( 'woocommerce_product_options_advanced', 'hide_product_from_unathorised_users' );

// Save Fields
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $hide_product_unathorised_users = isset( $_POST['_hide_from_unauthorize_users'] ) ? 'yes' : 'no';
        update_post_meta($post_id, '_hide_from_unauthorize_users', esc_attr( $hide_product_unathorised_users ));
}
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');

Now that i have this two options (user role and a checkbox to know which product to hide) ... I want to Hide such product if the following conditions are met;

HIDE PRODUCT COMPLETELY (Even from search Queries) IF;

1. Checkbox is checked on product & User is not logged in

2. Checkbox is checked on product & User logged in & not Verified Buyer or admin Role

Like this

function hide_product_completely_conditionally() {

global $post;

$hide_product_checkbox = get_post_meta( $post->ID, '_hide_from_unauthorize_users', true )

$user = wp_get_current_user();
$authorized_user_role = in_array( 'verified_buyer', (array) $user->roles );
$admin_role = in_array( 'administrator', (array) $user->roles );

    if ( ($hide_product_checkbox == 'yes' && !is_user_loggedin()) || ($hide_product_checkbox == 'yes' && is_user_loggedin() && (!$authorized_user_role || !$admin_role) ) ) {

     //(...) HIDE SUCH PRODUCT COMPLETELY CODE THAT I'M NOT SURE HOW TO WRITE

    }
}

Thanks for your help in advance.

Body:
The following will code will filter products based on a your custom product field when users are not allowed (and will redirect them to shop page if they try to access manually to a protected product).

// Conditional function checking for authorized users
function is_authorized_user(){
    if ( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $caps = $user->allcaps;

        if ( ( isset($caps['edit_product']) && $caps['edit_product'] )
        || in_array( 'verified_buyer', $user->roles ) ) return true;
    }
    else return false;
}

// Filter product query (and search) from unauthorized users
add_filter( 'woocommerce_product_query_meta_query', 'only_authorized_users_meta_query', 10, 2 );
function only_authorized_users_meta_query( $meta_query, $query ) {
    // Hide specific products from unauthorized users
    if( ! is_authorized_user() && ! is_admin() ) {
        $meta_query['relation'] = 'OR';
        $meta_query[] = array(
            'key'     => '_hide_from_unauthorize_users',
            'value'   => 'no',
            'compare' => '='
        );
        $meta_query[] = array(
            'key'     => '_hide_from_unauthorize_users',
            'compare' => 'NOT EXISTS'
        );
    }
    return $meta_query;
}

// Security: Redirect unauthorized users if accessing prodtected products
add_action( 'template_redirect', 'only_authorized_users_redirect' );
function only_authorized_users_redirect() {
    // Specific products redirect for unauthorized users (to be sure)
    if( is_product() && ! is_authorized_user()
    && get_post_meta( get_the_id(), '_hide_from_unauthorize_users', true ) === 'yes' ) {
        wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
        exit;
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Instead of using an additional user role, you can:

1) Use use the WC_Customer is_paying_customer boolean property like:

 if( WC()->customer->get_is_paying_customer() ) {
     // Is a playing customer
 } else {
     // NOT a playing customer
 }

2) Or adding custom user meta as:

 update_user_meta( get_current_user_id(), 'allowed_customer', '1' );

Then you will check using:

 if( get_user_meta( get_current_user_id(), 'allowed_customer', true ) ) {
     // Allowed customer
 } else {
     // NOT Allowed customer
 }


问:
How to check the stdin buffer holds some data?
I was trying to develop a chat application using C programmable sockets. I need to check whether the stdin buffer has some value in it to send the message to the client/server and receive it. But I don't know how to check the stdin buffer for values.
Please help.</p>

答:
In POSIX systems you could do something along the lines:</p>

```<code>FD_ZERO (&rset);
FD_SET (fileno (stdin), &rset);

maxfd = fileno (stdin);
tv.tv_sec = 3;
tv.tv_usec = 0;

select (maxfd + 1, &rset, NULL, NULL, &tv);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In POSIX systems you could do something along the lines:

FD_ZERO (&rset);
FD_SET (fileno (stdin), &rset);

maxfd = fileno (stdin);
tv.tv_sec = 3;
tv.tv_usec = 0;

select (maxfd + 1, &rset, NULL, NULL, &tv);


问:
SSIS Lookup Multiple Columns in one table to the same ID column in another
I have the following table:

```<code>EventValue | Person1           | Person2    | Person3     | Person4       | Meta1  | Meta2
-------------------------------------------------------------------------------------------
123        | joePerson01       | samRock01  | nancyDrew01 | steveRogers01 | 505   | 606
321        | steveRogers02     | yoMama01   | ruMo01      | lukeJedi01    | 707   | 808
</code>```

I want to transform the Person columns into IDs for my destination table, so all of the ID's would be coming from the same Person table in my Destination DB:

```<code>ID | FirstName | LastName  | DatabaseOneID | DatabaseTwoID
----------------------------------------------------------
1  | Joe       | Person    | joePerson01   | personJoe01
2  | Sam       | Rockwell  | samRock01     | rockSam01
3  | Nancy     | Drew      | nancyDrew01   | drewNancy01
4  | Steve     | Rogers    | steveRogers01 | rogersSteve01
5  | Steve R   | Rogers    | steveRogers02 | rogersSteve02
6  | Yo        | Mama      | yoMama01      | mamaYo01
7  | Rufus     | Murdock   | ruMo01        | moRu01
8  | Luke      | Skywalker | lukeJedi01    | jediLuke01
</code>```

With results like so:

```<code>MetaID     | EventValue | Person1ID | Person2ID | Person3ID | Person4ID
------------------------------------------------------------------------
1          | 123        | 1         | 2         | 3         | 4
2          | 321        | 5         | 6         | 7         | 8
</code>```

I currently have a Lookup Transform looking up the first Person column, but couldn't figure out how to convert all 4 Person columns into IDs within the same lookup.

答:
You could do it in one query, or use UNPIVOT, or use a scalar function if you think it'll be more fixable for your implementation. Then, you just create a view of it, in which it'll be an easy access for you.

here is a quick example :

```<code>DECLARE
    @tb1 TABLE
(
    EventValue INT
, Person1 VARCHAR(250)
, Person2 VARCHAR(250)
, Person3 VARCHAR(250)
, Person4 VARCHAR(250)
, Meta1 INT
, Meta2 INT
)

DECLARE
    @Person TABLE
(
    ID INT
,   FirstName VARCHAR(250)
,   LastName  VARCHAR(250)
,   DatabaseOneID VARCHAR(250)
,   DatabaseTwoID VARCHAR(250)
)

INSERT INTO @tb1
VALUES
(123,'joePerson01','samRock01','nancyDrew01','steveRogers01',505,606),
(321,'steveRogers02','yoMama01','ruMo01','lukeJedi01',707,808)

INSERT INTO @Person
VALUES
(1,'Joe','Person','joePerson01','personJoe01'),
(2,'Sam','Rockwell','samRock01','rockSam01'),
(3,'Nancy','Drew','nancyDrew01','drewNancy01'),
(4,'Steve','Rogers','steveRogers01','rogersSteve01'),
(5,'SteveR','Rogers','steveRogers02','rogersSteve02'),
(6,'Yo','Mama','yoMama01','mamaYo01'),
(7,'Rufus','Murdock','ruMo01','moRu01'),
(8,'Luke','Skywalker','lukeJedi01','jediLuke01')

SELECT ROW_NUMBER() OVER(ORDER BY EventValue) AS MetaID, *
FROM (
    SELECT
        t.EventValue
    ,   MAX(CASE WHEN t.Person1 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person1ID
    ,   MAX(CASE WHEN t.Person2 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person2ID
    ,   MAX(CASE WHEN t.Person3 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person3ID
    ,   MAX(CASE WHEN t.Person4 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person4ID
    FROM @tb1 t
    LEFT JOIN @Person p
        ON p.DatabaseOneID IN(t.Person1, t.Person2, t.Person3, t.Person4)
        OR p.DatabaseTwoID IN(t.Person1, t.Person2, t.Person3, t.Person4)
    GROUP BY t.EventValue
) D
</code>```

Body:
I have the following table:

EventValue | Person1           | Person2    | Person3     | Person4       | Meta1  | Meta2
-------------------------------------------------------------------------------------------
123        | joePerson01       | samRock01  | nancyDrew01 | steveRogers01 | 505   | 606
321        | steveRogers02     | yoMama01   | ruMo01      | lukeJedi01    | 707   | 808

I want to transform the Person columns into IDs for my destination table, so all of the ID's would be coming from the same Person table in my Destination DB:

ID | FirstName | LastName  | DatabaseOneID | DatabaseTwoID
----------------------------------------------------------
1  | Joe       | Person    | joePerson01   | personJoe01
2  | Sam       | Rockwell  | samRock01     | rockSam01
3  | Nancy     | Drew      | nancyDrew01   | drewNancy01
4  | Steve     | Rogers    | steveRogers01 | rogersSteve01
5  | Steve R   | Rogers    | steveRogers02 | rogersSteve02
6  | Yo        | Mama      | yoMama01      | mamaYo01
7  | Rufus     | Murdock   | ruMo01        | moRu01
8  | Luke      | Skywalker | lukeJedi01    | jediLuke01

With results like so:

MetaID     | EventValue | Person1ID | Person2ID | Person3ID | Person4ID
------------------------------------------------------------------------
1          | 123        | 1         | 2         | 3         | 4
2          | 321        | 5         | 6         | 7         | 8

I currently have a Lookup Transform looking up the first Person column, but couldn't figure out how to convert all 4 Person columns into IDs within the same lookup.

Body:
You could do it in one query, or use UNPIVOT, or use a scalar function if you think it'll be more fixable for your implementation. Then, you just create a view of it, in which it'll be an easy access for you.

here is a quick example :

DECLARE
    @tb1 TABLE
(
    EventValue INT
, Person1 VARCHAR(250)
, Person2 VARCHAR(250)
, Person3 VARCHAR(250)
, Person4 VARCHAR(250)
, Meta1 INT
, Meta2 INT
)

DECLARE
    @Person TABLE
(
    ID INT
,   FirstName VARCHAR(250)
,   LastName  VARCHAR(250)
,   DatabaseOneID VARCHAR(250)
,   DatabaseTwoID VARCHAR(250)
)

INSERT INTO @tb1
VALUES
(123,'joePerson01','samRock01','nancyDrew01','steveRogers01',505,606),
(321,'steveRogers02','yoMama01','ruMo01','lukeJedi01',707,808)

INSERT INTO @Person
VALUES
(1,'Joe','Person','joePerson01','personJoe01'),
(2,'Sam','Rockwell','samRock01','rockSam01'),
(3,'Nancy','Drew','nancyDrew01','drewNancy01'),
(4,'Steve','Rogers','steveRogers01','rogersSteve01'),
(5,'SteveR','Rogers','steveRogers02','rogersSteve02'),
(6,'Yo','Mama','yoMama01','mamaYo01'),
(7,'Rufus','Murdock','ruMo01','moRu01'),
(8,'Luke','Skywalker','lukeJedi01','jediLuke01')

SELECT ROW_NUMBER() OVER(ORDER BY EventValue) AS MetaID, *
FROM (
    SELECT
        t.EventValue
    ,   MAX(CASE WHEN t.Person1 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person1ID
    ,   MAX(CASE WHEN t.Person2 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person2ID
    ,   MAX(CASE WHEN t.Person3 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person3ID
    ,   MAX(CASE WHEN t.Person4 IN(p.DatabaseOneID, p.DatabaseTwoID) THEN p.ID ELSE NULL END) AS Person4ID
    FROM @tb1 t
    LEFT JOIN @Person p
        ON p.DatabaseOneID IN(t.Person1, t.Person2, t.Person3, t.Person4)
        OR p.DatabaseTwoID IN(t.Person1, t.Person2, t.Person3, t.Person4)
    GROUP BY t.EventValue
) D


问:
I want to delete some inserts from the detail table and also the excisting Person in the master table
I got a procedure for a details table, where I delete patient records without appointments (termin table). But now I want to delete rows from the master table (patient).

I tried it with joins but it doesnt work

```<code> DELIMITER $$
 DROP PROCEDURE IF EXISTS  delete_patients $$
 CREATE PROCEDURE delete_patients ()
 BEGIN
  DECLARE v_patient_id INT(6); -- Variable für: ID des aktuellen Patienten
 DECLARE v_patient_number INT(64); -- Variable für: Anzahl der Termine des aktuellen Patienten
 DECLARE exit_loop BOOLEAN; -- Status, zeigt an ob alle Datensätze durchlaufen wurden
 DECLARE select_cursor CURSOR FOR
                        SELECT patient_id
                        FROM patient; -- Holt alle Datensätze (Alle Patienten)
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE; -- Der Handler setzt den Status, wenn alle Datensätze (patienten) durchlaufen wurden.
 OPEN select_cursor; -- Öffnet die Datensätze
 select_loop: LOOP -- Startet den Durchlauf aller Datensätze
 FETCH select_cursor INTO v_patient_id; -- Holt immer einen Datensatz (Patienten) und speichert die ID in v_patient_id
 IF exit_loop THEN -- Gibt es kein Datensatz mehr, wird der Durchlauf beendet.
     CLOSE select_cursor;
     LEAVE select_loop;
 END IF;
    SELECT count(patient_id) INTO v_patient_number FROM termin WHERE patient_id = v_patient_id; -- Zählt die Termine und speichert die Anzahl in v_patient_number
    IF v_patient_number = 0 THEN -- Sollte v_patient_id gleich 0 sein, also der Patient hat 0 Termine
        DELETE FROM patient WHERE patient_id = v_patient_id; -- Der Patient wurd gelöscht
    END IF;
END LOOP select_loop; -- Ende des Durchlaufs
END $$
DELIMITER ;
</code>```

答:
To find patients without appointments you can use

```<code>select p.*
from patient p
left join termin t on t.patient_id = p.patient_id
where t.patient_id is null
</code>```

db-fiddle demo

This can be converted to a DELETE statement:

```<code>delete p
from patient p
left join termin t on t.patient_id = p.patient_id
where t.patient_id is null
</code>```

db-fiddle demo

An equivalent query could also be:

```<code>delete p
from patient p
where not exists (
  select *
  from termin t
  where t.patient_id = p.patient_id
)
</code>```

db-fiddle demo

You can use it inside your procedure, but there is not really a need for a procedure at all.

Body:
I got a procedure for a details table, where I delete patient records without appointments (termin table). But now I want to delete rows from the master table (patient).

I tried it with joins but it doesnt work

 DELIMITER $$
 DROP PROCEDURE IF EXISTS  delete_patients $$
 CREATE PROCEDURE delete_patients ()
 BEGIN
  DECLARE v_patient_id INT(6); -- Variable für: ID des aktuellen Patienten
 DECLARE v_patient_number INT(64); -- Variable für: Anzahl der Termine des aktuellen Patienten
 DECLARE exit_loop BOOLEAN; -- Status, zeigt an ob alle Datensätze durchlaufen wurden
 DECLARE select_cursor CURSOR FOR
                        SELECT patient_id
                        FROM patient; -- Holt alle Datensätze (Alle Patienten)
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE; -- Der Handler setzt den Status, wenn alle Datensätze (patienten) durchlaufen wurden.
 OPEN select_cursor; -- Öffnet die Datensätze
 select_loop: LOOP -- Startet den Durchlauf aller Datensätze
 FETCH select_cursor INTO v_patient_id; -- Holt immer einen Datensatz (Patienten) und speichert die ID in v_patient_id
 IF exit_loop THEN -- Gibt es kein Datensatz mehr, wird der Durchlauf beendet.
     CLOSE select_cursor;
     LEAVE select_loop;
 END IF;
    SELECT count(patient_id) INTO v_patient_number FROM termin WHERE patient_id = v_patient_id; -- Zählt die Termine und speichert die Anzahl in v_patient_number
    IF v_patient_number = 0 THEN -- Sollte v_patient_id gleich 0 sein, also der Patient hat 0 Termine
        DELETE FROM patient WHERE patient_id = v_patient_id; -- Der Patient wurd gelöscht
    END IF;
END LOOP select_loop; -- Ende des Durchlaufs
END $$
DELIMITER ;

Body:
To find patients without appointments you can use

select p.*
from patient p
left join termin t on t.patient_id = p.patient_id
where t.patient_id is null

db-fiddle demo

This can be converted to a DELETE statement:

delete p
from patient p
left join termin t on t.patient_id = p.patient_id
where t.patient_id is null

db-fiddle demo

An equivalent query could also be:

delete p
from patient p
where not exists (
  select *
  from termin t
  where t.patient_id = p.patient_id
)

db-fiddle demo

You can use it inside your procedure, but there is not really a need for a procedure at all.


问:
What data structure should I use to index geographic coordinates?
I have a set of objects that have latitude and longitude coordinates and I need to be able to match another set to the closest item. Simple nearest-neighbor stuff. My best thought is to convert the lat/lng coordinates to 3D coordinates and then store in either a K-d tree or an octree for later lookup. It should work and be good enough for all practical purposes (see: kdtree for geospatial point search), but something about this feels off. I think it's the part where it's really just a 2D manifold in 3D space.

Is there a more appropriate structure to use or am I simply overthinking this?

答:
Even Wikipedia says:

a k-d tree (short for k-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space.

so go ahead and use your 2D points (without projecting them to 3D, or something similar).

Insert them into the tree, and then query the tree in logarithmic time - and there, all happy!


问:
Entity Framework Core How to make a Reference table for a model
I have been using SQL tables for referencing static data, for example in one of my apps a technician has a one-to-many relation with a clients table.

Basically what I want to do in SQL is this, so instead of dealing with strings I deal with ints as byte or tinyint which takes less size on disk since Clients are always static and it's rare to add new ones.

```<code> | Technicians |    |            Clients              |   | ClientsRef |
 |     Id      |    | Id | ClientRefId | TechnicianId |   | Id  | Name |
</code>```

My problem is to do this in EF Core 2.2, how do I create this static data? I read about using enum but how can I access that data in SQL Server after?

```<code>public class Technician
{
    int Id { get;set; }
}

public class Client
{
    int Id { get;set; }
    int Technicianid { get; set; }
}
</code>```

答:
This:

```<code>public class Technician
{
    int Id { get;set; }
}

public class Client
{
    int Id { get; set; }
    int TechnicianId { get; set; }
    public virtual Technician Technician {get; set;}
    public string Name { get; set; }
}
</code>```

Should be all you need.  There's no need for any other tables or keys in the model.

Body:
I have been using SQL tables for referencing static data, for example in one of my apps a technician has a one-to-many relation with a clients table.

Basically what I want to do in SQL is this, so instead of dealing with strings I deal with ints as byte or tinyint which takes less size on disk since Clients are always static and it's rare to add new ones.

 | Technicians |    |            Clients              |   | ClientsRef |
 |     Id      |    | Id | ClientRefId | TechnicianId |   | Id  | Name |

My problem is to do this in EF Core 2.2, how do I create this static data? I read about using enum but how can I access that data in SQL Server after?

public class Technician
{
    int Id { get;set; }
}

public class Client
{
    int Id { get;set; }
    int Technicianid { get; set; }
}

Body:
This:

public class Technician
{
    int Id { get;set; }
}

public class Client
{
    int Id { get; set; }
    int TechnicianId { get; set; }
    public virtual Technician Technician {get; set;}
    public string Name { get; set; }
}

Should be all you need.  There's no need for any other tables or keys in the model.


问:
StreamingResponseBody returning empty file
I'm trying to create a rest service to download files from a repository, using Springboot.

I'm trying to return a ResponseEntity with StreamingResponseBody, to return the file that i get from the repository, as an InputStream.

This is the current code i have:

@GetMapping(path = "/downloadFile")
    public ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam(value = "documentId") String documentId,
            HttpServletRequest request, HttpServletResponse response) throws InterruptedException, IOException {

        InputStream is = downloadService.getDocument(documentId);

        StreamingResponseBody out = outputStream -> {

            outputStream.write(IOUtils.toByteArray(is));
        };

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/csv");
        headers.add("Content-Disposition", "attachment; filename=" + documentId);
        headers.add("Pragma", "no-cache");
        headers.add("Cache-Control", "no-cache");

        return (new ResponseEntity<>(out, headers, HttpStatus.OK));

    }
```

When I consume this endpoint, using directly the browser, or postman, the file that is downloaded comes empty.
I understand that the OutputStream is written to asynchronously (Async is enabled in the config class).

How can I consume this service and get the file completely written, the way it comes from the repository I'm using ? ( if possible using Postman, just for testing purposes)

Am i building the service correctly?

答:
I have modified the code bit little, in my documentId is the name of the file to be downloaded. I have tested, it is working fine. Check below the code.</p>
```<code>@GetMapping(path = "/downloadFile")
public ResponseEntity<StreamingResponseBody> downloadFile(
      @RequestParam(value = "documentId") String documentId,
      HttpServletRequest request,
      HttpServletResponse response)
      throws InterruptedException, IOException {
    String dirPath = "E:/sure-delete/"; //Directory having the files
    InputStream inputStream = new FileInputStream(new File(dirPath + documentId));
    final StreamingResponseBody out =
        outputStream -> {
          int nRead;
          byte[] data = new byte[1024];
          while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            System.out.println("Writing some bytes of file...");
            outputStream.write(data, 0, nRead);
          }
        };
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "text/csv");
    headers.add("Content-Disposition", "attachment; filename=" + documentId);
    headers.add("Pragma", "no-cache");
    headers.add("Cache-Control", "no-cache");
    return ResponseEntity.ok().headers(headers).body(out);
  }
</code>```

Body:
I'm trying to create a rest service to download files from a repository, using Springboot.

I'm trying to return a ResponseEntity with StreamingResponseBody, to return the file that i get from the repository, as an InputStream.

This is the current code i have:

@GetMapping(path = "/downloadFile")
    public ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam(value = "documentId") String documentId,
            HttpServletRequest request, HttpServletResponse response) throws InterruptedException, IOException {

        InputStream is = downloadService.getDocument(documentId);

        StreamingResponseBody out = outputStream -> {

            outputStream.write(IOUtils.toByteArray(is));
        };

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/csv");
        headers.add("Content-Disposition", "attachment; filename=" + documentId);
        headers.add("Pragma", "no-cache");
        headers.add("Cache-Control", "no-cache");

        return (new ResponseEntity<>(out, headers, HttpStatus.OK));

    }

When I consume this endpoint, using directly the browser, or postman, the file that is downloaded comes empty.
I understand that the OutputStream is written to asynchronously (Async is enabled in the config class).

How can I consume this service and get the file completely written, the way it comes from the repository I'm using ? ( if possible using Postman, just for testing purposes)

Am i building the service correctly?

Body:
I have modified the code bit little, in my documentId is the name of the file to be downloaded. I have tested, it is working fine. Check below the code.

@GetMapping(path = "/downloadFile")
public ResponseEntity<StreamingResponseBody> downloadFile(
      @RequestParam(value = "documentId") String documentId,
      HttpServletRequest request,
      HttpServletResponse response)
      throws InterruptedException, IOException {
    String dirPath = "E:/sure-delete/"; //Directory having the files
    InputStream inputStream = new FileInputStream(new File(dirPath + documentId));
    final StreamingResponseBody out =
        outputStream -> {
          int nRead;
          byte[] data = new byte[1024];
          while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            System.out.println("Writing some bytes of file...");
            outputStream.write(data, 0, nRead);
          }
        };
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "text/csv");
    headers.add("Content-Disposition", "attachment; filename=" + documentId);
    headers.add("Pragma", "no-cache");
    headers.add("Cache-Control", "no-cache");
    return ResponseEntity.ok().headers(headers).body(out);
  }


问:
Leaflet - Gray stripes after panning
EDIT

This question is not a duplicate of How to get a leaflet map canvas to have a 100% height? as for the obvious reason, that you can see my map spanning the 100% height (compare the attribution on my picture being in the gray zone, while the container of the other question obviously ends before the blank zone. Also i can identify the size of my container spanning the 100% of the parent container in the developer tools. Just take a look at my css and and a very close look at the picture and maybe at leaftlet if you don't know how it works.)

Original

I use leaflet 1.5.1 in ionic 3.

After panning the map a bit, oftentimes the contents for gray parts are not being loaded (no network requests/traffic indicated in my browsers dev tools) and i am left with gray parts/stripes in the map as in the picture (the gray horizontal stripe below).

When i pan a lot further the missing map parts are loaded, but sometimes not (especially in iOS).

My map page's HTML using my map component (below)

<map style="height: 100%; width: 100%;">

The map component's HTML

The component's scss file

```<code>map {
    #map{
        height:100%;
        width: 100%;
    }
}
</code>```

And here the component's typescript which creates the map

```<code>this.map = L.map('map', {
      center: L.LatLng(center.latitude, center.longitude),
      zoom: 13,
      attribution: Attribution,
      tap: false
    });

    //Add OSM Layer
    L.tileLayer("https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png", { attribution: Attribution }).addTo(this.map);

    this.map.setView([center.latitude, center.longitude], 14);
</code>```

Any hints on what i'm doing wrong?

答:
The solution was to trigger a resizing event via window.dispatchEvent(new Event('resize')) every time the user enters the tab page holding all the tabs including the map tab.

The map is reacting to this by adjusting itself to the "new" size.

Title: Leaflet - Gray stripes after panning

Body:
EDIT

This question is not a duplicate of How to get a leaflet map canvas to have a 100% height? as for the obvious reason, that you can see my map spanning the 100% height (compare the attribution on my picture being in the gray zone, while the container of the other question obviously ends before the blank zone. Also i can identify the size of my container spanning the 100% of the parent container in the developer tools. Just take a look at my css and and a very close look at the picture and maybe at leaftlet if you don't know how it works.)

Original

I use leaflet 1.5.1 in ionic 3.

After panning the map a bit, oftentimes the contents for gray parts are not being loaded (no network requests/traffic indicated in my browsers dev tools) and i am left with gray parts/stripes in the map as in the picture (the gray horizontal stripe below).

When i pan a lot further the missing map parts are loaded, but sometimes not (especially in iOS).

My map page's HTML using my map component (below)

<map style="height: 100%; width: 100%;">

The map component's HTML

The component's scss file

map {
    #map{
        height:100%;
        width: 100%;
    }
}

And here the component's typescript which creates the map

this.map = L.map('map', {
      center: L.LatLng(center.latitude, center.longitude),
      zoom: 13,
      attribution: Attribution,
      tap: false
    });

    //Add OSM Layer
    L.tileLayer("https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png", { attribution: Attribution }).addTo(this.map);

    this.map.setView([center.latitude, center.longitude], 14);

Any hints on what i'm doing wrong?


问:
Calling an Object by an Integer
I'm trying to edit some objects texts with this:

```<code>' Textbox1
' Textbox2
' Textbox3

Sub Change_Text()

    Dim i As Integer

    For i = 1 To 3

        UserForm1.Textbox & i = "Hi"

    Next i

End Sub
</code>```

I think the code explain my problem, of course it's returning an error, I don't have idea what to do...

答:
Probably the optimal solution (least from your example) would be to loop over all the Textboxes

```<code>Private Sub loop_through_conts()
  Dim cont as Control
  For Each cont in Me.Controls
     If TypeName(cont) = "Textbox" Then
        Select Case Right(cont.Name, 1) ' in case you want only first three
        Case 1 To 3
           cont.Text = "Hi"
        End Select
     End If
  Next cont
End Sub
</code>```

This way your code is dynamic and does not have to be re-written in case a new Textbox were to be added

Title: Calling an Object by an Integer

Body:
I'm trying to edit some objects texts with this:

' Textbox1
' Textbox2
' Textbox3

Sub Change_Text()

    Dim i As Integer

    For i = 1 To 3

        UserForm1.Textbox & i = "Hi"

    Next i

End Sub

I think the code explain my problem, of course it's returning an error, I don't have idea what to do...

Body:
Probably the optimal solution (least from your example) would be to loop over all the Textboxes

Private Sub loop_through_conts()
  Dim cont as Control
  For Each cont in Me.Controls
     If TypeName(cont) = "Textbox" Then
        Select Case Right(cont.Name, 1) ' in case you want only first three
        Case 1 To 3
           cont.Text = "Hi"
        End Select
     End If
  Next cont
End Sub

This way your code is dynamic and does not have to be re-written in case a new Textbox were to be added


问:
file handling using structured array
I want to store string and char data into a .dat file.. program is running correctly.But after open the .dat file the same name is written twise.Why is that ? I can't find the problem.

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

struct patients{
        char name[8];
        char appType[1];
};

int main(void)
{

    FILE *F1;
    F1 = fopen("appointment.dat","a");

    int i = 0;
    struct patients detailsArr[5];

    for( i = 0 ; i < 5 ; i++ )
    {
        printf("Enter Patient Name : ");
        scanf("%s",detailsArr[i].name);

        printf("Enter Appointment Type :");
        scanf(" %c",detailsArr[i].appType);

    }

    if ( F1 == NULL )
    {
        printf("Error in File Reading !");
        return -1;
    }

    for( i = 0 ; i < 5 ; i++ )
    {
        fprintf(F1 ,"%s\t",detailsArr[i].name);
        fprintf(F1 ,"%s",detailsArr[i].appType);
        fprintf(F1 ,"\n");

    }

    fclose(F1);

    return 0;
}
</code>```

This is my Output :

```<code>Dilshan CRuwan
Ruwan   TMangala
Mangala SGanesh
Ganesh  CJithen
Jithen  SV
</code>```

答:
This looks like the ancient padded-fixed struct format so these fprintfs are wrong. Should be:

```<code>fprintf(F1 ,"%.8s\t",detailsArr[i].name);
fprintf(F1 ,"%.1s",detailsArr[i].appType);
</code>```

We should also change the scanf line to

```<code>scanf("%8s",detailsArr[i].name);
</code>```

so it can actually store all 8.

The reason this fails otherwise is your struct format appears to be non-null-terminated strings when the maximum string size is used. This requires handling as such with printf and scanf format strings, and copying in and out with strncpy. It's kind of awkward code so it's rarely used except for low-level on disk formats.

Title: file handling using structured array

Body:
I want to store string and char data into a .dat file.. program is running correctly.But after open the .dat file the same name is written twise.Why is that ? I can't find the problem.

#include<stdio.h>

struct patients{
        char name[8];
        char appType[1];
};

int main(void)
{

    FILE *F1;
    F1 = fopen("appointment.dat","a");

    int i = 0;
    struct patients detailsArr[5];

    for( i = 0 ; i < 5 ; i++ )
    {
        printf("Enter Patient Name : ");
        scanf("%s",detailsArr[i].name);

        printf("Enter Appointment Type :");
        scanf(" %c",detailsArr[i].appType);

    }

    if ( F1 == NULL )
    {
        printf("Error in File Reading !");
        return -1;
    }

    for( i = 0 ; i < 5 ; i++ )
    {
        fprintf(F1 ,"%s\t",detailsArr[i].name);
        fprintf(F1 ,"%s",detailsArr[i].appType);
        fprintf(F1 ,"\n");

    }

    fclose(F1);

    return 0;
}

This is my Output :

Dilshan CRuwan
Ruwan   TMangala
Mangala SGanesh
Ganesh  CJithen
Jithen  SV

Body:
This looks like the ancient padded-fixed struct format so these fprintfs are wrong. Should be:

fprintf(F1 ,"%.8s\t",detailsArr[i].name);
fprintf(F1 ,"%.1s",detailsArr[i].appType);

We should also change the scanf line to

scanf("%8s",detailsArr[i].name);

so it can actually store all 8.

The reason this fails otherwise is your struct format appears to be non-null-terminated strings when the maximum string size is used. This requires handling as such with printf and scanf format strings, and copying in and out with strncpy. It's kind of awkward code so it's rarely used except for low-level on disk formats.


问:
How do I fix this: Use of undefined constant slug - assumed 'slug'
I took my HTML website and turned it into a PHP site. I'm in the testing phase currently however, I keep getting "Notices" on the rendered page instead of content.

I've tried turning the constants to variables with $, but the notice still appears. However, it changed from undefined constant to undefined variable. I changed them back to constants.

I'm on a WinXP 32-bit, therefore, I use Xammp 1.8.2 with PHP 5.4.31

the array in question:

```<code>    $navItems = array(
                      array(
                              slug => "index.php",
                              title => "Home"
                            ),
                      array(
                              slug => "about.php",
                              title => "About Me"
                            ),
                      array(
                              slug => "portfolio.php",
                              title => "Portfolio"
                            ),
                      array(
                              slug => "contact.php",
                              title => "Contact"
                            )
        );
</code>```

I am expecting to see the actual page content. However, I get:

Notice: Use of undefined constant slug - assumed 'slug' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 5

Notice: Use of undefined constant title - assumed 'title' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 6

答:
Your array looks great, you might just want to slightly modify it, and add " or ' in some places that are required, for example like:

```<code>$navItems = array(
    array(
        "slug" => "index.php",
        "title" => "Home",
    ),
    array(
        "slug" => "about.php",
        "title" => "About Me",
    ),
    array(
        "slug" => "portfolio.php",
        "title" => "Portfolio",
    ),
    array(
        "slug" => "contact.php",
        "title" => "Contact",
    ),
);
</code>```

or maybe:

```<code>$navItems = [
    [
        "slug" => "index.php",
        "title" => "Home",
    ],
    [
        "slug" => "about.php",
        "title" => "About Me",
    ],
    [
        "slug" => "portfolio.php",
        "title" => "Portfolio",
    ],
    [
        "slug" => "contact.php",
        "title" => "Contact",
    ],
];

var_dump($navItems);
</code>```

Output

This is the output of var_dump($navItems);:

```<code>array(4) {
  [0]=>
  array(2) {
    ["slug"]=>
    string(9) "index.php"
    ["title"]=>
    string(4) "Home"
  }
  [1]=>
  array(2) {
    ["slug"]=>
    string(9) "about.php"
    ["title"]=>
    string(8) "About Me"
  }
  [2]=>
  array(2) {
    ["slug"]=>
    string(13) "portfolio.php"
    ["title"]=>
    string(9) "Portfolio"
  }
  [3]=>
  array(2) {
    ["slug"]=>
    string(11) "contact.php"
    ["title"]=>
    string(7) "Contact"
  }
}
</code>```

Reference 1

What does the PHP error message “Notice: Use of undefined constant” mean?

Body:
I took my HTML website and turned it into a PHP site. I'm in the testing phase currently however, I keep getting "Notices" on the rendered page instead of content.

I've tried turning the constants to variables with $, but the notice still appears. However, it changed from undefined constant to undefined variable. I changed them back to constants.

I'm on a WinXP 32-bit, therefore, I use Xammp 1.8.2 with PHP 5.4.31

the array in question:

    $navItems = array(
                      array(
                              slug => "index.php",
                              title => "Home"
                            ),
                      array(
                              slug => "about.php",
                              title => "About Me"
                            ),
                      array(
                              slug => "portfolio.php",
                              title => "Portfolio"
                            ),
                      array(
                              slug => "contact.php",
                              title => "Contact"
                            )
        );

I am expecting to see the actual page content. However, I get:

Notice: Use of undefined constant slug - assumed 'slug' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 5

Notice: Use of undefined constant title - assumed 'title' in C:\xampp\htdocs\zmglobal-it.com.php\includes\arrays.php on line 6

Body:
Your array looks great, you might just want to slightly modify it, and add " or ' in some places that are required, for example like:

$navItems = array(
    array(
        "slug" => "index.php",
        "title" => "Home",
    ),
    array(
        "slug" => "about.php",
        "title" => "About Me",
    ),
    array(
        "slug" => "portfolio.php",
        "title" => "Portfolio",
    ),
    array(
        "slug" => "contact.php",
        "title" => "Contact",
    ),
);

or maybe:

$navItems = [
    [
        "slug" => "index.php",
        "title" => "Home",
    ],
    [
        "slug" => "about.php",
        "title" => "About Me",
    ],
    [
        "slug" => "portfolio.php",
        "title" => "Portfolio",
    ],
    [
        "slug" => "contact.php",
        "title" => "Contact",
    ],
];

var_dump($navItems);

Output

This is the output of var_dump($navItems);:

array(4) {
  [0]=>
  array(2) {
    ["slug"]=>
    string(9) "index.php"
    ["title"]=>
    string(4) "Home"
  }
  [1]=>
  array(2) {
    ["slug"]=>
    string(9) "about.php"
    ["title"]=>
    string(8) "About Me"
  }
  [2]=>
  array(2) {
    ["slug"]=>
    string(13) "portfolio.php"
    ["title"]=>
    string(9) "Portfolio"
  }
  [3]=>
  array(2) {
    ["slug"]=>
    string(11) "contact.php"
    ["title"]=>
    string(7) "Contact"
  }
}

Reference 1

What does the PHP error message “Notice: Use of undefined constant” mean?


问:
Make div from hover stay in its same position after scrolling
I have a div that appears when the user hovers over one of the "squares", however when the user scrolls to access the squares furthest away from the bottom, the div that's appearing now looks to be in another position.

I know it appears in the same spot each time, but I'd like to have a fixed position on screen, even when the user scrolls.

JSFiddle: https://jsfiddle.net/6j1nhxy4/

Here's a snippet:

body {

}

.squarehover {
  visibility: hidden;
position: absolute;
left: 130%;
top: -0%;
background-color: white;
height: 200px;
width: 200px;
z-index: 999999999999999999999999999999;
-webkit-box-shadow: 0px 4px 13px 3px rgba(0,0,0,0.18);
-moz-box-shadow: 0px 4px 13px 3px rgba(0,0,0,0.18);
box-shadow: 0px 4px 13px 3px rgba(0,0,0,0.18);

}

.hovercontainer {

  position: absolute;
    left: 50px;
    overflow: overlay;
    top: -164px;
    height: 300px;
    /* opacity: 0; */
    /* visibility: hidden; */
    background-color: none;
    z-index: 2;
    /* margin-bottom: 100px; */
    width: 500px;
}

.squarecontainer {
  position: absolute;

      display: flex;
      width: 100%;

      flex-wrap: column-reverse;

      flex-direction: column-reverse;
      height: 95%;

      overflow-y: scroll;
      overflow-x: hidden;

      z-index: 99999;
      margin-left: auto;
      margin-right: auto;
}

.square {
    transition: 0.3s ease-in-out;
    width: 1px;
    height: 1px;

    /* position: relative; */
    /* top: -36%; */
    /* margin-bottom: 20px; */
    /* float: left; */
    /* left: 30.35%; */
    color: grey;
    background-color: grey;
    /* text-align: center; */
    /* cursor: pointer; */
    /* overflow: auto; */
    -webkit-box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
    -moz-box-shadow: 8px 0px 05.3px -8px black, -8px 0px 05.3px -8px black;
    box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
    /* z-index: 99999999; */
    /* display: flex; */
    /* justify-content: flex-end; */
    /* flex-direction: column; */
    max-height: auto;
    /* overflow-y: scroll; */
    /* flex: 1 1 300px; */
    /* flex: 1; */
    margin-bottom: 20px;
    top: 0px;
    padding: 0.9em;
    margin-right: auto;
    margin-left: auto;
    /* border: 1px dashed green; */

      }

      .square:hover .squarehover {

        visibility: visible;
        z-index: 999999999999999999999999999999;
        position: absolute;
        margin-left: 50px;
        margin-bottom: 50px;
        left: 5%;
        background-color: none;

      }

.squarewrapper {
  position: relative;
top: 0;
bottom: 0;
left:0;
  display: inline-flex;
   width: 50px;
   flex-direction: row;
   flex-wrap: wrap-reverse;  /* ADJUSTED */
   height: 650px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
   <head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="styles/testingcss.css?v=1.0">
   </head>
   <body>
  <div class="squarecontainer" id="squarecontainer">
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
     </div>
     <div class="square">
        <div class="optionhover"></div>
        <div class="squarehover">
        </div>
        <
     </div>
  </div>
   </body>
</html></code>```

答:
Welcome to StackOverflow (I can tell you're new). Welcome to the land of Coding Nerds, lel, anyways back to your question:

So, Your code is a little bit confusing for me >.< I'm gonna rewrite it a bit.

If you're like me, you probably don't care what has actually been done. So I'll give you the working code first, then tell you the reason afterwards.

(These two are the same thing)

Firstly, here's the JSFiddle: https://jsfiddle.net/xfh2Ldov/

Secondly, here's the code:

body {
  margin: 0;
}

.squarehover {
  display: none;
  position: fixed;
  top: 5vh;
  left: 5vw;
  background-color: white;
  height: 200px;
  width: 200px;
  z-index: 999999999999999999999999999999;
  -webkit-box-shadow: 0px 4px 13px 3px rgba(0, 0, 0, 0.18);
  -moz-box-shadow: 0px 4px 13px 3px rgba(0, 0, 0, 0.18);
  box-shadow: 0px 4px 13px 3px rgba(0, 0, 0, 0.18);
}

.squarecontainer {
  width: 100vw;
  height: 95vh;
  margin: 0 auto;
}

.square {
  width: 28px;
  height: 28px;
  background-color: grey;
  -webkit-box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
  -moz-box-shadow: 8px 0px 05.3px -8px black, -8px 0px 05.3px -8px black;
  box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
  top: 0px;
  margin: 10px auto;
}

.square:hover ~ .squarehover {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="squarecontainer">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="squarehover"></div>
</div></code>```

So basically, I just added position: fixed and simplified your code from "this works but I kinda just put a bunch of letters together and turned it into a large chunk of code" to "this works and I carefully positioned each letter to a really small chunk of code"

Looking at the code you had, you can simply see that it was just code pulled out from your actual coode. So... you may have to add in some bits to make it work how you want it to work

Explanation:

So...

position: fixed allows the div (or any other element) to stay fixed on the webpage even if you scroll. Good Example: https://www.w3schools.com/howto/howto_css_fixed_sidebar.asp

position: absolute allows the div to... well, since you used position: absolute in your code, I can just assume you know what it does.

position: sticky is position fixed and position absolute's baby. It acts like absolute until its about to leave the page view and then gets stuck at the bottom/top. Good Example: https://www.w3schools.com/howto/howto_js_sticky_header.asp

Body:
I have a div that appears when the user hovers over one of the "squares", however when the user scrolls to access the squares furthest away from the bottom, the div that's appearing now looks to be in another position.

I know it appears in the same spot each time, but I'd like to have a fixed position on screen, even when the user scrolls.

JSFiddle: https://jsfiddle.net/6j1nhxy4/

Here's a snippet:

body {

}

.squarehover {
  visibility: hidden;
position: absolute;
left: 130%;
top: -0%;
background-color: white;
height: 200px;
width: 200px;
z-index: 999999999999999999999999999999;
-webkit-box-shadow: 0px 4px 13px 3px rgba(0,0,0,0.18);
-moz-box-shadow: 0px 4px 13px 3px rgba(0,0,0,0.18);
box-shadow: 0px 4px 13px 3px rgba(0,0,0,0.18);

}

.hovercontainer {

  position: absolute;
    left: 50px;
    overflow: overlay;
    top: -164px;
    height: 300px;
    /* opacity: 0; */
    /* visibility: hidden; */
    background-color: none;
    z-index: 2;
    /* margin-bottom: 100px; */
    width: 500px;
}

.squarecontainer {
  position: absolute;

      display: flex;
      width: 100%;

      flex-wrap: column-reverse;

      flex-direction: column-reverse;
      height: 95%;

      overflow-y: scroll;
      overflow-x: hidden;

      z-index: 99999;
      margin-left: auto;
      margin-right: auto;
}

.square {
    transition: 0.3s ease-in-out;
    width: 1px;
    height: 1px;

    /* position: relative; */
    /* top: -36%; */
    /* margin-bottom: 20px; */
    /* float: left; */
    /* left: 30.35%; */
    color: grey;
    background-color: grey;
    /* text-align: center; */
    /* cursor: pointer; */
    /* overflow: auto; */
    -webkit-box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
    -moz-box-shadow: 8px 0px 05.3px -8px black, -8px 0px 05.3px -8px black;
    box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
    /* z-index: 99999999; */
    /* display: flex; */
    /* justify-content: flex-end; */
    /* flex-direction: column; */
    max-height: auto;
    /* overflow-y: scroll; */
    /* flex: 1 1 300px; */
    /* flex: 1; */
    margin-bottom: 20px;
    top: 0px;
    padding: 0.9em;
    margin-right: auto;
    margin-left: auto;
    /* border: 1px dashed green; */

      }

      .square:hover .squarehover {

        visibility: visible;
        z-index: 999999999999999999999999999999;
        position: absolute;
        margin-left: 50px;
        margin-bottom: 50px;
        left: 5%;
        background-color: none;

      }

.squarewrapper {
  position: relative;
top: 0;
bottom: 0;
left:0;
  display: inline-flex;
   width: 50px;
   flex-direction: row;
   flex-wrap: wrap-reverse;  /* ADJUSTED */
   height: 650px;

}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="styles/testingcss.css?v=1.0">

        <

        <

        <

        <

        <

        <

        <

        <

        <

        <

Body:
Welcome to StackOverflow (I can tell you're new). Welcome to the land of Coding Nerds, lel, anyways back to your question:

So, Your code is a little bit confusing for me >.< I'm gonna rewrite it a bit.

If you're like me, you probably don't care what has actually been done. So I'll give you the working code first, then tell you the reason afterwards.

(These two are the same thing)

Firstly, here's the JSFiddle: https://jsfiddle.net/xfh2Ldov/

Secondly, here's the code:

body {
  margin: 0;
}

.squarehover {
  display: none;
  position: fixed;
  top: 5vh;
  left: 5vw;
  background-color: white;
  height: 200px;
  width: 200px;
  z-index: 999999999999999999999999999999;
  -webkit-box-shadow: 0px 4px 13px 3px rgba(0, 0, 0, 0.18);
  -moz-box-shadow: 0px 4px 13px 3px rgba(0, 0, 0, 0.18);
  box-shadow: 0px 4px 13px 3px rgba(0, 0, 0, 0.18);
}

.squarecontainer {
  width: 100vw;
  height: 95vh;
  margin: 0 auto;
}

.square {
  width: 28px;
  height: 28px;
  background-color: grey;
  -webkit-box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
  -moz-box-shadow: 8px 0px 05.3px -8px black, -8px 0px 05.3px -8px black;
  box-shadow: 8px 0px 5.3px -8px black, -8px 0px 5.3px -8px black;
  top: 0px;
  margin: 10px auto;
}

.square:hover ~ .squarehover {
  display: block;
}

<div class="squarecontainer">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="squarehover"></div>
</div>

So basically, I just added position: fixed and simplified your code from "this works but I kinda just put a bunch of letters together and turned it into a large chunk of code" to "this works and I carefully positioned each letter to a really small chunk of code"

Looking at the code you had, you can simply see that it was just code pulled out from your actual coode. So... you may have to add in some bits to make it work how you want it to work

Explanation:

So...

position: fixed allows the div (or any other element) to stay fixed on the webpage even if you scroll. Good Example: https://www.w3schools.com/howto/howto_css_fixed_sidebar.asp

position: absolute allows the div to... well, since you used position: absolute in your code, I can just assume you know what it does.

position: sticky is position fixed and position absolute's baby. It acts like absolute until its about to leave the page view and then gets stuck at the bottom/top. Good Example: https://www.w3schools.com/howto/howto_js_sticky_header.asp