text:
Q: Lambda Yields empty buffer error with large images I'm getting some problems with this code in Lambda when I try to send large images.
I sent a bunch of images, and resized and create several differents sizes, as the array SIZES show.
My Lambda configuration is on high, max memory (1536mb) and max timeout 5mim.
The problem occurs When large images are uploded. I searched through all internet but I could not find a solution.
Error
Unhandled rejection Error: Stream yields empty buffer
at Socket.<anonymous> (/var/task/node_modules/gm/lib/command.js:57:17)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)

**Here's the code.*
var gm = require('gm').subClass({
        imageMagick: true
    }),
    aws = require('aws-sdk'),
    async = require('async'),
    fs = require('fs'),
    promise = require('bluebird'),
    request = require('request').defaults({
        encoding: null
    });

var BUCKET = "myBucket",
    FOLDER = 'photos/',
    s3 = new aws.S3({
        accessKeyId: 'myKeyId',
        secretAccessKey: 'mySecretKey'
    }),
    SIZES = [{
        type: 'original',size: 1080,mark: false,hide: true
    }, {
        type: 'thumb',size: 120, mark: false, hide: false
    }, {
        type: 'thumb',size: 240, mark: false, hide: false
    }, {
        type: 'thumb',size: 360, mark: false, hide: false
    }, {
        type: 'card',size: 350 ,mark: false, hide: false
    }, {
        type: 'full',size: 360, mark: true, hide: false
    }, {
        type: 'full',size: 540, mark: true, hide: false
    }, {
        type: 'full',size: 720, mark: true, hide: false
    }, {
        type: 'full',size: 900, mark: true, ide: false
    }, {
        type: 'full',size: 1080, mark: true, hide: false
    }];

var service = {
    s3: {
        download: function(bucket, key) {
            return new promise(function(resolve, reject) {
                s3.getObject({
                    Bucket: bucket,
                    Key: key
                }, function(err, data) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(data);
                    }
                });

            });
        },
        upload: {
            async: function(photo, bucket, key, content_type, private) {
                return new promise(function(resolve, reject) {
                    s3.putObject({
                        Bucket: bucket,
                        Key: key,
                        Body: photo,
                        ContentType: content_type,
                        ACL: private ? 'private' : 'public-read'
                    }, function(err, data) {
                        if (err) {
                            reject(err)
                        } else {
                            resolve(key);
                        }
                    });
                });
            }
        }
    },
    watermark: {
        resize: function(photo, name) {
            var temp = '/tmp/w_' + name + '.png';
            return new promise(function(resolve, reject) {
                gm(photo).size(function(err, size) {
                    var that = this;
                    if (err) {
                        reject(err);
                    }
                    var smaller = size.width > size.height ? size.height : size.width;
                    var _size = smaller * 0.8;

                    request.get('https://s3.amazonaws.com/FOLDER/photos/watermark.png', function(e, r, body) {
                        gm(body)
                            .resize(_size)
                            .write(temp, function(error) {
                                if (error) reject(error);

                                that.composite(temp)
                                    .gravity('Center')
                                    .toBuffer(function(e, buffer) {
                                        if (e) reject(e);

                                        fs.access(temp, fs.F_OK, function(err) {
                                            if (!err) {
                                                fs.unlinkSync(temp);
                                            }
                                        });

                                        resolve(buffer);
                                    });
                            });
                    });
                });
            });
        }
    },
    resize: function(photo, width, height) {
        return new promise(function(resolve, reject) {
            gm(photo).resize(width, height).toBuffer(function(err, buffer) {
                if (err) {
                    reject(err);
                }

                resolve(buffer);
            });
        });
    },
    crop: function(photo, width, height) {
        return new promise(function(resolve, reject) {
            gm(photo).size(function(err, size) {
                if (err) {
                    reject(err);
                }

                var x = 0,
                    y = 0;
                if (size.width > size.height) {
                    this.resize(null, height);
                    x = (((height * size.width) / size.height) - width) / 2;
                } else {
                    this.resize(width);
                    y = (((width * size.height) / size.width) - height) / 2;
                }

                this.crop(width, height, x, y).toBuffer(function(err, buffer) {
                    resolve(buffer);
                });
            });
        });
    },
    process: function(type, photo, width, height) {
        if (type == 'thumb') {
            return service.crop(photo, width, height);
        } else {
            return service.resize(photo, width, height);
        }
    }
};

exports.handler = function(event, context, callback) {
    var $filename = event.filename,
        $session = event.session,
        $mimetype = null,
        $original = null,
        $watermarked = null;

    async.waterfall([
        function(_next) {
            service.s3.download(BUCKET, FOLDER + $session + '/original/' + $filename).then(function(_original) {
                $mimetype = _original.ContentType;
                $original = _original.Body;
                _next(null);
            }, function(_error) {
                _next(_error);
            });
        },
        function(_next) {
            service.watermark.resize($original, (Math.random().toString(36).slice(-6) + new Date().getTime())).then(function(_watermarked) {
                $watermarked = _watermarked;
                _next(null);
            });
        },
        function(_next) {
            async.each(SIZES, function(_image, _callback) {
                service.process(_image.type, _image.mark ? $watermarked : $original, _image.size, _image.size).then(function(_generated) {
                    service.s3.upload.async(_generated, BUCKET, FOLDER + $session + '/' + _image.type + '/' + (_image.type != 'card' ? _image.size + '_' : '') + $filename, $mimetype, _image.hide).then(function() {
                        _callback(null);
                    });
                });
            }, function() {
                _next(null);
            });
        }
    ], function() {
        callback(null, 'Imagens processadas. Session: ' + $session);
    });
};

A: The older process it took long to finish, then lambda run out of memory.
I resolved this problem breaking the array in two Sizes. Then duplicating the function with async.each to the new array.
This new method run perfectly and create all images.

A: I've had this error before and eventually traced it to hitting the memory limits. Fortunately, I was able to increase the size of my memory and that solved the problem.
Unfortunately, I see you're already on the maximum allowable memory and still hitting the limit. Just how big are these images that are being uploaded? If they really are big, and you need the output as one image, the only way I can see how you could do it would be to upload the huge image file, crop it to form x4 or more smaller images, resize each of those and then stick each one back together again.


text:
Q: RAPIDS.ai dependencies cuml and cudf not found no matter how I install I have followed every version of the instructions on the AWS-EC2 setup for RAPIDS.ai: https://rapids.ai/cloud#AWS-EC2
I can confirm that I am using the exact instance type in the instructions, and following the steps exactly.
When I try to use the docker approach, the --gpus all command is not accepted.
When I try to use the conda approach, the install fails with the error:
PackageNotFoundError: Packages missing in current channels:

 - glibc

I have tried (many) different solutions provided to solve both of these problems, none of them seem to work. I really just need to test some python code with cuml and cudf imports in a notebook. Been at this for 7 hours (after giving up on my local and SageMaker).

A: You note that the --gpus all command is not accepted, which suggests that you do not have the NVIDIA Docker runtime installed.
I followed the instructions you linked and I did run into an issue where the sudo yum install -y nvidia-docker2 command failed and I needed to disable an Amazon yum repo that was causing come conflicts as outlined in this issue.
$ sudo yum-config-manager --disable amzn2-graphics

$ sudo yum install -y nvidia-docker2

$ sudo yum-config-manager --enable amzn2-graphics

Once I'd done that and run sudo systemctl restart docker I was able to start the RAPIDS container.
$ docker run --gpus all --rm -it -p 8888:8888 -p 8787:8787 -p 8786:8786     rapidsai/rapidsai:cuda11.2-runtime-ubuntu18.04-py3.7
This container image and its contents are governed by the NVIDIA Deep Learning Container License.
By pulling and using the container, you accept the terms and conditions of this license:
https://developer.download.nvidia.com/licenses/NVIDIA_Deep_Learning_Container_License.pdf

A JupyterLab server has been started!
To access it, visit http://localhost:8888 on your host machine.
Ensure the following arguments were added to "docker run" to expose the JupyterLab server to your host machine:
      -p 8888:8888 -p 8787:8787 -p 8786:8786
Make local folders visible by bind mounting to /rapids/notebooks/host
(rapids) root@be7253bb4fdb:/rapids/notebooks#

A: Turns out, the frist AMI suggested in the documentation is not compatible. Use the Deep Learning NVIDIA one instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to determine the size of an array of pointers Consider the following code in C:
int size = sizeof(a)/sizeof(a[0])

a is of the type char ** and its purpose to my code is as an array. It is guaranteed that a has more than one element. Somehow, size always obtains the value 1.
My initial guess is that the a in sizeof(a) is being treated as the first pointer instead of an array. How do I fix this?

A: From just a pointer, you can't know the size of the buffer/array it points to. You must always track/pass the size of an array yourself.
The trick you're trying to use only applies to arrays (which degrade to pointers). It is unfortunate that it can accidentally be applied to pointers. This is why the Linux kernel defines the following macro:
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))

http://lxr.free-electrons.com/source/include/linux/kernel.h#L53
The __must_be_array() invokes some compiler-specific functionality to ensure the mistake you just made causes a compilation error, instead of an incorrect value.

A: You don't. Only with arrays (variables declared with square brackets, like as char x[80]) will do this correctly. There is no way to determine the size of an area a pointer (a variable with declared with an asterisk, like char *y) points to. If you are passing an array into a function, the function either has to already know the size, or you need to pass the size in with the pointer.
So what is happening in your example is: sizeof(a) is the size of a pointer (to pointer to char) in your CPU's architecture; likely 8. sizeof(a[0]) is the size of the pointer (to char) - still 8, because pointer size is pointer size, no matter what they point to. There is no way to promote a pointer to an array (although it is easy to go in the other direction and assign an array to a pointer).


text:
Q: Pass Model from View To Controller Using ActionLink what is the best way to pass model data from View to Controller using actionLink. actually my action link is download link and i want to pass report model as it contains datatable information.
   private void DownloadReport(ReportModel rptModel)
   {
       // want to recieve report model here.
     // to do so.
   }

A: An ActionLink is ultimately just an anchor element.
Instead, use a form with an anchor element that submits the form.
The corresponding controller method would accept your ReportModel.

A: You can use Ajax post method for the same..
For example in your view :-
<script type="text/javascript">
var rptModel = {
    val1: "val1",
    ....
};

$.ajax({
    url: '/NameOfController/DownloadReport,
    type: 'POST',
    data: JSON.stringify(rptModel),
    contentType: 'application/json; charset=utf-8',
    success: function (data.success) {
        alert(data);
    },
    error: function () {
        alert("error");
    }
});
</script>

And this whatever you pass from view you will get in your action method.


