text:
Q: sqlalchemy equvalent of sql syntax I have a sql code that will print out all events that user with id=3 did not join particular yet:
SELECT * from Event where id not in (select event_id from Participant where user_id =3);

I want to write it in SQLAlchemy and so far I've got this
Event.query.filter(not_(Participant.user_id==3))

but produced query is not what I initially wrote:
SELECT "Event".id AS "Event_id",
"Event".name AS "Event_name",
"Event".published AS "Event_published",
"Event".published_when AS "Event_published_when",
"Event".published_by AS "Event_published_by"
FROM "Event", "Participant"
WHERE "Participant".user_id != ?

The above is not giving any results. I guess I wrote this SQLAlchemy query incorrectly. What is wrong with it?

A: Try something like this:
sub = Participant.query(Participant.event_id).filter(Participant.user_id==3)
res = Event.query.filter(Event.id.notin_(sub))

or maybe this way:
res = Session.query(Event, Participant).filter(Event.id == Participant.user_id).filter(Participant.user_id == 3)

A: Correct syntax:
Event.query.filter(Event.id.notin_(db.session.query(Participant.event_id).filter(Participant.user_id==session['uid'])))

Subquery had to be limited to event_id only. Thanks to this it will now return correct data from DB.


text:
Q: Problem with $wpdb I was trying to learn to use $wpdb but I don't know why it's not working.
<?php
/*
Plugin Name:  TEST

*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

function ctz_show(){
    global $wpdb;

    $table = "${$wpdb->prefix}postmeta";
    $query = "SELECT * FROM $table";
    $results = $wpdb->get_results($query);

    var_dump($results);
}

add_shortcode( 'cotizador', 'ctz_show' );

The output is always

array(0) { }

Even if I change the name of the table.

A: Try this, it should work much better ;)
  $table = "{$wpdb->prefix}postmeta";
  $query = "SELECT * FROM {$table}";

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to force an input frame rate on libav for mjpeg I am using libav to parsing a MJPEG Stream to get the packet data for resending it over an websocket, now I am facing the issue that ffmpeg use only 25 FPS. I know the Stream has 60FPS for 100%
These are the values after open and read the stream Informations:
avg_frame_rate = 0, r_frame_rate = 25/1,  time_base = 1/25
I tried to set all of them to a setting for 60FPS, but this looks has no effect.
I have set time_base to 1/60 and also frame rates to 60 but none of them are making any difference.
Because its an MJPEG Stream libav needs to guess the framerate, but I don't know why setting time_base or framerate does not have any effect.
Maybe someone could help me how I could force 60 FPS for parsing an MJEPG Stream, this would be great.
Thank u
This is just an Illustration of my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <libavutil/avutil.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

int main(int argc, char *argv[]) {
    AVFormatContext *fmt_ctx = NULL;
    AVCodecContext *codec_ctx = NULL;
    AVCodec *codec = NULL;
    AVPacket pkt;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <mjpeg-stream-url>\n", argv[0]);
        exit(1);
    }

    av_register_all();

    if (avformat_open_input(&fmt_ctx, argv[1], NULL, NULL) < 0) {
        fprintf(stderr, "Could not open stream '%s'\n", argv[1]);
        exit(1);
    }

    if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
        fprintf(stderr, "Could not find stream information\n");
        exit(1);
    }

    int video_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);

    if (video_stream_index < 0) {
        fprintf(stderr, "Could not find video stream\n");
        exit(1);
    }

    AVStream *video_stream = fmt_ctx->streams[video_stream_index];
    stream->time_base = (AVRational) { 1, 60};
    stream->avg_frame_rate = (AVRational) { 60, 1 };
    stream->r_frame_rate = (AVRational) { 60, 1 };

    av_init_packet(&pkt);

    while (av_read_frame(fmt_ctx, &pkt) >= 0) {
        if (pkt.stream_index == video_stream_index) {
            // Sending it to an websocket ....
        }
        av_packet_unref(&pkt);
    }

    avformat_close_input(&fmt_ctx);
    avformat_free_context(fmt_ctx);

    return 0;
}

A: The AVDictionary sets additional/specific parameters to endpoints and if you call it while opening the endpoint, it uses these specific parameters to open the endpoint.
It could take multiple key - value pairs and applies all of them to the endpoint.
I suppose creating an AVDictionay and passing a "framerate", "60" or may be "framerate" "60000/1000" parameter could solve your problem. Or if your source supports format_code then you could also use the format code something like "format_code", "Hp60" in the AVDictionary.
AVDictionary *options{nullptr};

// You should find the right parameter name
// like "frame_rate", "format_code", "sample_rate" etc.
// You can also set multiple options there!
// you may put all the possibilities once!

if(av_dict_set(&options, "framerate", "60", 0) < 0) {
        fprintf(stderr, "Could not set the option!\n");
        exit(1);
}

if (avformat_open_input(&fmt_ctx, argv[1], NULL, &options) < 0) {
        fprintf(stderr, "Could not open stream '%s'\n", argv[1]);
        exit(1);
}


text:
Q: How to make the mapview get from current location? As title, how to make the mapview zoom into the current location? By the way, I can get the current Log and Lon in getLocation(). Just don't know how to implement into the map. Thanks in advance someone who can help me.. I'm new to the android studio. This problem have make me confuse few day already.
package com.example.edward.neweventmanagementsystem;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Locale;

public class StaffAttendanceCheckIn extends AppCompatActivity  {

    private TextView mtxtTime, mtxtDate, txtDisplayName;
    private Spinner eventSpinner;

    private static final int REQUEST_LOCATION = 1;
    TextView textLocation;
    LocationManager locationManager;
    String latitude,longitude;
    MapView mapview;
    private GoogleMap map;

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

        mtxtDate = (TextView) findViewById(R.id.txtCurrentDate);
        mtxtTime = (TextView) findViewById(R.id.txtCurrentTime);
        txtDisplayName = (TextView) findViewById(R.id.txtDisplayName);
        eventSpinner = (Spinner) findViewById(R.id.eventSpinner);
        mapview = (MapView) findViewById(R.id.mapview);

        mapview.onCreate(savedInstanceState);

        SimpleDateFormat date = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
        String currentDate = date.format(new Date());

        SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
        String currentTime = time.format(new Date());

        mtxtDate.setText(currentDate);
        mtxtTime.setText(currentTime);

        FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
        txtDisplayName.setText(currentFirebaseUser.getDisplayName());

        /**
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("EventName");

        System.out.println("Test Script: " + myRef); */

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        textLocation = (TextView)findViewById(R.id.location);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();

        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            getLocation();
        }

    }

//    @Override
//    public void onClick(View view) {
//
//    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

            if (location != null) {
                double latti = location.getLatitude();
                double longi = location.getLongitude();

                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

                float ZOOM_MAP = 17.0f;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
                map.animateCamera(myLocation);

//                CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
//                System.out.println("Test Script" + myLocation);
//                map.animateCamera(myLocation);

            } else  if (location1 != null) {
                double latti = location1.getLatitude();
                double longi = location1.getLongitude();
                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

            } else  if (location2 != null) {
                double latti = location2.getLatitude();
                double longi = location2.getLongitude();
                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

            }else{

                Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();

            }
        }
    }

    protected void buildAlertMessageNoGps() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please Turn ON your GPS Connection")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        mapview.onDestroy();
    }

    @Override
    public void onLowMemory(){
        super.onLowMemory();
        mapview.onLowMemory();
    }

    @Override
    protected void onPause(){
        super.onPause();
        mapview.onPause();
    }
    @Override
    protected void onResume(){
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }
}

A: It's very easy you just need to do like:
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
mMap.animateCamera(myLocation);

ZOOM_MAP its float
Update ----
    mapview.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
                    googleMap.animateCamera(myLocation);
                }
            });


text:
Q: VBA: How to combine two ranges on different sheets into one, to loop through Trying to read two ranges of equal width but different lengths, each on different sheets, into another range which I need to loop through the combined data in a particular order.
Set wRIL = Worksheets("INS")
Set rRIL = wRIL.Range("L2")
Set rRIL = rRIL.CurrentRegion
Set rRIL = rRIL.Offset(1, 0).Resize(rRIL.Rows.Count - 1, rRIL.Columns.Count)

Set wROL = Worksheets("OUTS")
Set rROL = wROL.Range("N2")
Set rROL = rROL.CurrentRegion
Set rROL = rROL.Offset(1, 0).Resize(rROL.Rows.Count - 1, rROL.Columns.Count)

Set rRILROL = Union(rRIL, rROL)

Hoping to get a range of size rROL.Rows.Count + rRIL.Rows.Count long and rROL.Columns.Count wide.
This code stops at the Union command.

A: The Union function cannot span multiple worksheets (as any range object is contained by a single Worksheet object). If you want to process multiple ranges on different sheets in one loop you need to think about a different strategy, e.g.
Sub test()
Dim AllAreas(2) As Range, Idx As Integer, MyCell As Range, TargetRange As Range

    Set AllAreas(0) = Worksheets("Sheet1").[C4]
    Set AllAreas(1) = Worksheets("Sheet2").[D5]
    Set AllAreas(2) = Worksheets("Sheet3").[E6]
    Set TargetRange = Worksheets("Sheet4").[A1]

    For Idx = 0 To 2
        For Each MyCell In AllAreas(Idx).Cells
            MyCell = "co-cooo!"
            ' combine in targetrange - each cell of any source range is put at same position
            ' in sheet 4 ... mind the precedence ... highest sheet highest prio
            TargetRange(MyCell.Row, MyCell.Column) = MyCell
        Next MyCell
    Next Idx
End Sub

You can find the overlay of all ranges by the minimum and maximum .Row and .Column of all ranges within the array of ranges, so if you have a complex set of rules to aggregate parially overlapping ranges, start with finding min and max corners, run through all cells of the target range and ask: is there a value in area 0, 1, 2, ... and if so, then decide which one takes precedence.
To make things even more elegant you can build  ...
Type RngDef
    Rng As Range
    MinCol As Integer
    MaxCol As Integer
    MinRow As Integer
    MaxRow As Integer
End Type

Sub test2()

Dim AllAreas(2) As RngDef, Idx As Integer, MyCell As Range, TargetRange As Range

    Set AllAreas(0).Rng = Worksheets("Sheet1").[C4]
    Set AllAreas(1).Rng = Worksheets("Sheet2").[D5]
    Set AllAreas(2).Rng = Worksheets("Sheet3").[E6]

    For Idx = 0 To 2
        AllAreas(Idx).MinCol = AllAreas(Idx).Rng(1, 1).Column
        AllAreas(Idx).MinRow = AllAreas(Idx).Rng(1, 1).Row
        AllAreas(Idx).MaxCol = AllAreas(Idx).MinCol + AllAreas(Idx).Rng.Columns.Count - 1
        AllAreas(Idx).MaxRow = AllAreas(Idx).MinRow + AllAreas(Idx).Rng.Rows.Count - 1
    Next Idx

    Set TargetRange = Worksheets("Sheet4").[A1]

End Sub

Now you have all ranges and their boundaries at hand ...


text:
Q: Div container not expanding - please help newbie web page is http://www.naifaraleigh.com/template2.php
css is http://www.naifaraleigh.com/layerstyle.css
I so much want this to work, to learn how to do this, but I am beginning to hate CSS and think that tables are not a bad thing after all! grins! Just kidding!
everything is contained in the div called container
I have managed to make the main content div slightly off center and rounded corners in white_back
I have managed to put in an absolute div to the right containing nav and logo
But I simply cannot, whatever I try, get the white_back div to stretch downwards to envelop the content of the web page.
Please please help, stop me turning back to the "Dark Side" of tabular layouts!
Thanks!

A: Do you mean #white_back{height:auto;} ???
Why do you have #white_back{height: 458px;} if you want it to stretch downwards?


text:
Q: Adding a text field with click of a button with javascript: all content except text field disappears on click I would like to have an Add another field button that creates a text field <input type="text" name="pet"> each time that button is pressed.
I currently have this code:

