问:
Opening UIDatePicker under UITextView
I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.

I am just starting with IOS app development and I hope someone can help me.

```<code>datePicker = UIDatePicker
</code>```

and

```<code>inputTextfield = UITextField
</code>```

myCode:

```<code>//Function to create the datepicker
func createDatePicker(){
            //create instance of the datepicker
            datePicker = UIDatePicker()
            //sets format, so only day month and year can be selected
            //datePicker?.datePickerMode = .date
            datePicker?.backgroundColor = .white
            datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
            //to limit the datepicker, you can not pick a date older than yesterday
            let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
            datePicker?.minimumDate = yesterday
            datePicker?.minuteInterval = 30
            let loc = Locale(identifier: "de")
            datePicker?.locale = loc

            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))

            view.addGestureRecognizer(tapGesture)

            inputTextfield.inputView = datePicker

            //create a toolbar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()

            //add done button to the toolbar
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
            toolbar.setItems([doneButton], animated: true)

            inputTextfield.inputAccessoryView = toolbar
        }

        //function to select a date
        @objc func dateChanged(datePicker: UIDatePicker){

            //selected date by the user
            let dateFormate = DateFormatter()
            //Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
            dateFormate.dateFormat = "MM/dd/yyyy"
            inputTextfield.text = dateFormate.string(from: datePicker.date)
        }

        //function to close the datepicker, when tapping on the inputText again -handler method
        @objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
            view.endEditing(true)
        }

        //function to close the datepicker when clicking on the done button
        @objc func doneClicked(){
            self.view.endEditing(true)
        }
</code>```

答:
No need to use any third party library. This can be achieved very easily. What I understand is that you want the picker to be displayed below the textfield and not as the input view instead of keyboard. Follow the following code to achieve what you want.

Here, name of my ViewController is TextFieldWithDatePickerVC. Don't get confused with name. With following code you would be able to do this very easily without using any third part library. I am attaching a output video also along with the code.

```<code>class TextFieldWithDatePickerVC: UIViewController {

    lazy var inputTextfield: UITextField = {
        let txtField = UITextField()
        txtField.backgroundColor = .white
        txtField.borderStyle = .roundedRect
        txtField.translatesAutoresizingMaskIntoConstraints = false
        txtField.placeholder = "Click me to open date picker"
        return txtField
    }()

    lazy var datePicker: UIDatePicker = {
        let picker = UIDatePicker()
        picker.backgroundColor = .white
        picker.addTarget(self, action: #selector(TextFieldWithDatePickerVC.dateChanged(_:)), for: .valueChanged)

        let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
        picker.minimumDate = yesterday
        picker.minuteInterval = 30
        let loc = Locale(identifier: "de")
        picker.locale = loc
        picker.translatesAutoresizingMaskIntoConstraints = false
        return picker
    }()

    lazy var doneToolBar: UIToolbar = {
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
        toolbar.setItems([doneButton], animated: true)
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        return toolbar
    }()

    lazy var pickerContainer: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupAutoLayout()
        pickerContainer.isHidden = true
        inputTextfield.delegate = self
        hideDatePicker()
    }

    func showDatePickerView() {
        DispatchQueue.main.async {
            self.pickerContainer.isHidden = false
        }
    }

    func hideDatePicker() {
        DispatchQueue.main.async {
            self.pickerContainer.isHidden = true
        }
    }

    func setupAutoLayout() {
        self.view.addSubview(inputTextfield)
        self.view.addSubview(pickerContainer)
        self.view.bringSubview(toFront: pickerContainer)
        pickerContainer.addSubview(doneToolBar)
        pickerContainer.addSubview(datePicker)
        NSLayoutConstraint.activate([
            inputTextfield.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
            inputTextfield.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
            inputTextfield.topAnchor.constraint(equalTo: view.topAnchor, constant: 60),

            pickerContainer.topAnchor.constraint(equalTo: inputTextfield.bottomAnchor, constant: 5),
            pickerContainer.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
            pickerContainer.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
            pickerContainer.heightAnchor.constraint(equalToConstant: datePicker.intrinsicContentSize.height + doneToolBar.intrinsicContentSize.height),

            doneToolBar.topAnchor.constraint(equalTo: pickerContainer.topAnchor, constant: 0),
            doneToolBar.leftAnchor.constraint(equalTo: pickerContainer.leftAnchor, constant: 0),
            doneToolBar.rightAnchor.constraint(equalTo: pickerContainer.rightAnchor, constant: 0),

            datePicker.bottomAnchor.constraint(equalTo: pickerContainer.bottomAnchor, constant: 0),
            datePicker.leftAnchor.constraint(equalTo: pickerContainer.leftAnchor, constant: 0),
            datePicker.rightAnchor.constraint(equalTo: pickerContainer.rightAnchor, constant: 0)
            ])

    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print(sender.date)
        inputTextfield.text = sender.date.description
    }

    @objc func doneClicked() {
        hideDatePicker()
    }

}

extension TextFieldWithDatePickerVC: UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.resignFirstResponder()
        showDatePickerView()
    }

}
</code>```

Title: Opening UIDatePicker under UITextView

Body:
I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.

I am just starting with IOS app development and I hope someone can help me.

datePicker = UIDatePicker

and

inputTextfield = UITextField

myCode:

//Function to create the datepicker
func createDatePicker(){
            //create instance of the datepicker
            datePicker = UIDatePicker()
            //sets format, so only day month and year can be selected
            //datePicker?.datePickerMode = .date
            datePicker?.backgroundColor = .white
            datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
            //to limit the datepicker, you can not pick a date older than yesterday
            let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
            datePicker?.minimumDate = yesterday
            datePicker?.minuteInterval = 30
            let loc = Locale(identifier: "de")
            datePicker?.locale = loc

            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))

            view.addGestureRecognizer(tapGesture)

            inputTextfield.inputView = datePicker

            //create a toolbar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()

            //add done button to the toolbar
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
            toolbar.setItems([doneButton], animated: true)

            inputTextfield.inputAccessoryView = toolbar
        }

        //function to select a date
        @objc func dateChanged(datePicker: UIDatePicker){

            //selected date by the user
            let dateFormate = DateFormatter()
            //Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
            dateFormate.dateFormat = "MM/dd/yyyy"
            inputTextfield.text = dateFormate.string(from: datePicker.date)
        }

        //function to close the datepicker, when tapping on the inputText again -handler method
        @objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
            view.endEditing(true)
        }

        //function to close the datepicker when clicking on the done button
        @objc func doneClicked(){
            self.view.endEditing(true)
        }

Body:
No need to use any third party library. This can be achieved very easily. What I understand is that you want the picker to be displayed below the textfield and not as the input view instead of keyboard. Follow the following code to achieve what you want.

Here, name of my ViewController is TextFieldWithDatePickerVC. Don't get confused with name. With following code you would be able to do this very easily without using any third part library. I am attaching a output video also along with the code.

class TextFieldWithDatePickerVC: UIViewController {

    lazy var inputTextfield: UITextField = {
        let txtField = UITextField()
        txtField.backgroundColor = .white
        txtField.borderStyle = .roundedRect
        txtField.translatesAutoresizingMaskIntoConstraints = false
        txtField.placeholder = "Click me to open date picker"
        return txtField
    }()

    lazy var datePicker: UIDatePicker = {
        let picker = UIDatePicker()
        picker.backgroundColor = .white
        picker.addTarget(self, action: #selector(TextFieldWithDatePickerVC.dateChanged(_:)), for: .valueChanged)

        let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
        picker.minimumDate = yesterday
        picker.minuteInterval = 30
        let loc = Locale(identifier: "de")
        picker.locale = loc
        picker.translatesAutoresizingMaskIntoConstraints = false
        return picker
    }()

    lazy var doneToolBar: UIToolbar = {
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
        toolbar.setItems([doneButton], animated: true)
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        return toolbar
    }()

    lazy var pickerContainer: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupAutoLayout()
        pickerContainer.isHidden = true
        inputTextfield.delegate = self
        hideDatePicker()
    }

    func showDatePickerView() {
        DispatchQueue.main.async {
            self.pickerContainer.isHidden = false
        }
    }

    func hideDatePicker() {
        DispatchQueue.main.async {
            self.pickerContainer.isHidden = true
        }
    }

    func setupAutoLayout() {
        self.view.addSubview(inputTextfield)
        self.view.addSubview(pickerContainer)
        self.view.bringSubview(toFront: pickerContainer)
        pickerContainer.addSubview(doneToolBar)
        pickerContainer.addSubview(datePicker)
        NSLayoutConstraint.activate([
            inputTextfield.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
            inputTextfield.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
            inputTextfield.topAnchor.constraint(equalTo: view.topAnchor, constant: 60),

            pickerContainer.topAnchor.constraint(equalTo: inputTextfield.bottomAnchor, constant: 5),
            pickerContainer.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
            pickerContainer.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
            pickerContainer.heightAnchor.constraint(equalToConstant: datePicker.intrinsicContentSize.height + doneToolBar.intrinsicContentSize.height),

            doneToolBar.topAnchor.constraint(equalTo: pickerContainer.topAnchor, constant: 0),
            doneToolBar.leftAnchor.constraint(equalTo: pickerContainer.leftAnchor, constant: 0),
            doneToolBar.rightAnchor.constraint(equalTo: pickerContainer.rightAnchor, constant: 0),

            datePicker.bottomAnchor.constraint(equalTo: pickerContainer.bottomAnchor, constant: 0),
            datePicker.leftAnchor.constraint(equalTo: pickerContainer.leftAnchor, constant: 0),
            datePicker.rightAnchor.constraint(equalTo: pickerContainer.rightAnchor, constant: 0)
            ])

    }

