text:
Q: InvocatoinTargetExceptoin when using JavaFx 11 Robot API JavaFx 11 comes with a Robot API and I was excited to use it. The problem is that just instantiating the Robot results in an InvocationTargetException.
Has anyone successfully used the JavaFx 11 Robot, and if so how?
Note: I added JavaFx 11 as a dependency in maven
Edit: Some code that will reproduce the error
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.robot.Robot;
import javafx.stage.Stage;

@Override
public void start(Stage stage) throws Exception {
    Robot robot = new Robot();
    Scene scene = new Scene(new AnchorPane(), 400, 400);
    stage.setScene(scene);
    stage.show();
}
public static void main(String[] args) {
    launch(args);
}

Error
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.base/java.lang.Thread.run(Thread.java:844)

Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:973)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
... 1 more

Caused by: java.lang.NoSuchMethodError: com.sun.javafx.tk.Toolkit.createRobot()Lcom/sun/glass/ui/GlassRobot;
at javafx.scene.robot.Robot.<init>(Robot.java:78)


text:
Q: How to wrap nicely using css columns in a horizontal scrolling layout I am stuck on a problem: I have a horizontally scrolling layout (no vertical scroll), where I want to lay out text content in columns. Since I don't know how long the text will be, I want all the available text to be filled up in columns according to the available space (column width can be fixed, max height is the viewport height).
See the problem illustrated here (resize to see how text flows): https://ldaniel.eu/_/fj-test/text-test.html
Thought I could use CSS columns for it — including column-fill: auto; to let text fill up from left to right instead of evenyl distribute — but it seems that the containing div always tries to fill up the remaining space, even if set to inline-block or flex.
I have been breaking my neck over this problem for a while now, talked about it with some people, but nobody seems to have a solution... is this a limitation of the CSS spec to only work with vertical layouts? Or is it a limitation of my brain to want to solve this with only CSS and leave JS out of it? :)

body {
  font-family: sans-serif;
}

.test-wrapper {
  border: 1px solid red;
}

.block {
  position: relative;
  display: flex;
  height: 250px;
  border: 1px solid blue;
}

.block__text {
  position: relative;
  display: block;
  width: auto;
  height: 100%;
  flex-grow: 0;
  column-width: 200px;
  -moz-column-fill: auto;
  column-fill: auto;
  border: 1px solid cyan;
}

.block__text p {
  border: 1px solid orange;
}

How I work

I work by harnessing the intimate power of words, guiding you through face-to-face, hour-long interviews during which we will detail and dissect your projects, your ambitions, and the obstructions you might be facing. These consultations will occasionally
        alternate with more active exercises designed to restore the natural connection between thoughts and feelings.

While it may feel at first like we are merely chatting, we will be using your own words and actions as leverage to tap the power of your unconscious mind...

Giftedness

Gifted and talented adults face unique challenges made all the more pressing by the normative demands of contemporary life. While their highly functional intellect enables them to conform outwardly to social and professional expectations, these
        coping mechanisms often come at a high personal cost, resulting in silent suffering and the loss of tremendous creative potential.

Giftedness is not solely about IQ, nor is it a badge of honour to be worn in public. In fact, many gifted adults have never undergone an IQ test, nor do they have any reason to. It is, rather, a way of relating to the world, a way that is rich,
        layered, intense, and all-too-often coloured by inner conflicts and a distressing surfeit of information. Giftedness can be both a blessing and a curse: only you can decide.

The joys and pains of gifted individuals have been a particular study of mine ever since I witnessed at first hand what suffering and loneliness these exceptional adults could experience. Today, I am privileged to work with these talented minds
        as they unlock their full potential in fields as diverse as technology, marketing, politics, and the arts (If my name rings a bell, it might be because my mother literally wrote the book on giftedness). The diversity and intensity of their achievements
        never fails to humble and inspire me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sockets update all the users who are subscribed to the model itself expect for the user who got updated I have user get subscribed to chat users, the user has the ability to make himself online or offline through sockets,
One of the users have the role of the manager, where he can force users to be online or offline, through Http request User.update, and the also I added User.publishUpdate to alert the subscribers.
the problem is when the manager turn user from offline to online status, it appears that user is online to other users expect for the user himself who we updated, and  the problem vanish when I enable autoWatch in sails.
here the socket code:
 var query= {authType: 'google'}; //TODO this is temp, currently the staff will see only staff users, until we fix the performance issue
        if (user.dealershipCompany) {
          query = {
            or: [{
              authType: 'google',
              dealershipCompany: null
            }, {
              authType: 'local',
              dealershipCompany: user.dealershipCompany
            }]
          };
        }
        sails.log.info('Chat Users Query:\n', query);
        User.find(query).exec(function (err, chatUsers) {
          if (err) {
            return callback(err, {
              projectedUser: null,
              porjectedChatUsers: null
            });
          } else {
            // remove the logged in users to avoid self messaging
            _.remove(chatUsers, {
              id: userId
            });
          }
          // Subscribe the connected socket to changes in the online state of chatUsers
          User.subscribe(req.socket, chatUsers, 'update');
        });

Here User update:
 update: function (req, res) {
    var id = req.param('id');
    User.findOne(id).exec(function (err, user) {
      if (err)
        res.serverError(err)
      else if (user) {
        var firstName = req.param('firstName') || user.firstName;
        var lastName = req.param('lastName') || user.lastName;
        var role = req.param('role') || user.role;
        var email = req.param('email') || user.email;
        var online = req.param('online') || user.online;
        user.firstName = firstName;
        user.lastName = lastName;
        user.email = email;
        user.role = role;
        user.online = online;
        user.save(function (err, updatedUser) {
          if (err)
            res.serverError(err);

          User.publishUpdate(updatedUser.id, {
            online: updatedUser.online
          }, req);
          res.ok(updatedUser);

        });
      }
      else {
        res.notFound({error: 'User with id: ' + id + ' Could not be found'});
      }

    });
  },

A: Well, the user doesn't get updated status because sails think that the user himself changed his own status and not the manager,  the solution was to create socket listener that listen to the changes of the model and in User.update I send socket with the updatedUserId  and so socket listener check if the user.id equal updatedUserId, it change their own online status.


text:
Q: Pubsub message is missing a timestamp attribute I'm trying to read the timestamp value of a Pubsub message from Apache Beam.
p.apply("Read PubSub messages", PubsubIO.readMessagesWithAttributes()
    .withIdAttribute("msg_id")
    .withTimestampAttribute("timestamp")
    .fromSubscription(options.getPubsubSubscription()))

But unfortunately, I got the following error which really surprises me as I thought every messages had a default timestamp.
An exception occured while executing the Java class.
PubSub message is missing a value for timestamp attribute timestamp

Why is my message not timestamped ? Is it because I published it via the Pubsub UI ?

A: Every Pub/Sub message will have default timestamps assigned if you omit .withTimestampAttribute(). When you add .withTimestampAttribute("timestamp") it implies that you will be providing the timestamps in the timestamp attribute of each message. For example, using the UI:

Then, windowing will be relative to these timestamps and, if you need to access it from within the pipeline, you can use ProcessContext.timestamp() (more details here).


text:
Q: Ionic- display picture taken with camera on same page I'm trying to display image captured through camera on the same page without visiting phone's memory. Somewhat like watsapp, the way we click and upload right away from there only. So, it is like we capture something and display it automatically on the same page, where we have capture button.
 .controller('CameraCtrl', function($scope, $cordovaCamera) {

  document.addEventListener("deviceready", function () {

    var options = {
      quality: 50,
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType: Camera.PictureSourceType.CAMERA,
      allowEdit: true,
      encodingType: Camera.EncodingType.JPEG,
      targetWidth: 100,
      targetHeight: 100,
      popoverOptions: CameraPopoverOptions,
      saveToPhotoAlbum: false,
      correctOrientation:true
    };

    $cordovaCamera.getPicture(options).then(function(imageData) {
        var image = document.getElementById('myImage');
        image.src = "data:image/jpeg;base64," + imageData;
       }, function(err) {
      // error
    });

   }, false);

})

app.js
 .state('tab.detail', {
  url: '/new-order/id',
  views: {
    'tab-new': {
      templateUrl: 'templates/detail.html',
      controller: 'DetailCtrl'
    }
  }
})

.state ('camera',{
  url:'/camera',
  templateUrl: 'templates/detail.html',
  controller:'CameraCtrl'
})

html
       <ion-content>

 </ion-content>

A: you need to declare image.src on the scope like this $scope.image.src="data:image/jpeg;base64," + imageData;
Then in you html bind the image like this


text:
Q: What data-structure should I use to create my own "BigInteger" class? As an optional assignment, I'm thinking about writing my own implementation of the BigInteger class, where I will provide my own methods for addition, subtraction, multiplication, etc.
This will be for arbitrarily long integer numbers, even hundreds of digits long.
While doing the math on these numbers, digit by digit isn't hard, what do you think the best datastructure would be to represent my "BigInteger"?
At first I was considering using an Array but then I was thinking I could still potentially overflow (run out of array slots) after a large add or multiplication.  Would this be a good case to use a linked list, since I can tack on digits with O(1) time complexity?
Is there some other data-structure that would be even better suited than a linked list?  Should the type that my data-structure holds be the smallest possible integer type I have available to me?
Also, should I be careful about how I store my "carry" variable?  Should it, itself, be of my "BigInteger" type?

A: Check out the book C Interfaces and Implementations by David R. Hanson.  It has 2 chapters on the subject, covering the vector structure, word size and many other issues you are likely to encounter.
It's written for C, but most of it is applicable to C++ and/or Java.  And if you use C++ it will be a bit simpler because you can use something like std::vector to manage the array allocation for you.

A: Always use the smallest int type that will do the job you need (bytes). A linked list should work well, since you won't have to worry about overflowing.

A: If you use binary trees (whose leaves are ints), you get all the advantages of the linked list (unbounded number of digits, etc) with simpler divide-and-conquer algorithms. You do not have in this case a single base but many depending the level at which you're working.
If you do this, you need to use a BigInteger for the carry. You may consider it an advantage of the "linked list of ints" approach that the carry can always be represented as an int (and this is true for any base, not just for base 10 as most answers seem to assume that you should use... In any base, the carry is always a single digit)
I might as well say it: it would be a terrible waste to use base 10 when you can use 2^30 or 2^31.