<form name="input" method="get">
Favourite pets:

<input type="text" name="pet">
<button type="button" onclick="add_field()">Add another field</button>

<input type="submit" value="Submit">

</form>

But when I press the Add another field button I just get a page with only a text field, all my other content disappears. How do I still keep my other html content while adding another text field?

A: This line:
document.write( '<input type="text" name="pet">' );

Will replace the entire document with the inserted markup. If you want to append the input field, you need to find the form you want to append to, create the input field and append it. Try something like:
var form = document.getElementsByTagName('form')[0],
    input = document.createElement('input');

input.setAttribute('type', 'text');
input.setAttribute('name', 'pet');
form.appendChild(input);

This will insert the input in the end of the form. You can use other methods, such as insertBefore to place the input field where you want it.
Or use jQuery.


text:
Q: How to reclaiming deleted space without `db.repairDatabase()`? I want to shrink data files size by reclaiming deleted space, but I can't run db.repairDatabase(), because free disk space is not enough.

A: If you're running a replica-set, you will want to issue a resync on each of your secondaries, one at a time.  Once this has been completed, step-down your primary and resync the newly assigned secondary.
To resync, stop your mongod instance, delete the locals and start the process back up.  Watch the logs to ensure everything starts back up properly and the resync has initiated.
If you have a lot of data / indexes, ensure your oplog is large enough, otherwise it's likely to go stale.

A: Update: With WiredTiger, compact does free space.
The original answer to this question is here:
Reducing MongoDB database file size
There really is nothing outside of repair that will reclaim space. The compact should allow you to go much longer on the existing space. Otherwise, you will have to migrate to a bigger drive.
One way to do this is to use an off-line secondary from your Replica Set. This should give you a whole maintenance window to migrate, repair, move back and bring back up.
If you are not running a Replica Set, it's time to look at doing just that.

A: You could run the compact command on a single collection, or one by one in all the collections you want to shrink.
http://www.mongodb.org/display/DOCS/Compact+Command
db.runCommand( { compact : 'mycollectionname' } )

As noted in comments, I was mistaken, compact does not actually reclaim disk space, it only defragments and rebuilds collection indexes.
Instead though, you could use "--repairpath" option if you have another drive available which has available freespace.
For example:
mongod --dbpath /data/db --repair --repairpath /data/db0

Shown here: http://docs.mongodb.org/manual/tutorial/recover-data-following-unexpected-shutdown/

A: You can as well do a manual mongodump and mongorestore. That's basically the same what repairDatabase does. That way you can dump and restore it to/from a different machine with sufficient disk space.

A: There is one other option, if you are using a replica set, but with a lot of caveats.  You can fail over to another set member, then delete the files on the now former primary and do a full resync.  A full resync rewrites the files from scratch in a similar way to a repair, but you will also have to rebuild indexes.  This is not to be done lightly.
If you go down this path, my recommendation would be to have a 3 member replica set before doing this for disk space reclamation, so that at any time when a member is syncing from scratch you have 2 set members fully functional.
If you do not have a replica set, I recommend creating one, with two secondaries.  When you sync them initially you will be creating a nice unfragmented and unpadded versions of your data.  More here:
http://www.mongodb.org/display/DOCS/Replica+Set+Configuration


text:
Q: Правила и фильтры OpenLayers (отбор по свойствам объектов) Есть GeoJSON вида:
{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-108.04,44.68]},"properties":{"course":184.7,"vid":1}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-111.04,45.68]},"properties":{"course":44.1,"vid":2}}]}

Являющийся источником слоя vectors (см. "Как послать JSON в теле HTTP-ответа?").
Нужен фильтр показывающий только точки с vid входящим массив, вида:
var pointShow = [1,3];

Вроде бы для этого нужно использовать правила (Rule), но я с OpenLayers не особо знаком, да и в интернете найти что-то по теме кроме описания FeatureId на сайте "OpenLayers" не получилось.
Пробовал сделать так:
var myStyle = new OpenLayers.Style();
var defRule = new OpenLayers.Rule({
    filter: new OpenLayers.Filter.FeatureId({fids: ["2242"]}),
    symbolizer: {
        externalGraphic: "OpenLayersRotationExample_files/marker-red.png",
        graphicWidth: 21,
        graphicHeight: 25,
        graphicXOffset: -10,
        graphicYOffset: -12
    }
});
myStyle.addRules([defRule]);

...

vectors = new OpenLayers.Layer.Vector(
   "Simple Geometry",
   {
      protocol: new OpenLayers.Protocol.Script({
        url: "http://localhost:8181/view",
        callbackKey: "format_options",
        callbackPrefix: "callback:",
        filterToParams: function(filter, params) {
          if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
            params.bbox = filter.value.toArray();
            if (filter.projection) {
              params.bbox.push(filter.projection.getCode());
            }
          }
          return params;
        }
      }),
      strategies: [
        new OpenLayers.Strategy.Refresh({force: true, interval:10000}),
        new OpenLayers.Strategy.BBOX({resFactor:2})
      ],
      styleMap: new OpenLayers.StyleMap({
        "default": myStyle
      })
   }
);

Но в итоге я ничего не вижу.
В связи с этим вопрос - как правильно писать правила и фильтры OpenLayers?
Буду признателен за полезные ссылки на примеры и примеры использования разных фиьтров, в частности FeatureId (желательно более понятных чем тут "Filtering a WFS Layer").
PS: Пока решил так:
var myStyle = new OpenLayers.Style();
var defRule = new OpenLayers.Rule({
  symbolizer: {
    externalGraphic: "OpenLayersRotationExample_files/marker.png",
    graphicWidth: 14,
    graphicHeight: 17,
    graphicXOffset: -7,
    graphicYOffset: -8,
    graphicOpacity: 0.9,
    rotation: "${course}",
    display: "none"
  }
});
myStyle.addRules([defRule]);
for (keyVar in arr) {
  myStyle.addRules([
    new OpenLayers.Rule({
      filters: [new OpenLayers.Filter.Comparison({
        type: OpenLayers.Filter.Comparison.EQUAL_TO,
        property: "vid",
        value: arr[keyVar]
      }),
      symbolizer: {
        externalGraphic: "OpenLayersRotationExample_files/marker-red.png",
        display: ""
      }
    })
  ])
}

//arr - список id объектов которые нужно показать
//vid, course - поля свойств объектов (properties)

Возможно не очень красиво и медленно, но работает. Кто знает как разобраться с FeatureId, прошу подскажите - все таки, я думаю, он быстрее отработает чем куча фильтров.

A: У вас JSON не полный. У каждой feature должен быть некоторый "id", по которому фильтровать фильтром FeatureId.


text:
Q: Select the latest record based on certain criteria in PL/SQL I have a table with real-time scanning data from our employees. As you can see, each boxes can be scanned multiple times, even employees can scan the boxes multiple time for one status.
I am trying to pull the latest record for each box, but the status for the latest record should be "Refused"
From the picture, as you can see, although Carton 1234 has a record with status "Refused", but this record is not the last one, so I don't need this. And the carton 1235 is what I need.
I don't want to use a window function to rank each record in the table first, because I have a lot of rows in the table, and I think it will be time consuming.
So is there any better way to achieve my goal?

A: Supposing that you don't really need a PL/SQL solution. Here is SQL only:
This is a solution without window functions:
select *
from mytable
where (carton_id, scantime) in
(
  select carton_id, max(scantime)
  from mytable
  group by carton_id
  having max(status) keep (dense_rank last order by scantime) = 'Refused'
);

But I don't think that this is superior to using a window function. So you can just as well try
select *
from
(
  select mytable.*, max(scantime) over (partition by carton_id) as max_scantime
  from mytable
  group by carton_id
)
where scantime = max_scantime and status = 'Refused';

A: Here is one method:
select t.*
from t
where t.status = 'Refused' and
      t.scantime = (select max(t2.scantime) from t t2 where t2.carton_id = t.carton_id);


text:
Q: Serial Port Fails to open, Error 2? I'm having problems with opening a serial port in C++ on Windows 7. I'd like to send serial data from my computer to another one through a USB cable. The code I've found from various online sources is as follows:
#include <windows.h>
#include <stdio.h>

int main()
{
    // Define the five bytes to send ("hello")
    char bytes_to_send[5];
    bytes_to_send[0] = 104;
    bytes_to_send[1] = 101;
    bytes_to_send[2] = 108;
    bytes_to_send[3] = 108;
    bytes_to_send[4] = 111;

    // Declare variables and structures
    HANDLE hSerial;
    DCB dcbSerialParams = {0};
    COMMTIMEOUTS timeouts = {0};

    // Open the highest available serial port number
    fprintf(stderr, "Opening serial port...");
    hSerial = CreateFile(
                "COM8", GENERIC_READ|GENERIC_WRITE, 0, 0,
                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 );
    if (hSerial == INVALID_HANDLE_VALUE)
    {
            fprintf(stderr, "Error\n");
            printf ("CreateFile failed with error %d.\n", GetLastError());
            return 1;
    }
    else fprintf(stderr, "OK\n");

The programme never gets past this point, and the error which it throws is "Error 2". From what I've read I think this corresponds to "System cannot find the file specified". However it won't open for whatever COM port I try to use. I've also tried "\\.\COM8" but to no avail. Does anyone know some common problems that could be causing this issue? Are there any hardware specific issues to look out for?


text:
Q: How to set the httpd.conf when using php-fpm with php(5.3.8) and apache2? I want to use fastcgi in apache2 with php(5.3.8).
I installed fastcgi_module in apache, and compiled php with--enable-fpm.
I also found some tutorials,there were two methods in their settings:

FastCgiServer /usr/local/apache2/fcgi-bin/php-cgi -processes 10

or

FastCgiExternalServer /usr/local/apache2/fcgi-bin/php-cgi -host 127.0.0.1:9000

But I can not find the php-cgi in php 5.3.8. what should I do next?
How to set the httpd.conf when using php-fpm with php(5.3.8) and apache2?

A: The secret here is that php-cgi is nto a real file, it's a wrong file name use internally in Apache. You could call it as well : false-php-cgi-catcher-which-do-not-exists.
I wrote a complete php-fpm+apache2.2+chroot install guide a few days ago here. You may have a look. But try to get it working without the chroot first. Note that starting with apache 2.3 the best tool for php-fpm will be mod_proxy_fcgi
Here's an extract of the complete install guide. I use php5.external where you want to use php-cgi.
# phpfpm/fastcgi
# Here we catch the 'false' Location used to inexistent php5.external
# and push it to the external FastCgi process via a socket
# note: socket path is relative to FastCgiIpcDir
# which is set in Main configuration /etc/apache2/mods-available/fastcgi.conf
<IfModule mod_fastcgi.c>
    # all .php files will be pushed to a php5-fcgi handler
    AddHandler php5-fcgi .php

    #action module will let us run a cgi script based on handler php5-fcgi
    Action php5-fcgi /fcgi-bin/php5.external

    # and we add an Alias to the fcgi location
    Alias /fcgi-bin/php5.external /php5.external

    # now we catch this cgi script which in fact does not exists on filesystem
    # we catch it on the url (Location)
    <Location /fcgi-bin/php5.external>
        # here we prevent direct access to this Location url,
        # env=REDIRECT_STATUS will let us use this fcgi-bin url
        # only after an internal redirect (by Action upper)
        Order Deny,Allow
        Deny from All
        Allow from env=REDIRECT_STATUS
    </Location>
</IfModule>
FastCgiExternalServer /php5.external -socket myapplication.sock -appConnTimeout 30 -idle-timeout 60


text:
Q: Loop through hash in puppet define I'm passing a hash to a define like so:
nodes.pp
    net::addr { 'routes':
    ipr => {
        ipr1 => {
            address => '192.168.34.38',
            netmask => '255.255.255.0',
            gateway => '192.168.34.1',
            dev     => 'eth3',
        },
        ipr22 => {
            address => '10.1.5.33',
            netmask => '255.255.255.0',
            gateway => '10.1.5.1',
            dev     => 'eth2',
        },
  }
  }

addr.pp
define net::addr (
    $routes={},
)
{
    if ($num != "") {
     $iname=${routes[route${num}][dev]}
     $num+1
    }
    else{
     $num=0;
    }
}

What I want to do is define a variable called iname and set it to the dev under each hash element, so on iteration 1 I want dev to be set to eth3, which corresponds to the "ipr1" element, on the next iteration I was iname set to eth2 and so on.
I'm struggling to do this as everytime my num variable keeps getting undefined and then ends up being set to 0, can someone please suggest a way round this or a more intelligent solution?

A: As of Puppet version 3.3, the Puppet DSL language does not support iteration.
You should check out the create_resources() function from Puppet Labs:
https://puppet.com/docs/puppet/latest/function.html#createresources
Example
# A hash of user resources:
$myusers = {
  'nick' => { uid    => '1330',
              group  => allstaff,
              groups => ['developers', 'operations', 'release'], }
  'dan'  => { uid    => '1308',
              group  => allstaff,
              groups => ['developers', 'prosvc', 'release'], }
}

create_resources(user, $myusers)

However, as of Puppet 4.0, the Future Parser now supports iteration with Lambdas:
$data = ['a','b','c']

$data.each |Integer $index, String $value| {
    notice("${index} = ${value}")
}


text:
Q: FormBorderStyle.None removes the native open effect of windows 8 I like to have my form borderless in C#. So I used this code:
FormBorderStyle = FormBorderStyle.None;

But it removes the aero effect of windows 8. The form opens suddenly like a blink.
How can i bring the aero effect back?

A: I am answering my own question using the C++ reference
I wrote a class inherited from Form Class. Each form in application should be inherited from this class instead of Form Class.
 public class AeroForm : Form
 {
    int _w = 100, _h = 100;
    bool aero = false;

    [StructLayout(LayoutKind.Sequential)]
    struct MARGINS { public int Left, Right, Top, Bottom;  }

    [DllImport("dwmapi.dll", PreserveSig = false)]
    static extern void DwmExtendFrameIntoClientArea
                              (IntPtr hwnd, ref MARGINS margins);

    [DllImport("dwmapi.dll", PreserveSig = false)]
    static extern bool DwmIsCompositionEnabled();

    public AeroForm()
    {
            aero = IsCompositionEnabled();
        }

        public AeroForm(int width, int height)
            : this()
        {
            _w = width;
            _h = height;
            Size = new Size(width, height);
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_NCCALCSIZE = 0x0083;
            switch (m.Msg)
            {
                case WM_NCCALCSIZE:
                    if (aero)
                        return;
                    break;
            }
            base.WndProc(ref m);
        }

        //this is for checking the OS's functionality.
        //Windows XP does not have dwmapi.dll
        //also, This corrupts the designer...
        //so i used the Release/Debug configuration
        bool IsCompositionEnabled()
        {
    #if !DEBUG
            return File.Exists(Environment.SystemDirectory + "\\dwmapi.dll")
                 && DwmIsCompositionEnabled();
    #else
            return false;
    #endif
        }

        //this one is used for a shadow when aero is not available
        protected override CreateParams CreateParams
        {
            get
            {
                const int CS_DROPSHADOW = 0x00020000;
                const int WS_MINIMIZEBOX = 0x20000;
                const int CS_DBLCLKS = 0x8;
                CreateParams cp = base.CreateParams;
                if (!aero)
                    cp.ClassStyle |= CS_DROPSHADOW;
                cp.Style |= WS_MINIMIZEBOX;
                cp.ClassStyle |= CS_DBLCLKS;
                return cp;
            }
        }

        //this is for aero shadow and border configurations
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (aero)
            {
                FormBorderStyle = FormBorderStyle.FixedSingle;
                ControlBox = false;
                MinimizeBox = false;
                MaximizeBox = false;
                Size = new Size(_w, _h);
                MARGINS _glassMargins = new MARGINS()
                {
                    Top = 5,
                    Left = 5,
                    Bottom = 5,
                    Right = 5
                };
                DwmExtendFrameIntoClientArea(this.Handle, ref _glassMargins);
            }
            else
                FormBorderStyle = FormBorderStyle.None;
        }

        //When you minimize and restore, the size will change.
        //this override is for preventing this unwanted resize.
        protected override void OnPaint(PaintEventArgs e)
        {
            if (aero)
                Size = new Size(_w, _h);
            base.OnPaint(e);
        }
    }

with Show() and Application.Run() it works great!
but it has some regressions when the form opens with ShowDialog(). Closing the form, you will see a border that closes after your client content hides.


text:
Q: Retrieve Jtree from DataBase Table I made an Jtree in which take values from user and store it in linkedHashMap and then LinkedHashMap values store in a database table (with columns id,name,parent,level). Now I retrieve the table from database and I also print all the rows.
But I am unable to understand how I can retrieve Jtree from the table data.
 Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
        String url="jdbc:oracle:thin:@localhost:1521:XE";
        conn = DriverManager.getConnection(url, "Hr", "Hr");
        System.out.println("Connection Established");

         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM contacts");
         System.out.println("id  name    job"+ rs);

         while (rs.next()) {
            int id = rs.getInt("node_Id");
            String name = rs.getString("node_Name");
            String job = rs.getString("node_Parent");
            String lvl = rs.getString("node_Level");
            System.out.println(id+"   "+name+"    "+job+" "+lvl );
            System.out.println("lalalala "+ id);
            System.out.println("nasjdnasj");
        }}

        catch(Exception e){
            System.out.println("connection error "+ e);
        }