    @objc func dateChanged(_ sender: UIDatePicker) {
        print(sender.date)
        inputTextfield.text = sender.date.description
    }

    @objc func doneClicked() {
        hideDatePicker()
    }

}

extension TextFieldWithDatePickerVC: UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.resignFirstResponder()
        showDatePickerView()
    }

}


来源: stackexchange

问:
Docker-Compose can't connect to Docker Daemon
I am getting an error message saying I can't connect to the docker daemon.  I have looked into other people's answers who have had similar issues but it hasn't helped.  I am running the version of Ubuntu 15.10.  I will try to provide all the info I have.

```<code>root@# docker-compose -f docker-compose-deps.yml up -d
ERROR: Couldn't connect to Docker daemon at http+docker://localunixsocket - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
</code>```

Docker Version

```<code>root@# sudo docker     version
Client:
Version:      1.9.1
API version:  1.21
Go version:   go1.4.2
Git commit:   a34a1d5
Built:        Fri Nov 20 13:20:08 UTC 2015
OS/Arch:      linux/amd64
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
</code>```

Docker-Compose Version

```<code>root@# docker-compose --version
docker-compose version 1.5.2, build 7240ff3
</code>```

This is what happens if I try to stop or start the service...

```<code>root@# sudo service docker stop
stop: Unknown instance:
root@# sudo service   docker start
docker start/running, process 5375
</code>```

If I run ps aux | grep docker

```<code>root@# ps aux | grep docker
root      4233  0.0  0.0  13692  2204 pts/15   S+   10:27   0:00 grep --color=auto docker
</code>```

Any help would be greatly appreciated.  Let me know if you may need anymore information.

答:
You should adding your user to the "docker" group with something like:

sudo usermod -aG docker ${USER}

ContentLicense: CC BY-SA 3.0

Body:
I am getting an error message saying I can't connect to the docker daemon.  I have looked into other people's answers who have had similar issues but it hasn't helped.  I am running the version of Ubuntu 15.10.  I will try to provide all the info I have.

root@# docker-compose -f docker-compose-deps.yml up -d
ERROR: Couldn't connect to Docker daemon at http+docker://localunixsocket - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.

Docker Version

root@# sudo docker     version
Client:
Version:      1.9.1
API version:  1.21
Go version:   go1.4.2
Git commit:   a34a1d5
Built:        Fri Nov 20 13:20:08 UTC 2015
OS/Arch:      linux/amd64
Cannot connect to the Docker daemon. Is the docker daemon running on this host?

Docker-Compose Version

root@# docker-compose --version
docker-compose version 1.5.2, build 7240ff3

This is what happens if I try to stop or start the service...

root@# sudo service docker stop
stop: Unknown instance:
root@# sudo service   docker start
docker start/running, process 5375

If I run ps aux | grep docker

root@# ps aux | grep docker
root      4233  0.0  0.0  13692  2204 pts/15   S+   10:27   0:00 grep --color=auto docker

Any help would be greatly appreciated.  Let me know if you may need anymore information.

ContentLicense: CC BY-SA 4.0


问:
Converting Hexadecimal NUmbers in English ASCII characters
In the below given code I am getting Hexa decimal values..i.e. 68 65 68 65... I want to convert it into English alphabetical characters like hehe...

I am not able to convert the hexadecimal numbers obtained to their          English characters

```<code>printf("\nCommand: ");
for(i = 54; i<=57; i++)
{
printf("%X", packet[i]);
printf(" ");
}
</code>```

Prints 68 65 68 65 but I want hehe

答:
You need to use %c

```<code>printf("%c", packet[i]);
</code>```

As %X will print the value as hexadecimal number. See http://www.cplusplus.com/reference/cstdio/printf/

Body:
In the below given code I am getting Hexa decimal values..i.e. 68 65 68 65... I want to convert it into English alphabetical characters like hehe...

I am not able to convert the hexadecimal numbers obtained to their          English characters

printf("\nCommand: ");
for(i = 54; i<=57; i++)
{
printf("%X", packet[i]);
printf(" ");
}

Prints 68 65 68 65 but I want hehe

Body:
You need to use %c

printf("%c", packet[i]);

As %X will print the value as hexadecimal number. See http://www.cplusplus.com/reference/cstdio/printf/


问:
Wait for image loading to complete in JavaScript
I'm loading images with JavaScript. Something like this:

```<code>images[0]=new Image();
images[0].onload=function(){loaded++;console.log(loaded)};
images[0].src="assets/img/image.png";
</code>```

When I look at the log, I see that all the images are loaded nicely, since the value of the "loaded" variable increases with each loaded image.

However I would like to stop any further action to be executed until this amount reaches it's maximum, so right after setting up the images, I place a while cycle.

```<code>while(loaded<11){
    document.getElementById("test").innerHTML="Loading "+loaded+"/11";
    console.log(loaded);
}
//Some code here which should only run after everything has been loaded
//In other words: when the statement in the while cycle becomes false
</code>```

However my browser simply crashes, since the while seems to be stuck in an infinite loop. When I check the log, I see that "0" was written 1000 times, and after that, the numbers from 1 to 11 (which implies that the images in fact gets loaded, but the while does not care about it, and crashes faster than it could happen).

I believe that the method I'm trying to use here is not the right approach to solve this problem.

How can I put everything on hold until every asset which is needed for the site is loaded?

答:
Using promises and async functions, there is a nice way to wait until all the images are loaded (no callbacks, no loaded image counting):

```<code>async function loadImages(imageUrlArray) {
    const promiseArray = []; // create an array for promises
    const imageArray = []; // array for the images

    for (let imageUrl of imageUrlArray) {

        promiseArray.push(new Promise(resolve => {

            const img = new Image();
            // if you don't need to do anything when the image loads,
            // then you can just write img.onload = resolve;

            img.onload = function() {
                // do stuff with the image if necessary

                // resolve the promise, indicating that the image has been loaded
                resolve();
            };

            img.src = imageUrl;
            imageArray.push(img);
        }));
    }

    await Promise.all(promiseArray); // wait for all the images to be loaded
    console.log("all images loaded");
    return imageArray;
}
</code>```

Or you can wait for a single image to load:

```<code>async function loadImage(imageUrl) {
    let img;
    const imageLoadPromise = new Promise(resolve => {
        img = new Image();
        img.onload = resolve;
        img.src = imageUrl;
    });

    await imageLoadPromise;
    console.log("image loaded");
    return img;
}
</code>```

You can use it like this (using promise chaining):

```<code>loadImages(myImages).then(images => {
    // the loaded images are in the images array
})
</code>```

Or inside an async function:

```<code>const images = await loadImages(myImages);
</code>```

Body:
I'm loading images with JavaScript. Something like this:

images[0]=new Image();
images[0].onload=function(){loaded++;console.log(loaded)};
images[0].src="assets/img/image.png";

When I look at the log, I see that all the images are loaded nicely, since the value of the "loaded" variable increases with each loaded image.

However I would like to stop any further action to be executed until this amount reaches it's maximum, so right after setting up the images, I place a while cycle.

while(loaded<11){
    document.getElementById("test").innerHTML="Loading "+loaded+"/11";
    console.log(loaded);
}
//Some code here which should only run after everything has been loaded
//In other words: when the statement in the while cycle becomes false

However my browser simply crashes, since the while seems to be stuck in an infinite loop. When I check the log, I see that "0" was written 1000 times, and after that, the numbers from 1 to 11 (which implies that the images in fact gets loaded, but the while does not care about it, and crashes faster than it could happen).

I believe that the method I'm trying to use here is not the right approach to solve this problem.

How can I put everything on hold until every asset which is needed for the site is loaded?

Body:
Using promises and async functions, there is a nice way to wait until all the images are loaded (no callbacks, no loaded image counting):

async function loadImages(imageUrlArray) {
    const promiseArray = []; // create an array for promises
    const imageArray = []; // array for the images

    for (let imageUrl of imageUrlArray) {

        promiseArray.push(new Promise(resolve => {

            const img = new Image();
            // if you don't need to do anything when the image loads,
            // then you can just write img.onload = resolve;

            img.onload = function() {
                // do stuff with the image if necessary

                // resolve the promise, indicating that the image has been loaded
                resolve();
            };

            img.src = imageUrl;
            imageArray.push(img);
        }));
    }

    await Promise.all(promiseArray); // wait for all the images to be loaded
    console.log("all images loaded");
    return imageArray;
}

Or you can wait for a single image to load:

async function loadImage(imageUrl) {
    let img;
    const imageLoadPromise = new Promise(resolve => {
        img = new Image();
        img.onload = resolve;
        img.src = imageUrl;
    });

    await imageLoadPromise;
    console.log("image loaded");
    return img;
}

You can use it like this (using promise chaining):

loadImages(myImages).then(images => {
    // the loaded images are in the images array
})

Or inside an async function:

const images = await loadImages(myImages);