A: Accessing elements of linked lists is slow. I think arrays are the way to go, with lots of bound checking and run time array resizing as needed.

Clarification: Traversing a linked list and traversing an array are both O(n) operations. But traversing a linked list requires deferencing a pointer at each step. Just because two algorithms both have the same complexity it doesn't mean that they both take the same time to run. The overhead of allocating and deallocating n nodes in a linked list will also be much heavier than memory management of a single array of size n, even if the array has to be resized a few times.

A: Wow, there are some… interesting answers here. I'd recommend reading a book rather than try to sort through all this contradictory advice.
That said, C/C++ is also ill-suited to this task. Big-integer is a kind of extended-precision math. Most CPUs provide instructions to handle extended-precision math at comparable or same speed (bits per instruction) as normal math. When you add 2^32+2^32, the answer is 0… but there is also a special carry output from the processor's ALU which a program can read and use.
C++ cannot access that flag, and there's no way in C either. You have to use assembler.
Just to satisfy curiosity, you can use the standard Boolean arithmetic to recover carry bits etc. But you will be much better off downloading an existing library.

A: I would say an array of ints.

A: i would say a std::vector of char (since it has to hold only 0-9) (if you plan to work in BCD)
If not BCD then use vector of int (you didnt make it clear)
Much less space overhead that link list
And all advice says 'use vector unless you have a good reason not too'

A: An Array is indeed a natural fit. I think it is acceptable to throw OverflowException, when you run out of place in your memory. The teacher will see attention to detail.
A multiplication roughly doubles digit numbers, addition increases it by at most 1. It is easy to create a sufficiently big Array to store the result of your operation.
Carry is at most a one-digit long number in multiplication (9*9 = 1, carry 8). A single int will do.

A: std::vector<bool> or std::vector<unsigned int> is probably what you want. You will have to push_back() or resize() on them as you need more space for multiplies, etc. Also, remember to push_back the correct sign bits if you're using two-compliment.

A: As a rule of thumb, use std::vector instead of std::list, unless you need to insert elements in the middle of the sequence very often. Vectors tend to be faster, since they are stored contiguously and thus benefit from better spatial locality (a major performance factor on modern platforms).
Make sure you use elements that are natural for the platform. If you want to be platform independent, use long. Remember that unless you have some special compiler intrinsics available, you'll need a type at least twice as large to perform multiplication.
I don't understand why you'd want carry to be a big integer. Carry is a single bit for addition and element-sized for multiplication.
Make sure you read Knuth's Art of Computer Programming, algorithms pertaining to arbitrary precision arithmetic are described there to a great extent.


text:
Q: RAID array doesn't reassemble after reboot RAID array doesn't assemble after reboot.
I have one SSD from which the system is booted, and three HDD that are part of the array. The system is Ubuntu 16.04.
The steps that I've followed are based mostly on this guide:
https://www.digitalocean.com/community/tutorials/how-to-create-raid-arrays-with-mdadm-on-ubuntu-16-04#creating-a-raid-5-array

*

*Verifying if I'm good to go.
lsblk -o NAME,SIZE,FSTYPE,TYPE,MOUNTPOINT

The output shows sda, sdb, and sdc devices besides the SSD partitions. I've verified if these in fact represent HDDs by looking at output of this:
hwinfo --disk

Everything matches.

*Assembling the array.
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

I verify if it looks OK by entering: cat /proc/mdstat
The output looks something like this:
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sdc[3] sdb[1] sda[0]
      7813774336 blocks super 1.2 level 5, 512k chunk, algorithm 2 [3/2] [UU_]
      [=======>.............]  recovery = 37.1% (1449842680/3906887168) finish=273.8min speed=149549K/sec
      bitmap: 0/30 pages [0KB], 65536KB chunk

unused devices: <none>

I wait till the process ends.
Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10]
md0 : active raid5 sdc[3] sdb[1] sda[0]
      209584128 blocks super 1.2 level 5, 512k chunk, algorithm 2 [3/3] [UUU]

unused devices: <none>

*Creating and mounting the filesystem.
sudo mkfs.ext4 -F /dev/md0

sudo mkdir -p /mnt/md0

sudo mount /dev/md0 /mnt/md0

df -h -x devtmpfs -x tmpfs

I put some data in, and the output looks like this:
Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p2  406G  191G  196G  50% /
/dev/nvme0n1p1  511M  3.6M  508M   1% /boot/efi
/dev/md0        7.3T  904G  6.0T  13% /mnt/md0

*Saving the array layout.
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf

sudo update-initramfs -u

echo '/dev/md0 /mnt/md0 ext4 defaults,nofail,discard 0 0' | sudo tee -a /etc/fstab

*Rebooting and verifying if everything works correctly.
After reboot I try:
    cat /proc/mdstat
It isn't showing any active raid devices.
ls /mnt/md0

is empty.
The following command isn't printing anything and doesn't work either:
mdadm --assemble --scan -v

Only the following restores the array with data on it:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

What should be done differently?
Additional, probably useful info:
sudo dpkg-reconfigure mdadm

The output shows:
update-initramfs: deferring update (trigger activated)
Generating grub configuration file ...
Warning: Setting GRUB_TIMEOUT to a non-zero value when GRUB_HIDDEN_TIMEOUT is set is no longer supported.
Found linux image: /boot/vmlinuz-4.4.0-51-generic
Found initrd image: /boot/initrd.img-4.4.0-51-generic
Found linux image: /boot/vmlinuz-4.4.0-31-generic
Found initrd image: /boot/initrd.img-4.4.0-31-generic
Adding boot menu entry for EFI firmware configuration
done
update-rc.d: warning: start and stop actions are no longer supported; falling back to defaults
Processing triggers for initramfs-tools (0.122ubuntu8.5) ...
update-initramfs: Generating /boot/initrd.img-4.4.0-51-generic

The intriguing part for me is "start and stop actions are no longer supported; falling back to defaults"
Also the output of /usr/share/mdadm/mkconf doesn't print any arrays at the end.
# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default (built-in), scan all partitions (/proc/partitions) and all
# containers for MD superblocks. alternatively, specify devices to scan, using
# wildcards if desired.
#DEVICE partitions containers

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR craftinity@craftinity.com

# definitions of existing MD arrays

whereas the output of cat /etc/mdadm/mdadm.conf does.
# mdadm.conf
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default (built-in), scan all partitions (/proc/partitions) and all
# containers for MD superblocks. alternatively, specify devices to scan, using
# wildcards if desired.
#DEVICE partitions containers

# DEVICE /dev/sda /dev/sdb /dev/sdc

# auto-create devices with Debian standard permissions
CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR craftinity@craftinity.com

# definitions of existing MD arrays

# This file was auto-generated on Sun, 04 Dec 2016 18:56:42 +0100
# by mkconf $Id$

ARRAY /dev/md0 metadata=1.2 spares=1 name=hinton:0 UUID=616991f1:dc03795b:8d09b1d4:8393060a

What's the solution? I've browsed through half the internet and no one seems to have the same problem.
I've also added the exact same question on serverfault a couple of days ago (no answer). I apologize if I violated stack exchange's community rules by doing that.

A: I had the same problem, I am not sure but the work around I have found was to create new partitions on the raid members of type LINUX Raid and then when creating the array I used the partition rather than using the device.

A: It seems, this is quite a common problem when using whole disks in an array.
This post gives the latest summary of the problem and how I solved it: mdadm RAID underlaying an LVM gone after reboot
This post helped me to understand and solve my problem: What's the difference between creating mdadm array using partitions or the whole disks directly

A: I was unable to reproduce your exact problem, but I think I found a possible reason for the behavior of your system:
When you create the 3 disk RAID5 array with the command:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

While the RAID device is in recovery, the mdadm scan command shows:
sudo mdadm --detail --scan
ARRAY /dev/md0 metadata=1.2 spares=1 name=desktop:0 UUID=da60c69a:1cbe4f2e:e83d0971:0520ac89

After the recovery process is completed, the spares=1 parameter is gone:
sudo mdadm --detail --scan
ARRAY /dev/md0 metadata=1.2 name=desktop:0 UUID=da60c69a:1cbe4f2e:e83d0971:0520ac89

I assume, that reassembling the 3 disk read with the spares=1 parameter will fail on a fully recovered software RAID5, since you don't have any more spared disks. If you try to assemble a RAID with the following command, it will fail:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 --spare-devices=1 /dev/sda /dev/sdb /dev/sdc

and the next command will create a different RAID layout:
sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=2 --spare-devices=1 /dev/sda /dev/sdb /dev/sdc

On a different note: If you don't need to boot from the RAID5, there is no need to add the configuration to the /etc/mdadm/mdadm.conf file. Ubuntu will automatically start the RAID, since the configuration is available in the RAID superblock.

A: I had the exact same problem.  Solved by:
$ sudo update-initramfs -u

followed by a reboot