text:
Q: How to avoid compilation error while referring common jar files? I have a common jar that needs to be placed in Tomcat / Jetty lib folder, so that all the WAR files will be able to access the JAR. My code gets compilation error as it could not link to the JAR. How to access the common JAR that is placed in the lib folder of the server?

A: I have used Manifest file in WAR to link to the external JAR. In manifest file I specified the external JARs as, "Class-Path: ". To avoid compilation error, I linked the external JARs as "Java BuildPath -> Libraries". Though the JARs are linked using above method, only the JARs found in "lib" folder of the server is used by the application :-)


text:
Q: Do you need elevated privileges at runtime if application uses COM? I am not familiar with the various options you have when dealing with COM components. A legacy system in our company has published a COM API with a mixed mode dll to allow .NET components to interact with it.
It also allows the legacy system to run out-of-proc.
However, when setting up a simple windows app, it seems that both install and normal usage of the program needs Administrator privileges.
Is this a consequence inherently in deciding to use COM? Is this something we should be tweaking in the COM registration? I don't know much about this, but I know that there is a user/machine level separation.
Or should I be looking at the legacy system and assume that the demand for administrator privilege comes from something it does "on the other side" of the COM?

A: COM is at its core a binary-interface standard, allowing applications and libraries of different types to communicate with each other.
While it does have some security features, it's unlikely you are encountering those. With a few exceptions, calling into COM code is essentially the same as calling e.g. C code from Python, or any cross-language binding. There's a good chance there are key .net framework components that are wrappers around base windows services, connected via COM, which would mean an application might use COM without its developer even knowing it.
I've never used COMs security features, but I think you'd know it if that was the case. The features are for setting up convoluted user/role/security systems, and that would have to be well documented otherwise it'd be virtually impossible to accidentally hook it all up correctly into an application.
What is far more likely is that the particular COM components you are using require elevated permissions to do whatever they're doing. COM goes back to 1993, it's been built into a lot of stuff in the meantime, with a lot of it not playing nice with restricted permissions, which itself was a big problem when Vista came around, and onwards. This is especially likely when you say you are dealing with a legacy component.
You should definitely look first at the legacy component and see if it is doing some of the classic troublemaking maneuvers such as writing files to the Program Files or windows system directories.

A: COM has a very rich security feature set.  Depending on how you set it up, accessing the component could require elevated permissions, or it may not; the component itself may require elevated permissions, or it may not, or it may impersonate an user with elevated privileges even if you call it from a user who doesn't have those privileges.


text:
Q: How to move FileSystem persistent-volumes's data to new Node? When I force my pod to run on a new Node the persistent volume data (FileSystem) is left behind. How can I move it along with my Pod?
I am deploying portainer with the following yamls:
---
# Source: portainer/templates/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: portainer
---
# Source: portainer/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: portainer-sa-clusteradmin
  namespace: portainer
  labels:
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
---
# Source: portainer/templates/pvc.yaml
kind: "PersistentVolume"
apiVersion: "v1"
metadata:
  name: "portainer-pv"
  namespace: "portainer"
  labels:
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
spec:
  capacity:
    storage: "10Gi"
  volumeMode: Filesystem
  accessModes:
    - 'ReadWriteOnce'  # Only 1 pod can access at the same time
  persistentVolumeReclaimPolicy: "Retain"
  hostPath:
    path: "/opt/kubernetes/volumes/portainer"
---
# Source: portainer/templates/pvc.yaml
kind: "PersistentVolumeClaim"
apiVersion: "v1"
metadata:
  name: portainer-pv-claim
  namespace: portainer
spec:
  accessModes:
    - "ReadWriteOnce"
  resources:
    requests:
      storage: "10Gi"
---
# Source: portainer/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: portainer
  labels:
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  namespace: portainer
  name: portainer-sa-clusteradmin
---
# Source: portainer/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: portainer
  namespace: portainer
  labels:
    io.portainer.kubernetes.application.stack: portainer
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
spec:
  type: NodePort
  ports:
    - port: 9000
      targetPort: 9000
      protocol: TCP
      name: http
      nodePort: 30777
  selector:
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
---
# Source: portainer/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: portainer
  namespace: portainer
  labels:
    io.portainer.kubernetes.application.stack: portainer
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
spec:
  replicas: 1
  strategy:
    type: "Recreate"
  selector:
    matchLabels:
      app.kubernetes.io/name: portainer
      app.kubernetes.io/instance: portainer
  template:
    metadata:
      labels:
        app.kubernetes.io/name: portainer
        app.kubernetes.io/instance: portainer
    spec:
      nodeSelector:
        {}
      serviceAccountName: portainer-sa-clusteradmin
      volumes:
        - name: "data"
          persistentVolumeClaim:
            claimName: portainer-pv-claim
      containers:
        - name: portainer
          image: "portainer/portainer:2.13.1"
          imagePullPolicy: Always
          volumeMounts:
            - name: data
              mountPath: /data    # Mount inside the container
          ports:
            - name: http
              containerPort: 9000
              protocol: TCP
          resources:
            {}

On first deployment everything works, but when I tested a migration of my Pod to another Node it just started a new fresh portainer Pod without the retained persistent volume data.
I was expecting the persistent-volume data to move with it to the new Node, but it didn't.
What I did to migrate my pod was:

*

*kubectl cordon {nodeName}

*kubectl delete pod {podName} -n portainer
Then my pod was moved to a new Node, but the persistent volume data got left behind.
How can I make the (FileSytem) persistent volumes migrate along with my Pods incase such an event, of pod migration to a new Node, happens?
Edit:
I also tried like suggested to use 'local' type of PersistentVolume:
kind: "PersistentVolume"
apiVersion: "v1"
metadata:
  name: portainer
  namespace: portainer
  labels:
    app.kubernetes.io/name: portainer
    app.kubernetes.io/instance: portainer
spec:
  capacity:
    storage: "10Gi"
  volumeMode: Filesystem
  accessModes:
    - 'ReadWriteOnce'  # Only 1 pod can access at the same time
  persistentVolumeReclaimPolicy: "Retain"
  local:
    path: "/opt/kubernetes/volumes/portainer"
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: node-role.kubernetes.io/worker
          operator: In
          values:
          - "true"

But the results were the same

A: PV which has been created is with hostPath option.
hostPath - HostPath volume (for single node testing only; WILL NOT WORK in a multi-node cluster; consider using local volume instead)
https://kubernetes.io/docs/concepts/storage/persistent-volumes/
You need to create PV with different type persistent volume.  you can refer above link which has different types of PV mentioned.  Based on you requirement you can choose one.

A: The problem is the Access Mode defined for your PersistentVolume and PersistentVolumeClaim objects.
The ReadWriteOnce mode does not allow only one Pod at the same time, it actually allows multiple Pods at the same time, but it only allows one node to mount the volume:

ReadWriteOnce
the volume can be mounted as read-write by a single
node. ReadWriteOnce access mode still can allow multiple pods to
access the volume when the pods are running on the same node.

Hence the loss of the data when the Pod is recreated in another node.
The access mode needed in this situation is ReadWriteMany:

ReadWriteMany
the volume can be mounted as read-write by many nodes.

If your cluster is hosted in Google Kubernetes Engine (GKE), the PersistentVolumeClaim will fail because GKE does not support ReadWriteMany natively. In that case, the option is to use Cloud Filestore as described in this question.


text:
Q: immediately start MediaPlayer and update MediaPlayerControl I want to immediately start playing a sound when the activity is first launched and I want the MediaPlayerControl object to reflect this change. On the code given below the controls will start with play-mode activated instead of pause-mode (since the file is already playing).
public class Guide extends AppCompatActivity implements MediaPlayerControl, MediaPlayer.OnPreparedListener {

    private MediaPlayer m_audio_player;
    private MediaController m_audio_controller;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);
        set_up_audio();
    }

    private void set_up_audio(){
        m_audio_player = MediaPlayer.create(this, *SOMESOUNDFILE*);
        m_audio_player.setOnPreparedListener(this);
        m_audio_controller = new MediaController(this);
    }

    public void onPrepared(MediaPlayer mediaPlayer) {
        m_audio_controller.setMediaPlayer(this);
        m_audio_controller.setAnchorView(findViewById(R.id.main_audio_view));
        handler.post(new Runnable() {
            public void run() {
                m_audio_controller.setEnabled(true);
                m_audio_controller.show();
                m_audio_player.start();
                // how do I update m_audio_controller's state here?
            }
        });
    }
}

how can I do this?

A: I've found the solution. If I call show after first having started the player, it does work.
m_audio_player.start();
m_audio_controller.show();


text:
Q: Swift, load data into temp file stream for transferFile Is it possible to load a [String : Any] dictionary into a temporary file stream, without writing the contents to disk anywhere, then feed the stream to transferFile, as the file parameter? I know this is possible in PHP, but am not so sure about Swift.
I have come across a problem whereby my data exceeds the messaging limits. Therefore I either need to develop my own protocol to transfer the data, or somehow pass the data to transferFile.
I do not want to write my data to temporary files, transfer, and then delete them, as this is pretty dirty.

A: Why not just write the contents of the dictionary to a temporary file and pass the URL of that file to transferFile? I know you think that this is a "dirty" way to do things but since you need to pass a file URL to transferFile, that might be your only option - at least, that's the only option I know of ...


text:
Q: Python is not showing floating decimals correctly I have python2.7 installed on ubuntu 16.04. It's showing strange behavior. If I check for (5/4), it will just display 1 as output.
for (6/7) it is showing 0
Can anyone help me to fix this?

A: Not a strange error at all. Python 2.7 does Integer division, so you will always get an integers as the result of the expressions you have named. You can view it this way if you want:
5/4=int(5/4)=int(1.25) = 1
And this is how you can understand the expression you have shown:
float(5/4)= float(int(5/4)) = float(1) = 1.0
you need to use floats:
5.0/4.0


text:
Q: webclient exception 403 Forbidden Если открывать через браузер, то видна проверка от ddos-guard, может что то нужно добавить в запрос? Или как то дождаться ответ и перенаправление?
Пробовал через команду curl.
string text = string.Empty;

        string url = "";//курсы цб

        Uri urlAddress = new Uri(url);

        using (var client = new WebClient())
        {
            try
            {
                text = client.DownloadString(url);
            }
            catch (Exception e)
            {
                //пишем в логи
            }
        }