问:
Use a variable as a function name in PHP
I'm creating a dynamic function in WordPress that requires I create my function names dynamically.

In this instance, I need to generate a unique function name for this gravityforms code:

```<code>add_filter( 'gform_validation_message', 'change_message', 10, 2 );
function change_message( $message, $form ) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}
</code>```

So, I have a variable (which will change from time to time) that I want to use for my function name...

```<code>$newitem = 'new_item';
</code>```

...and tried this...

```<code>add_filter( 'gform_validation_message', $newitem, 10, 2 );
function $newitem( $message, $form ) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}
</code>```

...but obviously that does not work. But I think you get the idea of what I am trying to achieve.

Is anything like this even possible?

Any help is appreciated.

答:
$thing = 'some_function';
$$thing = function() {
   echo 'hi';
};
$some_function();
```

Source - Use a variable to define a PHP function

Body:
I'm creating a dynamic function in WordPress that requires I create my function names dynamically.

In this instance, I need to generate a unique function name for this gravityforms code:

add_filter( 'gform_validation_message', 'change_message', 10, 2 );
function change_message( $message, $form ) {
    return "
Failed Validation - " . $form['title'] . '
';
}

So, I have a variable (which will change from time to time) that I want to use for my function name...

$newitem = 'new_item';

...and tried this...

add_filter( 'gform_validation_message', $newitem, 10, 2 );
function $newitem( $message, $form ) {
    return "
Failed Validation - " . $form['title'] . '
';
}

...but obviously that does not work. But I think you get the idea of what I am trying to achieve.

Is anything like this even possible?

Any help is appreciated.

Body:
$thing = 'some_function';
$$thing = function() {
   echo 'hi';
};
$some_function();

Source - Use a variable to define a PHP function


问:
C# delegate to struct method
I am trying to create a delegate to a struct method for a particular instance. However, it turns out that a new instance of the struct is created and when I call the delegate it performs the method over the newly created instance rather than the original.

```<code>
static void Main(string[] args)
{
Point A = new Point() { x = 0 };
Action move = A.MoveRight;
move();
//A.x is still zero!
}</p>

struct Point
{
    public int x, y;

    public void MoveRight()
    {
        x++;
    }
}
</code>```

Actually, what happens in this example is that a new instance of struct Point is created on the delegate creaton and the method when called through the delagate is performed on it.

If I use class instead of the struct the problem is solved, but I want to use a struct. I also know there is a solution with creating an open delegate and passing the struct as the first parameter to a delegate, but this solution seems rather too heavy. Is there any simple solution to this problem?

答:
Anathema or not maybe in office use of C#. In 3D engines we do any kind of devil work. So for example in Unity3D engine Vector3 is struct by you have function Set(x,y,z) and you can even change x,y,z as they are public fields. Everything for speed(e.g if you have less calculation for this, you will have for something else.</p>

```<code>  static void Main(string[] args)
    {
    Point A = new Point() { x = 0 };
    MyPointDelegate<Point> move=(ref Point p)=> p.MoveRight();
    move(ref A);
    Console.Write(A.x);
    //A.x is one!
    }

public delegate void MyPointDelegate<Point>(ref Point t);

struct Point
{
    public int x, y;

    public void MoveRight()
    {
        x++;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C# delegate to struct method

Body:
I am trying to create a delegate to a struct method for a particular instance. However, it turns out that a new instance of the struct is created and when I call the delegate it performs the method over the newly created instance rather than the original.

static void Main(string[] args)
{
Point A = new Point() { x = 0 };
Action move = A.MoveRight;
move();
//A.x is still zero!
}

struct Point
{
    public int x, y;

    public void MoveRight()
    {
        x++;
    }
}

Actually, what happens in this example is that a new instance of struct Point is created on the delegate creaton and the method when called through the delagate is performed on it.

If I use class instead of the struct the problem is solved, but I want to use a struct. I also know there is a solution with creating an open delegate and passing the struct as the first parameter to a delegate, but this solution seems rather too heavy. Is there any simple solution to this problem?

Body:
Anathema or not maybe in office use of C#. In 3D engines we do any kind of devil work. So for example in Unity3D engine Vector3 is struct by you have function Set(x,y,z) and you can even change x,y,z as they are public fields. Everything for speed(e.g if you have less calculation for this, you will have for something else.

  static void Main(string[] args)
    {
    Point A = new Point() { x = 0 };
    MyPointDelegate<Point> move=(ref Point p)=> p.MoveRight();
    move(ref A);
    Console.Write(A.x);
    //A.x is one!
    }

public delegate void MyPointDelegate<Point>(ref Point t);

struct Point
{
    public int x, y;

    public void MoveRight()
    {
        x++;
    }
}


问:
Strings in 2D lists in Python
This is a normal 2D list in python containing what supposed to be white spaces:

```<code>shape = [
["", "", ""],
["", "", ""],
["", "", ""]]
</code>```

but when printing this array using for loop that's what happens:

```<code>['', '', '']
['', '', '']
['', '', '']
</code>```

isn't it supposed to show only white space ? How do I remove these single quot marks but leave the commas ?

答:
No, it shows everything there is, to remove it, you need to do some string replacing stuff:

```<code>print(str(shape).replace("'", '').replace('], [', '],\n ['))
</code>```

Which outputs:

```<code>[[, , ],
 [, , ],
 [, , ]]
</code>```

Title: Strings in 2D lists in Python

Body:
This is a normal 2D list in python containing what supposed to be white spaces:

shape = [
["", "", ""],
["", "", ""],
["", "", ""]]

but when printing this array using for loop that's what happens:

['', '', '']
['', '', '']
['', '', '']

isn't it supposed to show only white space ? How do I remove these single quot marks but leave the commas ?

Body:
No, it shows everything there is, to remove it, you need to do some string replacing stuff:

print(str(shape).replace("'", '').replace('], [', '],\n ['))

Which outputs:

[[, , ],
 [, , ],
 [, , ]]


问:
TSQL copy table data to another table with custom values
I have 2 tables with identical columns expect one which is userId. I want to copy all the data from the first table into the second one and add custom userId to the column that is missing. Thus far without success.

The query is shown below. Insert Quality, Quantity, Supplier and UserId (which doesn't exist in the table im getting data)

```<code>`DECLARE @UserId int = 5611; -- add this to all the data from dbo.GasStation

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT * FROM dbo.GasStation -- UserId doesn't exist in this table
-- Add somehow @UserId to all the data i'm getting from GasStation in order to satisfy the column UserId in the NewGasStation`
</code>```

All the data i'm getting from dbo.GasStation to be inserted to dbo.NewGasStation adding this custom UserId to all the results.

答:
```<code>INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT Quality, Quantity, Supplier, '5611' FROM dbo.GasStation
</code>```

should do the trick (assuming column names are the same for both tables)

Body:
I have 2 tables with identical columns expect one which is userId. I want to copy all the data from the first table into the second one and add custom userId to the column that is missing. Thus far without success.

The query is shown below. Insert Quality, Quantity, Supplier and UserId (which doesn't exist in the table im getting data)

`DECLARE @UserId int = 5611; -- add this to all the data from dbo.GasStation

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT * FROM dbo.GasStation -- UserId doesn't exist in this table
-- Add somehow @UserId to all the data i'm getting from GasStation in order to satisfy the column UserId in the NewGasStation`

All the data i'm getting from dbo.GasStation to be inserted to dbo.NewGasStation adding this custom UserId to all the results.

Body:
INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT Quality, Quantity, Supplier, '5611' FROM dbo.GasStation

should do the trick (assuming column names are the same for both tables)


问:
Why does a macro assigned to a cell fail?
I have a macro assigned to a cell that executes once clicked on. The macro involves SAP scripting, which if ever interrupted (via CTRL+DEL+ALT), also causes my previously clickable cell to stop working.

I can run the macro via Developer yet the cell is not working. Note that the code provided below is pasted in the sheet where the clickable cell is, not in ThisWorkbook.

```<code>Option Explicit

Private Sub Worksheet_SelectionChange(ByVal target As Range)

   If Selection.CountLarge = 1 Then

   If Not Intersect(target, Range("A10")) Is Nothing Then
       Call FolderPicker
   End If

End Sub
</code>```

Any ideas what might be causing the issue?

答:
You could use:</p>

```<code>Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    'Check count how many cells affected to avoid errors
    If Target.Count = 1 Then

        If Not Intersect(Target, Range("A10")) Is Nothing Then
            Application.EnableEvents = False 'Disable events to avoid pointless code trigger
                Call FolderPicker
            Application.EnableEvents = True
        End If

    End If

End Sub
</code>```

Body:
I have a macro assigned to a cell that executes once clicked on. The macro involves SAP scripting, which if ever interrupted (via CTRL+DEL+ALT), also causes my previously clickable cell to stop working.

I can run the macro via Developer yet the cell is not working. Note that the code provided below is pasted in the sheet where the clickable cell is, not in ThisWorkbook.

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal target As Range)

   If Selection.CountLarge = 1 Then

   If Not Intersect(target, Range("A10")) Is Nothing Then
       Call FolderPicker
   End If

End Sub

Any ideas what might be causing the issue?

Body:
You could use:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    'Check count how many cells affected to avoid errors
    If Target.Count = 1 Then

        If Not Intersect(Target, Range("A10")) Is Nothing Then
            Application.EnableEvents = False 'Disable events to avoid pointless code trigger
                Call FolderPicker
            Application.EnableEvents = True
        End If

    End If

End Sub


问:
How to fake background activity while using Xamarin.UITest
I'm creating a Xamarin.Forms App and want to use UITest to test the correct behavior of my View. The View does not only react on user input like button click or the like. Instead there are background operations which should lead to changes in the View like hiding one element and showing another element at this point. Another example is filling a ListView with elements which would be produced by a background operation. These changes would be made on the ViewModel whose properties are bound to the View.
Now I want to simulate the background operation and test that my View behaves correctly. But I can not manipulate my ViewModel while in the UITest project because I cannot reference Xamarin.Forms in the Test class.
It seems like it isn't intended to test the application this way. The whole app is a black box for the UITest and you can only interact through mouse and keyboard input with it.
How can I access internals of my app, the corresponding ViewModel for example.
I already searched for this problem but found nothing. Maybe I'm searching in the wrong direction.
Any help would be highly appreciated. </p>

答:
On iOS, you already have a method to achieve it called SendAppToBackground. You can also pass the time to be in the background with a TimeSpan object (wiki info). However, you cannot achieve this on Android.

Here is a sample to use it on your UITest project:

public void SendAppToBackground(IApp app, TimeSpan timeSpan)
{
    if (OnAndroid)
    {
        return;
    }

    ((iOSApp)app).SendAppToBackground(timeSpan);

    app.Screenshot("Return from background state.");

    return this;
}
```


问:
What's the fastest way to test the validity of a large number of well-formed URLs
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs

I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).

Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.

Can it be done?

答: Instead of sending an HTTP GET request for each URL you can try sending an HTTP HEAD request.  They are described in this document.</p>

OwnerDisplayName: Salim Fadhley

OwnerDisplayName: David Locke


问:
Topic prediction using Latent Dirichlet Allocation
I have used LDA on a corpus of documents and found some Topics. The output of my code is two matrices containing probabilities. one doc-topic probabilities and the other word-topic probabilities. But I actually don't know how to use these results to predict the topic of a new document. I am using Gibbs sampling. Does anyone know how?
thanks</p>

答:
The Java implementation http://www.arbylon.net/projects/lda-j/lda-j-src-20050325.zip has an short example program in src\org\knowceans\lda\SearchEnglet.java. I hope you are a bit familiar with java and the code helps you.

The original paper http://jmlr.csail.mit.edu/papers/volume3/blei03a/blei03a.pdf describes inference in sections 5.1 and 5.2.


问:
Plot graph from the bunch of selected excel sheet
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

```<code>import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
test_folders = os.listdir(path)
folder_data = os.listdir(path)
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print("%d-%s"%( i,f))
    csv_code = int(input("Enter corresponding code to plot: "))
    csv_path = folder_data + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])