A: The solution is the following: You scan all drives that do not carry your OS. Then you choose from those what drives you want to select. Before creating any RAID you need to format the drives to a compatible format like ext4. See my example bash code to select all drives from a rented computer except the OS drive and build a RAID0 for maximum speed to later form a fast database node.
{
  #database here
  cd "/home/$1/UltiHash/"
  cwd=$(pwd)
  sudo systemctl start postgresql.service
  sudo service postgresql restart
  if ! [[ $(sudo -u postgres psql --command='SHOW data_directory') == *"/mnt/md0/postgresql/13/main"* ]]; then
    sudo chown -R ${mainuser} /home/${mainuser}/
    echo "${passwd}\n${passwd}\n" | sudo passwd postgres
    echo "postgres password set!"
    sudo usermod -aG sudo postgres
    echo "Configured postgres as a root user"
    sudo postgres -D /usr/local/pgsql/data > logfile 2>&1 &
    version=$(psql --version)
    cutter="$(cut -d ' ' -f 3- <<< "$version" )" && tmpcut="${cutter%% *}"
    folver="${tmpcut%%.*}"
    cd /etc/postgresql/${folver}/main
    sudo -u postgres psql --command="ALTER USER postgres WITH PASSWORD '${passwd}';"
    sudo -u postgres psql --command="CREATE USER admin WITH PASSWORD '${passwd}';"
    sudo -u postgres psql --command="ALTER USER admin WITH SUPERUSER;"
    sudo -u postgres psql --command="ALTER USER admin CREATEDB;"
    sudo service postgresql restart
    sudo systemctl stop postgresql
    cd ~/

    #unmask cinnamon
    if [[ $(file /lib/systemd/system/x11-common.service) == "/lib/systemd/system/x11-common.service: symbolic link to /dev/null" ]]; then
      sudo rm /lib/systemd/system/x11-common.service
      sudo apt-get install --reinstall x11-common
      sudo systemctl daemon-reload
      #systemctl status x11-common
    fi

    #scan drives except OS drive
    drivelist=""
    count=0
    os_drive_path="$(df -hT | grep /$ | awk -F " " '{print $1}')"
    os_drive=${os_drive_path%p*}
    no_dev=${os_drive#*/dev/}
    NL=$'\n'
    while read line; do
      if [[ ($line == *nvme* || $line == sd*) && ! ( $line == *"${no_dev}"* ) ]]; then
        drivelist="${drivelist}/dev/${line}${NL}"
        count=$((count+1))
      fi
    done <<< "$(lsblk -f)"

    #create partitions on the free drives directly in ext4 format
    drivelist_overrideable=""
    while read line; do
      drivename=$(echo "$line" | awk -F " " '{print $1}')
      drivelist_overrideable="${drivelist_overrideable}${drivename}${NL}"
      if [[ $drivename == *nvme* ]]; then
        sudo mkfs.ext4 -b 1024 -m 0 -F "$drivename"
      else
        sudo mkfs.ext4 -m 0 -F "$drivename"
      fi
    done <<< "${drivelist}"

    #now we know what has been formatted, so we know the hardware name, now we must scan again and mount the partition to the files created
    #create RAID0
    printf "Y\n" | sudo mdadm --create --verbose /dev/md0 --level=0 --raid-devices="${count}" ${drivelist_overrideable}
    cat /proc/mdstat
    sudo mkfs.ext4 -b 1024 -m 0 -F /dev/md0
    sudo mkdir -p /mnt/md0
    sudo chown -R benjamin-elias /mnt/md0
    sudo chmod -R 777 /mnt/md0
    sudo mount /dev/md0 /mnt/md0
    df -h -x devtmpfs -x tmpfs
    hardware_uid_string=$(sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf)
    sudo update-initramfs -u
    echo "$(echo "${hardware_uid_string}" | awk -F " " '{print $5}') /mnt/md0 ext4 defaults,nofail,discard 0 0" | sudo tee -a /etc/fstab
    sudo update-initramfs -u

    #safely move database
    sudo rsync -av /var/lib/postgresql /mnt/md0
    sudo mv /var/lib/postgresql/${folver}/main /var/lib/postgresql/${folver}/main.bak
    sudo chown -R postgres /mnt/md0/

    postgresconf="/etc/postgresql/${folver}/main/postgresql.conf"
    sudo cp -f ${postgresconf} ${postgresconf}.bak

    while read line; do
        if [[ $line == data_directory* ]]; then
          echo "data_directory = '/mnt/md0/postgresql/${folver}/main'" | sudo tee -a "${postgresconf}"
        else
          echo "${line}" | sudo tee -a "${postgresconf}"
        fi
    done <<< $(cat ${postgresconf}.bak)

    #setup ports
    sudo sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" ${postgresconf}

    postgresconf="/etc/postgresql/${folver}/main/pg_hba.conf"

    while read line; do
      echo "${line}" | sudo tee -a "${postgresconf}"
      ipadress=$(echo "${line}" | awk -F " " '{print $4}')
      echo $ipadress
      ipfilter=${ipadress%%/*}
      echo $ipfilter
      sudo iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d ${ipfilter} --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT
      sudo iptables -A OUTPUT -p tcp -s ${ipfilter} --sport 5432 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT
    done <<< $(cat /home/${mainuser}/UltiHash/trust_host.txt)
    #restart to load changes
    sudo systemctl start postgresql
    sudo systemctl status postgresql
    #setup firewall
    echo "$(sudo -u postgres psql --command="SHOW data_directory;")"
    sudo rm -Rf /var/lib/postgresql/${folver}/main.bak
    sudo ufw allow 5432/tcp
    sudo systemctl restart postgresql
    sudo systemctl status postgresql
  fi
}||{
  echo "Could not configure database!"
}


text:
Q: How to prevent a GWT Flash/ActionScript component from reloading when visibility is toggled? I have a Google Web Toolkit (GWT) application that utilizes a Flash/PaperVision3D component that I have created. The GWT app places instances of the Flash component on different tabs in a tab panel. During execution of the app, everything works great until the user starts clicking in between tabs. At the GWT level, the JavaScript is changing the style.display attribute to hide and show the contents of the 'tabs'. It appears that the Flash component (included in the page by scripting an 'embed' tag) is reloading/restarting each time that it is made visible.
How can I prevent it from restarting/reloading? I don't have much control at all over the fact that the DIV tag is getting set to style.display = 'none', as that is being controlled by the autogenerated GWT code. Is there some setting perhaps in the Flex/Flash development to allow it to do this? Or maybe in the Embed tag?  Or even at the JavaScript level?

A: Apparently this is a Firefox bug. It doesn't appear to be a problem in Internet Explorer.
A possible solution would be to already have the Flash elements hidden and positioned absolutely ("position: absolute; visibility: hidden;") and then bring them into visibility via a JavaScript function called when the user clicks on a tab.
Depending on the complexity of the Flash files, you could also use the ExternalInterface object, which allows for communication between JavaScript functions and ActionScript. You could save the current state of the movie and then dump this state information back in when the the user clicks on the tab.
Sorry I couldn't be more help.


text:
Q: How to concatenate two columns in my case using SQL? I have 2 tables called Standards and StandardDetails
Standards
ItemID       ItemCode       BranchID
------------------------------------
135576       555            1111
135576       555            2222

StandardDetails
ItemID       ItemCode       BranchID      RcItemCode      Numbers
-----------------------------------------------------------------
135576       555               1111       555              22
135576       555               1111       556              23

135576       555               2222       555              77
135576       555               2222       556              29
135576       555               2222       557              46

I want to concatenate two columns RcItemCode and Numbers from StandardDetails and expected result looks like this:
ItemID       ItemCode       BranchID    RcCodes
------------------------------------------------------------------
135576       555            1111        555-22,556-23
135576       555            2222        555-77,556-29,557-46

Seriously have no clue for converting rows into column and concatenate it.
Note

I need to make it as a VIEW

A: You may try this. Use group by for grouping your id and stuff to concatenate your Code into comma separated values.
; with cte as (
select ItemID,ItemCode,BranchID,RcItemCode + '-' + Numbers as Code from StandardDetails
)
select ItemID,ItemCode,BranchID,
Stuff( (select ', ' + code from cte as c
       where c.ItemID = ct.ItemID and c.ItemCode = ct.ItemCode  and c.BranchID = ct.BranchID
       for xml path('')),1,1,'') as RCode
from cte as ct
group by ItemID,ItemCode,BranchID

For View
Please try this.

Create view MyView
As
Begin
select ItemID,ItemCode,BranchID,
Stuff( (select ', ' + code from (select ItemID,ItemCode,BranchID,RcItemCode + '-' + Numbers as Code from StandardDetails) as c
       where c.ItemID = ct.ItemID and c.ItemCode = ct.ItemCode  and c.BranchID = ct.BranchID
       for xml path('')),1,1,'') as RCode
from StandardDetails as ct
group by ItemID,ItemCode,BranchID
End


text:
Q: NGSI update attributes from complex entities in Wirecloud Is it possible to update a child attribute through the updateAttributes() function from Wirecloud NGSI API?
For example, a coordinate (entity.location.coords.coordinates[0]=-2.000000) in this piece of entity.
   "attrNames": [ "A1", "A2", "position" ],
   "creDate": 1389376081,
   "modDate": 1389376244,
   "location": {
       "attrName": "position",
       "coords": {
           "type": "Point",
           "coordinates": [ -3.691944, 40.418889 ]
       }

EDITED
My own answer: It is possible by passing an object as value of the attribute.
ngsi.updateAttributes([
                    {
                        'entity': {'id': "entity-id"},
                        'attributes':[{
                          "name":"location","contextValue": {
                               "attrName": "position",
                               "coords": {
                                     "type": "Point",
                                     "coordinates": [ -2.000000, 40.418889 ]
                               }
                          }
                        }]
                    }
                ], {
                    onSuccess: onUpdateAttributesSuccess,
                    onFailure: onUpdateAttributesFail
                }
            );

However, Wirecloud is using NGSI API v1, therefore all attributes are treated as strings when they are sent/received to/from Orion.
More info: http://fiware-orion.readthedocs.io/en/master/user/structured_attribute_valued/

A: Currently, it's not possible to make partial changes into an structure attribute using the WireCloud's NGSI API. Moreover, as far as I know, the NGSI API doesn't provide a direct way for making partial updates into structured attributes (neither v1 nor v2).
However, v1 of the NGSI API supports structured attribute values. So you can make use of the updateContext method to update only one attribute (e.g. the coordinates attribute). The only thing to take into account it's that you will have to provide the full value, so if you want to make a partial change you have to read the value, make the partial change and update it.
In fact, you almost have it working. You only have to fix the way you are passing the attributes to update, you should wrap them into an array:
ngsi.updateAttributes([{
        "entity": {"id": "entity-id"},
        "attributes": [
            {
                "name": "location",
                "contextValue": {
                    "attrName": "position",
                    "coords": {
                        "type": "Point",
                        "coordinates": [-2.000000, 40.418889]
                    }
                }
            }
        ]
    }],
    {
        onSuccess: onUpdateAttributesSuccess,
        onFailure: onUpdateAttributesFail
    }
);


text:
Q: Extreme differences in Odds Ratios in Logistic Regression with or without a predictor I was trying to get an intuition for the interpretation of the coefficients in a logistic regression that was intended to reproduce to some extent that presented in a youtube video (http://youtu.be/vq-_4kWmzTo).
So I created a fictitious data set reflecting the chances of getting accepted (Accepted: int: 0 0 ... 1 0) into a college as related to SAT scores (int 1136 1347 1504) and family/ethnic background (categories = "red" vs "blue").
fit <- glm(Accepted ~ Background - 1,data=dat,
           family="binomial")
exp(cbind(OR = coef(fit),confint(fit)))

yielded:
                      OR     2.5 %    97.5 %
Backgroundblue 0.7088608 0.5553459 0.9017961
Backgroundred  1.7352941 1.3632702 2.2206569

The interpretation seemed easy: Red applicants have 1.7 times more chances of getting in over the rest; blue applicants were at a disadvantage, and had  7 over 10 odds of getting in.
However, the more complete model,
fit <- glm(Accepted ~ SAT.scores + Background - 1,
           data=dat, family="binomial")
exp(cbind(OR = coef(fit),confint(fit)))

yielded coefficients for background that are difficult to reconcile or interpret:
                             OR        2.5 %       97.5 %
    SAT.scores     1.008558e+00 1.006940e+00 1.010297e+00
    Backgroundblue 8.730056e-06 8.459031e-07 7.634723e-05
    Backgroundred  2.329513e-05 2.426748e-06 1.929259e-04

Can you help point out what I am missing?
Thanks to the enlightening answer from Maarten below, I was able to make some progress, and obtain the correct Odds Ratios without and with the SAT confounder:
Here is just regressing to Background ("Red" versus "Blue"):
fit <- glm(Accepted ~ Background, data = dat,
           family = "binomial")
exp(cbind(Odds_Ratio_RedvBlue = coef(fit),
    confint(fit)))
                            Odds_Ratio_RedvBlue             2.5 %       97.5 %
    (Intercept)             0.7088608                     0.5553459   0.9017961
    Backgroundred           2.4480042                     1.7397640   3.4595454
``
Which brought up a couple of additional questions (probably very basic):

 1. Why is the Odds Ratio of the (Intercept) - 0.7088608 - the same for this model as for the *Odds* - as opposed to *Odds Ratio* - of the Background Blue in the model without the intercept above? And

 2. Shouldn't the OddsRatio of Blue and Red be the reciprocal of each other $OddsRatioBlue = 1 / OddsRatioRed$?

A: Your interpretation of the numbers in your model is incorrect because you used an unusual (but not incorrect) parameterization. You omitted the constant and included both categories of family background. As a consequence the coefficients labeled OR are not Odds Ratios but just odds. In this case the odds of being accepted  for someone with blue background in your first model is 0.71, which you can interpret as for every person with blue background that is not accepted you expect to find 0,71 persons with blue back ground that is accepted. Notice that this does not involve a comparison between blue and red backgrounds, it just a quantification of the likelihood that someone with blue background is accepted. If you had included the constant and excluded the variable backgroundred, your interpretation would be correct (but the numbers would obviously be different). For more on these different but equivalent parameterizations see here.
By adding the (uncentered) SAT scores your background variables now estimate the odds of being accepted for someone with an SAT score of 0. This odds is not surprisingly very very small regardless of family background. You can get more meaningful estimates when you center SAT scores at some meaningful number. Say that meaningful number is 1200 (I know next to nothing about SAT scores), than you just create a new variable that is the original SAT scores minus 1200 and you add that new variable to your model instead of the original. Your background variables now measure the odds of being accepted for someone with an SAT score of 1200.

Additional question 1: your original model and your new model are just different ways of saying the same thing, so it is not a surprise that some coefficients are the same. As you can guess, the exponentiated constant is not an odds ratio but an odds. To be precise the odds of success for the reference category, in your case blue background. Your old model said "This is the odds of success for blue background, and that is the odds of success for the red background". Your new model says "This is the odds of success for the blue background, and the odds of success for someone with a red background is a factor such and so smaller/larger". For the two models to be equivalent the exponentiated constant in your new model should be the same as the exponentiated coefficient of backgroundblue in your old model. The ratio of exponentiated coefficients of backgroundblue and backgroundred in your old model should be the same as the exponentiated coefficient of backgroundred in your new model. This is indeed the case $\frac{1.7352941}{0.7088608}=2.448004$.
Additional quesiton 2: yes, try and estimate your new model with backgroundblue instead of backgroundred and you'll see that that is the case.


text:
Q: How can i find GMT from given date I have a date like 2017-08-12 11:30:00 and i want to display Date as
sat, 12 aug 2017 11:30 am( 06:00 GMT )  i get sat, 12 aug 2017 11:30 am using following code
    let myDate = "2017-08-12 11:30:00"

    let date = myDate.date(format: .custom("yyyy-MM-dd HH:mm:ss"))
    let strDate = date?.string(format: .custom("EEE, dd MMM yyyy hh:mm a"))
    let localDate = strDate?.date(format: .custom("EEE, dd MMM yyyy hh:mm a"))
    let strLocalDate = localDate?.string(format: .custom("EEE, dd MMM yyyy hh:mm a"))

but how can i find GMT ?
for GMT i have also tried formatter.timeZone = TimeZone(identifier:"GMT") but it didn't work.
please help,
Thanks!

A: Try this code.I have tested, it is working for me in swift3.0.
        let myDate = "2017-08-12 11:30:00"
        let localDateFormat = DateFormatter()
        localDateFormat.dateFormat = "YYYY-mm-dd hh:mm:ss"
        let localDate = localDateFormat.date(from: myDate)
        localDateFormat.dateFormat = "EEE, dd MMM yyyy hh:mm a"
        let myNewDate = localDateFormat.string(from: localDate!)
        print(myNewDate)
        //GMT Date
        let gmtDateFormat = DateFormatter()
        gmtDateFormat.dateFormat = "HH:mm a"
        gmtDateFormat.timeZone = NSTimeZone(abbreviation: "GMT")! as TimeZone
        let gmtDateString = gmtDateFormater.string(from: localDate!)
        print(gmtDateString)

        print("time:\(myNewDate)(\(gmtDateString))")

A: Do you want show time with zone ? If yes, you need to use  zzz format. According to the your code please see the code.
        let strLocalDate = localDate?.string(format: .custom("EEE, dd MMM yyyy hh:mm a zzz"))

if you have text date then you need to set the timezone as well.
formatter.timeZone = TimeZone(identifier: "GMT");

Please let me know about the answer, will give example to set timezone


text:
Q: Compute a function from a loop to apply it in a list of dataframe I have a dataframe df
    structure(list(ID = structure(c(8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L,
9L, 9L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 12L, 12L,
13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L, 17L,
17L, 17L, 18L, 18L, 18L, 18L, 18L, 18L, 20L, 20L, 20L, 40L, 40L,
40L, 40L, 40L, 40L, 40L, 57L, 57L, 62L, 62L, 62L, 70L, 70L, 70L,
70L, 70L, 2L, 2L, 2L, 43L, 43L, 43L, 43L, 43L, 43L, 43L, 46L,
46L, 46L, 46L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L), .Label = c("AU-Tum",
"BE-Bra", "BR-Sa3", "CA-Ca1", "CA-Ca2", "CA-Ca3", "CA-Gro", "Ca-Man",
"CA-NS1", "CA-NS2", "CA-NS3", "CA-NS4", "CA-NS5", "CA-NS6", "CA-NS7",
"CA-Oas", "CA-Obs", "CA-Ojp", "CA-Qcu", "CA-Qfo", "CA-SF1", "CA-SF2",
"CA-SF3", "CA-SJ1", "CA-SJ2", "CA-SJ3", "CA-TP1", "CA-TP2", "CA-TP4",
"CZ-Bk1", "DE-Har", "DE-Wet", "DK-Sor", "FI-Hyy", "FR-Hes", "FR-Pue",
"ID-Pag", "IT-Ro1", "IT-Ro2", "IT-Sro", "JP-Tak", "JP-Tef", "NL-Loo",
"SE-Abi", "SE-Fla", "SE-Nor", "SE-Sk1", "SE-Sk2", "SE-St1", "UK-Gri",
"US-Blo", "US-Bn1", "US-Bn2", "Us-Bn3", "US-Dk3", "US-Fmf", "US-Fwf",
"US-Ha1", "US-Ha2", "US-Ho1", "US-Ho2", "US-Lph", "US-Me1", "US-Me3",
"US-Nc2", "US-NR1", "US-Sp1", "US-Sp2", "US-Sp3", "US-Umb", "US-Wcr",
"US-Wi0", "US-Wi1", "US-Wi2", "US-Wi4", "US-Wi8"), class = "factor"),
    x = c(156, 157, 160, 162, 163, 164, 165, 153, 154, 155, 71,
    72, 73, 74, 37, 38, 39, 40, 41, 39, 40, 22, 23, 24, 12, 13,
    14, 15, 16, 4, 5, 6, 7, 74, 75, 76, 77, 78, 79, 80, 81, 82,
    126, 127, 128, 129, 130, 131, 132, 71, 72, 73, 74, 75, 76,
    99, 100, 101, 49, 50, 51, 52, 53, 54, 56, 9, 10, 46, 47,
    48, 84, 85, 86, 87, 88, 77, 78, 79, 101, 105, 106, 107, 108,
    109, 110, 81, 82, 84, 88, 131, 132, 133, 134, 135, 136, 137,
    138, 139), y = c(50.0472381226718, 706.825824817992, 729.621982051409,
    593.225827791495, 685.154353165934, 574.088067465695, 650.30821636616,
    494.185166497016, 436.312162090908, 631.891738044098, 280.949480787385,
    641.231373456365, 412.116433330579, 416.824746264203, 415.905685925856,
    494.374217984441, 201.745910386788, 486.030122926459, 647.782697262242,
    389.839577941515, 256.552344558528, 605.790549736819, 483.045965372879,
    668.017897433514, 35.2706101682852, 265.693628564011, 285.116345260642,
    291.023782284086, 357.428790589795, 205.920375034591, 229.606221692753,
    230.952761338012, 241.641164634028, 1089.06303295676, 1255.88808925333,
    1087.75402177912, 1068.248897182, 1212.17254891642, 884.222588171535,
    938.887718005513, 863.582247020735, 1065.91969416523, 902.338968377328,
    790.570635510725, 834.500908313203, 710.755041345197, 814.002362551197,
    726.814950022846, 828.559687148314, 611.564698476112, 603.238720579422,
    524.322001078981, 565.296378873638, 532.431853589369, 597.174114277044,
    606.075737104722, 686.408686154056, 705.914347674276, 1858.98340779543,
    1893.38468471169, 1819.83262739703, 1827.31409981102, 1640.5816780664,
    1689.0365549922, 2112.67917439342, 479.374777290737, 326.663507855032,
    1184.81825619942, 1281.2920902365, 1269.12480160726, 1265.48484068702,
    1193.29000986667, 1156.81486114406, 1199.7373066445, 1116.24029749935,
    1100.47051284742, 1072.57190890331, 1228.25697739795, 1576.32775748242,
    1631.14609672129, 1796.87265141308, 1712.90461264737, 1844.87409764528,
    1938.56225809082, 1663.52108450048, 1626.12740687071, 1333.52924151719,
    1349.01338642137, 1376.41668179166, 1362.32371946308, 1317.75608457439,
    1519.12511487596, 1558.26111694807, 1588.8933303128, 1624.50100837374,
    1433.10019567201, 1371.01498340943, 1439.94849821774)), .Names = c("ID",
"x", "y"), row.names = c(290L, 291L, 292L, 293L, 294L, 295L,
296L, 297L, 298L, 299L, 300L, 301L, 302L, 303L, 304L, 305L, 306L,
307L, 308L, 309L, 310L, 311L, 312L, 313L, 314L, 315L, 316L, 317L,
318L, 319L, 320L, 321L, 322L, 323L, 324L, 325L, 326L, 327L, 328L,
329L, 330L, 331L, 332L, 333L, 334L, 335L, 336L, 337L, 338L, 339L,
340L, 341L, 342L, 343L, 344L, 351L, 352L, 353L, 424L, 425L, 426L,
427L, 428L, 429L, 430L, 471L, 472L, 493L, 494L, 495L, 512L, 513L,
514L, 515L, 516L, 266L, 267L, 268L, 438L, 439L, 440L, 441L, 442L,
443L, 444L, 451L, 452L, 453L, 454L, 484L, 485L, 486L, 487L, 488L,
489L, 490L, 491L, 492L), class = "data.frame")

I wanted to compute a the model efficiency in a cross validation leave one subject out mode on this dataframe by using one non-linear function, which I have implemented as such:
library(stats)
library (hydroGOF)

Out <- c()
id <- unique(df$ID)
for (i in id){
  fit1 <- try(nls(y~A*x^3+B*x^2+C*x+D, data = df[df$ID != i,], start = list(A=0.02, B=-0.6, C= 50, D=200)), silent=TRUE)
  Out[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=df[df$ID==i,])
}

MEF<- NSE(Out, df$y)

However, I would like to create a function out of it in order to apply it in n dataframe with the same structure but by also including two non-linear functions in the loop. I have started to implement this line of codes but without success.
stat <- function(dat) {
  id <- unique(dat$ID)
  Out<-c()
  Out2<-c()
  for (i in id){
    fit1 <- try(nls(y~A*(x^B)*(exp(k*x)), data = dat[dat$ID != i,], start = list(A = 1000, B = 0.170, k = -0.00295)), silent=TRUE);
    Out[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
fit2 <- try(nls(y~A*x^2+B*x+C, data = dat[dat$ID != i,], start = list(A=-0.4, B=50, C= 300)), silent=TRUE);
    Out2[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
c(Out, Out2)
}}

df.list<-list(df) # Here I put only one dataframe but it will be more than one.

res<-lapply(df.list, stat)

Anyone could solve my issue?

A: I didn't get if you want it to output the NSE result or just the Out and Out2 so I included two variations.
First of all I think your function needs to list Out and Out2 instead of using c which will concatenate the two.
Then you can do:
stat <- function(dat) {
  id <- unique(dat$ID)
  Out<-c()
  Out2<-c()
  for (i in id){
    fit1 <- try(nls(y~A*(x^B)*(exp(k*x)), data = dat[dat$ID != i,], start = list(A = 1000, B = 0.170, k = -0.00295)), silent=TRUE);
    Out[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
    fit2 <- try(nls(y~A*x^2+B*x+C, data = dat[dat$ID != i,], start = list(A=-0.4, B=50, C= 300)), silent=TRUE);
    Out2[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
  }

  list(Out, Out2)
  #list(NSE(Out, dat$y), NSE(Out2, dat$y))
}

Which will output just Out and Out2 on which then you could use NSE:
df.list<-list(df) # Here I put only one dataframe but it will be more than one.

res<-lapply(df.list, stat)
> res
[[1]]
[[1]][[1]]
 [1] 1293.19052 1296.35786 1291.80408 1290.99605 1298.77649 1288.68723 1280.85556 1274.29969   73.09179  137.39803  199.57234  253.22724  306.64911  767.04455
[15]  805.64571  830.52502  852.82856  392.31343  392.76582  381.99857  471.69255  468.30934 1213.32652 1318.90282 1336.20432 1331.59450 1093.61066  776.19050
[29]  816.66237  855.65923  347.74230  411.60219 1187.15420 1175.01320 1169.16425 1160.33162 1148.21352 1145.15265 1134.55927 1126.44445 1112.65676  667.97854
[43]  656.19839  654.13085  639.01529  635.08903  620.08683 1222.46503 1214.07093 1206.90274 1197.26398 1188.93353 1178.60658  142.68868  209.94101  278.51757
[57]  339.27000  401.06092  952.40556  939.72216  928.89347  627.67858  671.42009  217.45400 1229.16628 1303.97471 1305.00665 1303.10220 1306.25091 1302.15214
[71] 1284.16542 1268.00061 1252.26307 1241.32474 1236.48697 1234.85012 1273.66465 1283.02331 1305.82044 1316.90994  137.40424 1326.03716 1323.69234  896.51028
[85]  936.55168  945.38984  937.21832  919.84053  909.75825 1088.71144 1080.18786 1070.87042 1059.73379 1051.40485 1239.73625 1215.11176 1193.85910

[[1]][[2]]
 [1] 1293.19052 1296.35786 1291.80408 1290.99605 1298.77649 1288.68723 1280.85556 1274.29969   73.09179  137.39803  199.57234  253.22724  306.64911  767.04455
[15]  805.64571  830.52502  852.82856  392.31343  392.76582  381.99857  471.69255  468.30934 1213.32652 1318.90282 1336.20432 1331.59450 1093.61066  776.19050
[29]  816.66237  855.65923  347.74230  411.60219 1187.15420 1175.01320 1169.16425 1160.33162 1148.21352 1145.15265 1134.55927 1126.44445 1112.65676  667.97854
[43]  656.19839  654.13085  639.01529  635.08903  620.08683 1222.46503 1214.07093 1206.90274 1197.26398 1188.93353 1178.60658  142.68868  209.94101  278.51757
[57]  339.27000  401.06092  952.40556  939.72216  928.89347  627.67858  671.42009  217.45400 1229.16628 1303.97471 1305.00665 1303.10220 1306.25091 1302.15214
[71] 1284.16542 1268.00061 1252.26307 1241.32474 1236.48697 1234.85012 1273.66465 1283.02331 1305.82044 1316.90994  137.40424 1326.03716 1323.69234  896.51028
[85]  936.55168  945.38984  937.21832  919.84053  909.75825 1088.71144 1080.18786 1070.87042 1059.73379 1051.40485 1239.73625 1215.11176 1193.85910

Or use:
stat <- function(dat) {
  id <- unique(dat$ID)
  Out<-c()
  Out2<-c()
  for (i in id){
    fit1 <- try(nls(y~A*(x^B)*(exp(k*x)), data = dat[dat$ID != i,], start = list(A = 1000, B = 0.170, k = -0.00295)), silent=TRUE);
    Out[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
    fit2 <- try(nls(y~A*x^2+B*x+C, data = dat[dat$ID != i,], start = list(A=-0.4, B=50, C= 300)), silent=TRUE);
    Out2[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
  }

  #list(Out, Out2)
  c(NSE(Out, dat$y), NSE(Out2, dat$y))
}

If you want it to output the NSEs instead:
df.list<-list(df) # Here I put only one dataframe but it will be more than one.

res<-lapply(df.list, stat)
> res
[[1]]
[1] 0.3125795 0.3125795

Edit for answering the comment:
stat <- function(dat) {
  id <- nrow(dat)
  Out<-c()
  Out2<-c()
  for (i in 1:id){
    fit1 <- try(nls(y~A*(x^B)*(exp(k*x)), data = dat[-i,], start = list(A = 1000, B = 0.170, k = -0.00295)), silent=TRUE);
    Out[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[i,]) else NA;
    fit2 <- try(nls(y~A*x^2+B*x+C, data = dat[-i,], start = list(A=-0.4, B=50, C= 300)), silent=TRUE);
    Out2[i] <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[i,]) else NA;
  }

  #list(Out, Out2)
  c(NSE(Out, dat$y), NSE(Out2, dat$y))
}

> stat(df)
[1] 0.2571609 0.2571609

Edit2:
stat <- function(dat) {
  id <- unique(dat$ID)
  NSEs<-list()
  for (i in id){
    fit1 <- try(nls(y~A*(x^B)*(exp(k*x)), data = dat[dat$ID != i,], start = list(A = 1000, B = 0.170, k = -0.00295)), silent=TRUE);
    Out <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
    fit2 <- try(nls(y~A*x^2+B*x+C, data = dat[dat$ID != i,], start = list(A=-0.4, B=50, C= 300)), silent=TRUE);
    Out2 <- if (inherits(fit1, "nls")) sim = predict(fit1, newdata=dat[dat$ID==i,]) else NA;
    NSEs[[length(NSEs)+1]] <- c(NSE(Out, dat$y[dat$ID == i]), NSE(Out2, dat$y[dat$ID == i]))
  }
  NSEs
}

> stat(df)
[[1]]
[1] -4.218322 -4.218322

[[2]]
[1] -27.30966 -27.30966

[[3]]
[1] -35.98506 -35.98506

[[4]]
[1] -10.89336 -10.89336

[[5]]
[1] -73.49176 -73.49176
#and so on...

A: output <- sapply(
  seq_len(nrow(df)),
  function(i){
    model <- list(
      try(
        nls(
          y ~ A * (x ^ B) * (exp(k * x)),
          data = df[-i,],
          start = list(A = 1000, B = 0.170, k = -0.00295)
        ),
        silent=TRUE
      ),
      try(
        nls(
          y ~ A * x ^ 2 + B * x + C,
          data = df[-i,],
          start = list(A = -0.4, B = 50, C= 300)
        ),
        silent=TRUE
      )
    )
    sapply(model, function(x){
      ifelse(
        class(x) == "try-error",
        NA,
        predict(x, newdata = df[i, ])
      )
    })
  }
)


text:
Q: Passing enum item to child component in template I try to pass enum item to the child compoenent:
 <app-enum-selection  [itemIgnore]=DataStatus.Coming_Soon ></app-enum-selection>

But I get this error:
 error TS2339: Property 'DataStatus' does not exist on type 'ConstructorComponent'.

  <app-enum-selection [itemIgnore]=DataStatus.Coming_Soon></app-enum-selection>

  src/app/constructor/constructor.component.ts:29:16
   templateUrl: './constructor.component.html',

    Error occurs in the template of component ConstructorComponent.

Any Idea why I get error? And how to pass enum item to child component?

A: Try like this:
Parent Component:
enum DataStatus{
    Coming_Soon,
    ...
}

export class ParentComponent {
    public dataStatus = DataStatus;
}

Child Component:
export class ChildComponent {
    @Input() public set itemIgnore(value: any) {
        console.log(value);
    };
}

Parent Component Template:
Your child component selector (assuming app-enum-selection) inside parent component (assuming ConstructorComponent) will be like this:
<app-enum-selection [itemIgnore]=dataStatus.Coming_Soon ></app-enum-selection>

Child Component Template:
<div>{{itemIgnore}}</div>


text:
Q: Report Builder 3.0 always consider Month perameter as default perameter I have the reports with Month as Input parameter also had the other parameters. When I open the Reports getting the data for data default month October.
I have data for November month also. So in reports when I change the month to November as report parameter then view the report getting the report data for November month successfully.
But when I Open the report in Report Builder It is pulling the report data for default month October. Though I have changed the Month parameter to November and view the report in Report Builder it always getting October month data.
Please advice.


text:
Q: How to use sleep time on another Selenium's driver (with threading) in Pyhton3 I've been working on two sites and I tried to make use of one driver's sleep time on another Selenium's driver by using threading library but so far it doesn't seem to work in the way I thought it would. So, I'm looking for an explanation, suggestion and fix to my problem.
This is an example code.
import threading
from selenium import webdriver
import time

def go_Yahoo():
    driver = webdriver.Firefox()
    driver.get('https://www.yahoo.com/')
    time.sleep(10)
    driver.find_element_by_xpath('//*[@id="uh-search-box"]').clear()
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="uh-search-box"]').send_keys('facebook')
    time.sleep(7)
    driver.find_element_by_xpath('//*[@id="uh-search-button"]').click()

def go_Bing():
    driver = webdriver.Firefox()
    driver.get('https://www.bing.com/')
    time.sleep(5)
    driver.find_element_by_xpath('//*[@id="sb_form_q"]').clear()
    time.sleep(3)
    driver.find_element_by_xpath('//*[@id="sb_form_q"]').send_keys('facebook')
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="sb_form_go"]').click()

t1 = threading.Thread(target=go_Yahoo())
t2 = threading.Thread(target=go_Bing())
t1.start()
t2.start()
t1.join()
t2.join()

So, I thought that while 'go_Yahoo()' was asleep, 'go_Bing()' would kick in. However, I was incorrect somehow. I would like to know why and how I can fix it.
Thx.

A: If we starting two drives in multi threading mode, it doesn't mean it will run in one step of driver 1 and another step in driver 2, so on. Both will run in parallel if your machine is with dual processors. It can both drivers will be sleep at a time. we can't decide the steps order inside each thread.
if your machine have only one processor then each thread will be executed in allocated processor time in time sliced mode. But It looks like parallel even though it uses single processor.
Even though, we set time.sleep after each step. we don't have control on another thread sleep time.


text:
Q: vb.net "invalid parameter passed to C runtime function" I use vs2015.
I see this in Immediate Window:

"Invalid parameter passed to C runtime function. Invalid parameter
  passed to C runtime function."

After this line
 Dim response = req.GetResponse().GetResponseStream()

What is this problem? The program not crashing, it's just strange.


text:
Q: Why does IContext.RetractLinked require two parameters? I added a linked fact using:
context.InsertLinked(longOrderKey, longOrder);

At some point later, I want to remove this fact.  It's easy for me to construct the key without having the record:
var longOrderKey = (managedAccount.AccountId, PositionType.Long, fungible.FungibleId);

So why do I need the record when removing a linked fact using the method:
context.RetractLinked(longOrderKey, longOrder);

Why can't this method just use the longOrderKey?  What if I don't have the 'longOrder' record.  Do I really need to look it up before I can remove it?

A: Linked facts are tied to an activation that created them. The purpose of the key is to be able to identify the specific fact if the activation produced more than one linked fact. If you are inserting just one linked fact in the RHS of a rule, you can really set the key to anything, e.g. "1"; if you were to insert two facts, you could set keys to "1" and "2", and so on. In essence, the key is to identify the linked fact within the activation. The fact itself is needed, so that the engine can find the corresponding entries in the working memory. Much like ISession.Retract requires the fact object, so that it can find it in the working memory.
Another point is that in most scenarios you should not need to retract the linked facts as they would get retracted automatically, once the activation gets deleted (i.e. the conditions that created the activation become false).


text:
Q: How does ActiveRecord enforce has_one relationship? How does ActiveRecord enforce the has_one relationship? (versus has_many relationship)
It seems that it does NOT and I have to create a unique constraint using migration
(that is, on the MySQL table level).
I think ActiveRecord should handle this constraint and not rely on the database\
table-level enforcement.
Have I missed something?

A: I think it doesn't force the unique constraint. It works almost exactly like has_many does, except that when the database query is executed to retrieve the related object, a LIMIT 1 clause is added to the generated SQL.


text:
Q: PHP S3 upload progress This has gone around a number of times but I'm still a bit bewildered. A lot of answers only copncern themselves with talking about upload progress bars and not getting the actual upload progress from an S3 upload.
I have read a number of questions and found a number of software pieces but I am still no closer to understanding the fundamental question of S3 uploads.
Is there a way of uploading to S3 while understanding the progress of that upload without having to use my own app servers resources to store the file in the temp directory first?
Do I have to store the file on my own server first and then push to S3? I have heard people talk about streaming bit at a time to S3 (one chunk at a time) but I am unsure what this involves. Imagine I was uploading from client side in a HTML page how would I stream the file chunk by chunk from a multi-part from as it comes in? (I don't see any example of that only an example of when the file is already on your system and you know the chunks which is kinda useless tbh).
There is of course an example of upload progress in the API docs but again that is assuming the file is on your server first and is not coming from another computer supplied by the user.
EDIT: My original thought was to make a PHP script that could ping AWS once every so oftern getting upload progress. I am looking through the API to see if they do support something like that but atm no luck. Let me know if there is something...
Further EDIT: Is flash the only way to go with this?
Thanks,

A: YES, it is possible in AWS PHP SDK v3.
$client = new S3Client(/* config */);

$result = $client->putObject([
    'Bucket'     => 'bucket-name',
    'Key'        => 'bucket-name/file.ext',
    'SourceFile' => 'local-file.ext',
    'ContentType' => 'application/pdf',
    'params' => [
            '@http' => [
                'progress' => function ($downloadTotalSize, $downloadSizeSoFar, $uploadTotalSize, $uploadSizeSoFar) {
                    printf(
                        "%s of %s downloaded, %s of %s uploaded.\n",
                        $downloadSizeSoFar,
                        $downloadTotalSize,
                        $uploadSizeSoFar,
                        $uploadTotalSize
                    );
                }
            ]
    ]
]);

This is explained in the AWS docs - S3 Config section. It works by exposing GuzzleHttp's progress property-callable, as explained in this SO answer.

A: After a lot of searching around I found the simple answer to this question is NO.
Basically the best way to do this, as I have found out from Amazons own coding (their little uploading widget on the AWS S3 console) it is only really possible to get upload progress by sending to another server first which PHP can read for progress information.
This creates a 'pass-through' policy using your own app servers /tmp directory as the stepping stone. This seems to be the preferred method.

A: AWS PHP SDK has a code example where they show upload progress while uploading to S3. I am not sure if its valid for small files but for streaming it sure works.
You can check more out at - http://aws.amazon.com/sdkforphp/
In a way if they are showing progress - we surely can get that in the form of a progress bar with the help of a Javascript framework like jquery etc.
I shall be working on it very soon and will surely post a tutorial. Cheers!

A: Yes you can via multipart uploading: http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMPphpAPI.html
Multipart uploading is a three-step process: You initiate the upload, you upload the object parts, and after you have uploaded all the parts, you complete the multipart upload. Upon receiving the complete multipart upload request, Amazon S3 constructs the object from the uploaded parts, and you can then access the object just as you would any other object in your bucket.
http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html
I will be doing this personally very soon but this is what you need to start.

A: Yes,you can do this by modifying s3.php like this,
<?php
class S3Withprogressbar {
// ACL flags
const ACL_PRIVATE = 'private';
const ACL_PUBLIC_READ = 'public-read';
const ACL_PUBLIC_READ_WRITE = 'public-read-write';
private static $__accessKey; // AWS Access key
private static $__secretKey; // AWS Secret key
public static $_uploadProgressFileName="" ;//uploadProgressFileName
public function __construct($accessKey = null, $secretKey = null) {
if ($accessKey !== null && $secretKey !== null)
self::setAuth($accessKey, $secretKey);
}
public static function setAuth($accessKey, $secretKey) {
self::$__accessKey = $accessKey;
self::$__secretKey = $secretKey;
}
public static function listBuckets($detailed = false) {
$rest = new S3Request('GET', '', '');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
$results = array(); //var_dump($rest->body);
if (!isset($rest->body->Buckets)) return $results;
if ($detailed) {
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
$results['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID
);
$results['buckets'] = array();
foreach ($rest->body->Buckets->Bucket as $b)
$results['buckets'][] = array(
'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)
);
} else
foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
return $results;
}
public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null) {
$rest = new S3Request('GET', $bucket, '');
if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
if ($marker !== null && $prefix !== '') $rest->setParameter('marker', $marker);
if ($maxKeys !== null && $prefix !== '') $rest->setParameter('max-keys', $maxKeys);
$response = $rest->getResponse();
if ($response->error === false && $response->code !== 200)
$response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
if ($response->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING);
return false;
}
$results = array();
$lastMarker = null;
if (isset($response->body, $response->body->Contents))
foreach ($response->body->Contents as $c) {
$results[(string)$c->Key] = array(
'name' => (string)$c->Key,
'time' => strToTime((string)$c->LastModified),
'size' => (int)$c->Size,
'hash' => substr((string)$c->ETag, 1, -1)
);
$lastMarker = (string)$c->Key;
//$response->body->IsTruncated = 'true'; break;
}
if (isset($response->body->IsTruncated) &&
(string)$response->body->IsTruncated == 'false') return $results;
// Loop through truncated results if maxKeys isn't specified
if ($maxKeys == null && $lastMarker !== null && (string)$response->body->IsTruncated == 'true')
do {
$rest = new S3Request('GET', $bucket, '');
if ($prefix !== null) $rest->setParameter('prefix', $prefix);
$rest->setParameter('marker', $lastMarker);
if (($response = $rest->getResponse(true)) == false || $response->code !== 200) break;
if (isset($response->body, $response->body->Contents))
foreach ($response->body->Contents as $c) {
$results[(string)$c->Key] = array(
'name' => (string)$c->Key,
'time' => strToTime((string)$c->LastModified),
'size' => (int)$c->Size,
'hash' => substr((string)$c->ETag, 1, -1)
);
$lastMarker = (string)$c->Key;
}
} while ($response !== false && (string)$response->body->IsTruncated == 'true');
return $results;
}
public function putBucket($bucket, $acl = self::ACL_PRIVATE) {
$rest = new S3Request('PUT', $bucket, '');
$rest->setAmzHeader('x-amz-acl', $acl);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
//trigger_error(sprintf("S3Withprogressbar::putBucket({$bucket}): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public function deleteBucket($bucket = '') {
$rest = new S3Request('DELETE', $bucket);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::deleteBucket({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function inputFile($file, $md5sum = true) {
if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
trigger_error('S3Withprogressbar::inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
return false;
}
return array('file' => $file, 'size' => filesize($file),
'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum :
base64_encode(md5_file($file, true))) : '');
}
public static function inputResource(&$resource, $bufferSize, $md5sum = '') {
if (!is_resource($resource) || $bufferSize <= 0) {
trigger_error('S3Withprogressbar::inputResource(): Invalid resource or buffer size', E_USER_WARNING);
return false;
}
$input = array('size' => $bufferSize, 'md5sum' => $md5sum);
$input['fp'] =& $resource;
return $input;
}
// Modified Function with one more  parameter $uploadProgressFileName
public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null,$uploadProgressFileName) {
if ($input == false) return false;
$rest = new S3Request('PUT', $bucket, $uri);
// Set public variable value($uploadProgressFileName) in S3Request class
$rest->uploadProgressFileName = $uploadProgressFileName;
if (is_string($input)) $input = array(
'data' => $input, 'size' => strlen($input),
'md5sum' => base64_encode(md5($input, true))
);
// Data
if (isset($input['fp']))
$rest->fp =& $input['fp'];
elseif (isset($input['file']))
$rest->fp = @fopen($input['file'], 'rb');
elseif (isset($input['data']))
$rest->data = $input['data'];
// Content-Length (required)
if (isset($input['size']) && $input['size'] > 0)
$rest->size = $input['size'];
else {
if (isset($input['file']))
$rest->size = filesize($input['file']);
elseif (isset($input['data']))
$rest->size = strlen($input['data']);
}
// Content-Type
if ($contentType !== null)
$input['type'] = $contentType;
elseif (!isset($input['type']) && isset($input['file']))
$input['type'] = self::__getMimeType($input['file']);
else
$input['type'] = 'application/octet-stream';
// We need to post with the content-length and content-type, MD5 is optional
if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) {
$rest->setHeader('Content-Type', $input['type']);
if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
$rest->setAmzHeader('x-amz-acl', $acl);
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
$rest->getResponse();
} else
$rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false) {
//trigger_error(sprintf("S3Withprogressbar::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
return false;
}
return true;
}
// Modified Function with one more  parameter $uploadProgressFileName
public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null,$uploadProgressFileName) {
return self::putObject(S3Withprogressbar::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType,$uploadProgressFileName);
}
public function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
}
public static function getObject($bucket = '', $uri = '', $saveTo = false) {
$rest = new S3Request('GET', $bucket, $uri);
if ($saveTo !== false) {
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = @fopen($saveTo, 'wb')) == false)
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
return false;
}
$rest->file = realpath($saveTo);
return $rest->response;
}
public static function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) {
$rest = new S3Request('HEAD', $bucket, $uri);
$rest = $rest->getResponse();
if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getObjectInfo({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
}
public static function setBucketLogging($bucket, $targetBucket, $targetPrefix) {
$dom = new DOMDocument;
$bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
$bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
$loggingEnabled = $dom->createElement('LoggingEnabled');
$loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
$loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
// TODO: Add TargetGrants
$bucketLoggingStatus->appendChild($loggingEnabled);
$dom->appendChild($bucketLoggingStatus);
$rest = new S3Request('PUT', $bucket, '');
$rest->setParameter('logging', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::setBucketLogging({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function getBucketLogging($bucket = '') {
$rest = new S3Request('GET', $bucket, '');
$rest->setParameter('logging', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getBucketLogging({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
if (!isset($rest->body->LoggingEnabled)) return false; // No logging
return array(
'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
);
}
public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
$dom = new DOMDocument;
$dom->formatOutput = true;
$accessControlPolicy = $dom->createElement('AccessControlPolicy');
$accessControlList = $dom->createElement('AccessControlList');
// It seems the owner has to be passed along too
$owner = $dom->createElement('Owner');
$owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
$owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
$accessControlPolicy->appendChild($owner);
foreach ($acp['acl'] as $g) {
$grant = $dom->createElement('Grant');
$grantee = $dom->createElement('Grantee');
$grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
$grantee->setAttribute('xsi:type', 'CanonicalUser');
$grantee->appendChild($dom->createElement('ID', $g['id']));
} elseif (isset($g['email'])) { // AmazonCustomerByEmail
$grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
$grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
} elseif ($g['type'] == 'Group') { // Group
$grantee->setAttribute('xsi:type', 'Group');
$grantee->appendChild($dom->createElement('URI', $g['uri']));
}
$grant->appendChild($grantee);
$grant->appendChild($dom->createElement('Permission', $g['permission']));
$accessControlList->appendChild($grant);
}
$accessControlPolicy->appendChild($accessControlList);
$dom->appendChild($accessControlPolicy);
$rest = new S3Request('PUT', $bucket, '');
$rest->setParameter('acl', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function getAccessControlPolicy($bucket, $uri = '') {
$rest = new S3Request('GET', $bucket, $uri);
$rest->setParameter('acl', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
$acp = array();
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) {
$acp['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
);
}
if (isset($rest->body->AccessControlList)) {
$acp['acl'] = array();
foreach ($rest->body->AccessControlList->Grant as $grant) {
foreach ($grant->Grantee as $grantee) {
if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
$acp['acl'][] = array(
'type' => 'CanonicalUser',
'id' => (string)$grantee->ID,
'name' => (string)$grantee->DisplayName,
'permission' => (string)$grant->Permission
);
elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
$acp['acl'][] = array(
'type' => 'AmazonCustomerByEmail',
'email' => (string)$grantee->EmailAddress,
'permission' => (string)$grant->Permission
);
elseif (isset($grantee->URI)) // Group
$acp['acl'][] = array(
'type' => 'Group',
'uri' => (string)$grantee->URI,
'permission' => (string)$grant->Permission
);
else continue;
}
}
}
return $acp;
}
public static function deleteObject($bucket = '', $uri = '') {
$rest = new S3Request('DELETE', $bucket, $uri);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::deleteObject(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function __getMimeType(&$file) {
$type = false;
// Fileinfo documentation says fileinfo_open() will use the
// MAGIC env var for the magic file
if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
if (($type = finfo_file($finfo, $file)) !== false) {
// Remove the charset and grab the last content-type
$type = explode(' ', str_replace('; charset=', ';charset=', $type));
$type = array_pop($type);
$type = explode(';', $type);
$type = array_shift($type);
}
finfo_close($finfo);
// If anyone is still using mime_content_type()
} elseif (function_exists('mime_content_type'))
$type = mime_content_type($file);
if ($type !== false && strlen($type) > 0) return $type;
// Otherwise do it the old fashioned way
static $exts = array(
'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
'zip' => 'application/zip', 'gz' => 'application/x-gzip',
'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
);
$ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
}
public static function __getSignature($string) {
return 'AWS '.self::$__accessKey.':'.base64_encode(extension_loaded('hash') ?
hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1(
(str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^
(str_repeat(chr(0x36), 64))) . $string)))));
}
}
final class S3Request {
private $verb, $bucket, $uri, $resource = '', $parameters = array(),
$amzHeaders = array(), $headers = array(
'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
);
public $fp = false, $size = 0, $data = false, $response;
public $uploadProgressFileName;
function __construct($verb, $bucket = '', $uri = '') {
$this->verb = $verb;
$this->bucket = strtolower($bucket);
$this->uri = $uri !== '' ? '/'.$uri : '/';
if ($this->bucket !== '') {
$this->bucket = explode('/', $this->bucket);
$this->resource = '/'.$this->bucket[0].$this->uri;
$this->headers['Host'] = $this->bucket[0].'.s3.amazonaws.com';
$this->bucket = implode('/', $this->bucket);
} else {
$this->headers['Host'] = 's3.amazonaws.com';
if (strlen($this->uri) > 1)
$this->resource = '/'.$this->bucket.$this->uri;
else $this->resource = $this->uri;
}
$this->headers['Date'] = gmdate('D, d M Y H:i:s T');
$this->response = new STDClass;
$this->response->error = false;
$this->response->body  = false;
$CI =& get_instance();
$CI->load->helper('file');
}
public function setParameter($key, $value) {
$this->parameters[$key] = $value;
}
public function setHeader($key, $value) {
$this->headers[$key] = $value;
}
public function setAmzHeader($key, $value) {
$this->amzHeaders[$key] = $value;
}
//:callback function for upload progress.
public function progressCallback_new_curl($new,$download_size, $downloaded_size, $upload_size, $uploaded_size )
{
ob_start();
static $previousProgress = 0;
if ( $upload_size == 0 )
$progress = 0;
else
$progress = round( $uploaded_size * 100 / $upload_size );
if ( $progress > $previousProgress)
{
flush();
$previousProgress = $progress;
$new_file_path = FCPATH.'upload/'.$this->uploadProgressFileName.'.txt'; // modify this line to point to the actual location of the file
write_file($new_file_path, $progress."\n");
// Check for Cancel upload text file and if exists return 1 to interrupt curl upload process.
$cancel_path=FCPATH.'upload/cancel_'.$this->uploadProgressFileName.'.txt';
if(file_exists($cancel_path)){
unlink($cancel_path);
if(file_exists($new_file_path)){
unlink($new_file_path);
}
return 1;
}
}
ob_flush();
flush();
}
public function progressCallback_old_curl($download_size, $downloaded_size, $upload_size, $uploaded_size )
{
ob_start();
static $previousProgress = 0;
if ( $upload_size == 0 )
$progress = 0;
else
$progress = round( $uploaded_size * 100 / $upload_size );
if ( $progress > $previousProgress)
{
flush();
$previousProgress = $progress;
$new_file_path = FCPATH.'upload/'.$this->uploadProgressFileName.'.txt'; // modify this line to point to the actual location of the file
write_file($new_file_path, $progress."\n");
// Check for Cancel upload text file and if exists return 1 to interrupt curl upload process.
$cancel_path=FCPATH.'upload/cancel_'.$this->uploadProgressFileName.'.txt';
if(file_exists($cancel_path)){
unlink($cancel_path);
if(file_exists($new_file_path)){
unlink($new_file_path);
}
return 1;
}
}
ob_flush();
flush();
}
public function getResponse() {
$query = '';
if (sizeof($this->parameters) > 0) {
$query = substr($this->uri, -1) !== '?' ? '?' : '&';
foreach ($this->parameters as $var => $value)
if ($value == null || $value == '') $query .= $var.'&';
else $query .= $var.'='.$value.'&';
$query = substr($query, 0, -1);
$this->uri .= $query;
if (isset($this->parameters['acl']) || !isset($this->parameters['logging']))
$this->resource .= $query;
}
$url = (extension_loaded('openssl')?'https://':'http://').$this->headers['Host'].$this->uri;
//var_dump($this->bucket, $this->uri, $this->resource, $url);
// Basic setup
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_URL, $url);
//:callback function call for upload progress.
curl_setopt($curl, CURLOPT_NOPROGRESS, false);
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50500) {
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION,  array($this, 'progressCallback_old_curl'));
} else {
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION,  array($this, 'progressCallback_new_curl'));
}
// Headers
$headers = array(); $amz = array();
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $headers[] = $header.': '.$value;
foreach ($this->headers as $header => $value)
if (strlen($value) > 0) $headers[] = $header.': '.$value;
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value;
$amz = (sizeof($amz) > 0) ? "\n".implode("\n", $amz) : '';
// Authorization string
$headers[] = 'Authorization: ' . S3Withprogressbar::__getSignature(
$this->verb."\n".
$this->headers['Content-MD5']."\n".
$this->headers['Content-Type']."\n".
$this->headers['Date'].$amz."\n".$this->resource
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
// Request types
switch ($this->verb) {
case 'GET': break;
case 'PUT':
if ($this->fp !== false) {
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $this->fp);
if ($this->size > 0)
curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
} elseif ($this->data !== false) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
if ($this->size > 0)
curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size);
} else
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'HEAD':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_NOBODY, true);
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default: break;
}
// Execute, grab errors
if (curl_exec($curl))
$this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
else
$this->response->error = array(
'code' => curl_errno($curl),
'message' => curl_error($curl),
'resource' => $this->resource
);
@curl_close($curl);
// Parse body into XML
if ($this->response->error === false && isset($this->response->headers['type']) &&
$this->response->headers['type'] == 'application/xml' && isset($this->response->body)) {
$this->response->body = simplexml_load_string($this->response->body);
// Grab S3 errors
if (!in_array($this->response->code, array(200, 204)) &&
isset($this->response->body->Code, $this->response->body->Message)) {
$this->response->error = array(
'code' => (string)$this->response->body->Code,
'message' => (string)$this->response->body->Message
);
if (isset($this->response->body->Resource))
$this->response->error['resource'] = (string)$this->response->body->Resource;
unset($this->response->body);
}
}
// Clean up file resources
if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);
return $this->response;
}
private function __responseWriteCallback(&$curl, &$data) {
if ($this->response->code == 200 && $this->fp !== false)
return fwrite($this->fp, $data);
else
$this->response->body .= $data;
return strlen($data);
}
private function __responseHeaderCallback(&$curl, &$data) {
if (($strlen = strlen($data)) <= 2) return $strlen;
if (substr($data, 0, 4) == 'HTTP')
$this->response->code = (int)substr($data, 9, 3);
else {
list($header, $value) = explode(': ', trim($data));
if ($header == 'Last-Modified')
$this->response->headers['time'] = strtotime($value);
elseif ($header == 'Content-Length')
$this->response->headers['size'] = (int)$value;
elseif ($header == 'Content-Type')
$this->response->headers['type'] = $value;
elseif ($header == 'ETag')
$this->response->headers['hash'] = substr($value, 1, -1);
elseif (preg_match('/^x-amz-meta-.*$/', $header))
$this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;
}
return $strlen;
}
}
?>