This is the code which retrieve table columns from database and prints all the values


text:
Q: Lambda or Linq method to search multiple parameters I have a List of Of Objects and id like to query the list with multiple parameters to whittle down the results on a search page.
     int SecLink = (!string.IsNullOrEmpty(Request.QueryString["Sector"])) ? Convert.ToInt32(Request.QueryString["Sector"]) : 0;
        int LocLink = (!string.IsNullOrEmpty(Request.QueryString["Location"])) ? Convert.ToInt32(Request.QueryString["Location"]) : 0;
        int IndLink = (!string.IsNullOrEmpty(Request.QueryString["Industry"])) ? Convert.ToInt32(Request.QueryString["Industry"]) : 0;
        int VacLink = (!string.IsNullOrEmpty(Request.QueryString["Vacancy"])) ? Convert.ToInt32(Request.QueryString["Vacancy"]) : 0;

        string keyword = Request.QueryString["SearchTerm"];

        var dx = new DataX();
        var lstJobs = dx.GetAllJobs().Where(x => x.SectorLink.Equals(SecLink) && x.LocationLink.Equals(LocLink) && x.IndustryLink.Equals(IndLink) && x.VacancyTypeLink.Equals(VacLink) && x.JobName.Contains(keyword)).ToList();

        if (lstJobs.Count > 0)
        {
            uiRptSearchJobs.DataSource = lstJobs;
            uiRptSearchJobs.DataBind();

            uiLitSearchResults.Text = string.Format("
Search result found {0} matches
", lstJobs.Count);
        }

The search params may be '0' as not selected from the previous page, so the results should reflect his.
This is the querystring im passing:
Default.aspx?section=search&Sector=4&Location=0&Industry=0&Vacancy=0&SearchTerm=
but as you can see they querystring will change with what the user selects from the previous page.

A: If I understand correctly, you don't want to filter if the value of the parameters is 0? If so, two solutions:

*

*Check if the parameter is equal to 0 in your condition:
var lstJobs = dx.GetAllJobs().Where(x =>
    (SecLink == 0 || x.SectorLink.Equals(SecLink))
    && (LocLink == 0 || x.LocationLink.Equals(LocLink))
    && (IndLink == 0 || x.IndustryLink.Equals(IndLink))
    && (VacLink == 0 || x.VacancyTypeLink.Equals(VacLink))
    && x.JobName.Contains(keyword)).ToList();

*Linq goodness, dynamically construct your query:
    var query = dx.GetAllJobs().Where(x => x.JobName.Contains(keyword));

    if (SecLink != 0)
    {
        query = query.Where(x => x.SectorLink.Equals(SecLink));
    }

    if (LocLink != 0)
    {
        query = query.Where(x => x.LocationLink.Equals(LocLink));
    }

    if (IndLink != 0)
    {
        query = query.Where(x => x.IndustryLink.Equals(IndLink));
    }

    if (VacLink != 0)
    {
        query = query.Where(x => x.VacancyTypeLink.Equals(VacLink));
    }

    var lstJobs = query.ToList();

A: One option is to conditionally perform the Where clauses:
If the search terms should be ANDed together:
var lstJobs = dx.GetAllJobs();

if (SecLink > 0)
    lstJobs = lstJobs.Where(x => x.SectorLink.Equals(SecLink))

if (LocLink > 0)
    lstJobs = lstJobs.Where(x => x.LocationLink.Equals(LocLink))

if (IndLink > 0)
    lstJobs = lstJobs.Where(x => x.IndustryLink.Equals(IndLink))

if (VacLink > 0)
    lstJobs = lstJobs.Where(x => x.VacationLink.Equals(VacLink))

// Performance does not suffer because the query will
// not get evaluated until it's required. For example,
// here we call .ToList, which forces the query to be evaluated.
var result = lstJobs.ToList();

However, you've made it clear you need the search terms ORed together. In that case:
var lstJobs = dx.GetAllJobs().Where(x => x.JobName.Contains(keyword));

if (SecLink > 0)
    lstJobs = lstJobs.Union(
        dx.GetAllJobs().Where(x => x.SectorLink.Equals(SecLink))

if (LocLink > 0)
    lstJobs = lstJobs.Union(
        dx.GetAllJobs().Where(x => x.LocationLink.Equals(LocLink))

etc...


text:
Q: Read comma separated csv file with fields containing commas using fread in r I have a csv file separated by comma. However, there are fields containing commas like company names "Apple, Inc" and the fields will be separated into two columns, which leads to the following error using fread.
"Stopped early on line 5. Expected 26 fields but found 27."
Any suggestions on how to appropriately load this file?
Example rows are as follows. It seems that there are some fields with comma without quotes. But they have whitespace following the comma inside the field.
100,Microsoft,azure.com
300,IBM,ibm.com
500,Google,google.com
100,Amazon, Inc,amazon.com
400,"SAP, Inc",sap.com

A: 1) Using the test file created in the Note at the end and assuming that the file has no semicolons (use some other character if it does) read in the lines, replace the first and last comma with semicolon and then read it as a semicolon separated file.
L <- readLines("firms.csv")
read.table(text = sub(",(.*),", ";\\1;", L), sep = ";")
##    V1          V2         V3
## 1 100   Microsoft  azure.com
## 2 300         IBM    ibm.com
## 3 500      Google google.com
## 4 100 Amazon, Inc amazon.com
## 5 400    SAP, Inc    sap.com

2) Another approach is to use gsub to replace every comma followed by space with semicolon followed by space and then use chartr to replace every comma with semicolon and every semicolon with comma and then read it in
as a semicolon separated file.
L <- readLines("firms.csv")
read.table(text = chartr(",;", ";,", gsub(", ", "; ", L)), sep = ";")
##    V1          V2         V3
## 1 100   Microsoft  azure.com
## 2 300         IBM    ibm.com
## 3 500      Google google.com
## 4 100 Amazon, Inc amazon.com
## 5 400    SAP, Inc    sap.com

3) Another possibility if there are not too many such rows is to locate them and then put quotes around the offending fields in a text editor.  Then it can be read in normally.
which(count.fields("firms.csv", sep = ",") != 3)
## [1] 4

Note
Lines <- '100,Microsoft,azure.com
300,IBM,ibm.com
500,Google,google.com
100,Amazon, Inc,amazon.com
400,"SAP, Inc",sap.com
'
cat(Lines, file = "firms.csv")

A: Works fine for me. Can you provide a reproducible example?
library(data.table)