</code>```

When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

```<code>0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc
</code>```

so that i select the corresponding code like 1 or 2 or 3 to plot.

Here is the error

```<code>   csv_path = folder_data + "\\" + folder_data[csv_code]

TypeError: can only concatenate list (not "str") to list
</code>```

答:
Regarding your actual error message:
folder_data is a list, to which you want to add a string "\\", which does not work. In case you want to append "\\" to each element in the list, you would have to do the following: folder_data = [i+"\\" for i in folder_data]. What you might be wanting to do is use path + "\\" + folder_data[csv_code} instead to get the full path to a single csv file.

Body:
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
test_folders = os.listdir(path)
folder_data = os.listdir(path)
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print("%d-%s"%( i,f))
    csv_code = int(input("Enter corresponding code to plot: "))
    csv_path = folder_data + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])

When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

so that i select the corresponding code like 1 or 2 or 3 to plot.

Here is the error

   csv_path = folder_data + "\\" + folder_data[csv_code]

TypeError: can only concatenate list (not "str") to list


问:
Responsive hero with Vimeo background
I'm trying to replicate background-size: cover; with a Vimeo video in my website's hero section. I can get the video to sit nicely but it's not scaling down properly on small screens.

Here's what I've got at the moment:

HTML:

```<code><div id="vimeohero">
  <iframe src="https://player.vimeo.com/video/319007333?background=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</code>```

CSS:

```<code>#vimeohero {
  height: 300px;
}

iframe {
  width: 100vw;
  height: 56.25vw; // Given a 16:9 aspect ratio, 9/16*100 = 56.25
  min-height: 100vh;
  min-width: 177.77vh; // Given a 16:9 aspect ratio, 16/9*100 = 177.77
  position: relative;
  top: 50%;
  left: 50%;
  transform: perspective(1px) translate(-50%, -50%);
}
</code>```

https://jsfiddle.net/a7j0rbmq/1/

When you look at this on a small screen (375px by 812px) the video is zoomed in and not displaying the same as background-size: cover; would.

(Obviously the video will have to zoom in a bit to fill the space but this zooms in more than necessary. If you change the height of your screen to match the height of the div (300px) it displays fine).