text:
Q: I removed Boot Camp the hard way, but then I got a Windows error anyway. Should I be concerned? The short version:
I was running Boot Camp on my Retina MacBook Pro, but I decided just recently to ditch it because I never use it and I'd like to reclaim the space. The official method of removing it with Boot Camp Assistant failed so I went the harder route involving booting into Internet Recovery mode and deleting the partitions manually, which worked and gave me the space back - except when I rebooted I got a Windows screen telling me booting failed, and when I hold down OPTION on a boot I still see "Windows" as an option.
If I pick OS X when I hold down OPTION it boots like I want it to but on a restart it still gave me the Windows error screen. Booting into Internet Recovery again and setting "Macintosh HD" as the Startup Disk seems to have fixed it and now on subsequent reboots I'm in OS X like I want again, but I can still see "Windows" as an option as I hold down OPTION on reboot.
Is there any way to get rid of this "ghost" of Windows/Boot Camp on my system and if there's not, is this something I should be concerned with?
The long version
So here's the sequence of events:

*

*Got my rMBP in 10/2014

*A few months later I added Boot Camp, initially with Windows 8.1 and later upgraded to Windows 10

*The other day I decided to ditch Boot Camp as it's taking up space and I never use it.

*Did a few different backups

*Uninstalling Boot Camp via the Boot Camp Assistant didn't work, which is apparently really common