text:
Q: Date picker dialog is not working in fragment here i  have made a simple code for date picker which works for current date, year and day,it is not working for fragment
   public class Activity extends Sherlockfragment {

    EditText  dob;
    public static final int DATE_DIALOG_ID = 1009;
    String dob_string;
    int year = 2013, month = 10, day = 1, dayofmonth = 1;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
view = inflater.inflate(R.layout.update_profile, container, false);

            mdob = (EditText)view. findViewById(R.id.dob);
          mdob.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(DATE_DIALOG_ID);
        }});
return view;
}

// ****************************#DATE PICKER DIALOG# **************************
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    }
    return null;
}

 private DatePickerDialog.OnDateSetListener datePickerListener = new   DatePickerDialog.OnDateSetListener() {
    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth + 1;
        day = selectedDay;
        Calendar cal = Calendar.getInstance();
        cal.set(selectedYear, selectedMonth, selectedDay);
        DateFormatSymbols dfs = new DateFormatSymbols(Locale.getDefault());
        String weekdays[] = dfs.getWeekdays();
        int daykk = cal.get(Calendar.DAY_OF_WEEK);
        String dayof = weekdays[daykk];
        mdob.setText(day + "-" + month + "-" + year + dayof);
        mdob_string = day + "-" + month + "-" + year;
    }};
    }

A: public class Activity extends Sherlockfragment {

    static EditText  mdob;

    static String dob_string;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
view = inflater.inflate(R.layout.update_profile, container, false);

            mdob = (EditText)view. findViewById(R.id.dob);
          mdob.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            // TODO Auto-generated method stub
DialogFragment newFragment = new DatePickerFragment();

                        newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");

        }});
return view;
}
    // *********************************CLASS****************************************************************************

public static class DatePickerFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {

        int year = 2013, month = 10, day = 1, dayofmonth = 1;

        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            // Do something with the date chosen by the user

            year = selectedYear;
            month = selectedMonth + 1;
            day = selectedDay;
            Calendar cal = Calendar.getInstance();
            cal.set(selectedYear, selectedMonth, selectedDay);
            DateFormatSymbols dfs = new DateFormatSymbols(Locale.getDefault());
            String weekdays[] = dfs.getWeekdays();
            int daykk = cal.get(Calendar.DAY_OF_WEEK);
            String dayof = weekdays[daykk];

 Activity.mdob.setText(day + "-" + month + "-" +        year + dayof);
 Activity.mdob_string = day + "-" + month + "-" + year;

        }
    }

    }

A: You can make a custom class for that as below:
public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }
}

Reference: Pickers with Fragment.


text:
Q: How do I add in a "range of years" to my Case Statement How do I add in a "range of years" to my Case Statement below? I just need to fix the "INTERVAL 6 YEAR" & "INTERVAL 5 YEAR" criteria.
Here is the criteria I need to model:
If 1~5 years, then 11
If 6~10 years, then 14
If 11+ years, then 18
CASE WHEN hiredate < DATE_SUB(NOW(),INTERVAL 11 YEAR)
 THEN '18'
 WHEN hiredate < DATE_SUB(NOW(),INTERVAL 6 YEAR)
 THEN '14'
 WHEN hiredate < DATE_SUB(NOW(),INTERVAL 5 YEAR)
 THEN '11'
 ELSE '0'    END AS Non_Management_Accrual

A: You can use DATEDIFF method to calculate number of days between two days and divide it by 365 to get years. Based on these, you can write up the case statement, e.g.:
SELECT id, CASE WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 1
 THEN '0'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 6
 THEN '11'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 11
 THEN '14'
 ELSE '18'
 END AS Non_Management_Accrual
 FROM emp;

Here is the SQL Fiddle.

A: Darshan, I ended up creating Views on the MySQL side then adding the view into FROM statement of your code above. This gave me the correct output. Thanks.
<!--- Create the Manager Monthly Accruals (Mgt) dataset --->
  <cfquery name="rsLeaveTimeManagerAccruals" datasource="care">
SELECT    username, status, active, email, hiredate, tblUsers.picture AS eP
, TIMESTAMPDIFF(YEAR, hiredate, NOW()) AS year_passed
, TIMESTAMPDIFF(MONTH, hiredate, NOW()) MOD 12 AS month_passed
, TIMESTAMPDIFF(DAY, hiredate, NOW()) MOD 365 AS day_passed
, CONCAT(TIMESTAMPDIFF(YEAR, hiredate, NOW())," years, ",TIMESTAMPDIFF(MONTH, hiredate, NOW()) MOD 12," months, ",TIMESTAMPDIFF(DAY, hiredate, NOW()) MOD 365," days") AS EmployLengthActive
, TIMESTAMPDIFF(YEAR, hiredate, NOW()) AS monthly_accrual_time

, CASE WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 1
 THEN '0'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) <= 5
 THEN '14'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) >= 6
 THEN '18'
 END AS Management_Accrual

FROM      v_reports_to_mgt_list LEFT OUTER JOIN tblusers ON tblusers.ID = v_reports_to_mgt_list.id
WHERE     clr_accrual = '1' AND hiredate  IS NOT NULL
ORDER BY  hiredate
</cfquery>


text:
Q: Can universe be a closed manifold? I had a question at MSE which gave a rise to another question.
Maxwell equations can be written in form $$d\star F = J$$
Then by Stokes theorem we have
$$ \int_U J = \int_U d \star F = \int_{\partial U} \star F.$$
If $U$(universe) is closed then $\partial U=\emptyset$ is empty. So $\int_U J=0$.
What does says about space time. Is it possible that $\int_U J=0$? Or is it proof that universe cannot be closed?


text:
Q: Url is redirects to .shtml unknown link I need to implement SSL redirection. The HTTP/https and non-www URLs should forcefully redirect to https://www URLs.
There exists browser authentication code in htaccess file and this is the reason behind which redirecting to https://exmpledomain/.shtml

A: After the Authentication code please write this

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ ([^\ ]+)
RewriteRule ^ https://www.%{HTTP_HOST}%2 [L,R=301]

RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ ([^\ ]+)
RewriteRule ^ https://%{HTTP_HOST}%2 [L,R=301]


text:
Q: How to merge overlapping raster data sets in GDAL for Python to select maximum value at each pixel I am trying to merge a variable number of geotiffs into a single, clipped output geotiff, using GDAL 's Python bindings (or via command line).
Requirements:

*

*there will be 2 to N input files each time

*the inputs are all in a common projection, with different (but overlapping) extents

*the input files contain no_data pixels

*I want to keep the maximum input value at each each output pixel

*I want to clip the final image to a known extent

*the final output will be in the same projection as the input files

Ideally, I'd like to use something like gdal.Warp on a VRT that is built using the input files, to avoid having to create intermediate files/arrays.  However, my experience and research indicate that a VRT will use pixels based on the order in which the input files are specified, which is also the case for gdal_merge and gdal_translate.
This seems like it should be a common task, but I've been unable to find a solution that works.  The most likely looking approach I've found is to use a PixelFunction, based on this example: Combining overlapping rasters by minimum value in python.  Failing so, far though.  I have implemented this:
    ########### Create the VRT ###########
    vrt_file = 'mosaic.vrt'
    cmd = ['gdalbuildvrt', vrt_file]
    for file in file_list:
        cmd.append(file) # add all the files to be mosaicked

    proc = subprocess.Popen(cmd)
    stdout,stderr=proc.communicate()
    exit_code=proc.wait()

    if exit_code:
        raise RuntimeError(stderr)
    else:print(stdout)

    ########### Add the Pixel Function ###########
    try_pixel_function = True
    gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', 'YES')

    if try_pixel_function: # FAILS WHEN THIS BLOCK IS RUN
        # Adapted from https://gis.stackexchange.com/questions/350233/how-can-i-modify-a-vrtrasterband-sub-class-etc-from-python
        from lxml import etree
        vrt_tree = etree.parse(vrt_file)
        vrt_root = vrt_tree.getroot()
        vrt_band = vrt_root.findall(".//VRTRasterBand[@band='1']")[0]
        vrt_band.set('subClass', 'VRTDerivedRasterBand')
        pixelFunctionType = etree.SubElement(vrt_band, 'PixelFunctionType')
        pixelFunctionType.text = 'find_max'
        pixelFunctionLanguage = etree.SubElement(vrt_band, 'PixelFunctionLanguage')
        pixelFunctionLanguage.text = 'Python'
        pixelFunctionCode = etree.SubElement(vrt_band, 'PixelFunctionCode')
        pixelFunctionCode.text = etree.CDATA("""
        import numpy as np

        def find_max(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
            np.amax(in_ar, axis=0, initial=255, out=out_ar)
        """)
        vrt_tree.write(vrt_file)

    ########### get vrt's projection info ###########
    ds=gdal.Open(vrt_file)
    prj=ds.GetProjection()
    print(prj)

    ########### create mosaic ###########
    outfile_name = 'scratch.tif'
    cmd = ['gdalwarp', '-s_srs', prj, '-t_srs', 'EPSG:3857', '-r', 'max', '-of', 'VRT', vrt_file, outfile_name, '-te_srs', 'EPSG:4326', '-te', str(min_lon), str(min_lat), str(max_lon), str(max_lat), '-ts', str(resolution), str(resolution), '-et', '0', '-ot', 'Int16', '-ovr', 'NONE', '-srcnodata', '0', '-overwrite']

    proc = subprocess.Popen(cmd)
    stdout,stderr=proc.communicate()
    exit_code=proc.wait()

    if exit_code:
        raise RuntimeError(stderr)
    else:print(stdout)

    ########### retrieve the mosaicked data ###########
    ds = gdal.Open(outfile_name)
    data = ds.GetRasterBand(1).ReadAsArray()
    gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', 'NO')

This works fine when try_pixel_function is false (except that the last file overwrites everything else, as mentioned above), but fails on the last line, data = ds.GetRasterBand(1).ReadAsArray(), when try_pixel_function is true, with the error:

ERROR 1: Couldn't compile code: <class 'IndentationError'>,
('unexpected indent', ('gdal_vrt_module_0x287682af0', 6, 8, '
import numpy as np\n', 6, -1)) ERROR 1: scratch.tif, band 1:
IReadBlock failed at X offset 0, Y offset 0: Couldn't compile code:
<class 'IndentationError'>, ('unexpected indent',
('gdal_vrt_module_0x287682af0', 6, 8, '        import numpy as np\n',
6, -1))

I'm guessing the indent error refers to the code I'm trying to add using pixelFunctionCode.text = etree.CDATA(...
Any suggestions on what I'm doing wrong?
Other research: I also looked at using gdal_calc, as in this example from https://gdal.org/programs/gdal_calc.html
gdal_calc.py -A input1.tif -B input2.tif -C input3.tif --outfile=result.tif --calc="numpy.max((A,B,C),axis=0)
This seems doable but not super performant. I may have up to about 20 input files. I would have to either run on the inputs (which could involve wasting a lot of computation on the overlap areas that will be outside the desired final extent), OR clip each input individually to the final output extent before running this max operation.
(Most relevant results I've found:)

*

*Merge overlapping rasters using GDAL

*Combining overlapping rasters by minimum value in python

A: I've encountered the same problem.
I should say that I did hear that there were plugins for this, but I don't recall what those were.
My solution was python-based. It ended up being long, but the core of it was to import/export with gdal, and use numpy to do array math.


text:
Q: C++: override class inheritance? There are two classes in a library I use, lets call them class A and class B to keep things generic. Class B inherits from class A, so something like:
class A{
    ...
}

class B: public A{
    ...
}

So nothing fancy, but I can't edit either of these classes directly. Now I wanted to add some functionality to class A, so I subclass it as, say, myClassA, and add the functionality in the subclass. This works great when I use myClassA, but of course anywhere I use classB still inherits from the original class A, and not myClassA.
How can I make a subclass of class B that inherits from myClassA instead of the original classA? Would it work to simply have the subclass inherit from BOTH class B and myClassA, even though class B already inherits from the original class A?
EDIT: I just tried the "Inherit from BOTH" option and can confirm it does not work, at least not without a lot more work. Probably the diamond issue mentioned in the comments. So unless there is a way to override class B's inheritance of class A with myClassA, I may have to simply re-implement the changes I made to my subclass of class A in a subclass of class B, although that would be a violation of the DRY principle...
EDIT 2: To make this a little more concrete, take for example the standard "shape" class example. So in this case you'll have a base class of, say, rectangle, and rectangle is in tern inherited by a class of square. Now I want to add functionality, say a "move" function that shifts the position of the object by a specified amount. This would be the same for both rectangle and square, so ideally I'd implement it in the rectangle class, and square would inherit it. However, since I don't have access to the rectangle or square classes directly, I can only work with subclasses. Thus my desire to make a square subclass that inherits from my rectangle subclass rather than the base rectangle class.
EDIT 3: To restate and clarify the question in terms of the more concrete example, "Can I/How can I create a subclass of square but have it inherit from my_rectange (a rectangle subclass) INSTEAD OF inheriting from rectangle?" Or, to put it another way, "Can I/How can I replace a base class with something of my own if I can't modify the class directly?"

A: template<class T /* T must be derived from A */> class myclsssA:T { /* ... */ }

new myclassA<B>()

This works sometimes depending on what you are doing. There's an extreme exactness to what this can do or not do, and there just aren't enough details in the question to even get close to knowing.
This makes myclassA the most-derived form so it can override all virtual methods successfully. But if you don't make the instances of B, it won't help at all.


text:
Q: Using npm package ssh2 within an Angular2 application running under electron I want to create an Angular2 service which uses the npm package ssh2 - https://www.npmjs.com/package/ssh2.
I have installed and configured it as I would expect - the code for my service can be seen below (this code is based on the first example shown on the ssh2 npm site and github repo(the only change being I am using a password rather than a key for authentication)):
const Client = require('ssh2').Client;
const fs = require('fs');

import { NextObserver } from 'rxjs/Observer';
import { Observable } from 'rxjs/Rx';

export class SSHClient {
    username: string;
    password: string;
    host: string;
    port: number;
    ssh: any;

    constructor() {
    }

    init(username, password, host, port) {
        console.log("initiating SSH connection to:" + host + "on port:" + port);

        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;

        console.log("Connecting now...");
        var conn = new Client();
        conn.on('ready', function() {
          console.log('Client :: ready');
          conn.exec('uptime', function(err, stream) {
            if (err) throw err;
            stream.on('close', function(code, signal) {
              console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
              conn.end();
            }).on('data', function(data) {
              console.log('STDOUT: ' + data);
            }).stderr.on('data', function(data) {
              console.log('STDERR: ' + data);
            });
          });
        }).connect({
          host: this.host,
          port: this.port,
          username: this.username,
          password: this.password
        });
        console.log("SSH Client created and demo has run");
    }

}

I make my call to the service as per this from within my component:
this.ssh.init("username","password","my.little.host",22);

And I expect to get back the output of the uptime command having executed over SSH on my server - via the console. However instead of that - I get this:
EXCEPTION: Uncaught (in promise): Error: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined
TypeError: Cannot read property 'connect' of undefined
    at SSHClient.init (file:///Users/myapp/build/app.js:40259:12)
    at new ServerBrowserComponent (file:///Users/myapp/build/app.js:34158:19)
    at new Wrapper_ServerBrowserComponent (/AppModule/ServerBrowserComponent/wrapper.ngfactory.js:7:18)
    at DebugAppView._View_ServerBrowserComponent_Host0.createInternal (/AppModule/ServerBrowserComponent/host.ngfactory.js:16:38)
    at DebugAppView.AppView.create (file:///Users/myapp/build/app.js:27754:26)
    at DebugAppView.create (file:///Users/myapp/build/app.js:27954:49)
    at ComponentFactory.create (file:///Users/myapp/build/app.js:24393:41)
    at ViewContainerRef_.createComponent (file:///Users/myapp/build/app.js:23441:50)
    at RouterOutlet.activate (file:///Users/myapp/build/app.js:72709:45)
    at ActivateRoutes.placeComponentIntoOutlet (file:///Users/myapp/build/app.js:72207:21)
ORIGINAL STACKTRACE:
Error: Uncaught (in promise): Error: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined
TypeError: Cannot read property 'connect' of undefined
    at SSHClient.init (ssh.service.ts:49)
    at new ServerBrowserComponent (server.browser.component.ts:31)
    at new Wrapper_ServerBrowserComponent (wrapper.ngfactory.js:7)
    at DebugAppView._View_ServerBrowserComponent_Host0.createInternal (host.ngfactory.js:16)
    at DebugAppView.AppView.create (core.umd.js:9170)
    at DebugAppView.create (core.umd.js:9370)
    at ComponentFactory.create (core.umd.js:5809)
    at ViewContainerRef_.createComponent (core.umd.js:4857)
    at RouterOutlet.activate (router.umd.js:3457)
    at ActivateRoutes.placeComponentIntoOutlet (router.umd.js:2955)
    at resolvePromise (zone-node.js:468)
    at zone-node.js:445
    at ZoneDelegate.invoke (zone-node.js:232)
    at Object.onInvoke (core.umd.js:6206)
    at ZoneDelegate.invoke (zone-node.js:231)
    at Zone.run (zone-node.js:114)
    at zone-node.js:502
    at ZoneDelegate.invokeTask (zone-node.js:265)
    at Object.onInvokeTask (core.umd.js:6197)
    at ZoneDelegate.invokeTask (zone-node.js:264)
Unhandled Promise rejection: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined ; Zone: angular ; Task: Promise.then ; Value: ViewWrappedError TypeError: Cannot read property 'connect' of undefined
    at SSHClient.init (file:///Users/myapp/build/app.js:40259:12)
    at new ServerBrowserComponent (file:///Users/myapp/build/app.js:34158:19)
    at new Wrapper_ServerBrowserComponent (/AppModule/ServerBrowserComponent/wrapper.ngfactory.js:7:18)
    at DebugAppView._View_ServerBrowserComponent_Host0.createInternal (/AppModule/ServerBrowserComponent/host.ngfactory.js:16:38)
    at DebugAppView.AppView.create (file:///Users/myapp/build/app.js:27754:26)
    at DebugAppView.create (file:///Users/myapp/build/app.js:27954:49)
    at ComponentFactory.create (file:///Users/myapp/build/app.js:24393:41)
    at ViewContainerRef_.createComponent (file:///Users/myapp/build/app.js:23441:50)
    at RouterOutlet.activate (file:///Users/myapp/build/app.js:72709:45)
    at ActivateRoutes.placeComponentIntoOutlet (file:///Users/myapp/build/app.js:72207:21)
Error: Uncaught (in promise): Error: Error in ./ServerBrowserComponent class ServerBrowserComponent_Host - inline template:0:0 caused by: Cannot read property 'connect' of undefined(…)

The bulk of that seems to be struggling because : Cannot read property 'connect' of undefined -- yet I am following the example documentation. Can somebody please help my understand why this is not working - and how I can fix it?
I tried to pull the code out of my project and into its own file which looks like:
    const Client = require('ssh2').Client;
console.log("Connecting now...");
         var conn = new Client();
         conn.on('ready', function() {
          console.log('Client :: ready');
          conn.exec('uptime', function(err, stream) {
            if (err) throw err;
            stream.on('close', function(code, signal) {
                 console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
                  conn.end();
            }).on('data', function(data) {
                  console.log('STDOUT: ' + data);
            }).stderr.on('data', function(data) {
                  console.log('STDERR: ' + data);
            });
          });
       }).connect({
          host: 'my.little.host',
          port: 22,
          username: 'uname',
          password: 'pwd'
        });
         console.log("SSH Client created and demo has run");

But I get the same error:
 var conn = new Client();
                ^

ReferenceError: Client is not defined
    at Object.<anonymous> (/Users/myapp/attempt.js:2:21)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.runMain (module.js:575:10)
    at run (node.js:348:7)
    at startup (node.js:140:9)
    at node.js:463:3

So something simple is going wrong here, what could it be!?

A: the ssh2-package is for node.js, not frontend/web.
The browser can't use network like that (electron uses two processes, the browser/renderer -process does not have access to the network features you need)
does your electron app have a main.js file?
that's where you need to implement the ssh functionality.
i.e. in the main-process, not in the renderer-process.
http://electron.atom.io/docs/tutorial/quick-start/#main-process

A: In my wrapper of ssh2 (ssh2shell) I have this.connection = new require('ssh2')(); within the constructor of the class or it could be put in the init function. Creating it within the instance might help.
"use strict";

class SSHClient {
    constructor() {}

    init(username, password, host, port) {
        console.log("initiating SSH connection to:" + host + "on port:" + port);
        var ssh = require('ssh2').Client
        this._conn = new ssh();

        console.log("Connecting");

        console.log('Client :: ready');
        var self = this
        this._conn.on('ready', function() {
            self._conn.exec('uptime', function(err, stream) {
                if (err) throw err;

                stream.on('data', function(data) {
                    console.log('STDOUT: ' + data);
                }).stderr.on('data', function(data) {
                    console.log('STDERR: ' + data);
                }).on('close', function(code, signal) {
                    console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
                    self._conn.end();
                });
            });
        }).connect({
            host: host,
            port: port,
            username: username,
            password: password
        });

        console.log("SSH Client created and demo has run");
    }
}
module.exports = SSHClient

Or using my package ssh2shell the ssh connection instance is within the sope of ssh2shell instance so you don't have to worry about it.
"use strict";

class SSHClient {
    constructor() {}

    init(username, password, host, port) {
        console.log("initiating SSH connection to:" + host + "on port:" + port);

        var host = {
            server: {
                host:         host,
                port:         port,
                userName:     username,
                password:     password
                },
            commands:      [ "uptime" ]
        }

        var SSH2Shell = require ('ssh2shell'),

            //Use a callback function to handle the response text
            callback = function(sessionText){
                console.log("SSH Client created and demo has run");
                console.log("Response:\n" + sessionText)
            }

        //Create a new instance passing in the host object
        this._conn = new SSH2Shell(host)

        //Start the process
        this._conn.connect(callback);
    }
}

module.exports = SSHClient


text:
Q: Why is execution context needed for JS I am new to JS and was learning the role of execution context in JS and asked myself what is the benefit of execution context in JS and why JS is run via execution context. The second question is as we know there are global and functional execution contexts and each context has two phases creation phase and execution phase. So, why we need these two phases? what is the point of having them.

A: The concept of an "execution context" provides a way of reasoning about what happens when the global environment is created and executed, or when a function is called. It's a conceptual container for the local variables (globals, in the case of the global environment), parameters (for functions), etc. A JavaScript engine can be written without literally having any object it calls an "execution context," as long as it implements the language in keeping with the spec's defined execution context behavior.
One thing that the execution context helps explain is the behavior of closures. A function created within a given execution context has (conceptually) a reference to that context, even after the function call related to the context has completed:
function foo(answer) {
    return function say() {
        console.log(answer);
    };
}
const s = foo(42);
s(); // 42

That works because the function say has a reference to the context of the call to foo that created it (well, more specifically to the thing called its "lexical environment"). That lexical environment continues to exist after foo returns because something still has a reference to it (say). So the call to say afterward works.
The reason for having two phases is to allow use of identifiers before their declaration. This is primarily useful for function declarations:
main();

function main() {
    console.log("Worked");
}

The first phase processes the function declarations (and var statements), and then the step-by-step phase runs the code. Without the first phase, the code above would fail as of main(); because main would be undeclared. Of course, with the simple example above, you could just move the main(); call to after the function declaration, but more complicated cases become harder to solve in that way. Languages that didn't have two phases (early C, for instance) had to provide a mechanism for "forward declaring" things that would be defined later. Having two phases means JavaScript doesn't have to have those. (To be fair, C also differs from JavaScript in that it needs to know what all identifiers refer to during compilation, even if the identifiers are in code within functions. So it needed forward declarations just to allow foo and bar to call one another. JavaScript doesn't check the identifiers used within functions until the function is called, so some of the reasons for forward declarations in C wouldn't come up in JavaScript even if it didn't have two phases.)
It wasn't perfectly successful. Having var statements initialize the variables they declare with undefined before the var statement is reached in the code was often the source of bugs and confusion:
console.log(answer); // undefined
var answer = 42;

It's easy for people to be confused by the fact that half of the var answer = 42; was done early (the var answer part), but the other half (answer = 42;) isn't done until later when that statement is reached.
That's why let and const create, but don't initialize, their variables during that first phase. You can use a variable above where it's declared, but only in code that runs after the initialization:
function foo() {
    console.log(answer);
}
// foo(); <== Would fail, `answer` isn't initialized yet
let answer = 42;
foo(); // Works, logs 42


text:
Q: Data column(s) for axis #0 cannot be of type string (sometimes) - Google Charts I'm getting into Angular Google Charts lately but there is an issue that I couldn't handle.
On my chart page, there are 2 select buttons and based on the selection, it queries data from the database and renders the chart. The problem is that it sometimes renders it and sometimes it shows the following error:

Data column(s) for axis #0 cannot be of type string

Any ideas why this is happening?
export interface BinanceKline {
  openTime: Date;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  closeTime: Date;
}

Server output:
[
  {
    "openTime": "2019-10-20T06:00:00Z",
    "open": 7910.87,
    "high": 7940.47,
    "low": 7902,
    "close": 7928.05,
    "volume": 504.719646,
    "closeTime": "2019-10-20T06:59:59.999Z"
  },
  {
    "openTime": "2019-10-20T07:00:00Z",
    "open": 7928.05,
    "high": 7935.94,
    "low": 7900.22,
    "close": 7905.17,
    "volume": 751.587636,
    "closeTime": "2019-10-20T07:59:59.999Z"
  }
]

Code here:
home.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { combineLatest, Subject, ReplaySubject, Observable } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';

import { CryptoPairService } from 'src/app/core/services/crypto-pair.service';
import { TimeIntervalService } from 'src/app/core/services/time-interval.service';
import { BinanceService } from 'src/app/core/services/binance.service';

import { CryptoPair } from 'src/app/core/types/crypto-pair';
import { TimeInterval } from 'src/app/core/types/time-interval';
import { BinanceKline } from 'src/app/core/types/binance';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
  cryptoPairs$: Observable<CryptoPair[]>;
  timeIntervals$: Observable<TimeInterval[]>;
  binances$: Observable<BinanceKline[]>;

  private completedFunctionOne$ = new ReplaySubject(0);
  private completedFunctionTwo$ = new ReplaySubject(0);
  private componentDestroyed$ = new Subject<boolean>();

  // Selected items
  symbolSelected: any;
  intervalSelected: any;

  // Pagination
  page = 1;
  pageSize = 10;

  // Angular Google Charts
  chartData = [];
  chartOptions = {
    tooltip: { isHtml: true },
    title: 'Chart',
    height: 500,
    chartArea: { width: '80%', height: '80%' },
    legend: 'none',
    // candlestick: {
    //   fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
    //   risingColor: { strokeWidth: 0, fill: '#0f9d58' }   // green
    // }
  };
  chartColumnNames = ['Label', 'Low', 'Open', 'Close', 'High', { type: 'string', role: 'tooltip', p: { html: true } }];

  constructor(
    private cryptoPairService: CryptoPairService,
    private timeIntervalService: TimeIntervalService,
    private binanceService: BinanceService) { }

  ngOnInit() {
    setTimeout(async () => {
      this.getAllCryptoPairs();
      this.getAllTimeIntervals();
    }, 1000);

    combineLatest([this.completedFunctionOne$, this.completedFunctionTwo$])
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe(() => this.getAllKlines());
  }

  ngOnDestroy() {
    this.componentDestroyed$.next(true);
    this.componentDestroyed$.complete();
  }

  private getAllCryptoPairs() {
    this.cryptoPairs$ = this.cryptoPairService.getAllCryptoPairs().pipe(
      tap(result => {
        if (result.length) {
          this.symbolSelected = (result as CryptoPair[])[0].symbol;
        }
        this.completedFunctionOne$.next(1);
      }));
  }

  private getAllTimeIntervals() {
    this.timeIntervals$ = this.timeIntervalService.getAllTimeIntervals().pipe(
      tap(result => {
        if (result.length) {
          this.intervalSelected = (result as TimeInterval[])[0].interval;
        }
        this.completedFunctionTwo$.next(1);
      }));
  }

  private customTooltip(candlestick: BinanceKline): string {
    let pipe = new DatePipe('en-US');
    let openTime = pipe.transform(candlestick.openTime, 'HH:mm');
    let closeTime = pipe.transform(candlestick.closeTime, 'HH:mm');

    return `

    Open Time: ${openTime}
Close Time: ${closeTime}

    Open: ${candlestick.open.toFixed(2)}
Close: ${candlestick.close.toFixed(2)}

    High: ${candlestick.high.toFixed(2)}
Low: ${candlestick.low.toFixed(2)}

    VOL: ${candlestick.volume.toFixed(2)}

`;
  }

  private getAllKlines() {
    if (this.symbolSelected && this.intervalSelected) {
      this.binances$ = this.binanceService.getAllKlines(this.symbolSelected, this.intervalSelected);

      this.chartData = [];

      this.binances$
        .pipe(takeUntil(this.componentDestroyed$))
        .subscribe(candlesticks => {
          for (let i = 0; i < candlesticks.length; i++) {
            this.chartData.push([
              null,
              candlesticks[i].low,
              candlesticks[i].open,
              candlesticks[i].close,
              candlesticks[i].high,
              this.customTooltip(candlesticks[i])
            ]);
          }
        });
    }
  }
}

home.component.html

          <select class="custom-select" [(ngModel)]="symbolSelected" (ngModelChange)="getAllKlines()">
            <ng-container *ngIf="cryptoPairs$ | async as cryptoPairs; else loading">
              <option *ngFor="let option of cryptoPairs" [ngValue]="option.symbol">{{ option.description }}</option>
            </ng-container>
          </select>

          <select class="custom-select" [(ngModel)]="intervalSelected" (ngModelChange)="getAllKlines()">
            <ng-container *ngIf="timeIntervals$ | async as timeIntervals; else loading">
              <option *ngFor="let option of timeIntervals" [ngValue]="option.interval">{{ option.description }}</option>
            </ng-container>
          </select>

    <ng-template #loading>
      <option>Loading...</option>
    </ng-template>

    <ng-container *ngIf="symbolSelected && intervalSelected">

          <ng-container *ngIf="binances$ | async as binances; else loading2">
            <ng-container *ngIf="binances.length; else nocontent">
              <google-chart class="mb-1" type="CandlestickChart" [data]="chartData" [options]="chartOptions"
                [columnNames]="chartColumnNames">
              </google-chart>

                      Open time
                      Open
                      High
                      Low
                      Close
                      VOL
                      Close time

                      {{ binance.openTime | date: "yyyy/MM/dd HH:mm" }}
                      {{ binance.open | number: '1.2-2' }}
                      {{ binance.high | number: '1.2-2' }}
                      {{ binance.low | number: '1.2-2' }}
                      {{ binance.close | number: '1.2-2' }}
                      {{ binance.volume | number: '1.2-2' }}
                      {{ binance.closeTime | date: "yyyy/MM/dd HH:mm" }}

              <pagination [boundaryLinks]="true" [totalItems]="binances?.length" [(ngModel)]="page"
                [itemsPerPage]="pageSize" previousText="‹" nextText="›" firstText="«"
                lastText="»">
              </pagination>
            </ng-container>
          </ng-container>

    </ng-container>

    <ng-template #nocontent>

No content...

    </ng-template>

    <ng-template #loading2>

Loading...

    </ng-template>

A: Sorry, that was because it was showing the chart before the actual data arrives. I added a new boolean chartData = false and edited that function as following:
  private getAllKlines() {
    if (this.symbolSelected && this.intervalSelected) {
      this.binances$ = this.binanceService.getAllKlines(this.symbolSelected, this.intervalSelected);

      this.chartDrawn = false;
      this.chartData = [];

      this.binances$
        .pipe(takeUntil(this.componentDestroyed$))
        .subscribe(candlesticks => {
          for (let i = 0; i < candlesticks.length; i++) {
            this.chartData.push([
              null,
              candlesticks[i].low,
              candlesticks[i].open,
              candlesticks[i].close,
              candlesticks[i].high,
              this.customTooltip(candlesticks[i])
            ]);
          }

          this.chartDrawn = true;
        });
    }
  }

and then corrected the check inside the html file to:
<ng-container *ngIf="symbolSelected && intervalSelected && chartDrawn">

Sorry again, I didn't think it could be caused by this because that misleading error message.


text:
Q: How to create a new database table whenever user changes options I'am new to wordpress plugin development and I'am stuck in developing menu for my plugin.
By going through documentation and many sites i created following menu. But i want to create a new table in the database specified by user..Is there any action hook to detect whenever user types something and presses save button.
How can i know whenever user changes option..Any action hooks that i can use..
I want to create a new table whenever user changes his options.


text:
Q: Display random files from a directory? how to display random files from a directory? The code below only shows random 1 file, output should be 10 files.
<?php
$path = "/files";

$files = scandir($path);
shuffle($files);

for($i = 0; ($i < count($files)) && (!is_file($files[$i])); $i++);

echo $files[$i];
?>

A: for($i = 0; ($i < count($files)) && (!is_file($files[$i])); $i++);
                                                                 ^

Putting the semicolon there terminates the for loop statement, hence it doesn't actually do anything, and just loops until the condition is false. Remove the semi-colon to fix.
As a clearer example, take the following code:
for($i = 0; $i < 5; $i++);
    echo $i;

This will loop five times, as the for loop body statement is blank (due to the statement terminator, the semicolon). Because indentation doesn't matter in PHP, the echo $i will only echo once at the end of the loop, when $i == 5. You can view it better as the following:
for($i = 0; $i < 5; $i++)
    ;
    echo $i;


text:
Q: list indexing confusion I know that python list starts its  index from the value of 0 to n.
So like the first element of the list l is l[0] etc.
This is super trivial to think of. However, I find myself struggling to find the correct index when things get messy and complicated. Due to the fact, I have to compensate for the length by +/- 1 every time I want to access an element.
This look like a simple problem. But it is not. Is there a systematic way I can deal with this? Is there a way to look at this problem from a different point of view?

A: When I teach the concept of element indexing to novice programmers, a metaphor I use is to think of the indexes and numbers in a ruler. And of the contents in the list (or array, vector, string, etc...), as physical objects that are placed on this ruler - say a pebble or anything. You place the objects between the the numbers - not on their midle. So the first peble is in the space between the 0 and 1 markers. The second is the space between the 1 and 2.
And the last one will be on the space between the 29 and 30 markers, even if the ruler is 30cm long - after the 30, the rule is over, and no other elements can be placed.
That not only helps visualize how elements start at index 0, but also with Python slicing notation, in which the end of the slice denotes the limit up to the elements are picked (and not the last element to be picked).
So, on a list, lst[0:1] will pick all elements between the 0 and 1 markers, and lst[0:28] will pick the elements between those numbers, and the last two elements, between [28:30] are left out.
(on an unrelated note, I hope you do not actually use l as a variable name - one letter variable names are usually not a good practice, with good sense prevailing, but l specifically is hard to distinguish from 1, so it makes the code harder to read)

A: I am not sure exactly how you are looking at it. But this is how I first grasped this concept:
In python, as well as in majority of other programming languages, the array positions are more like a distance from the beginning. It really helps if you start your programming learning with C, in which arrays are stored in consecutive memory blocks. Therefore, if I have an int array of length 5, the language will assign a 10 byte block (by default int in C is 2 byte). Now, the first int is stored in the first 2-byte slot of the block, i.e. right at the beginning. Hence the distance of that item from beginning is 0, which is the index of the item in the array. The next int is stored in bytes 3-4, i.e. the 2nd slot of the block. Now distance of this slot from the beginning is 1 slot, hence the index is 1, and so on.
Hope this way of looking into the intricacies of the language helps you. But I will be able to help you more if you give me one use-case where you are facing the challenge with indexing.


text:
Q: How do I access text between tags with xml.etree.ElementTree I am trying to extract the text value between two tags of an XML document with xml.etree.ElementTree. In the following example, that would be the values text two and text three. I can extract only text one.
How would I find the other texts from the <c> tag?
import xml.etree.ElementTree as ET

root = ET.fromstring(
"<foo><c>text onettttext twouuutext three</c></foo>")

print root[0].text # text one

A: Use itertext:
>>> z
<Element 'c' at 0x1030697d0>
>>> for i in z.itertext():
...   print(i)
...
text one
ttt
text two
uuu
text three


text:
Q: Adding shapes over a listing in Latex Is there a way to add the geometrical shapes (triangle,...) as in the Listing below?

Thanks a lot!

A: Here is an example, based on this post.
\documentclass{article}
\usepackage{tikz}
\usepackage{listings}
\usetikzlibrary{calc}
\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\begin{document}
\begin{lstlisting}[escapechar= !]
!\tikzmark{x1}!int gilligan(int j){
    int marmot(int i){ do something really cool !\tikzmark{x4}!
         int duck(int k){
        !\tikzmark{x2}!cout<< i; !\tikzmark{x5}!
      }
!\tikzmark{x3}!   }
!\tikzmark{x6}!} !\tikz[overlay,remember picture]{\draw[fill=gray](x1.south)--([yshift=1pt]x2.west)--(x3.south)--cycle;}!
\end{lstlisting}
\tikz[overlay,remember picture]{%
\draw[fill=gray]([xshift=4pt]x6.south)--([xshift=8pt]x2.south)--(x5|-x2.south)--(x4.south)--(x4|-x6.south)
--cycle;}
\end{document}

I was not sure how close the shaded region should be to the code, but this can be adjusted. I also put one TikZ picture inside the listing because you'll need this if the code goes over more than one page.
UPDATE: It would have been nice (or even appropriate) if you would have mentioned that you got a really good answer on a related question. And yes, one can also use the methods used there.
\documentclass{article} % from https://tex.stackexchange.com/a/419865/121799
%\url{https://tex.stackexchange.com/q/419759/86}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\newcounter{tmlistings}
\newcounter{newtmlistings}

\newcommand\makenode[2]{%
  \tikz[baseline=0pt, remember picture] { \node[fill=gray!50,thick,rounded corners,anchor=base,#1/.try] (listings-\the\value{tmlistings}) {#2}; }%
  \stepcounter{tmlistings}%
}

\newcommand\makenewnode[2]{%
  \tikz[baseline=0pt, remember picture] { \node[inner
  sep=0pt,anchor=base,#1/.try] (newlistings-\the\value{newtmlistings}) {#2}; }%
  \stepcounter{newtmlistings}%
%  \typeout{\thenewtmlistings}
}

% \tikzset{
%   keyword/.style={
%     fill=gray!75,
%     draw=black
%   }
% }

\lstset{
  keywordstyle=\makenewnode{keyword},
  stringstyle=\makenewnode{string},
  identifierstyle=\makenewnode{identifier},
}

\begin{document}

\begin{lstlisting}[language=c,escapechar=!]
int gilligan (int j) {
  for (int i = 1; i < j; i++) {
    if (i % 2 == 0) {
      cout << i
    }
  }
}!\makenewnode{keyword}{\strut}!
\end{lstlisting}

\begin{tikzpicture}[remember picture,overlay]
% \foreach \i [evaluate={\j=int(\i+1)}] in {0,...,12}
% {\draw  (newlistings-\i)node[left]{\i} --(newlistings-\j); }
\draw[fill=gray] (newlistings-0.south west) -- ([xshift=-4pt]newlistings-12.west)
-- (newlistings-14.north-| newlistings-0.south west) -- cycle;
\draw[fill=gray] (newlistings-14.south) -- ([yshift=-2pt]newlistings-12.south)
-- ([xshift=1.1cm,yshift=-2pt]newlistings-12.south east)
-- ([xshift=1.3cm,yshift=-2pt]newlistings-9.south east)
-- ([xshift=1.3cm,yshift=-2pt]newlistings-9.south east |- newlistings-14.south)
-- cycle;
\end{tikzpicture}

\end{document}


text:
Q: Let random variable be $X\sim U([-2,2])$, random variable $Y=5X-4$. Calculate $EY$ and $D^{2}Y$ Let random variable be $X\sim U([-2,2])$, random variable $Y=5X-4$.
Calculate $EY$ and $D^{2}Y$
D-variance
My take:
$EX=-2$
$D^{2}X$= 4
$EY=E(5x-4)=5EX-4=5*(-2)-4=-14$
$D^{2}Y=D^{2}(5X-4)=25D^{2}X=25*4=100$
Could anyone check if my answers are correct?
@Edit
$EX=0$
$D^{2}X$= 4
$EY=E(5x-4)=5EX-4=5*0-4=-4$
$D^{2}Y=D^{2}(5X-4)=25D^{2}X=25*4=100$

A: The expectation is right, but $Var(X) = \frac {16}{12}= \frac {4}{3} $ and then $Var(Y) = 25*Var(X)= 33.333 $


text:
Q: My Ref is undefined when I try to hide a component in React I'm building an app in React with React-Bootstrap components (which includes the OverlayTrigger component).
I am getting an error on load when I try to call a function within the OverlayTrigger component. The hide() function exists inside the OverlayTrigger component and I've done something similar with it before (and it worked fine). I'm having a hard time debugging this.
This is the error I'm getting:
TypeError: Cannot read property 'hide' of undefined
    at React.createClass.closeOverlay (TaskStatusIcon.jsx:7)

And this is the actual code:
TaskStatusIcon = React.createClass({
  propTypes: {
      task: React.PropTypes.object,
  },

  closeOverlay() {
    this.refs.overlayTrigger.hide();  // THIS IS THE PROBLEM
  },

  handlePopoverClick(status) {
    Actions.tasks.setStatus.bind(null, this.props.task, status);
    this.closeOverlay();
  },

  renderOverlay() {
    return (
      <Popover title="Mark as...">

Incomplete

In Progress

Done

      </Popover>
    );
  },

  render() {
    let imgSrc = "/icon1.jpg";
    return (
      <OverlayTrigger ref="overlayTrigger" trigger="click" rootClose placement="bottom" overlay={this.renderOverlay()}>

      </OverlayTrigger>
    );
  }
});


text:
Q: Can't switch of "validation input" and getting error message .net Tried:
[ValidateInput(false)]
    public class MatchesController : ApiController

In web.config I have:
<httpRuntime  requestValidationMode="2.0" targetFramework="4.5.2"/>
<pages validateRequest="false"/>

But still I am getting an error while using put method on address
http://localhost:51770/servers/62.210.26.98-1337/matches/2017-01-22T15:17:00Z
Error:
a potentially dangerous request.form value was detected from the client (:)
Apparently, it has problem with ":", how can I solve this problem?

A: If Validate input  not works may you try to use AllowHtml attirbute on your model.
as referenced here

For ASP.NET MVC 3 applications, when you need to post HTML back to
  your model, don't use ValidateInput(false) to turn off Request
  Validation. Simply add [AllowHtml] to your model property, like so:

public class BlogEntry {
    public int UserId {get;set;}
    [AllowHtml]
    public string BlogText {get;set;}
 }

UPDATE:
For web api request my you try like this:
<system.web>
    <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
    <pages validateRequest="false" />
</system.web>


text:
Q: What is the suffix used for long long constants If i want to use something like below in a C code:
if(num < 0x100000000LL)

I want the comparison to happen on a long long constant, but suffix LL doesn't work in MSVC6.0 , but it works in MS Visual Studio 2005.
How can i get it working in MSVC 6.0?
-Ajit

A: AFAIK, long long isn't supported in MSVC 6.0.
For example, have a look at this discussion thread. Perhaps, __int64 works instead. Anyway, I wouldn't know which other suffix to use.
EDIT: __int64 seems to work and for the supporting functions, it seems that no suffix is needed at all. Have a look here, for example. There's also some workaround at the end of this page.

A: The long long type was standardized in the 1999 ISO C Standard, and is expected to be standardized in C++ this year or next (whenever the standard is finalized).  Like all of these standard features, there have been early adopters and late adopters.  Language standards committees are usually reluctant to include things that haven't been tried before.
Visual C 6.0 was released in 1998, and therefore predates any standard with long long in it.

A: I don't have a copy of VC 6.0 to check, but does i64 work? (e.g. 12i64)


text:
Q: KO: Click event not firing in some situations I'm developing a SPA (Single Page Application) that looks like a book.
On the side of the book there are tabs that the user can click in order to navigate to different areas of the book.
The tabs also have transition effect applied to them using CSS3 transitions.
Problem is that sometimes, when I click one of the tabs, I see the transition happen (i.e the tab changes colour and moves 20px to left ) but the click event is not firing and I need to click 3-4 times for it to fire, while in most cases everything works fine.
UPDATE:
It seems like the problem is with the rotation (The tabs are rotated in 90deg), if i don't rotate them everything works fine,any idea how to overcome this?
HTML:

JS:
self.selectTab = function(chapter, e){
        goToPage({ chapter: chapter.chapterName });
        e.preventDefault();
        // e.stopPropagation();
    };

CSS (using LESS):
.caspBookTabs {
    position: absolute;
    top:85px;
    right:-15px;
    width: 150px;
    height: 100%;
    /* iPads (landscape) ----------- */
    @media only screen
    and (min-width : 768px)
    and (max-width : 1024px)
    and (orientation : landscape) {
        top: 75px;
        right:-35px;
    }
    li {
        margin-bottom: 110px;
        height: 33px;
        width: 130px;
        /* iPads (landscape) ----------- */
        @media only screen
        and (min-width : 768px)
        and (max-width : 1024px)
        and (orientation : landscape) {
            margin-bottom: 100px;
        }

        .rotation(90deg);
        display: block;
        background: url('@{caspImgPath}/tabs-i2.png') no-repeat 0 5px;
        text-align: center;
        line-height: 46px;
        /*padding-top: 20px;*/
        color: @tabsColor;
        .font-size(1.4);
        font-weight: bold;
        .transition-property(right);
        position: relative;
        right:0;
        &:hover {
            background-position: 0 -40px;
            cursor: pointer;
        }
        &:active {
            right: 10px;
        }
    }
    .caspActiveTab {
        right: 10px;
        background-position: 0 -40px;
    }
}

A: Found a solution, not sure it is the best one but that is the only one i've got, feel free to post other ideas if you have any:
After some testing it seems like the problem occurs when using rotation and transition on the same element, if I use only one of them everything seems to work.
So I just removed the CSS transition and instead mimic the effect using jQuery.animate().


text:
Q: How to check equality between two integers in Coq? I'm trying to check the equality between two integers in Coq, but I get this error: "The term "first = second" has type "Prop" which is not a (co-)inductive type.". Is there any library in Coq that provides equality checking? Here is my code:
Definition verify_eq (first : Z) (second : Z) : Z :=
   if first = second then 0 else 1.

A: You're in luck! In the same module where Z is defined (I'm assuming ZArith in the standard library), there's a term Z.eqb : Z -> Z -> bool that gives a a boolean test for integer equality (technically it's in the submodule Z — that's why there's a Z in the name).
Require Import ZArith. (* I assume you already imported this, since you're using Z *)

Definition verify_eq (first : Z) (second : Z) : Z :=
   if Z.eqb first second then 0 else 1.


text:
Q: How can I remove duplicates from a spinner in android The code for the spinner is below, The spinners on my app tend to duplicate it's content sometimes for some weird reason. How do I prevent this from happening?:
Spinner spinnerG = (Spinner) findViewById(R.id.spGroup);
    final ArrayAdapter<String> dataAdapterG = new ArrayAdapter<>
            (this, R.layout.simple_spinner_item, groups);
    dataAdapterG.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
    spinnerG.setAdapter(dataAdapterG);                                   //general basics       //sets up the group spinner, filled with the groups list

    spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            selectedGroup = groups.get(position);
            studentsToShow.clear();
            for(int i = 0; i < studList.size(); i++){
                if(studList.get(i).getGroup().equals(selectedGroup)){
                    Students a = new Students();
                    a.setFirstName(studList.get(i).getFirstName());
                    a.setLastName(studList.get(i).getLastName());
                    a.setStudentID(studList.get(i).getStudentID());
                    a.setGroup(studList.get(i).getGroup());
                    studentsToShow.add(a);                                                      //when a new group is chosen the list of students in the selected group needs to be updated
                }                                                                               //this re uses the code earlier to make a list of student in the selected group
            }
            updateSpS();                                                                        //updates the student spinner
        }
        public void onNothingSelected(AdapterView<?> parent){
        }
    });

A: The spinner will duplicate if you have put this oncreate event. Put the spinner population code on the onResume method.

A: From the snippet shared with the question, its hard to guess why OP would have duplicate value. An educated guess is his onItemSelected() is being called multiple times.
Spinner's (in my personal view, is one of the worst android widget) onItemSelected() can be called multiple times for different reasons, one of the thing I would recommend to try this way -
class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

        boolean userSelect = false;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            userSelect = true;
            return false;
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            if (userSelect) {
                // Your selection handling code here
                userSelect = false;
                if(view!=null){
                    selectedGroup = groups.get(position);
                    studentsToShow.clear();
                    for(int i = 0; i < studList.size(); i++){
                        if(studList.get(i).getGroup().equals(selectedGroup)){
                            Students a = new Students();
                            a.setFirstName(studList.get(i).getFirstName());
                            a.setLastName(studList.get(i).getLastName());
                            a.setStudentID(studList.get(i).getStudentID());
                            a.setGroup(studList.get(i).getGroup());
                            studentsToShow.add(a);                                                      //when a new group is chosen the list of students in the selected group needs to be updated
                        }                                                                               //this re uses the code earlier to make a list of student in the selected group
                    }
                    updateSpS();                                                                        //updates the student spinner
                }
            }
        }
    }

And then set -
SpinnerInteractionListener listener = new SpinnerInteractionListener();
spinnerG.setOnTouchListener(listener);
spinnerG.setOnItemSelectedListener(listener);

This at the same time takes care unwanted callbacks of onItemSelected() without user touch and if any previous leaked listeners.


text:
Q: Jdk 1.6.37 installation and setting up in fedora 17 I have installed jdk 1.6.37 in fedora 17 which already has java 1.7 openjdk i want to set java 1.6 as my default java how can i do this...
When i check the following command in terminal
                 alternatives --display java

the result does not list the jdk 1.6.37 but it actually installed and exist in /usr/java/

A: First you need to install alternatives :
update-alternatives --install /usr/bin/java java /path/to/bin/java 100

Then you can configure your java alternatives :
update-alternatives --config java

A: Let, update-alternatives --config java guide you.
Are you sure you want jdk (java development kit) instead of standart jre (java runtime environment) ?


text:
Q: Tensorflow hub-NNLM word embedding using sentiment140 data gives input shape error I am using tensorflow hub "https://tfhub.dev/google/nnlm-en-dim128/2" word embedding for the sentiment analysis of Kaggle "sentiment140" dataset.
Data set : Kaggle("sentiment140") https://www.kaggle.com/kazanova/sentiment140
Tensorflow-Hub : https://tfhub.dev/google/nnlm-en-dim128/2
Here i am using keras sequential layer when i fit the model it gives value error
ValueError: Python inputs incompatible with input_signature:
      inputs: (
        Tensor("IteratorGetNext:0", shape=(None, 128), dtype=float32))
      input_signature: (
        TensorSpec(shape=(None,), dtype=tf.string, name=None))

My code:
    import pandas as pd
import tensorflow as tf
from sklearn.model_selection import  train_test_split
import seaborn as sns
import tensorflow_hub as hub
from tensorflow.keras import Sequential
import keras

tweet_df = pd.read_csv("training.1600000.processed.noemoticon.csv", names=['polarity', 'id', 'date', 'query', 'user', 'text'],encoding='latin-1')

tweet_df.info()

tweet_df.head()

"""#### 2.) Data Visualization"""

tweet_df['polarity'] = tweet_df['polarity'].replace(to_replace=4,value=1)

### Print two movies reviews from each class

print("Movie Review Polarity Negative class 0 :\n", tweet_df[tweet_df['polarity']==0]['text'].head(2) )

print("\n\nMovie Review Polarity Positive class 1 :\n", tweet_df['text'][tweet_df['polarity']==1].head(2) )

class_dist = tweet_df['polarity'].value_counts().rename_axis('Class Label').reset_index(name='Tweets')
#class_dist = class_dist['Class Label'].replace({0:'Negative',1:'Positve'})
class_dist

## Bar graph of Distribution of Classes
class_dist['class'] = ['Positive','Negative']
sns.set_theme(style='whitegrid')
sns.barplot(x='Class Label', y='Tweets', hue='class', data= class_dist)

### Train and test split
X = tweet_df.iloc[:,5]
y = tweet_df.iloc[:,0]
X_train, X_test,y_train, y_test = train_test_split(X,y,random_state=5, test_size=0.2)

print("Training shape of X and y : ", X_train.shape ,y_train.shape)
print("Testing shape of X and y : ", X_test.shape ,y_test.shape)

"""#### 3.) Data Pre-processing"""

embed = hub.load("https://tfhub.dev/google/nnlm-en-dim128/2")
X_train_embed = embed(X_train)

y_train = tf.keras.utils.to_categorical(y_train,2)

X_train_embed.shape

X_sample = X_train_embed[:1000]
y_sample = y_train[:1000]
y_sample = tf.keras.utils.to_categorical(y_sample,2)

"""#### 4.) Model Building"""

hub_layer = hub.KerasLayer('https://tfhub.dev/google/nnlm-en-dim128/2',input_shape=[],dtype=tf.string,trainable=False)

model = Sequential()
model.add(hub_layer)
model.add(keras.layers.Dense(128, 'relu', name ='layer_1'))
model.add(keras.layers.Dense(64, 'relu', name = 'layer_2'))
model.add(keras.layers.Dense(2, activation='sigmoid', name='output'))

model.compile(optimizer='adam',loss= 'BinaryCrossentropy',  #'categorical_crossentropy' ,
              metrics=['accuracy'] )

NN_model = model.fit(X_sample, y_sample, epochs=20, validation_split=0.1, verbose=1)

Input shape:
X_sample.shape

TensorShape([1000, 128])
y_sample.shape

(1000, 2, 2)
X_sample

<tf.Tensor: shape=(1000, 128), dtype=float32, numpy=
array([[ 0.10381411,  0.07044576, -0.0282673 , ...,  0.08205549,
0.15822364, -0.10019408],
[-0.03332436, -0.00529242,  0.20348714, ..., -0.14174528,
0.05178985, -0.12599435],
[ 0.2461916 , -0.03084931,  0.05861813, ...,  0.07956063,
-0.03579932,  0.07493019],
[ 0.4102695 ,  0.15445013,  0.19045362, ...,  0.12681636,
0.12362286, -0.03969387],
[-0.0144283 , -0.05236297,  0.04851832, ...,  0.05562773,
0.01529189,  0.12605236],
[ 0.29280087,  0.05795274, -0.11779188, ..., -0.01890504,
0.02824693, -0.13629636]], dtype=float32)>

A: As described on https://tfhub.dev/google/nnlm-en-dim128/2, the model expects a vector of strings as input. You're basically calling the model twice since you're executing
embed = hub.load("https://tfhub.dev/google/nnlm-en-dim128/2")
X_train_embed = embed(X_train)  # (n, 128) float matrix

and then passing that embedding to model, which actually takes strings as input since it starts with the NNLM KerasLayer.
I'd propose to remove embed and X_train_embed and just call model.fit with X_train:
model.fit(np.array(["Lyx is cool", "Lyx is not cool"]), np.array([1, 0]), epochs=20, validation_split=0.1, verbose=1)


text:
Q: more than one label in Graphics3D I'm trying to add some information to my Graphics3D Plot. At the moment I output the value of a function that changes when I use the sliders. I do that with PlotLabel. I need more data to be displayed so I tried to have more PlotLabel functions devided by a comma. Doesn't work unfortunately. This is my Graph:
    Grid[{Manipulate[
   Graphics3D[
    Cylinder[{{0, 0, 0}, {0, 0, h}} ,
     rad[v,h]], Axes -> Automatic, PlotLabel->o[h]], {h, 0.1, 1,
    Appearance -> "Labeled"}, {v, 0.1, 1,
    Appearance -> "Labeled"}]}]

Also I would like to display some information to the number that is put out by the function o[h], but I was not able to do that.
Any help, hints, links are appreciated. Thanks!

A: rad[v_, h_] := v + h; (* for example *)

Here are a few ways to add multiple labels in/around a graphics object:
Manipulate[Labeled[Graphics3D[Cylinder[{{0, 0, 0}, {0, 0, h}}, rad[v, h]],
  PlotLabel -> Column[Style[#, 20] & /@ {Row[{oo[h], ooo[v]}, ","],
     ooo[v + h],  "... so on"}, Alignment -> Center],
  Axes -> Automatic],
  {Style[oooo[v], "Subsection"], Rotate[Style[ooo[h], "Subsection"], -Pi/2]},
  {{Top, Left}, {Right, Top}}],
 {h, 0.1, 1, Appearance -> "Labeled"}, {v, 0.1, 1, Appearance -> "Labeled"}]

You can also use "\n"(newline) instead of Column in PlotLabel setting. For example:
PlotLabel -> (Style[#, 20] &[
   ToString[oo[h]] <> ", " <> ToString[ooo[v]] <> "\n" <>
    ToString[ooo[v + h]] <> "\n... so on\nso forth"])

Alternatively, you can use StringForm as follows:
PlotLabel -> Style[#, 20] &[StringForm["``  ``\n``\n... so on\nand so forth",
  oo[h], ooo[v], ooo[v + h]]]


text:
Q: Sheets Arrayformula with IF, AND & OR I really need some help.
Is it possible to create an arrayformula in Google Sheets for this:
=
IF(AND(OR($F3>0,$G3>0),$G$1=TRUE),"A",
IF(AND(OR($H3>0,$I3>0),$I$1=True),"B",
IF(AND(OR($J3>0,$K3>0),$K$1=True),"C",
IF(AND(OR($L3>0,$M3>0),$M$1=True),"D",
""))))

I would like the arrayformula to cover each of the columns above e.g. F3:F>0, G3:G>0, etc.
Many, many thanks in advance.

A: try:
=ARRAYFORMULA(
 IF((((F3:F>0)+(G3:G>0))*(G1=TRUE)); "A";
 IF((((H3:H>0)+(I3:I>0))*(I1=TRUE)); "B";
 IF((((J3:J>0)+(K3:K>0))*(K1=TRUE)); "C";
 IF((((L3:L>0)+(M3:M>0))*(M1=TRUE)); "D"; )))))


text:
Q: ANTLR4 - Help to use with gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-11) I am in need of help regarding using ANTLR4 with the compiler version of C ++ for gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-11) -> "And no, it is not possible to update.".
This is because we already have an existing application running today in this version, and we would like to integrate this application with ANTLR4 in C++.
When performing the source build in VS2013 or VS2015, and trying to integrate with our existing application it seems that it is only compatible with C++ in the above compiler version than we use today. Does this information confer? Is there any way to use ANTLR4 in our compiler version? Thanks...

A: Unfortunately, current C++ runtime implementation required g++ version 5 or higher.
Details and answer here.
In your case, it's not easy to fix because C++11 required.


text:
Q: Query azure table to return only specific entities I have an azure table that contains 2 different entities
These 2 entity have the same partition key, it is intentional by design so these entities are
stored in one partition.
Row key is of course unique.
Is it possible to query only a specific entity by partition key?
or do i have to manualy create a property as an identifier for each entity in the same
azure table?
basically the shape of my table is
Partition Key| Row Key  |Entity Type |
====================================
1            |  X       | Entity A
1            |  Y       | Entity B
1            |  Z       | Entity B

I only want to retrieve for Entity B using the Partition Key 1

A: Specify both the partition key and the row key to retrieve a single entity. See http://www.windowsazure.com/en-us/documentation/articles/storage-dotnet-how-to-use-table-storage-20/#retrieve-single-entity for example code.

A: To query a specific entity you need to supply both the partition and the row key.
If you query only on the partition key, you get all rows with that partition key.
In your example above, querying using the partition key and 'Entity Type' will be less efficient than querying on the partition key and the row key. If the partition is large, the query can be quite slow since a partition scan will be needed.


text:
Q: PHP - Find file in Directory based on date /YEAR/MONTH/DAY - But not based on current date - static Datestamp I have a variable pulled from a SQL DB which is in the "datetime" format of:
2017-02-22 16:24:12

I will be needing to find a file in this directory based on the results of the remaining code, but im not sure how to format the date variables for the directory.
Eg:
/basefolder/2017/02/22/File.extension

I have read lots about using date variables, but they are all based on the current date. My thoughts were that I could just strip the numbers like
/basefolder/"first 4 numbers"/"second 2 numbers"/"last 2 numbers"/

VS trying to do this with any sort of date/time functions. But perhaps there is a date fuction I can/should use.
I do know that the datetime will always be formatted as such, but it feels "hackish" to do it the first way. I could do it in bash in a second, but I'm not so good w/ PHP.
Thanks for any help!
PS: To give context, I will be getting 2 variables passed to this php script, phone number and date. I will then query the CDR table for the Unique ID of this call record based on that information, then I know the file will be in:
/monitor/2017/02/22/*uniqueID*

Which I will then pass back to the original script to have it download the file.

A: You can use the function strtotime to convert your date string to a timestamp, and then use the date function to create the date formatted as you like, and you can pass the timestamp as the second argument (it only uses current time if you pass only the format)
docs for strtotime: http://php.net/manual/en/function.strtotime.php
<?php
$dateString = '2017-02-22 16:24:12';

$timestamp = strtotime($dateString);

$datepath = date('Y/m/d',$timestamp);

$path = "/basefolder/$datepath/";

var_dump($path);

This outputs: string(20) "/basefolder/2017/02/22/"
This code could be shortened to:
$path = "/basefolder/".date('Y/m/d/',strtotime('2017-02-22 16:24:12'));

It sounds like you already found the date function but there is more info on it here: http://php.net/manual/en/function.date.php
Note that you have to do it in two stages, as if you include the /basefolder/ part in the format passed to date, then it will replace individual characters with various formats of the date - e.g.:
$datepath = date('/basefolder/Y/m/d',$timestamp);

Sets $datepath to something like bpm12US/Pacificf2017Wednesday22US/PacificWed, 22 Feb 2017 16:24:12 -0800/2017/02/22
b is left alone because it means nothing, but then a is replaced with pm because of the time, s is replaced with the seconds value, e is replaced with the time zone and so on.

A: date_parse_from_format() will convert from string to broken down time array:
<?php
$d = date_parse_from_format("Y-m-d H:i:s", "2017-02-22 16:24:12");
$ds = sprintf("/base/%d/%02d/%d", $d['year'], $d['month'], $d['day']);
echo $ds;

A: This is my final code snippit!
<?php

$dateString = '2017-02-22 16:24:12';
$base = "/monitor/";

$path = "$base".date('Y/m/d/',strtotime("$dateString"));

echo $path;

?>