If you remove the min-width declaration it almost fixes the problem, however on some screen sizes you get whitespace either side of the video :(

答:
#vimeohero {
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

iframe {
  width: 100vw;
  height: 56.25vw;
  min-height: 100vh;
  min-width: 177.77vh;
}
*{
  padding:0;
  margin:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="vimeohero">
  <iframe src="https://player.vimeo.com/video/319007333?background=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div></code>```

remove padding and margin on all element solve it!

Title: Responsive hero with Vimeo background

Body:
I'm trying to replicate background-size: cover; with a Vimeo video in my website's hero section. I can get the video to sit nicely but it's not scaling down properly on small screens.

Here's what I've got at the moment:

HTML:

CSS:

#vimeohero {
  height: 300px;
}

iframe {
  width: 100vw;
  height: 56.25vw; // Given a 16:9 aspect ratio, 9/16*100 = 56.25
  min-height: 100vh;
  min-width: 177.77vh; // Given a 16:9 aspect ratio, 16/9*100 = 177.77
  position: relative;
  top: 50%;
  left: 50%;
  transform: perspective(1px) translate(-50%, -50%);
}

https://jsfiddle.net/a7j0rbmq/1/

When you look at this on a small screen (375px by 812px) the video is zoomed in and not displaying the same as background-size: cover; would.

(Obviously the video will have to zoom in a bit to fill the space but this zooms in more than necessary. If you change the height of your screen to match the height of the div (300px) it displays fine).

If you remove the min-width declaration it almost fixes the problem, however on some screen sizes you get whitespace either side of the video :(

Body:
#vimeohero {
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

iframe {
  width: 100vw;
  height: 56.25vw;
  min-height: 100vh;
  min-width: 177.77vh;
}
*{
  padding:0;
  margin:0;
}

<div id="vimeohero">
  <iframe src="https://player.vimeo.com/video/319007333?background=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>

remove padding and margin on all element solve it!


答:
Make sure the NewGasStation table does not exsist when running this</p>

```<code>Select Quality, Quantity, Supplier,5611 as UserId
into NewGasStation
from GasStation
</code>```

Title: TSQL copy table data to another table with custom values

Body:
Make sure the NewGasStation table does not exsist when running this

Select Quality, Quantity, Supplier,5611 as UserId
into NewGasStation
from GasStation


问:
What is the size of column of int(11) in mysql in bytes?
What is the size of column of int(11) in mysql in bytes?

And Maximum value that can be stored in this columns?

答: According to here, int(11) will take 4 bytes of space that is 32 bits of space with  2^(31) = 2147483648 max value and -2147483648min value. One bit is for sign.


问:
How to programmatically invoke MBeans operation of target process
I want to simulate what jconsole does by:

Identifying a running process that exposes jmx functionality (e.g: pid: 14796 FreshProject.jar)

Listing the available MBeans libraries (e.g: org.jacoco)

Invoking an operation (e.g: clicking dump)

I've tried using the simplejmx library as mentioned here but I am confused as to what hostName and port I should use. I tried passing localhost and 1099 as I've read these are the default values but it errors java.net.ConnectException: Connection refused: connect.

Please don't point me to a different sof post and close this as I most probably already read and tried it several times.

答:
I did not try @Godin's version but I am sure it is working since it is so detailed.

I have done it a different way:  I have used the simplejmx library available at https://jar-download.com/?search_box=simplejmx.

In order to attach the JmxClient to the process you need to know the port it is running on. It can be set via the JVM arguments as such:

```<code>-Dcom.sun.management.jmxremote.port=1240
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
</code>```

Once the app is running on the specified port the following script will access it and invoke a target operation:

```<code>public static void main(String[] args) throws Exception {
    JmxClient client = new JmxClient("localhost", 1240);
    client.invokeOperation(new ObjectName("org.jacoco:type=Runtime"), "dump", new Object[] {true});
    client.close();
}
</code>```

Also check: How to programmatically check JMX MBean operations and attributes?

Note: It must be on jdk version 10 or higher. Does not work on 8.

Body:
I did not try @Godin's version but I am sure it is working since it is so detailed.

I have done it a different way:  I have used the simplejmx library available at https://jar-download.com/?search_box=simplejmx.

In order to attach the JmxClient to the process you need to know the port it is running on. It can be set via the JVM arguments as such:

-Dcom.sun.management.jmxremote.port=1240
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

Once the app is running on the specified port the following script will access it and invoke a target operation:

public static void main(String[] args) throws Exception {
    JmxClient client = new JmxClient("localhost", 1240);
    client.invokeOperation(new ObjectName("org.jacoco:type=Runtime"), "dump", new Object[] {true});
    client.close();
}

Also check: How to programmatically check JMX MBean operations and attributes?

Note: It must be on jdk version 10 or higher. Does not work on 8.


问:
How to regulate CollectionViewCell size, by code or by storyBoard(CollectionView is inside of TableView)

I have collectionView Inside UITableViewCell, and in UICollectionViewCell I have UImageView, when I run the project there are some free space, which i don't want: how can I fix it(by code or by storyboard - it doesn't matter)

答:
You should fix it by code. You can manage space between two UICollectionView cells by using UICollectionViewDelegateFlowLayout methods.

```<code>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
</code>```

Provide the cell height and width in the above method.

```<code>     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}
</code>```

The above method use for a vertically scrolling grid, this value represents the minimum spacing between successive rows. For a horizontally scrolling grid, this value represents the minimum spacing between successive columns.

Body:
You should fix it by code. You can manage space between two UICollectionView cells by using UICollectionViewDelegateFlowLayout methods.

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

Provide the cell height and width in the above method.

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

The above method use for a vertically scrolling grid, this value represents the minimum spacing between successive rows. For a horizontally scrolling grid, this value represents the minimum spacing between successive columns.


问:
How do I turn debug logging off, in log4j, for docx4j
I receive the following message when I deploy my maven/spring application on jboss as7 and attempt to upload a docx file.  The message is displayed within the body of the uploaded file when I view it in the app's WYSIWIG editor.  The message does not display when I run the app locally on jetty.  I included the log4j and docx4j property files.  I'm not sure what property would allow me to toggle the debug logging for the docx4j class mentioned in the error and so far I've come up empty on web searches.  BTW, my app is not using a log4j/docx4j xml file and from what I've read it's an either or setup.  If I should switch to xml, then please let me know and please inform me of which property needs to be adjusted so I can clear this message.

TY

TO HIDE THESE MESSAGES, TURN OFF log4j debug level logging for org.docx4j.convert.out.html.HtmlExporterNG2

log4j.properties

```<code>log4j.rootLogger=ERROR,stdout
#Console Appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%5p] [%t %d{hh:mm:ss}] (%F:%M:%L) %m%n
#Custom assignments
log4j.logger.Controllers=DEBUG,stdout
log4j.logger.Entities=DEBUG,stdout
log4j.logger.Models=DEBUG,stdout
#Disable additivity
log4j.additivity.Controllers=false
log4j.additivity.Entities=false
log4j.additivity.Models=false
</code>```

docx4j.properties

```<code># Page size: use a value from org.docx4j.model.structure.PageSizePaper enum
# eg A4, LETTER
docx4j.PageSize=LETTER
# Page size: use a value from org.docx4j.model.structure.MarginsWellKnown enum
docx4j.PageMargins=NORMAL
docx4j.PageOrientationLandscape=false
# Page size: use a value from org.pptx4j.model.SlideSizesWellKnown enum
# eg A4, LETTER
pptx4j.PageSize=LETTER
pptx4j.PageOrientationLandscape=false
# These will be injected into docProps/app.xml
# if App.Write=true
docx4j.App.write=true
docx4j.Application=docx4j
docx4j.AppVersion=2.7
# of the form XX.YYYY where X and Y represent numerical values
# These will be injected into docProps/core.xml
docx4j.dc.write=true
docx4j.dc.creator.value=docx4j
docx4j.dc.lastModifiedBy.value=docx4j
#
#docx4j.McPreprocessor=true
# If you haven't configured log4j yourself
# docx4j will autoconfigure it. Set this to true to disable that
docx4j.Log4j.Configurator.disabled=true
</code>```

答:
We had a similar issue while using docx4j with Spring Boot.

Since spring-boot-starter-logging auto-configures logback-classic which is used as implementation for loggers, it comes to just setting correct level for package. In our case we didn't need any logging from docx4j therefore adding below line to application.properties disabled whole output from 'docx4j':

```<code>logging.level.org.docx4j=OFF
</code>```

If you specifically need to disable console print of document, then you need to set turn off log level on this particular file:

```<code>logging.level.org.docx4j.model.datastorage.migration.VariablePrepare=OFF
</code>```

EDIT: I know this topic is old but there are very limited sources targeting this topic while using spring boot. I hope this helps someone in future.

Body:
I receive the following message when I deploy my maven/spring application on jboss as7 and attempt to upload a docx file.  The message is displayed within the body of the uploaded file when I view it in the app's WYSIWIG editor.  The message does not display when I run the app locally on jetty.  I included the log4j and docx4j property files.  I'm not sure what property would allow me to toggle the debug logging for the docx4j class mentioned in the error and so far I've come up empty on web searches.  BTW, my app is not using a log4j/docx4j xml file and from what I've read it's an either or setup.  If I should switch to xml, then please let me know and please inform me of which property needs to be adjusted so I can clear this message.

TY

TO HIDE THESE MESSAGES, TURN OFF log4j debug level logging for org.docx4j.convert.out.html.HtmlExporterNG2

log4j.properties

log4j.rootLogger=ERROR,stdout
#Console Appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%5p] [%t %d{hh:mm:ss}] (%F:%M:%L) %m%n
#Custom assignments
log4j.logger.Controllers=DEBUG,stdout
log4j.logger.Entities=DEBUG,stdout
log4j.logger.Models=DEBUG,stdout
#Disable additivity
log4j.additivity.Controllers=false
log4j.additivity.Entities=false
log4j.additivity.Models=false

docx4j.properties

# Page size: use a value from org.docx4j.model.structure.PageSizePaper enum
# eg A4, LETTER
docx4j.PageSize=LETTER
# Page size: use a value from org.docx4j.model.structure.MarginsWellKnown enum
docx4j.PageMargins=NORMAL
docx4j.PageOrientationLandscape=false
# Page size: use a value from org.pptx4j.model.SlideSizesWellKnown enum
# eg A4, LETTER
pptx4j.PageSize=LETTER
pptx4j.PageOrientationLandscape=false
# These will be injected into docProps/app.xml
# if App.Write=true
docx4j.App.write=true
docx4j.Application=docx4j
docx4j.AppVersion=2.7
# of the form XX.YYYY where X and Y represent numerical values
# These will be injected into docProps/core.xml
docx4j.dc.write=true
docx4j.dc.creator.value=docx4j
docx4j.dc.lastModifiedBy.value=docx4j
#
#docx4j.McPreprocessor=true
# If you haven't configured log4j yourself
# docx4j will autoconfigure it. Set this to true to disable that
docx4j.Log4j.Configurator.disabled=true

Body:
We had a similar issue while using docx4j with Spring Boot.

Since spring-boot-starter-logging auto-configures logback-classic which is used as implementation for loggers, it comes to just setting correct level for package. In our case we didn't need any logging from docx4j therefore adding below line to application.properties disabled whole output from 'docx4j':

logging.level.org.docx4j=OFF

If you specifically need to disable console print of document, then you need to set turn off log level on this particular file:

logging.level.org.docx4j.model.datastorage.migration.VariablePrepare=OFF

EDIT: I know this topic is old but there are very limited sources targeting this topic while using spring boot. I hope this helps someone in future.


问:
window.chrome.runtime is undefined for selenium webdriver
I am using Selenium for testing. I noticed a different behavior starting Chrome manually and starting it with selenium. After a lot of investigation I broke the problem down to JavaScript's window.chrome.runtime which is undefined if started with selenium.

After some research on Google I have found people facing similar issues, but none of their solutions worked for me.

I have tried so far to remove the test-type switch:

```<code>ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Arrays.asList("test-type"));
</code>```

Are there any other ways I can make it work?

答:
Answer which did the job for me was at https://groups.google.com/forum/#!topic/chromedriver-users/7wF9EHF2jxQ

Code snippet:

```<code>ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Arrays.asList("test-type"));
</code>```

Body:
I am using Selenium for testing. I noticed a different behavior starting Chrome manually and starting it with selenium. After a lot of investigation I broke the problem down to JavaScript's window.chrome.runtime which is undefined if started with selenium.

After some research on Google I have found people facing similar issues, but none of their solutions worked for me.

I have tried so far to remove the test-type switch:

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Arrays.asList("test-type"));

Are there any other ways I can make it work?

Body:
Answer which did the job for me was at https://groups.google.com/forum/#!topic/chromedriver-users/7wF9EHF2jxQ

Code snippet:

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Arrays.asList("test-type"));


问:
Couchapp directory structure, updates?
when generating a new couchapp, I get this structure:

```<code>appname
├── _attachments
│   └── style
├── evently
│   ├── items
│   │   └── _changes
│   └── profile
│       └── profileReady
│           └── selectors
│               └── form
├── lists
├── shows
├── updates
├── vendor
│   └── couchapp
│       ├── _attachments
│       ├── evently
│       │   ├── account
│       │   │   ├── adminParty
│       │   │   ├── loggedIn
│       │   │   ├── loggedOut
│       │   │   ├── loginForm
│       │   │   │   └── selectors
│       │   │   │       └── form
│       │   │   └── signupForm
│       │   │       └── selectors
│       │   │           └── form
│       │   └── profile
│       │       ├── loggedOut
│       │       ├── noProfile
│       │       │   └── selectors
│       │       │       └── form
│       │       └── profileReady
│       └── lib
└── views
    └── recent-items
</code>```