*Read online that the next best thing is deleting the Boot Camp partitions directly and/or modifying them to appease Boot Camp Assistant

*Tried removing the Boot Camp partition in Disk Utility. It wouldn't let me. (By the way, Disk Utility is really crappy and unusable in El Capitan - they've removed the old standard partitioning method and replaced them with a PIE CHART that doesn't work half the time)

*Did lots of reading, a fair amount of panicking, and booted into Internet Recovery mode

*Using the Disk Utility in Internet Recovery Mode (which is the old one from Mavericks/Yosemite, yay) I was able to do a series of maneuvers that, long story short, allowed me to delete the Boot Camp partition - along with a couple of others that, I'm guessing, are artifacts of Windows/Boot Camp - and got back to one big huge partition. I happily restarted...

*...and was presented with a clearly-from-Microsoft screen (fonts, colors, etc.) saying Windows couldn't load. At this point I've got the "No! We killed you!" scene from Robocop going through my head

*Reboot, hold down OPTION, and I see Macintosh HD and Windows. I pick Macintosh HD

*OS X boots up, I have all my space back, life is wonderful

*Reboot the Mac to see what happens and I'm back in Windows error land

*Back in OS X (after rebooting and holding down OPTION again) I go to Startup Disk in System Preferences and try to set Macintosh HD as the start disk but it won't let me do anything because there's only one hard drive now and as far as it can tell it's already the startup disk