# Create example and write out
df_out <- data.frame("X" = c("A", "B", "C"),
                     "Y"= c("a,A", "b,B", "C"))

write.csv(df_out, file = "df.csv", row.names = F)

# Read in CSV with fread
df_in <- fread("./df.csv")
df_in

   X   Y
1: A a,A
2: B b,B
3: C   C


text:
Q: fastest way to convert a file to list c++ i have a file full of integers, sorted, i need to get the content of the file to a list.
the file looks something like this:
     1
     4
     45
     150
     245
     365

i know it's possible to read line by line and push_back, but the file count more than 500 000 line so is their a quick way to do this?
the goal is to see if an integer is in the file, so i need to convert to list and then do a binary_search, if you have a better idea, i'll be gratefull.

A: To read into list you can use std::istreambuf_iterator:
std::ifstream t( "file.txt");
std::list<int> l( ( std::istreambuf_iterator<int>( t)),
                     std::istreambuf_iterator<int>());

A: If you want to search multiple times I suggest putting the file content into a hash table. This gives you O(1) lookup which is optimal.

A: I would do this like:
#include <iostream>
#include <iterator>
#include <unordered_set>

int main() {
  std::ifstream t { "file.txt", ios::ate };
  std::unordered_set s;
  s.reserve(t.tellg());
  t.seekg(0);
  s.insert(std::istream_iterator<int>(t), std::istream_iterator<int>());
// now you can use s.find(key) to see if something is in the set
}


text:
Q: Ability to multiple 1 row of existing column with another row of existing column in R to create a 3rd column I am trying to create a new column in the below data set column DPD roll over; wherein I want to calculate ratio based on value from row 1 in column DPD <29 and row 2 in column DPD 30 to 60 (eg: 30 / 55). Can anyone please help with answer? I am looking to do this in R
Month    DPD <29       DPD 30 to 60
May 12    55                25
Jun 12    60                30

A: We can use lead to get the next value
library(dplyr)
df1 %>%
    mutate(ratio = lead(`DPD 30 to 60`)/`DPD <29`)


text:
Q: How do I instantiate an object of a class that will generate and return an object of another class? This is the actual question.  Instantiate an object of the given class: AirPlaneGenerator that will generate and return an AirPlane object whenever the interval time (set during instantiation) has elapsed.  NOTE: the generator will return NULL between intervals; signifying that no plane is currently landing.
This is the cpp file for the airport generator file
    #include "airplanegenerator.h"
        // initialize the static list of tasks
    vector<AirPlane> AirPlaneGenerator::lstPlanes(0);
    // -- Constructors --
     // default constructor
    AirPlaneGenerator::AirPlaneGenerator(int i) {
// initialise all airplanes within the list
this->interval = i;
this->cursor = 0;
this->elapsed = 0;

     AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new

      AirPlane(JFF_GOVERNMENT));

      AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_VIP));

    AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_MAIL));
 AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_GOVERNMENT));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_VIP));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_VIP));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_SMALLPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_SMALLPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_SMALLPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_VIP));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_LARGEPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_LARGEPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_SMALLPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_GOVERNMENT));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_LARGEPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_GOVERNMENT));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
     AirPlane(JFF_GOVERNMENT));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_LARGEPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_SMALLPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_MAIL));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_SMALLPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_VIP));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_GOVERNMENT));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_LARGEPASS));
AirPlaneGenerator::lstPlanes.insert(AirPlaneGenerator::lstPlanes.end(), new
    AirPlane(JFF_GOVERNMENT));
cout << " GENERATOR: AirPlanes Are Ready For Landing." << endl;
}
// -- Other Interfaces --
// get the next task in the list
AirPlane* AirPlaneGenerator::getNext() {
     // find out the current elapsed time
    this->elapsed += 1;
    // return an airplane if the elapsed time exceeds the current cursor position
     if (this->elapsed / this->interval >= 1) {
    this->elapsed -= this->interval;
    if (this->cursor < TOTALPLANES) {
        cout << " GENERATOR: AirPlane# " <<
AirPlaneGenerator::lstPlanes[this->cursor].getIdnum() << " Now Landing." << endl;
        return &(AirPlaneGenerator::lstPlanes[this->cursor++]);
    } else {
        cout << " GENERATOR: No More AirPlanes In The Air To Land." << endl;
        return NULL;
    }
    } else {
    cout << " GENERATOR: No AirPlane Landing Now." << endl;
    return NULL;
   }
}

A: Question is you need to implement Creational Pattern (Factory Pattern), which will create object of class after given interval time.