Now, since this structure is meant to reflect the JSON structure of a CouchDB _design document, I figured this out:

[_attachments] Attachments are stored binary. JavaScript, CSS, and HTML files are stored here.

[evently] ???

[lists] Lists are JavaScript functions that are executed to render HTML or AtomFeeds from view results.

[shows] Show functions are the analogue to list functions, but render content by transforming a document into other formats (such as html, xml, csv, png).

[updates] ???

[vendor]Home of external libraries.

[views]View contain MapReduce functions that can later be queried though the HTTP API (see \ref{couchdb:views}).

Appart from me hopefully being not completely wrong with the filled out descriptions, how would I describe the updates directory? Is this hosting validation functions?

The second question would be how you would describe the evently directory...

If there is a summary for this already existing, please point me to it!

Kind Regards!

答:
The generate command builds the backbone document format that CouchDB needs; and it also builds a web app development framework, Evently. I don't know Evently very well; but basically it gives a developer tools and suggestions to make the UI and the couch interact.

Personally, I never use the couchapp generate command. I just create the _id file from scratch (echo -n _design/whatever > _id), then create folders and files as I need them.

List functions (one per file) receive _view output to produce any HTTP response (e.g. XML RSS).

Show functions (one per file) receive a one document to produce any HTTP repsonse.

Update functions (one per file) receive one HTTP query and output one prepared document to be stored by couch. (For example, receiving a form submission and building a JSON document.)

View functions (one map.js and one reduce.js in a folder) are CouchDB views and provide for the querying and stuff.

I'm not sure about updates and vendor. They aren't relevant to the CouchDB server.

Title: Couchapp directory structure, updates?

Body:
when generating a new couchapp, I get this structure:

appname
├── _attachments
│   └── style
├── evently
│   ├── items
│   │   └── _changes
│   └── profile
│       └── profileReady
│           └── selectors
│               └── form
├── lists
├── shows
├── updates
├── vendor
│   └── couchapp
│       ├── _attachments
│       ├── evently
│       │   ├── account
│       │   │   ├── adminParty
│       │   │   ├── loggedIn
│       │   │   ├── loggedOut
│       │   │   ├── loginForm
│       │   │   │   └── selectors
│       │   │   │       └── form
│       │   │   └── signupForm
│       │   │       └── selectors
│       │   │           └── form
│       │   └── profile
│       │       ├── loggedOut
│       │       ├── noProfile
│       │       │   └── selectors
│       │       │       └── form
│       │       └── profileReady
│       └── lib
└── views
    └── recent-items

Now, since this structure is meant to reflect the JSON structure of a CouchDB _design document, I figured this out:

[_attachments] Attachments are stored binary. JavaScript, CSS, and HTML files are stored here.

[evently] ???

[lists] Lists are JavaScript functions that are executed to render HTML or AtomFeeds from view results.

[shows] Show functions are the analogue to list functions, but render content by transforming a document into other formats (such as html, xml, csv, png).

[updates] ???

[vendor]Home of external libraries.

[views]View contain MapReduce functions that can later be queried though the HTTP API (see \ref{couchdb:views}).

Appart from me hopefully being not completely wrong with the filled out descriptions, how would I describe the updates directory? Is this hosting validation functions?

The second question would be how you would describe the evently directory...

If there is a summary for this already existing, please point me to it!

Kind Regards!


问:
Flex Navbar Loses Centering
Pen here.

HTML

```<code><header>
  <div id="logo-div">
    MyLogo
  </div>
  <nav>
    <ul class="nav-list">
      <li class="item">LINK #1</li>
      <li class="item">LINK #2</li>
      <li class="item">LINK #3</li>
      <li class="item">LINK #4</li>
      <li class="item">LINK #5</li>
    </ul>
  </nav>
</header>
</code>```

CSS

```<code>header{
  display: inline-block;
  width: 90%;
}

#logo-div{
  margin-right: 50px;
  float: left;
  font-size: 28px;
  color: red;
  font-weight: 800;
  line-height: 60px;
}

nav{
  float: right;
}

.nav-list{
  display: flex;
  height: 150px;
  width: auto;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  align-items: flex-start;
  align-content: flex-start;
  margin: 0%;
  padding: 0%;
  width: auto;
  list-style-type: none;
}

.item{
  background-color: #d6315d;
  height: 50px;
  width: 150px;
  margin: 5px;
  text-align: center;
  line-height: 45px;
  font-weight: 600;
}
</code>```

Typical website header with inline-block display, logo div on left and navbar on right.
I need to have flex-wrapping navbar to accommodate various device widths, at least until screen-width = 600px where it can be changed to a hamburger. So I make the nav-list height 3 times the height of the list item.
Problem is that if I float the nav block to the right within the header, the nav item-list will only wrap UNDER the logo-div, not beside it.
I can solve this by removing the float from the nav block altogether. But now the nav block drifts to the left on zoom, so the whole page looks off-center.

Anyone got any ideas ?

EDIT

This CodePen achieves the desired effect of stacking nav items on rows within a navbar without the navbar spilling below the logo - at least till screen widths go below ~ 400px.

答:
If I understand correctly you are having an issue with the items not being aligned when the screen is smaller. The best way to do this is using display: flex to get alignment done easily. I have done a sample code and hope it helps your problem (align-items-center aligns all items including your logo to the center in the row when the screen size changes. If you don't need it you can remove it)

HTML

```<code><header>
  <div class="d-flex flex-row align-items-center">
    <div class="logo">
      MyLogo
    </div>
    <nav>
      <ul class="nav-list">
        <li class="item">LINK #1</li>
        <li class="item">LINK #2</li>
        <li class="item">LINK #3</li>
        <li class="item">LINK #4</li>
        <li class="item">LINK #5</li>
      </ul>
    </nav>
  </div>
</header>
</code>```

CSS

```<code>.nav-list {
  display: flex;
  width: auto;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: flex-start;
  margin: 0%;
  padding: 0%;
  list-style-type: none;
}

.item {
  background-color: #d6315d;
  height: 50px;
  width: 150px;
  margin: 5px;
  text-align: center;
  line-height: 45px;
  font-weight: 600;
}

.d-flex {
  display: flex;
}

.flex-row {
  flex-direction: row;
}

.align-items-center {
  align-items: center;
}

.logo {
  margin-right: 50px;
  font-size: 28px;
  color: red;
  font-weight: 800;
}
</code>```

JS Fiddle Link: https://jsfiddle.net/SJ_KIllshot/7u36m194/

Title: Flex Navbar Loses Centering

Body:
Pen here.

HTML

    MyLogo

LINK #1

LINK #2

LINK #3

LINK #4

LINK #5

CSS

header{
  display: inline-block;
  width: 90%;
}

#logo-div{
  margin-right: 50px;
  float: left;
  font-size: 28px;
  color: red;
  font-weight: 800;
  line-height: 60px;
}

nav{
  float: right;
}

.nav-list{
  display: flex;
  height: 150px;
  width: auto;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  align-items: flex-start;
  align-content: flex-start;
  margin: 0%;
  padding: 0%;
  width: auto;
  list-style-type: none;
}

.item{
  background-color: #d6315d;
  height: 50px;
  width: 150px;
  margin: 5px;
  text-align: center;
  line-height: 45px;
  font-weight: 600;
}

Typical website header with inline-block display, logo div on left and navbar on right.
I need to have flex-wrapping navbar to accommodate various device widths, at least until screen-width = 600px where it can be changed to a hamburger. So I make the nav-list height 3 times the height of the list item.
Problem is that if I float the nav block to the right within the header, the nav item-list will only wrap UNDER the logo-div, not beside it.
I can solve this by removing the float from the nav block altogether. But now the nav block drifts to the left on zoom, so the whole page looks off-center.

Anyone got any ideas ?

EDIT

This CodePen achieves the desired effect of stacking nav items on rows within a navbar without the navbar spilling below the logo - at least till screen widths go below ~ 400px.