*I booted the Mac into Internet Recovery mode and set the Startup Disk to Macintosh HD (since, I'm guessing, when you're in Internet Recovery mode you're booting off of the temporary-from-the-Internet disk) and restarted.

*Mac restarts in OS X like I want it to

*Reboot again, Mac still restarts in OS X like I want it to. Did this a few times to be sure.

*Reboot again, hold down OPTION, I can still see Windows as an option but I don't know where it's coming from

So basically things are where I want them to - except there's this "ghost" of my Boot Camp install lingering. Is there any way to get rid of it? And failing that, can I just ignore it safely?

A: You did a good job removing the Widows related partitions. I assume your Windows 10 was an EFI/GPT install, therefore you probably still have code left in the EFI partition (disk0s1).
To view the contents of this EFI partition you have to mount it. You can do so with the command shown below.
sudo diskutil mount /dev/disk0s1

Below is a what I have in my EFI partition. I do not have any EFI dependent operating systems installed. If you have any folders that are Microsoft related, you can delete them. For example, the folder EFI/Microsoft.

You can also look for the folder EFI/BOOT. The apple firmware will recognize the file bootx64.efi in this folder as the default name for removable operating systems. You can delete this folder.
When finished, unmount the EFI partition with the following command.
diskutil unmount /dev/disk0s1

A: This worked a treat but for slow learners like myself it might be worth mentioning that after you mount EFI using the command window you then go to finder to look whats inside it and after deleting everything windows from EFI using finder you then return to the command line to unmount the EFI. But it worked brilliantly. Thanks


text:
Q: When using hyperref, references links doesn't work and turn into (??) When I use hyperref, my links just turn into (??).
Reproducible code:
\documentclass[12pt,a4paper,notitlepage,twoside]{article}

%\usepackage[hyphens]{url}
\usepackage[alf]{abntex2cite}  %My package for citations
\usepackage{hyperref}          %if i remove this, the references works

\begin{document}

\section{Intro}

According to \cite{test}

\bibliography{ref}

\end{document}

And I have a file (ref.bib) with  this:
@misc{test,
  author = {Bryce Graham},
  title = {Hydrological Modelling:
How and Why it is Used},
  year = 2009,
  url = {https://dpipwe.tas.gov.au/Documents/Hydrological%20modelling_how%20and%20why%20it%20is%20used.pdf},
  urlaccessdate = {08/07/2021}
}

Compiler: XeLaTeX

A: How about this?
\documentclass[12pt,a4paper,notitlepage,twoside]{article}
\usepackage{hyperref}
\usepackage[alf]{abntex2cite}

\begin{document}
\section{Intro}

According to \cite{test}

\bibliography{ref}
\end{document}