text:
Q: Invalid attempt to destructure non-iterable instance - Bot 4.0 WebChat.js
[object Error]: {message: "Invalid attempt to destructure non-iterable
  instance", stack: "TypeError: Invalid attempt to destructure
  non-iterable instance at e.exports
  (https://cdn.botframework.com/botframework-webchat/latest/webchat.js:1:566613)
  at e.exports  at t.unstable_runWithPriority
  (https://cdn.botframework.com/botframework-webchat/latest/webchat.js:1:351563)
  at Rs
  (https://cdn.botframework.com/botframework-webchat/latest/webchat.js:1:339772)
  at Ps
  (https://cdn.botframework.com/botframework-webchat/latest/webchat.js:1:339567)"}

 (async function () {
        const res = await fetch('https://tokenservice/api/DLToken', { method: 'POST' });
        const {token}  = await res.json();
        console.log({token});
        window.WebChat.renderWebChat(
            {
                bot: bot,
                directLine: window.WebChat.createDirectLine({token}),
                user: user,
                speechOptions: speechOptions,
                resize: 'detect',
                styleOptions: styleOptions
            },
            document.getElementById('BotChatGoesHere')
        );

I am getting this error in Edge and IE, in Chrome it works fine. Please suggest solution, will be obliged.

A: IE 11 doesn't support async/await keyword. We need to use es5 bundle in IE. Please try to use https://cdn.botframework.com/botframework-webchat/latest/webchat-es5.js instead.
Reference:
Latest WebChat : IE11 Compatibility
Sample - Getting Started with Web Chat CDN with ES5 Polyfills


text:
Q: Im using JOptionPane and I'm not sure why its not working when I try to enter the Item Id for the first "?" it asks in my code A company manufactures 10 items. write java program to store 10 items and their prices in arrays. if a customer ordered an item, your program checks whether it is valid, if it is valid print price
import javax.swing.JOptionPane;

public class ParallelArray3 {

    public static void main(String[] args){

        final int Num =10;
        int [] Item= {101, 110, 210, 220, 300, 310, 316, 355, 405, 410};
        double [] Price= {0.29, 1.23, 3.50, 0.89, 6.79, 3.12, 4.32, 3.6, 8.3, 5.4};

        String ItemId = null;
        while ((ItemId = JOptionPane.showInputDialog(null, "Please enter your Item ID number: ")) != null)
        {
            boolean correct = false;
            for (int x = 0; x < Item.length; ++x)
            {
                if(ItemId.equals(Item[x]))
                {
                    JOptionPane.showInputDialog(null, "Your Item is: " + Item[x] + "\n" + "the price is: " + Price[x], JOptionPane.INFORMATION_MESSAGE);
                    correct = true;
                    break;
                }
            }
            if(! correct)
            {
                JOptionPane.showMessageDialog(null, "item ID not found, try again.", "Not found", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
}

expected results will show the item number and the price to it
actual result is saying every item# is invalid

A: It is because you are comparing a String and an Int
   if(ItemId.equals(Item[x]))
    {

Should be changed to
   if(Integer.parseInt(ItemId)==(Item[x]))
    {

final code becomes
import javax.swing.JOptionPane;

public class ParallelArray3 {
   public static void main(String[] args) {
final int Num =10;
int [] Item= {101, 110, 210, 220, 300, 310, 316, 355, 405, 410};
double [] Price= {0.29, 1.23, 3.50, 0.89, 6.79, 3.12, 4.32, 3.6, 8.3, 5.4};

String ItemId = null;
while ((ItemId = JOptionPane.showInputDialog(null, "Please enter your Item ID number: ")) != null)
{
    System.out.println(ItemId);
    boolean correct = false;
    for (int x = 0; x < Item.length; x++)
    {
        if(Integer.parseInt(ItemId)==(Item[x]))
        {
            JOptionPane.showInputDialog(null, "Your Item is: " + Item[x] + "\n" + "the price is: " + Price[x], JOptionPane.INFORMATION_MESSAGE);
            correct = true;
            break;
        }
    }
    if(!correct)
    {
        JOptionPane.showMessageDialog(null, "item ID not found, try again.", "Not found", JOptionPane.INFORMATION_MESSAGE);
          }
       }
    }
 }


text: Q: showing elements of array in single edit box control I have created dialog based MFC and I want to show the array elements that come from serial COM PORT. it should be implemented using Edit box control. I want to show the received characters sequentially with one space between them.


text:
Q: Asymptotic vlaue of $ f(n)=\sum_{i=0}^n\lfloor \sqrt{i}\rfloor\binom{n}{i} $ Inspired by this question I tried to find an asymptotic formula for
$$
f(n)=\sum_{i=0}^n\lfloor \sqrt{i}\rfloor\binom{n}{i}
$$
With the observation:
$$
f(n)=\sum_{i=0}^n\frac{\lfloor \sqrt{i}\rfloor+\lfloor \sqrt{n-i}\rfloor}{2}\binom{n}{i}
$$
And the a bit naive approximation
$$
\frac{\lfloor \sqrt{i}\rfloor+\lfloor \sqrt{n-i}\rfloor}{2}=\frac{1}{n}\sum_{i=1}^{n}{\lfloor \sqrt{i}\rfloor}=\frac{n\lfloor \sqrt{n}\rfloor-\frac{1}{6}\lfloor \sqrt{n}\rfloor\left(\lfloor \sqrt{n}\rfloor-1\right)\left(2\lfloor \sqrt{n}\rfloor+5\right)}{n}\approx\frac{2}{3}\sqrt{n}
$$
We obtain $f(n)\approx\frac{2}{3}\sqrt{n}2^n=:g(n)$. The approximation doesn't seem that bad; I computed with wolfram alpha:
$$
$$
\begin{array}{c|c|c|c}
n & f(n) & g(n) & f(n)/g(n) \\
\hline
1 & 1 & 1.333 & 0.75 \\
2 & 3 & 3.771 & 0.795 \\
3 & 7 & 9.238 & 0.758 \\
4 & 16 & 21.333 & 0.75 \\
5 & 37 & 47.703 & 0.776 \\
10 & 1882 & 2158.782 & 0.872 \\
50 & 5.128\cdot10^{15} & 5.308\cdot10^{15} & 0.996 \\
100 & 8.391\cdot10^{30} & 8.451\cdot10^{30} & 0.993 \\
200 & 1.531\cdot10^{61} & 1.515\cdot10^{61} & 1.011 \\
350 & 2.929\cdot10^{106} & 2.86\cdot10^{106} & 1.024 \\
\end{array}
$$
$$
The error term fluctuates a bit so it seems natural to ask:
Is it true that:
$$
\lim_{n\to\infty}{\frac{f(n)}{g(n)}}=1
$$

A: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\color{#f00}{\mathrm{f}\pars{n}} & =\sum_{k = 0}^{n}\left\lfloor \root{k}\right\rfloor{n \choose k}\ =\
1\times\overbrace{\bracks{{n \choose 1} + {n \choose 2} + {n \choose 3}}}
^{\ds{\color{#f00}{3}\ terms}}
\\[3mm] & +
2 \times\overbrace{\bracks{{n \choose 4} + {n \choose 5} + {n \choose 6} + {n \choose 7} + {n \choose 8}}}
^{\ds{\color{#f00}{5}\ terms}}
\\[3mm] & +
3 \times\overbrace{\bracks{{n \choose 9} + {n \choose 10} + {n \choose 11} + {n \choose 12} + {n \choose 13}+ {n \choose 14}+ {n \choose 15}}}
^{\ds{\color{#f00}{7}\ terms}}\ +\ \cdots
\\[5mm] &=
1 \times \sum_{k = 1}^{3}{n \choose k} +
2 \times \sum_{k = 4}^{8}{n \choose k} +
3 \times \sum_{k = 9}^{15}{n \choose k} + \cdots
\\[3mm] & =
\sum_{m = 1}^{\infty}m\sum_{k = m^{2}}^{m^{2} + 2m}{n \choose k} =
\sum_{m = 0}^{\infty}m\sum_{k = 0}^{2m}{n \choose k + m^{2}} =
\sum_{k = 0}^{\infty}\sum_{m\ \geq\ k/2}^{\infty}m{n \choose k + m^{2}}
\end{align}

I stop here. Some of the binomial sum seems to be related to Hypergeometric Functions. So far, I was able to get rid of the $\ds{\left\lfloor\cdots\right\rfloor}$ function and along the way to find a pattern.


text:
Q: Regular expression vs Apache regular expressions I had a situation where same pattern is working for Java and not working for Apache regular experssions API.
import java.util.regex.*;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

public class PatternExample {

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9\\p{Punct}]+");  //working
        Matcher matcher = pattern.matcher("pass@1234");
        System.out.println("Input String matches regex - "+matcher.matches());
        match("pass@1234");
    }

    public static MatchResult match(String input) {
        PatternCompiler compiler = new Perl5Compiler();
        PatternMatcher matcher = new Perl5Matcher();
        org.apache.oro.text.regex.Pattern pattern = null;

        if (pattern == null) {
            try {
                pattern = compiler.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9\\p{Punct}]+");
            } catch (MalformedPatternException e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
                return null;
            }
        }
        if (matcher.matches(input, pattern)) {
            System.out.println("true");
        }else{
            System.out.println("false");
        }
        return null;
    }

}

Above code is giving output in two different ways inside main method pattern is working while match method is giving false.
Basically my requirement is to allow Alphanumeric and some special characters in Java and JavaScript I am validating in JavaScript and again in Java Using Perl5Compiler.
Javascript validation
    function _validatePasswordCharacter (/* Widget */ field){
    var regExp;
    var regExpInput = "^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9\\p{Punct}]+";
    console.log(regExpInput);
    try
    {
        regExp = new RegExp(regExpInput);
    }
    catch (Error)
    {
        console.debug('Error while parsing the password charset');

        return false;
    }

    if (!regExp.test(field.get('value')))
    {
        console.debug('Password not matching regular expression check -- portal.properties');
        return false;
    }
    else{
        console.debug('Password matching regular expression check -- portal.properties');
        return true;
    }

}

Please suggest to move forward

A: After some testing I believe Perl does not have the {Punct} class This regexp should work as intended:
"^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9!"#$%&'()*+,./:;<=>?@[\]^_{|}~-]+"`


text:
Q: Counting objects in image I want to count no of objects in an image using open cv. I have a soybean image and now I want to count the soybean numbers. If possible please help me and let me know the counting algorithms.
Thanks and I look forward to hear from you.
Regards,
Sumon

A: Sumon,
  There is no one algorithm for counting objects.  It greatly depends on the image itself.  Depending on the contrast of the beans to the background it may be possible to use a simple threshold then a labeling algorithm, or even just finding contours.
The threshold function in opencv is cvThreshold.  The contour finding algorithm is cvFindContours using this you could count the number of contours found.
Also the blob library has many facilities for this type of machine vision applications including connected component labeling which is basically what you need here.  The library's description I believe is already included in opencv. The description of it can be found here.
I could provide some more assistance if I knew a little more about the image.


text:
Q: R select previous car ownerships within 6 months Edited for clarity:
I am quite new to R. I have a data frame with vehicles with multiple ownership start and end dates. I am looking for vehicles with previous ownerships within 6 months of their current ownership.
vhc_key     start_date  end_date
1           2006-12-16  2015-10-05
1           2015-11-21  NA
2           2014-01-14  2014-02-14
2           2014-03-14  NA
3           2014-01-14  2014-02-14
3           2015-03-14  NA

Result:
vhc_key     start_date  end_date
1           2006-12-16  2015-10-05
2           2014-01-14  2014-02-14

TRUE = vehicle 1 and 2, their previous end dates are within 6 months of their last start dates.
FALSE = vehicle 3, its previous end_date 2014-02-14 is not within 6 months of its last start date 2015-03-14.
With Dplyr it would be something like this, yet this does not seem to work:
df <- df %>%
  group_by(vhc_key) %>%
  filter(end_date >= max(start_date) - months(6))

Any help would be greatly appreciated.

A: This will probably work, assuming that your dataset is properly ordered (in terms of start date for each vehicle).
library(dplyr)
library(lubridate)

dt = read.table(text = "vhc_key     start_date  end_date
                1           2006-12-16  2015-10-05
                1           2015-11-21  NA
                2           2014-01-14  2014-02-14
                2           2014-03-14  NA
                3           2014-01-14  2014-02-14
                3           2015-03-14  NA", header=T, stringsAsFactors=F)

dt %>%
  mutate(start_date = ymd(start_date),                                                  # update columns to date-time (if they are not)
         end_date = ymd(end_date)) %>%
  group_by(vhc_key) %>%
  mutate(dist = as.numeric(difftime(max(start_date), end_date, units="weeks"))) %>%     # get distance of end date and max start date (in weeks)
  filter(!is.na(dist) & dist <= 24) %>%                                                 # keep rows with distance up to 24 weeks (6 months)
  ungroup %>%
  select(-dist)

# # A tibble: 2 x 3
#   vhc_key start_date   end_date
#     <int>     <date>     <date>
# 1       1 2006-12-16 2015-10-05
# 2       2 2014-01-14 2014-02-14


text:
Q: Error: EACCES: permission denied, mkdir '/app/node_modules/.vite/deps_temp' Please, help me handle with this error. I have tried chmod 777 on /app/node_modules but it wast a lot of time and give 777 looks wrong to me.
web-app_1     | Error: EACCES: permission denied, mkdir '/app/node_modules/.vite/deps_temp'
web-app_1     |     at Object.mkdirSync (node:fs:1386:3)
web-app_1     |     at runOptimizeDeps (file:///app/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:42281:14)
web-app_1     |     at Timeout._onTimeout (file:///app/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:41698:54)
web-app_1     |     at processTicksAndRejections (node:internal/process/task_queues:96:5) {
web-app_1     |   errno: -13,
web-app_1     |   syscall: 'mkdir',
web-app_1     |   code: 'EACCES',
web-app_1     |   path: '/app/node_modules/.vite/deps_temp'
web-app_1     | }

Dockerfile
ROM node:16

WORKDIR /app
COPY package.json ./
RUN mkdir -p /app/node_modules
RUN chown -R node.node /app/node_modules

# https://stackoverflow.com/questions/34498736/npm-self-signed-cert-in-chain?lq=1
RUN npm install -g npm@8.19.2
RUN npm -v
RUN npm config set strict-ssl false

RUN npm install --loglevel silly

COPY . .
USER node

CMD [ "npm", "run", "dev" ]

A: I have tried suggestions of change /app owner to "node" but it does't works. It only works putting "RUN chmod 777 /app/node_modules" before "CMD [ "npm", "run", "dev" ]". Thank you all.


text:
Q: CheckBox covers text in GridView I'm pretty new to Android, and I'm looking for a little help.
I have a GridView with the following XML in a linear layout.
<GridView android:id="@+id/gridview"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:numColumns="2"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"/>

I'm adding a series of CheckBoxes to the view with...
    public View getView(int position, View convertView, ViewGroup parent)
    {
        CheckBox checkView;
        if (convertView == null) {
            checkView = new CheckBox(context);
            checkView.setPadding(5, 5, 5, 5);
        } else {
            checkView = (CheckBox) convertView;
        }
        checkView.setText(checkNames[position]);
        checkView.setWidth(400);

        return checkView;
    }

No matter how many different widths I try, including fill_parent and
wrap_content, the text winds up behind the box instead of next to it.
Any hints or tricks?
Thanks,
Andrew

A: Try using only wrap content for both layout width and layout height. Because the fill_parent will fill the full layout, where as wrap_content will fill only to the size of your text entered.


text:
Q: Adjust panel size bootstrap I'm using circosJS (d3.js library  for visualisation. This is my sample code. I'm not able to adjust the visualisation inside the bootstrap panel-body. I've set max-height to adjust panel size, but it's not taking effect...
FIDDLE LINK

var layout_data = [{
  "len": 31,
  "color": "#8dd3c7",
  "label": "January",
  "id": "january"
}, {
  "len": 28,
  "color": "#ffffb3",
  "label": "February",
  "id": "february"
}, {
  "len": 31,
  "color": "#bebada",
  "label": "March",
  "id": "march"
}, {
  "len": 30,
  "color": "#fb8072",
  "label": "April",
  "id": "april"
}, {
  "len": 31,
  "color": "#80b1d3",
  "label": "May",
  "id": "may"
}, {
  "len": 30,
  "color": "#fdb462",
  "label": "June",
  "id": "june"
}, {
  "len": 31,
  "color": "#b3de69",
  "label": "July",
  "id": "july"
}, {
  "len": 31,
  "color": "#fccde5",
  "label": "August",
  "id": "august"
}, {
  "len": 30,
  "color": "#d9d9d9",
  "label": "September",
  "id": "september"
}, {
  "len": 31,
  "color": "#bc80bd",
  "label": "October",
  "id": "october"
}, {
  "len": 30,
  "color": "#ccebc5",
  "label": "November",
  "id": "november"
}, {
  "len": 31,
  "color": "#ffed6f",
  "label": "December",
  "id": "december"
}];

var heatmap = [
  ['january', 0, 1, 1368001],
  ['january', 1, 2, 1458583],
  ['january', 2, 3, 1481633],
  ['january', 3, 4, 1408424],
  ['january', 4, 5, 1400597],
  ['january', 5, 6, 1548933],
  ['january', 6, 7, 1537059],
  ['january', 7, 8, 1517383],
  ['january', 8, 9, 1544359],
  ['january', 9, 10, 1580460],
  ['january', 10, 11, 1440710],
  ['january', 11, 12, 1417824],
  ['january', 12, 13, 1597834],
  ['january', 13, 14, 1666670],
  ['january', 14, 15, 1707785],
  ['january', 15, 16, 1656905],
  ['january', 16, 17, 1620539],
  ['january', 17, 18, 1487228],
  ['january', 18, 19, 1418230],
  ['january', 19, 20, 1666497],
  ['january', 20, 21, 1739178],
  ['january', 21, 22, 1755254],
  ['january', 22, 23, 1732520],
  ['january', 23, 24, 1702975],
  ['january', 24, 25, 1546438],
  ['january', 25, 26, 1454228],
  ['january', 26, 27, 1684766],
  ['january', 27, 28, 1759669],
  ['january', 28, 29, 1764844],
  ['january', 29, 30, 1737754],
  ['january', 30, 31, 1749857],
  ['february', 0, 1, 1577419],
  ['february', 1, 2, 1509311],
  ['february', 2, 3, 1688266],
  ['february', 3, 4, 1690517],
  ['february', 4, 5, 1719390],
  ['february', 5, 6, 1693426],
  ['february', 6, 7, 1613806],
  ['february', 7, 8, 1521449],
  ['february', 8, 9, 1473617],
  ['february', 9, 10, 1632787],
  ['february', 10, 11, 1698088],
  ['february', 11, 12, 1702137],
  ['february', 12, 13, 1690878],
  ['february', 13, 14, 1661660],
  ['february', 14, 15, 1445139],
  ['february', 15, 16, 1392075],
  ['february', 16, 17, 1565855],
  ['february', 17, 18, 1622609],
  ['february', 18, 19, 1593628],
  ['february', 19, 20, 1564282],
  ['february', 20, 21, 1569010],
  ['february', 21, 22, 1458216],
  ['february', 22, 23, 1338981],
  ['february', 23, 24, 1495727],
  ['february', 24, 25, 1554400],
  ['february', 25, 26, 1574841],
  ['february', 26, 27, 1643072],
  ['february', 27, 28, 1644590],
  ['march', 0, 1, 1500834],
  ['march', 1, 2, 1424820],
  ['march', 2, 3, 1607011],
  ['march', 3, 4, 1615301],
  ['march', 4, 5, 1559021],
  ['march', 5, 6, 1547753],
  ['march', 6, 7, 1508006],
  ['march', 7, 8, 1309583],
  ['march', 8, 9, 1189917],
  ['march', 9, 10, 1365881],
  ['march', 10, 11, 1403679],
  ['march', 11, 12, 1403001],
  ['march', 12, 13, 1397280],
  ['march', 13, 14, 1367524],
  ['march', 14, 15, 1251964],
  ['march', 15, 16, 1159217],
  ['march', 16, 17, 1334292],
  ['march', 17, 18, 1391104],
  ['march', 18, 19, 1366559],
  ['march', 19, 20, 1342872],
  ['march', 20, 21, 1327773],
  ['march', 21, 22, 1268340],
  ['march', 22, 23, 1276517],
  ['march', 23, 24, 1467731],
  ['march', 24, 25, 1503009],
  ['march', 25, 26, 1496469],
  ['march', 26, 27, 1500094],
  ['march', 27, 28, 1450254],
  ['march', 28, 29, 1240603],
  ['march', 29, 30, 1086657],
  ['march', 30, 31, 1282324],
  ['april', 0, 1, 1283014],
  ['april', 1, 2, 1270569],
  ['april', 2, 3, 1293570],
  ['april', 3, 4, 1293439],
  ['april', 4, 5, 1150461],
  ['april', 5, 6, 1050257],
  ['april', 6, 7, 1209470],
  ['april', 7, 8, 1260725],
  ['april', 8, 9, 1285887],
  ['april', 9, 10, 1266011],
  ['april', 10, 11, 1234722],
  ['april', 11, 12, 1100005],
  ['april', 12, 13, 1034963],
  ['april', 13, 14, 1221402],
  ['april', 14, 15, 1265036],
  ['april', 15, 16, 1279159],
  ['april', 16, 17, 1266882],
  ['april', 17, 18, 1241239],
  ['april', 18, 19, 1153081],
  ['april', 19, 20, 1082812],
  ['april', 20, 21, 1084284],
  ['april', 21, 22, 1245400],
  ['april', 22, 23, 1248887],
  ['april', 23, 24, 1235617],
  ['april', 24, 25, 1229560],
  ['april', 25, 26, 1117336],
  ['april', 26, 27, 1074233],
  ['april', 27, 28, 1249024],
  ['april', 28, 29, 1273337],
  ['april', 29, 30, 1246730],
  ['may', 0, 1, 1036144],
  ['may', 1, 2, 1156135],
  ['may', 2, 3, 1106555],
  ['may', 3, 4, 1041413],
  ['may', 4, 5, 1182786],
  ['may', 5, 6, 1192434],
  ['may', 6, 7, 1193624],
  ['may', 7, 8, 1047831],
  ['may', 8, 9, 1106669],
  ['may', 9, 10, 1043170],
  ['may', 10, 11, 1000001],
  ['may', 11, 12, 1205405],
  ['may', 12, 13, 1247394],
  ['may', 13, 14, 1238560],
  ['may', 14, 15, 1223267],
  ['may', 15, 16, 1199465],
  ['may', 16, 17, 1040418],
  ['may', 17, 18, 952650],
  ['may', 18, 19, 1126219],
  ['may', 19, 20, 1155800],
  ['may', 20, 21, 1173902],
  ['may', 21, 22, 1167218],
  ['may', 22, 23, 1160702],
  ['may', 23, 24, 1034886],
  ['may', 24, 25, 966509],
  ['may', 25, 26, 1156691],
  ['may', 26, 27, 1194054],
  ['may', 27, 28, 1190877],
  ['may', 28, 29, 1016149],
  ['may', 29, 30, 1068529],
  ['may', 30, 31, 993302],
  ['june', 0, 1, 935590],
  ['june', 1, 2, 1119046],
  ['june', 2, 3, 1150676],
  ['june', 3, 4, 1169570],
  ['june', 4, 5, 1162795],
  ['june', 5, 6, 1147372],
  ['june', 6, 7, 1004244],
  ['june', 7, 8, 921713],
  ['june', 8, 9, 968196],
  ['june', 9, 10, 1140341],
  ['june', 10, 11, 1152976],
  ['june', 11, 12, 1165844],
  ['june', 12, 13, 1154469],
  ['june', 13, 14, 999352],
  ['june', 14, 15, 917310],
  ['june', 15, 16, 1106649],
  ['june', 16, 17, 1141077],
  ['june', 17, 18, 1143086],
  ['june', 18, 19, 1149995],
  ['june', 19, 20, 1141059],
  ['june', 20, 21, 1008542],
  ['june', 21, 22, 939065],
  ['june', 22, 23, 1129289],
  ['june', 23, 24, 1161838],
  ['june', 24, 25, 1158130],
  ['june', 25, 26, 1159204],
  ['june', 26, 27, 1146093],
  ['june', 27, 28, 1009897],
  ['june', 28, 29, 928706],
  ['june', 29, 30, 1103970],
  ['july', 0, 1, 1143862],
  ['july', 1, 2, 1150514],
  ['july', 2, 3, 1167512],
  ['july', 3, 4, 1150024],
  ['july', 4, 5, 1008307],
  ['july', 5, 6, 934687],
  ['july', 6, 7, 1106666],
  ['july', 7, 8, 1143473],
  ['july', 8, 9, 1154196],
  ['july', 9, 10, 1167145],
  ['july', 10, 11, 1151100],
  ['july', 11, 12, 1006581],
  ['july', 12, 13, 930137],
  ['july', 13, 14, 941594],
  ['july', 14, 15, 1126558],
  ['july', 15, 16, 1166553],
  ['july', 16, 17, 1187503],
  ['july', 17, 18, 1182767],
  ['july', 18, 19, 1030447],
  ['july', 19, 20, 934780],
  ['july', 20, 21, 1107315],
  ['july', 21, 22, 1147785],
  ['july', 22, 23, 1161849],
  ['july', 23, 24, 1169049],
  ['july', 24, 25, 1131515],
  ['july', 25, 26, 993075],
  ['july', 26, 27, 925852],
  ['july', 27, 28, 1077760],
  ['july', 28, 29, 1095700],
  ['july', 29, 30, 1098378],
  ['july', 30, 31, 1096670],
  ['august', 0, 1, 1071402],
  ['august', 1, 2, 951503],
  ['august', 2, 3, 878472],
  ['august', 3, 4, 996356],
  ['august', 4, 5, 1016188],
  ['august', 5, 6, 1022237],
  ['august', 6, 7, 1027197],
  ['august', 7, 8, 1024299],
  ['august', 8, 9, 922671],
  ['august', 9, 10, 872742],
  ['august', 10, 11, 974684],
  ['august', 11, 12, 988100],
  ['august', 12, 13, 988993],
  ['august', 13, 14, 981883],
  ['august', 14, 15, 893681],
  ['august', 15, 16, 894506],
  ['august', 16, 17, 858478],
  ['august', 17, 18, 991784],
  ['august', 18, 19, 1022889],
  ['august', 19, 20, 1031167],
  ['august', 20, 21, 1038878],
  ['august', 21, 22, 1042880],
  ['august', 22, 23, 951127],
  ['august', 23, 24, 896613],
  ['august', 24, 25, 1078972],
  ['august', 25, 26, 1123401],
  ['august', 26, 27, 1122117],
  ['august', 27, 28, 1129891],
  ['august', 28, 29, 1114953],
  ['august', 29, 30, 986620],
  ['august', 30, 31, 921040],
  ['september', 0, 1, 1103673],
  ['september', 1, 2, 1143909],
  ['september', 2, 3, 1149438],
  ['september', 3, 4, 1157452],
  ['september', 4, 5, 1149054],
  ['september', 5, 6, 1010272],
  ['september', 6, 7, 942892],
  ['september', 7, 8, 1135215],
  ['september', 8, 9, 1163859],
  ['september', 9, 10, 1165798],
  ['september', 10, 11, 1163321],
  ['september', 11, 12, 1142868],
  ['september', 12, 13, 1007248],
  ['september', 13, 14, 938456],
  ['september', 14, 15, 1129580],
  ['september', 15, 16, 1160361],
  ['september', 16, 17, 1166669],
  ['september', 17, 18, 1166135],
  ['september', 18, 19, 1155657],
  ['september', 19, 20, 1013339],
  ['september', 20, 21, 939303],
  ['september', 21, 22, 1115789],
  ['september', 22, 23, 1155790],
  ['september', 23, 24, 1175290],
  ['september', 24, 25, 1171100],
  ['september', 25, 26, 1156096],
  ['september', 26, 27, 1016313],
  ['september', 27, 28, 946015],
  ['september', 28, 29, 1140783],
  ['september', 29, 30, 1171328],
  ['october', 0, 1, 1169047],
  ['october', 1, 2, 1166792],
  ['october', 2, 3, 1151218],
  ['october', 3, 4, 1013653],
  ['october', 4, 5, 961694],
  ['october', 5, 6, 1173529],
  ['october', 6, 7, 1208669],
  ['october', 7, 8, 1218388],
  ['october', 8, 9, 1203597],
  ['october', 9, 10, 1185802],
  ['october', 10, 11, 1047404],
  ['october', 11, 12, 1002951],
  ['october', 12, 13, 1176808],
  ['october', 13, 14, 1209924],
  ['october', 14, 15, 1220987],
  ['october', 15, 16, 1220765],
  ['october', 16, 17, 1193122],
  ['october', 17, 18, 1042063],
  ['october', 18, 19, 960302],
  ['october', 19, 20, 1151448],
  ['october', 20, 21, 1213130],
  ['october', 21, 22, 1255712],
  ['october', 22, 23, 1282461],
  ['october', 23, 24, 1267047],
  ['october', 24, 25, 1115921],
  ['october', 25, 26, 1086010],
  ['october', 26, 27, 1232889],
  ['october', 27, 28, 1282237],
  ['october', 28, 29, 1278848],
  ['october', 29, 30, 1258570],
  ['october', 30, 31, 1225435],
  ['november', 0, 1, 1072746],
  ['november', 1, 2, 1049955],
  ['november', 2, 3, 1272203],
  ['november', 3, 4, 1340860],
  ['november', 4, 5, 1408998],
  ['november', 5, 6, 1451479],
  ['november', 6, 7, 1437583],
  ['november', 7, 8, 1274988],
  ['november', 8, 9, 1210274],
  ['november', 9, 10, 1327675],
  ['november', 10, 11, 1246598],
  ['november', 11, 12, 1396790],
  ['november', 12, 13, 1432484],
  ['november', 13, 14, 1422153],
  ['november', 14, 15, 1275193],
  ['november', 15, 16, 1234596],
  ['november', 16, 17, 1453194],
  ['november', 17, 18, 1484727],
  ['november', 18, 19, 1514655],
  ['november', 19, 20, 1511929],
  ['november', 20, 21, 1462551],
  ['november', 21, 22, 1294247],
  ['november', 22, 23, 1202440],
  ['november', 23, 24, 1404219],
  ['november', 24, 25, 1459282],
  ['november', 25, 26, 1453893],
  ['november', 26, 27, 1454444],
  ['november', 27, 28, 1426951],
  ['november', 28, 29, 1294661],
  ['november', 29, 30, 1287777],
  ['december', 0, 1, 1549272],
  ['december', 1, 2, 1633784],
  ['december', 2, 3, 1684781],
  ['december', 3, 4, 1689624],
  ['december', 4, 5, 1666695],
  ['december', 5, 6, 1545527],
  ['december', 6, 7, 1523315],
  ['december', 7, 8, 1683824],
  ['december', 8, 9, 1754569],
  ['december', 9, 10, 1734975],
  ['december', 10, 11, 1669997],
  ['december', 11, 12, 1641086],
  ['december', 12, 13, 1489854],
  ['december', 13, 14, 1474692],
  ['december', 14, 15, 1633309],
  ['december', 15, 16, 1607862],
  ['december', 16, 17, 1632516],
  ['december', 17, 18, 1536016],
  ['december', 18, 19, 1490975],
  ['december', 19, 20, 1394406],
  ['december', 20, 21, 1387549],
  ['december', 21, 22, 1538557],
  ['december', 22, 23, 1550730],
  ['december', 23, 24, 1469007],
  ['december', 24, 25, 1314160],
  ['december', 25, 26, 1499708],
  ['december', 26, 27, 1508048],
  ['december', 27, 28, 1570757],
  ['december', 28, 29, 1792749],
  ['december', 29, 30, 1770200],
  ['december', 30, 31, 1721354]
]

days_off = [
  ['january', 0, 1, 2],
  ['january', 1, 2, 0],
  ['january', 2, 3, 0],
  ['january', 3, 4, 1],
  ['january', 4, 5, 1],
  ['january', 5, 6, 0],
  ['january', 6, 7, 0],
  ['january', 7, 8, 0],
  ['january', 8, 9, 0],
  ['january', 9, 10, 0],
  ['january', 10, 11, 1],
  ['january', 11, 12, 1],
  ['january', 12, 13, 0],
  ['january', 13, 14, 0],
  ['january', 14, 15, 0],
  ['january', 15, 16, 0],
  ['january', 16, 17, 0],
  ['january', 17, 18, 1],
  ['january', 18, 19, 1],
  ['january', 19, 20, 0],
  ['january', 20, 21, 0],
  ['january', 21, 22, 0],
  ['january', 22, 23, 0],
  ['january', 23, 24, 0],
  ['january', 24, 25, 1],
  ['january', 25, 26, 1],
  ['january', 26, 27, 0],
  ['january', 27, 28, 0],
  ['january', 28, 29, 0],
  ['january', 29, 30, 0],
  ['january', 30, 31, 0],
  ['february', 0, 1, 1],
  ['february', 1, 2, 1],
  ['february', 2, 3, 0],
  ['february', 3, 4, 0],
  ['february', 4, 5, 0],
  ['february', 5, 6, 0],
  ['february', 6, 7, 0],
  ['february', 7, 8, 1],
  ['february', 8, 9, 1],
  ['february', 9, 10, 0],
  ['february', 10, 11, 0],
  ['february', 11, 12, 0],
  ['february', 12, 13, 0],
  ['february', 13, 14, 0],
  ['february', 14, 15, 1],
  ['february', 15, 16, 1],
  ['february', 16, 17, 0],
  ['february', 17, 18, 0],
  ['february', 18, 19, 0],
  ['february', 19, 20, 0],
  ['february', 20, 21, 0],
  ['february', 21, 22, 1],
  ['february', 22, 23, 1],
  ['february', 23, 24, 0],
  ['february', 24, 25, 0],
  ['february', 25, 26, 0],
  ['february', 26, 27, 0],
  ['february', 27, 28, 0],
  ['march', 0, 1, 1],
  ['march', 1, 2, 1],
  ['march', 2, 3, 0],
  ['march', 3, 4, 0],
  ['march', 4, 5, 0],
  ['march', 5, 6, 0],
  ['march', 6, 7, 0],
  ['march', 7, 8, 1],
  ['march', 8, 9, 1],
  ['march', 9, 10, 0],
  ['march', 10, 11, 0],
  ['march', 11, 12, 0],
  ['march', 12, 13, 0],
  ['march', 13, 14, 0],
  ['march', 14, 15, 1],
  ['march', 15, 16, 1],
  ['march', 16, 17, 0],
  ['march', 17, 18, 0],
  ['march', 18, 19, 0],
  ['march', 19, 20, 0],
  ['march', 20, 21, 0],
  ['march', 21, 22, 1],
  ['march', 22, 23, 1],
  ['march', 23, 24, 0],
  ['march', 24, 25, 0],
  ['march', 25, 26, 0],
  ['march', 26, 27, 0],
  ['march', 27, 28, 0],
  ['march', 28, 29, 1],
  ['march', 29, 30, 1],
  ['march', 30, 31, 0],
  ['april', 0, 1, 0],
  ['april', 1, 2, 0],
  ['april', 2, 3, 0],
  ['april', 3, 4, 0],
  ['april', 4, 5, 1],
  ['april', 5, 6, 1],
  ['april', 6, 7, 0],
  ['april', 7, 8, 0],
  ['april', 8, 9, 0],
  ['april', 9, 10, 0],
  ['april', 10, 11, 0],
  ['april', 11, 12, 1],
  ['april', 12, 13, 1],
  ['april', 13, 14, 0],
  ['april', 14, 15, 0],
  ['april', 15, 16, 0],
  ['april', 16, 17, 0],
  ['april', 17, 18, 0],
  ['april', 18, 19, 1],
  ['april', 19, 20, 1],
  ['april', 20, 21, 2],
  ['april', 21, 22, 0],
  ['april', 22, 23, 0],
  ['april', 23, 24, 0],
  ['april', 24, 25, 0],
  ['april', 25, 26, 1],
  ['april', 26, 27, 1],
  ['april', 27, 28, 0],
  ['april', 28, 29, 0],
  ['april', 29, 30, 0],
  ['may', 0, 1, 2],
  ['may', 1, 2, 0],
  ['may', 2, 3, 1],
  ['may', 3, 4, 1],
  ['may', 4, 5, 0],
  ['may', 5, 6, 0],
  ['may', 6, 7, 0],
  ['may', 7, 8, 2],
  ['may', 8, 9, 0],
  ['may', 9, 10, 1],
  ['may', 10, 11, 1],
  ['may', 11, 12, 0],
  ['may', 12, 13, 0],
  ['may', 13, 14, 0],
  ['may', 14, 15, 0],
  ['may', 15, 16, 0],
  ['may', 16, 17, 1],
  ['may', 17, 18, 1],
  ['may', 18, 19, 0],
  ['may', 19, 20, 0],
  ['may', 20, 21, 0],
  ['may', 21, 22, 0],
  ['may', 22, 23, 0],
  ['may', 23, 24, 1],
  ['may', 24, 25, 1],
  ['may', 25, 26, 0],
  ['may', 26, 27, 0],
  ['may', 27, 28, 0],
  ['may', 28, 29, 2],
  ['may', 29, 30, 0],
  ['may', 30, 31, 1],
  ['june', 0, 1, 1],
  ['june', 1, 2, 0],
  ['june', 2, 3, 0],
  ['june', 3, 4, 0],
  ['june', 4, 5, 0],
  ['june', 5, 6, 0],
  ['june', 6, 7, 1],
  ['june', 7, 8, 1],
  ['june', 8, 9, 2],
  ['june', 9, 10, 0],
  ['june', 10, 11, 0],
  ['june', 11, 12, 0],
  ['june', 12, 13, 0],
  ['june', 13, 14, 1],
  ['june', 14, 15, 1],
  ['june', 15, 16, 0],
  ['june', 16, 17, 0],
  ['june', 17, 18, 0],
  ['june', 18, 19, 0],
  ['june', 19, 20, 0],
  ['june', 20, 21, 1],
  ['june', 21, 22, 1],
  ['june', 22, 23, 0],
  ['june', 23, 24, 0],
  ['june', 24, 25, 0],
  ['june', 25, 26, 0],
  ['june', 26, 27, 0],
  ['june', 27, 28, 1],
  ['june', 28, 29, 1],
  ['june', 29, 30, 0],
  ['july', 0, 1, 0],
  ['july', 1, 2, 0],
  ['july', 2, 3, 0],
  ['july', 3, 4, 0],
  ['july', 4, 5, 1],
  ['july', 5, 6, 1],
  ['july', 6, 7, 0],
  ['july', 7, 8, 0],
  ['july', 8, 9, 0],
  ['july', 9, 10, 0],
  ['july', 10, 11, 0],
  ['july', 11, 12, 1],
  ['july', 12, 13, 1],
  ['july', 13, 14, 2],
  ['july', 14, 15, 0],
  ['july', 15, 16, 0],
  ['july', 16, 17, 0],
  ['july', 17, 18, 0],
  ['july', 18, 19, 1],
  ['july', 19, 20, 1],
  ['july', 20, 21, 0],
  ['july', 21, 22, 0],
  ['july', 22, 23, 0],
  ['july', 23, 24, 0],
  ['july', 24, 25, 0],
  ['july', 25, 26, 1],
  ['july', 26, 27, 1],
  ['july', 27, 28, 0],
  ['july', 28, 29, 0],
  ['july', 29, 30, 0],
  ['july', 30, 31, 0],
  ['august', 0, 1, 0],
  ['august', 1, 2, 1],
  ['august', 2, 3, 1],
  ['august', 3, 4, 0],
  ['august', 4, 5, 0],
  ['august', 5, 6, 0],
  ['august', 6, 7, 0],
  ['august', 7, 8, 0],
  ['august', 8, 9, 1],
  ['august', 9, 10, 1],
  ['august', 10, 11, 0],
  ['august', 11, 12, 0],
  ['august', 12, 13, 0],
  ['august', 13, 14, 0],
  ['august', 14, 15, 2],
  ['august', 15, 16, 1],
  ['august', 16, 17, 1],
  ['august', 17, 18, 0],
  ['august', 18, 19, 0],
  ['august', 19, 20, 0],
  ['august', 20, 21, 0],
  ['august', 21, 22, 0],
  ['august', 22, 23, 1],
  ['august', 23, 24, 1],
  ['august', 24, 25, 0],
  ['august', 25, 26, 0],
  ['august', 26, 27, 0],
  ['august', 27, 28, 0],
  ['august', 28, 29, 0],
  ['august', 29, 30, 1],
  ['august', 30, 31, 1],
  ['september', 0, 1, 0],
  ['september', 1, 2, 0],
  ['september', 2, 3, 0],
  ['september', 3, 4, 0],
  ['september', 4, 5, 0],
  ['september', 5, 6, 1],
  ['september', 6, 7, 1],
  ['september', 7, 8, 0],
  ['september', 8, 9, 0],
  ['september', 9, 10, 0],
  ['september', 10, 11, 0],
  ['september', 11, 12, 0],
  ['september', 12, 13, 1],
  ['september', 13, 14, 1],
  ['september', 14, 15, 0],
  ['september', 15, 16, 0],
  ['september', 16, 17, 0],
  ['september', 17, 18, 0],
  ['september', 18, 19, 0],
  ['september', 19, 20, 1],
  ['september', 20, 21, 1],
  ['september', 21, 22, 0],
  ['september', 22, 23, 0],
  ['september', 23, 24, 0],
  ['september', 24, 25, 0],
  ['september', 25, 26, 0],
  ['september', 26, 27, 1],
  ['september', 27, 28, 1],
  ['september', 28, 29, 0],
  ['september', 29, 30, 0],
  ['october', 0, 1, 0],
  ['october', 1, 2, 0],
  ['october', 2, 3, 0],
  ['october', 3, 4, 1],
  ['october', 4, 5, 1],
  ['october', 5, 6, 0],
  ['october', 6, 7, 0],
  ['october', 7, 8, 0],
  ['october', 8, 9, 0],
  ['october', 9, 10, 0],
  ['october', 10, 11, 1],
  ['october', 11, 12, 1],
  ['october', 12, 13, 0],
  ['october', 13, 14, 0],
  ['october', 14, 15, 0],
  ['october', 15, 16, 0],
  ['october', 16, 17, 0],
  ['october', 17, 18, 1],
  ['october', 18, 19, 1],
  ['october', 19, 20, 0],
  ['october', 20, 21, 0],
  ['october', 21, 22, 0],
  ['october', 22, 23, 0],
  ['october', 23, 24, 0],
  ['october', 24, 25, 1],
  ['october', 25, 26, 1],
  ['october', 26, 27, 0],
  ['october', 27, 28, 0],
  ['october', 28, 29, 0],
  ['october', 29, 30, 0],
  ['october', 30, 31, 0],
  ['november', 0, 1, 1],
  ['november', 1, 2, 1],
  ['november', 2, 3, 0],
  ['november', 3, 4, 0],
  ['november', 4, 5, 0],
  ['november', 5, 6, 0],
  ['november', 6, 7, 0],
  ['november', 7, 8, 1],
  ['november', 8, 9, 1],
  ['november', 9, 10, 0],
  ['november', 10, 11, 2],
  ['november', 11, 12, 0],
  ['november', 12, 13, 0],
  ['november', 13, 14, 0],
  ['november', 14, 15, 1],
  ['november', 15, 16, 1],
  ['november', 16, 17, 0],
  ['november', 17, 18, 0],
  ['november', 18, 19, 0],
  ['november', 19, 20, 0],
  ['november', 20, 21, 0],
  ['november', 21, 22, 1],
  ['november', 22, 23, 1],
  ['november', 23, 24, 0],
  ['november', 24, 25, 0],
  ['november', 25, 26, 0],
  ['november', 26, 27, 0],
  ['november', 27, 28, 0],
  ['november', 28, 29, 1],
  ['november', 29, 30, 1],
  ['december', 0, 1, 0],
  ['december', 1, 2, 0],
  ['december', 2, 3, 0],
  ['december', 3, 4, 0],
  ['december', 4, 5, 0],
  ['december', 5, 6, 1],
  ['december', 6, 7, 1],
  ['december', 7, 8, 0],
  ['december', 8, 9, 0],
  ['december', 9, 10, 0],
  ['december', 10, 11, 0],
  ['december', 11, 12, 0],
  ['december', 12, 13, 1],
  ['december', 13, 14, 1],
  ['december', 14, 15, 0],
  ['december', 15, 16, 0],
  ['december', 16, 17, 0],
  ['december', 17, 18, 0],
  ['december', 18, 19, 0],
  ['december', 19, 20, 1],
  ['december', 20, 21, 1],
  ['december', 21, 22, 0],
  ['december', 22, 23, 0],
  ['december', 23, 24, 0],
  ['december', 24, 25, 2],
  ['december', 25, 26, 0],
  ['december', 26, 27, 1],
  ['december', 27, 28, 1],
  ['december', 28, 29, 0],
  ['december', 29, 30, 0],
  ['december', 30, 31, 0]
]

var circos = new circosJS({
  container: '#chart'
});

circos
  .layout({
      ticks: {
        display: false
      },
    },
    layout_data
  )
  .heatmap('h1', {
    innerRadius: 180,
    outerRadius: 240,
    logScale: false,
    colorPalette: 'YlOrRd'
  }, heatmap)
  .heatmap('h2', {
    innerRadius: 170,
    outerRadius: 179,
    logScale: false,
    colorPalette: 'Blues'
  }, days_off)
  .render();
<script type="text/javascript" src="//d3js.org/d3.v3.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://cdn.rawgit.com/nicgirault/circosJS/master/dist/circosJS.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/nicgirault/circosJS/master/dist/colorBrewer.css">
<svg id='chart'></svg>

A: I was able to get the chart inside the panel body with center aligned. Please check the the codepen link the chart is coming inside the panel body without overflowing panel body.
CODEPEN LINK
 <div class="container">
    <div class="row">
    <div class="col-lg-12">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title"><i class="fa fa-long-arrow-right fa-fw"></i> Host</h3>
    </div>
    <div class="panel-body centered">
      <svg id='chart' style="display:block; margin:auto;"></svg>

    </div>
  </div>
</div>
    </div>
  </div>


text:
Q: How do I make Multiple API Calls? I am pretty new to Javascript and APIs, and I really want to learn more about them! I have been following some tutorials with some very simple APIs, but I have run into a problem when trying to make multiple API calls.
I made a function with getting the info from the API inside, but when I call it multiple times, just manually or by for loop, it only accurate integrates the last one with my html file.
I'm pretty new, so I'm not sure what exactly I am doing wrong in this case. I am using the Pokemon API found here: https://pokeapi.co/
const app = document.getElementById('root')

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.append(container);

var request = new XMLHttpRequest()

function getPokemon(pokeNum) {
    request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokeNum + '/', true);

    request.onload = function() {
        var data = JSON.parse(this.response);
        console.log(data);

        const card = document.createElement('div');
        card.setAttribute('class', 'card');

        const h1 = document.createElement('h1');
        h1.textContent = data.name;

        const frontSprite = document.createElement('img');
        frontSprite.src = data.sprites.front_default;

        container.appendChild(card);
        card.appendChild(h1);
        card.appendChild(frontSprite);
        console.log(data.name);
    }
    request.send();
}
getPokemon(2);
getPokemon(3);

For example, in the request.onload part of the function when I try to console.log(data.name) only the name of the getPokemon(3) call is displayed in the console and not getPokemon(2)


text:
Q: How to AJAX update components in single tab of p:accordionPanel from outside? I have a p:accordionPanel which represents a list of items and in each tab there is a form.  Upon submitting any of the repeating forms, it is possible that extra data in needed, which is when a p:dialog is popped up prompting the user to enter some more data.  That dialog is defined outside the accordion panel because, unlike the items from the accordion, only one of them can be showing at a time so there is no need to augment the HTML served by repeating it in each tab of the accordion.
The definition of the accordion looks as follows (simplified but with all the relevant descriptors):
<p:accordionPanel id="myAccordion" value="#{managedBean.getAccordionList}" var="item" multiple="false" dynamic="true" cache="true">

    <p:ajax event="tabChange" listener="#{managedBean.processTabChange}"/>

    <p:tab title="#{item.tabTitle}" id="itemTab">

        <h:form id="itemForm">

            <h:outputLabel for="itemName" value="Item Name:"/>
            <p:inputText id="itemName" title="Item Name:"
                    maxlength="16" value="#{appeal.itemName}">
            </p:inputText>

Consequently, the HTML rendered for itemName is myAccordion:0:itemForm:itemName in the first instance, myAccordion:1:itemForm:itemName in the second, etc.
The dialog is defined as follows:
<p:dialog id="commentDialogID" header="Enter comment" widgetVar="commentDialog" modal="true" resizable="true" height="auto">
    <h:form id="commentForm">

        <h:outputLabel for="comment" value="Comment:"/>

        <p:inputTextarea id="comment" title="Comment"
                rows="6" cols="33"
                value="#{managedBean.activeItem.comment}"
                required="true">
            <f:ajax render="comment"/>
        </p:inputTextarea>

        <h:commandButton value="Submit" action="#{managedBean.proceed}" onclick="PF('commentDialog').hide();">
            <f:ajax render="*** ??? ***"/>
        </h:commandButton>

    </h:form>
</p:dialog>

What I have repeatedly been failing at are attempts to f:ajax update only a single tab in the accordion panel, the active one from which the dialog was popped up.  I tried using
:myAccordion:#{managedBean.activeItem.displayIndex}:itemForm:itemName
:myAccordion:#{managedBean.activeItem.displayIndex}:itemForm
:myAccordion:#{managedBean.activeItem.displayIndex}:itemTab

in place of *** ??? *** but none of them would compile:
javax.faces.FacesException: <f:ajax> contains an unknown id ':myAccordion:0:itemForm' - cannot locate it in the context of the component j_idt20

If I skip the index token (e.g. :myAccordion:itemForm:itemName) it does compile but it does functionally nothing. The Item entity class has a getDisplayIndex which does accurately return the index of the active tab.
My problem is quite similar to that which is described in this question, which doesn't really have a good answer. Could it be a limitation of PrimeFaces?

A: I don't know what version of Primefaces you are using, but this seems to be a bug in Primefaces 5.1.1 where i could recreate this issue. By upgrading to Primefaces 5.2, the ajax EL could suddenly find the referenced id. I can post a MCVE if needed.
Edit: The MCVE:
XHTML:

<h:form id="itemForm">
    <p:accordionPanel id="myAccordion" binding="#{accordionView}" value="#{playgroundController.users}" dynamic="true" activeIndex="#{playgroundView.activeIndex}" var="user" multiple="false">

        <p:ajax event="tabChange" update="commentDialogID"/>

        <p:tab title="#{user.name}">
                <h:outputLabel for="itemName" value="Item Name:" />
                <p:inputText id="itemName" title="Item Name:" maxlength="16"
                    value="#{user.amount}">
                </p:inputText>
                <p:commandButton value="showDialog" onclick="PF('commentDialog').show();"></p:commandButton>
        </p:tab>

    </p:accordionPanel>
</h:form>

<p:dialog id="commentDialogID" header="Enter comment" widgetVar="commentDialog" modal="true" resizable="true" height="auto">
    <h:form id="commentForm">

        <h:outputLabel for="comment" value="Comment:"/>

        <p:inputTextarea id="comment" title="Comment"
                rows="6" cols="33"
                value="#{playgroundView.activeIndex}"
                required="true">
            <f:ajax render="comment"/>
        </p:inputTextarea>

        <p:commandButton value="Submit" onclick="PF('commentDialog').hide();" update=":itemForm:myAccordion:#{playgroundView.activeIndex}:itemName" ></p:commandButton>

    </h:form>
</p:dialog>

PlaygroundView Bean:
Note that in this example the activeIndex has to have an initial value, otherwise this EL:
update=":itemForm:myAccordion:#{playgroundView.activeIndex}:itemName"

will resolve wrongly and will throw an error that it cannot find the id of the referenced component. This of course has the drawback that the first tab will be open when the page loads, but that's another issue
private String activeIndex = "0";

public String getActiveIndex() {
    return activeIndex;
}

public void setActiveIndex(String activeIndex) {
    this.activeIndex = activeIndex;
}

PlaygroundController Bean:
private List<User> users;
@Override
    public void initializeView() {
    createUsers();
}

public void createUsers() {
        User user1 = new User();
        User user2 = new User();
        User user3 = new User();
        user1.setName("User123");
        user1.setAmount(1);
        user2.setName("User456");
        user2.setAmount(2);
        user3.setName("User12312345111111111111111111111111111");
        user3.setAmount(3);
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        users = userList;
    }

User:
public class User implements Serializable {
    String name;
    int amount = 0;
}

A: You should update the commandButton on the tabChange event.
<p:ajax event="tabChange" listener="#{managedBean.processTabChange}" update=":commentForm:commandButtonId"/>

The render attribute <f:ajax> inside the <h:commandButton>is evaluated during the render phase and not sooner afaik. So if you do not update it, it will always point to '0'. Check the source in your browser developer tool and check your ajax requests (things you should always do for debugging). You will see the full clientId with the ':0:' and you will not see it changing on the ajax requests.


text:
Q: Create an order from several incomplete orders Here is the motivation and how it should behave, but I need a help how to implement it.
I have several (typically) incomplete orders given as ordered values, for ex.:
1. A, C, D
2. D, E
3. X, B
4. B, C
5. C, F
6. C, A
and the resulting order should be:
A, X, B, C, D, E, F or A, X, B, C, F, D, E or A, X, B, C, D, F, E
The idea behind it is sort the result based on first seen order. I will try explain it on the example in steps:
order A, C, D
D, E - D seen, so add E after D, so order A, C, D, E
X, B - no value seen yet, so we can not determine the order now, so create 2nd temporary order X, B
B, C - C already seen, so order A, B, C, D, E
and 2nd order can be merged via B, so A, X, B, C, D, E
C, F - C see, so order A, X, B, C, D, E, F
C, A - ignore, both values are part of already defined order (by first incomplete order A, C, D)
But what if an additional incomplete order F, D or F, E will be part (added to the end) of the input? The step-by-step mental algorithm will fail - F was already placed.
How can the idea be implemented, any idea?