Body:
If I understand correctly you are having an issue with the items not being aligned when the screen is smaller. The best way to do this is using display: flex to get alignment done easily. I have done a sample code and hope it helps your problem (align-items-center aligns all items including your logo to the center in the row when the screen size changes. If you don't need it you can remove it)

HTML

<header>
  <div class="d-flex flex-row align-items-center">
    <div class="logo">
      MyLogo
    </div>
    <nav>
      <ul class="nav-list">
        <li class="item">LINK #1</li>
        <li class="item">LINK #2</li>
        <li class="item">LINK #3</li>
        <li class="item">LINK #4</li>
        <li class="item">LINK #5</li>
      </ul>
    </nav>
  </div>
</header>

CSS

.nav-list {
  display: flex;
  width: auto;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: flex-start;
  margin: 0%;
  padding: 0%;
  list-style-type: none;
}

.item {
  background-color: #d6315d;
  height: 50px;
  width: 150px;
  margin: 5px;
  text-align: center;
  line-height: 45px;
  font-weight: 600;
}

.d-flex {
  display: flex;
}

.flex-row {
  flex-direction: row;
}

.align-items-center {
  align-items: center;
}

.logo {
  margin-right: 50px;
  font-size: 28px;
  color: red;
  font-weight: 800;
}

JS Fiddle Link: https://jsfiddle.net/SJ_KIllshot/7u36m194/


问:
How to fix errors when using opl.end() in main flow control loop
I'm batch running tens of thousands of tests using a loop inside a main flow control block. Each run of the loop spawns a new OPL model using the designated .dat data file and .mod model file (which is separate from the batch runner .mod file which solely contains the main flow control block).

Because every run of the loop creates a new model, the memory usage builds and builds until it eventually crashes the IDE when I don't use .end() statements to close all of the data structures created for each test. While most of the data structures close just fine, I've found that opl.end(); crashes the tester.

How do I close the OPL models without crashing the tester?

I've tried both the oplide application and the oplrun command line interface, both on macOS and Windows (though I need to run the tests on Windows in the end). I'm using CPLEX Optimization Studio 12.9.

I create the objects using:

```<code>// Create new model
var source = new IloOplModelSource("model-file.mod");
var def = new IloOplModelDefinition(source);
var cp = new IloCP();
var opl = new IloOplModel(def,cp);

// Set next test case as data source
var testCasePath = thisOplModel.TestCaseFilenames[testNumber];
var data = new IloOplDataSource(testCasePath);
opl.addDataSource(data);

// Generate model
opl.generate();
</code>```

And I attempt to close them when I'm done by using:

```<code>data.end();
opl.end(); // Causes it to crash
cp.end();
def.end();
source.end();
</code>```

Edited to add more specific information:
I'm running an RCPSP scheduling problem, using my own model which is a modified version of the built-in example.

Here's a stripped-down version of the code I'm using. I created a run configuration containing just this batch runner .mod file, with the model file and data files it references stored elsewhere:

```<code>using CP;

// Import test case filename data
int NumberOfFiles = 3;
range FileIDs = 0..NumberOfFiles-1;
string TestCaseFilenames[FileIDs] = ["TestCase-01.dat", "TestCase-02.dat", "TestCase-03.dat"];

main {
  var testCaseDirectory = "~/Desktop/TestCases/";

  // Solve each test case in the list
  for (var testNumber = 0; testNumber < thisOplModel.NumberOfFiles; testNumber++) {
    // Create new model
    var source = new IloOplModelSource("RCPSP.mod");
    var def = new IloOplModelDefinition(source);
    var cp = new IloCP();
    var opl = new IloOplModel(def,cp);

    // Set CP parameters
    cp.param.TimeLimit = 5; // Number is in seconds
    cp.param.Workers = 4; // Number of computer cores used
    cp.param.TimeMode = "ElapsedTime"; // How to report time
    cp.param.LogVerbosity = "Quiet"; // How much to write to the engine log

    // Set next test case as data source
    var testCaseFilename = thisOplModel.TestCaseFilenames[testNumber];
    var testCasePath = testCaseDirectory + testCaseFilename;
    var data = new IloOplDataSource(testCasePath);
    opl.addDataSource(data);

    // Generate model
    opl.generate();

    // Report test case name to script log for progress visibility
    writeln(testNumber+1 + ") Solving " + opl.TestCaseFilename + "...");

    // Solve model
    if (cp.solve()) { // Successfully found solution
      // Run solution validation code in model file's post-processing execute statement
        // If a solution is invalid, the entire bath runner will fail with an error at that test and line
      opl.postProcess();

      // Report some solve-dependent results to oplide log for visibility
      writeln(" - UB = " + cp.getObjValue() + ", LB = " + cp.getObjBound()); // Makespan
    } else { // Failed to find solution
      // Report no solution to oplide log for visibility
      writeln(" - No solution found.")
      writeln(" - Lower Bound = " + cp.getObjBound());
    }

    // Report some results to script log for visibility
    writeln(" - Status = " + cp.status); // Solver status
    writeln(" - Solve Time = " + cp.info.SolveTime + " sec"); // Time spent solving

    // End processes to prevent memory leaks
    data.end();
    opl.end(); // Causes it to crash
    cp.end();
    def.end();
    source.end();
  }

  // Confirm to user that tests are complete
  writeln();
  writeln("All done!");
}
</code>```

Here's what the output should be (produced by commenting out the opl.end() line):

```<code>1) Solving TestCase-01.dat...
 - UB = 48, LB = 48
 - Status = 2
 - Solve Time = 1.299999952 sec
2) Solving TestCase-02.dat...
 - UB = 65, LB = 36
 - Status = 1
 - Solve Time = 5.019999981 sec
3) Solving TestCase-03.dat...
 - No solution found.
 - LB = 1
 - Status = 0
 - Solve Time = 5.010000229 sec

All done!
</code>```

Instead, it just logs this output:

```<code>1) Solving TestCase-01.dat...
 - UB = 48, LB = 48
 - Status = 2
 - Solve Time = 1.299999952 sec
</code>```

and then pops up a window with this error message:

Oplrun process is not responding, you must relaunch the Run Configuration.

答:
We sorted this out by email. The reason for the crash is a bug in OPL. The problematic part of the code is something like this:

```<code>tuple T {
  key int id;
  int intArray[0..0];
}

{T} tuples = ...;

T tupleById[1..1];
execute {
  for (var t in tuples)
    tupleById[t.id] = t;
}
</code>```

The problem is the assigment of a tuple that contains an array or set member in scripting. This triggers a bug in OPL that then eventually leads to a crash. A workaround is to initialize tupleById without scripting via

```<code>T tupleById[id in 1..1] = first({ t | t in tuples : t.id == id});
</code>```

The trick here is that all the generated sets are singletons as ids are unique. We then use the first() function to extract the first element from the singleton sets to get plain tuples.

Body:
I'm batch running tens of thousands of tests using a loop inside a main flow control block. Each run of the loop spawns a new OPL model using the designated .dat data file and .mod model file (which is separate from the batch runner .mod file which solely contains the main flow control block).

Because every run of the loop creates a new model, the memory usage builds and builds until it eventually crashes the IDE when I don't use .end() statements to close all of the data structures created for each test. While most of the data structures close just fine, I've found that opl.end(); crashes the tester.

How do I close the OPL models without crashing the tester?

I've tried both the oplide application and the oplrun command line interface, both on macOS and Windows (though I need to run the tests on Windows in the end). I'm using CPLEX Optimization Studio 12.9.

I create the objects using:

// Create new model
var source = new IloOplModelSource("model-file.mod");
var def = new IloOplModelDefinition(source);
var cp = new IloCP();
var opl = new IloOplModel(def,cp);

// Set next test case as data source
var testCasePath = thisOplModel.TestCaseFilenames[testNumber];
var data = new IloOplDataSource(testCasePath);
opl.addDataSource(data);

// Generate model
opl.generate();

And I attempt to close them when I'm done by using:

data.end();
opl.end(); // Causes it to crash
cp.end();
def.end();
source.end();

Edited to add more specific information:
I'm running an RCPSP scheduling problem, using my own model which is a modified version of the built-in example.

Here's a stripped-down version of the code I'm using. I created a run configuration containing just this batch runner .mod file, with the model file and data files it references stored elsewhere:

using CP;

// Import test case filename data
int NumberOfFiles = 3;
range FileIDs = 0..NumberOfFiles-1;
string TestCaseFilenames[FileIDs] = ["TestCase-01.dat", "TestCase-02.dat", "TestCase-03.dat"];

main {
  var testCaseDirectory = "~/Desktop/TestCases/";

  // Solve each test case in the list
  for (var testNumber = 0; testNumber < thisOplModel.NumberOfFiles; testNumber++) {
    // Create new model
    var source = new IloOplModelSource("RCPSP.mod");
    var def = new IloOplModelDefinition(source);
    var cp = new IloCP();
    var opl = new IloOplModel(def,cp);

    // Set CP parameters
    cp.param.TimeLimit = 5; // Number is in seconds
    cp.param.Workers = 4; // Number of computer cores used
    cp.param.TimeMode = "ElapsedTime"; // How to report time
    cp.param.LogVerbosity = "Quiet"; // How much to write to the engine log

    // Set next test case as data source
    var testCaseFilename = thisOplModel.TestCaseFilenames[testNumber];
    var testCasePath = testCaseDirectory + testCaseFilename;
    var data = new IloOplDataSource(testCasePath);
    opl.addDataSource(data);

    // Generate model
    opl.generate();

    // Report test case name to script log for progress visibility
    writeln(testNumber+1 + ") Solving " + opl.TestCaseFilename + "...");

    // Solve model
    if (cp.solve()) { // Successfully found solution
      // Run solution validation code in model file's post-processing execute statement
        // If a solution is invalid, the entire bath runner will fail with an error at that test and line
      opl.postProcess();

      // Report some solve-dependent results to oplide log for visibility
      writeln(" - UB = " + cp.getObjValue() + ", LB = " + cp.getObjBound()); // Makespan
    } else { // Failed to find solution
      // Report no solution to oplide log for visibility
      writeln(" - No solution found.")
      writeln(" - Lower Bound = " + cp.getObjBound());
    }

    // Report some results to script log for visibility
    writeln(" - Status = " + cp.status); // Solver status
    writeln(" - Solve Time = " + cp.info.SolveTime + " sec"); // Time spent solving

    // End processes to prevent memory leaks
    data.end();
    opl.end(); // Causes it to crash
    cp.end();
    def.end();
    source.end();
  }

  // Confirm to user that tests are complete
  writeln();
  writeln("All done!");
}

Here's what the output should be (produced by commenting out the opl.end() line):

1) Solving TestCase-01.dat...
 - UB = 48, LB = 48
 - Status = 2
 - Solve Time = 1.299999952 sec
2) Solving TestCase-02.dat...
 - UB = 65, LB = 36
 - Status = 1
 - Solve Time = 5.019999981 sec
3) Solving TestCase-03.dat...
 - No solution found.
 - LB = 1
 - Status = 0
 - Solve Time = 5.010000229 sec

All done!

Instead, it just logs this output:

1) Solving TestCase-01.dat...
 - UB = 48, LB = 48
 - Status = 2
 - Solve Time = 1.299999952 sec

and then pops up a window with this error message:

Oplrun process is not responding, you must relaunch the Run Configuration.

Body:
We sorted this out by email. The reason for the crash is a bug in OPL. The problematic part of the code is something like this:

tuple T {
  key int id;
  int intArray[0..0];
}

{T} tuples = ...;

T tupleById[1..1];
execute {
  for (var t in tuples)
    tupleById[t.id] = t;
}

The problem is the assigment of a tuple that contains an array or set member in scripting. This triggers a bug in OPL that then eventually leads to a crash. A workaround is to initialize tupleById without scripting via

T tupleById[id in 1..1] = first({ t | t in tuples : t.id == id});

The trick here is that all the generated sets are singletons as ids are unique. We then use the first() function to extract the first element from the singleton sets to get plain tuples.


问:
Applying CSS from an Angular component to a sub-component
We have an in-house Angular component library (one project), each component has basic styling.

We use this library in our App (another project).

A component in the App contains a component from our library.

From the global styles.scss in the App, I can target the elements in the library component just fine.

If I move that global CSS into the App component CSS file, try what may, I cannot target any elements inside the library component.

app-component.html

  <library-component specificityattr></library-component>

```

<p>library-component.html</p>

<pre class="lang-html prettyprint-override"><code><div class="generic-styles">
  <p class="hello">Hello</p>
</div>
</code>```

app-component.scss

```<code>library-component[specificityattr] p.hello {
    background: red;
}
</code>```

styles.scss

```<code>library-component[specificityattr] p.hello {
    background: green;
}
</code>```

Without the selector in styles.scss, I expect the P tag to have a red background.
Only when I put the same selector in styles.scss do I get a green background.

How is this failing?

What is the correct way to style a components sub-components?

答:
What you are experiencing is an effect of the default ViewEncapsulation of components in Angular.

When you define a component such as below, the view encapsulation of the component will be the default value, which I've included inside a comment. This means that Angular won't create a so called 'shadow DOM' for your component, and all the styles will only be applied to your component.

Encapsulated component

```<code>@Component({
    selector: 'my-component',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    //encapsulation: ViewEncapsulation.Emulated
})
</code>```

If you instead want to apply the styles not only to your component, you can specify a specific ViewEncapsulation in your component declaration. Using ViewEncapsulation.None will move the styles to the DOM head, and it will still not create a shadow DOM.

Without encapsulation

```<code>@Component({
    selector: 'my-component',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})
</code>```

Have a look at this StackBlitz example

It's important to keep in mind that ViewEncapsulation.None will "leak" your styles to other components, which in turn will make it harder to style your application unless you know exactly where your styles are defined.

Body:
We have an in-house Angular component library (one project), each component has basic styling.

We use this library in our App (another project).

A component in the App contains a component from our library.

From the global styles.scss in the App, I can target the elements in the library component just fine.

If I move that global CSS into the App component CSS file, try what may, I cannot target any elements inside the library component.

app-component.html

  <library-component specificityattr></library-component>

library-component.html

Hello

app-component.scss

library-component[specificityattr] p.hello {
    background: red;
}

styles.scss

library-component[specificityattr] p.hello {
    background: green;
}

Without the selector in styles.scss, I expect the P tag to have a red background.
Only when I put the same selector in styles.scss do I get a green background.

How is this failing?

What is the correct way to style a components sub-components?

Body:
What you are experiencing is an effect of the default ViewEncapsulation of components in Angular.

When you define a component such as below, the view encapsulation of the component will be the default value, which I've included inside a comment. This means that Angular won't create a so called 'shadow DOM' for your component, and all the styles will only be applied to your component.

Encapsulated component

@Component({
    selector: 'my-component',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    //encapsulation: ViewEncapsulation.Emulated
})

If you instead want to apply the styles not only to your component, you can specify a specific ViewEncapsulation in your component declaration. Using ViewEncapsulation.None will move the styles to the DOM head, and it will still not create a shadow DOM.

Without encapsulation

@Component({
    selector: 'my-component',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})

Have a look at this StackBlitz example

It's important to keep in mind that ViewEncapsulation.None will "leak" your styles to other components, which in turn will make it harder to style your application unless you know exactly where your styles are defined.


答:
You need to make a few changes on your css to achieve what you are looking for.

Edited: ajusted the height to 300px.

#vimeohero {
    background: #eee;
    height: 300px;
    overflow: hidden;
    padding: 0;
    position: relative;
}

iframe {
  box-sizing: border-box;
    height: 56.25vw;
    left: 50%;
    min-height: 100%;
    min-width: 100%;
    transform: translate(-50%, -50%);
    position: absolute;
    top: 50%;
    width: 177.77777778vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="vimeohero">
  <iframe src="https://player.vimeo.com/video/319007333?background=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div></code>```

The snippet dont show the video, see at codepen.

https://codepen.io/flavio-caruso/pen/WBKZqY

Title: Responsive hero with Vimeo background

Body:
You need to make a few changes on your css to achieve what you are looking for.

Edited: ajusted the height to 300px.

#vimeohero {
    background: #eee;
    height: 300px;
    overflow: hidden;
    padding: 0;
    position: relative;
}

iframe {
  box-sizing: border-box;
    height: 56.25vw;
    left: 50%;
    min-height: 100%;
    min-width: 100%;
    transform: translate(-50%, -50%);
    position: absolute;
    top: 50%;
    width: 177.77777778vh;
}

<div id="vimeohero">
  <iframe src="https://player.vimeo.com/video/319007333?background=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>

The snippet dont show the video, see at codepen.

https://codepen.io/flavio-caruso/pen/WBKZqY


问:
store file names of files present on SFTP server in list
I got a code to download 5 days older files from SFTP server. But instead of downloading the files, I want to store the names of 5 days older files into a list. Please help me to modify the code. Thanks in advance

Code I am using right now (based on Download files from SFTP server that are older than 5 days using Python)

```<code>import time

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir_attr(remotedir):
        remotepath = remotedir + "/" + entry.filename
        localpath = os.path.join(localdir, entry.filename)
        mode = entry.st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            if (time.time() - entry.st_mtime) // (24 * 3600) >= 5:
                sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)
</code>```

答:
instead of using sftp.get to download the files, I'm just adding their path to a list, and returning it at the end

import time

def get_r_portable(sftp, remotedir):
    result = []
    for entry in sftp.listdir_attr(remotedir):
        remotepath = remotedir + "/" + entry.filename
        mode = entry.st_mode
        if S_ISDIR(mode):
            result += get_r_portable(sftp, remotepath)
        elif S_ISREG(mode):
            if (time.time() - entry.st_mtime) // (24 * 3600) >= 5:
                result.append(entry.filename)
    return result
```

Body:
I got a code to download 5 days older files from SFTP server. But instead of downloading the files, I want to store the names of 5 days older files into a list. Please help me to modify the code. Thanks in advance

Code I am using right now (based on Download files from SFTP server that are older than 5 days using Python)

import time

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir_attr(remotedir):
        remotepath = remotedir + "/" + entry.filename
        localpath = os.path.join(localdir, entry.filename)
        mode = entry.st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            if (time.time() - entry.st_mtime) // (24 * 3600) >= 5:
                sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)


问:
How to hold collection of files throughout application?
In my mobile application I need to hold a collection of File objects (pictures, documents) that can be accessed throughout the whole application and users can make various operations over the collection:

view all/individual files

upload subsets of the collection to a server

share individual files

...

The collection is initialized only once.

I was wondering if it is a good idea to use a singleton pattern as an object that holds the collection so I do not have to initialize the collection every time user opens a particular screen?

答:
For Java >=1.5</p>

```<code>public enum FileCollector
{
    INSTANCE;
    private FileCollector()
    {
        List _temp = new ArrayList();
        File f = new File("properties");
        _temp.add(f);
         fileContainer = Collections.unmodifiableList(_temp);
    }

   private final Collection<File> fileContainer;

   public Collection<File> getFiles() {
        return fileContainer;
    }

}
</code>```

Body:
For Java >=1.5

public enum FileCollector
{
    INSTANCE;
    private FileCollector()
    {
        List _temp = new ArrayList();
        File f = new File("properties");
        _temp.add(f);
         fileContainer = Collections.unmodifiableList(_temp);
    }

   private final Collection<File> fileContainer;

   public Collection<File> getFiles() {
        return fileContainer;
    }

}