text:
Q: C# merge 2 almost identical JSON objects
A while ago I made a function that merged JSON together.
I had a table looking like this, which in this example has been made by left joining the table 'friends' on the table 'persons':

Id
Name
FriendName
FriendAge

1
Danny
Jason
19

1
Danny
Cesie
18

2
Jason
Danny
19

And it would result in a json object looking like this:
[
  {
    "Id": 1,
    "Name": "Danny",
    "Friends": [
      {
        "Name": "Jason",
        "Age": 19
      },
      {
        "Name": "Cesie",
        "Age": 18
      }
    ]
  },
  {
    "Id": 2,
    "Name": "Jason",
    "Friends": [
      {
        "Name": "Danny",
        "Age": 19
      }
    ]
  }
]

I did this by using the following C# code:
using System;
using System.Data;
using Newtonsoft.Json;

namespace JsonTest
{
    class Program
    {
        private class Result
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public Friend[] Friends { get; set; }
        }

        private class Friend
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        static void Main(string[] args)
        {
            string json = "[{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Jason\",\"FriendAge\":19},{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Cesie\",\"FriendAge\":18},{\"Id\":2,\"Name\":\"Jason\",\"FriendName\":\"Danny\",\"FriendAge\":19}]";
            // Original table from example
            DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);

            // Get distinct values from DataTable
            DataView dv = new DataView(dt);
            DataTable distinct_values = dv.ToTable(true, "Id");

            Result[] result = new Result[distinct_values.Rows.Count];
            int i = 0;
            foreach (DataRow row in distinct_values.Rows)
            {
                // Filter the original table on one Id from the distinct values
                dv.RowFilter = $"Id = {row["Id"]}";
                DataTable temp_dt = dv.ToTable();
                Result temp = new Result();

                // Copy general data over to the temp
                temp.Id = Convert.ToInt32(temp_dt.Rows[0]["Id"].ToString());
                temp.Name = temp_dt.Rows[0]["Name"].ToString();

                Friend[] rows = new Friend[temp_dt.Rows.Count];

                // loop over all the rows and copy the array data over
                int j = 0;
                foreach (DataRow temprow in temp_dt.Rows)
                {
                    rows[j] = new Friend();
                    rows[j].Name = temprow["FriendName"].ToString();
                    rows[j].Age = Convert.ToInt32(temprow["FriendAge"].ToString());
                    j++;
                }

                // Assign everything to where it it supposed to be
                temp.Friends = rows;
                result[i] = temp;
                i++;
            }

            Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));

            Console.ReadLine();
        }
    }
}

It works really well. But my question, is there another, cleaner or faster, way to do this entire operation? If so, where can I find this? Thanks in advance.

A: I would create a model to carry your data easier than using DataTable
public class RequestModel{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FriendName { get; set; }
    public int FriendAge { get; set; }
}

Then you can try to use lambda to make it, using GroupBy method get grouping by Id, Name.
string json = "[{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Jason\",\"FriendAge\":19},{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Cesie\",\"FriendAge\":18},{\"Id\":2,\"Name\":\"Jason\",\"FriendName\":\"Danny\",\"FriendAge\":19}]";
var req = JsonConvert.DeserializeObject<IEnumerable<RequestModel>>(json);
var res= req.GroupBy(x=> new {x.Id,x.Name})
    .Select(x=> new Result{
        Name =x.Key.Name,
        Id = x.Key.Id,
        Friends = x.Select(z=> new Friend(){
            Name = z.FriendName,
            Age =  z.FriendAge
        }).ToArray()
    });
var jsonResult = JsonConvert.SerializeObject(res);


text:
Q: ls with umlaut words I never used umlaute with ls and came up with this problem:
$ ls ba*
ball_1.mp4                ball_partner.mp4          bälle_mit_2.mp4

$ ls bä*
ls: bä*: No such file or directory

$ ls bäl*
ls: bäl*: No such file or directory

$ ls bal*
ball_1.mp4   ball_partner.mp4

Some unconvenient solution for os x:
$ basename $(mdfind  bä  -onlyin .)
$ bälle_mit_2.mp4

How to get a more bash relevant solution?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the performance considerations of using Amazon SimpleDB? I'm creating a filesystem and I think I'll be storing files in a DB (http://sietch.net/ViewNewsItem.aspx?NewsItemID=124 and http://blog.druva.com/2009/01/25/file-systems-vs-databases/ seem to indicate it's a good idea).
Since it's a filesystem, I'll need A LOT of I/O and REALLY fast. If I'm hosting on EC2, will Amazon SimpleDB be a decent solution for this?

A: SimpleDB has a maximum record size of a 1,000 BYTES so it is VERY poorly suited to storing files/blobs (unless they are tiny).
It is fairly common for people to use SimpleDB to index files and then to store the files in S3 which is much better suited for storing large objects.

A: SimpleDB (and recent DynamoDB) aren't suited to store files. Why don't you just make the versioning control on one of them, indexing files stored on S3?
You don't need to override the files on S3, as you can name them whatever you want and get the original name (and other info) from the database. You can even, for text files, for example, have a preview or the begining of the file on the DB or, for images, have a thumbnail on S3 and also get this info from the DB, so when users list the files they get only the thumbnail and, if they want, they download the full-size file.
Take a look at http://aws.amazon.com/en/dynamodb/faqs/#When_should_I_use_Amazon_DynamoDB_vs_Amazon_S3 and http://aws.amazon.com/en/running_databases/


text:
Q: Linux logger doesn't write tags to log files? I have a problem with logger command. After upgrading syslog-ng to 3.3th version (maybe it is not directly depend on it), logger (using command below) doesn't log tag names:
logger -t "BLABLA"  some_log_string

How can I solve it? I searched around but couldn't find anything regarding this issue.
Thanks in advance.

A: Ok, I solved this problem myself. Apperantly, the creators of syslog-ng have changed it a bit in the new version (3.0), which I use syslog-ng 3.3. In order to display the log messages with application name, we have to include $MSGHDR directive with $MSG. Example template will be like:
template("$DATE $YEAR $MSGHDR$MSG\n")

From now on, the syslog-ng will log like this:
Dec 15 15:22:01 2012 fw_update_app: fw dir found


text:
Q: Wrong behaviour of fill_between with set_xlim() With python matplotlip I try to create a filled area between a numpy vector and zero. This works well, however with the use of set_xlim() something weird happens, see pictures below.
So the workaround with the mask works for now, but am I doing something wrong here or is this a bug?
Right behavior (with mask):

Wrong behavior (with set_xlim()):

mask = arange(4000,4050)
# wrong
fig, ax = plt.subplots()
ax.fill_between(t, Load, 0)
ax.set_xlim([4000,4050])
ax.set_ylim([0,4000])
# right
fig, ax = plt.subplots()
ax.fill_between(t[mask], Load[mask], 0)


text:
Q: show coordinates by a zoom level google maps I have a java script  code in which i am showing coordinates on page load.I want to show those coordinates like if the user is on a zoom level of  15 and higher instead of showing all those coordinates in a page load.Is it possible to tackle this?Below is what am trying but  still not hitting the correct way.
Below is the script i am trying but not getting through

    <title>Maps</title>

    <form id="form1" runat="server">

`enter code here`

    </form>

A: You could easy check for each marker if it they are visible at your current zoom level.
var markers; // your markerarray
var map; // your map
for (var i=0; i<markers.length; i++){
    if( map.getBounds().contains(markers[i].getPosition()) ){

       // only load markers which are currently visible in this zoom level

    }
}


text:
Q: Trouble with navigator.mediaDevices.getUserMedia with chrome on iPhone X I am trying to give my browser access to my devices camera, so that I can feed the media stream into a video, but when I am testing on google chrome getUserMedia is not supported, but when I use safari I am having no issues.
Does google chrome not have any support for getUserMedia anymore?
I have already read this article, but have had no luck.
This is the implementation I am currently using:
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;

    let constraints = {
      audio: false,
      video: { facingMode: "user" }
    }

    if (navigator.getUserMedia) {
      navigator.getUserMedia(constraints,
         function(stream) {
            var video = document.querySelector('video');
            video.srcObject = stream;
            video.onloadedmetadata = function(e) {
              video.play();
            };
         },
         function(err) {
            alert("The following error occured: " + err.name);
         }
      );
   } else {
      console.log("getUserMedia not supported");
   }

A: Having the same troubles on iOS 11.2x. My researches showed that FF and Chrome are supported on OS but NOT on iOS even they would be able to support media devices. You can test easy mediaDevice availability:
            if (navigator.mediaDevices) {
            alert ("Media device supported");
        }
        else {
            alert ("Media device not supported");
        }

You can check that here too: HTML5Test
FF and Chrome on iOS will show "Media device not supported" while Safari says its supported. The reason looks like Apple has still not given free the access to other browsers using mediaDevices.You can imagine some reasons why that is. ;/ So don't blame Chrome or Firefox this time.
Would be interesting to know if it now works in iOS 12.

A: This works with FF and Chrome on desktop and phone. Note: width and height are reversed on desktop and phone. Note: FF and Chrome allow it to run on localhost and https. Chrome will NOT allow it to run on a http site.
function fnStreamVideo(){
    navigator.mediaDevices.getUserMedia({ video:true })
    .then(function(stream) {
        let video = document.getElementById('video');
        video.srcObject = stream;
        video.onloadedmetadata = function(e) {
            video.play();
            video.width=480;
            video.height=320;
        };
    })
    .catch(function(e){});
}


text:
Q: Unable to access Spree Admin panel after updating the authentication, verify user email from console So I'm creating a very basic Spree Rails app. I was able to access the Admin panel by just going to http://localhost:3000/admin But after setting up the authentication when I try to access the administration after entering my email and password I get that I have to verify my email. How can I verify my user email using the console?

A: This should do the trick,
user = Spree::User.find_by(email: 'spree@example.com')
user.confirm!

A: This worked for me in my Spree Rails app, I think if your using Devise this will work.

user = Spree::User.first
user.password='123456'
user.password_confirmation='123456'
user.email='youremail@example.com'
user.skip_confirmation!
user.save


text:
Q: Unable to update data in dataframe i tried updating data in dataframe but its unable to get updating
//Initialize data and dataframe here
    user_data=read.csv("train_5.csv")
    baskets.df=data.frame(Sequence=character(),
                          Challenge=character(),
                          countno=integer(),
                          stringsAsFactors=FALSE)

/Updating data in dataframe here
for(i in 1:length((user_data)))
{
  for(j in i:length(user_data))
  {
    if(user_data$challenge_sequence[i]==user_data$challenge_sequence[j]&&user_data$challenge[i]==user_data$challenge[j])
    {
     writedata(user_data$challenge_sequence[i],user_data$challenge[i])

    }

  }

}
writedata=function( seqnn,challng)
{

  #print(seqnn)
  #print(challng)
  newRow <- data.frame(Sequence=seqnn,Challenge=challng,countno=1)
  baskets.df=rbind(baskets.df,newRow)

}

//view data here
View(baskets.df)

A: I've modified your code to what I believe will work.  You haven't provided sample data, so I can't verify that it works the way you want.  I'm basing my attempt here on a couple of common novice mistakes that I'll do my best to explain.
Your writedata function was written to be a little loose with it's scope.  When you create a new function, what happens in the function technically happens in its own environment. That is, it tries to look for things defined within the function, and then any new objects it creates are created only within that environment.  R also has this neat (and sometimes tricky) feature where, if it can't find an object in an environment, it will try to look up to the parent environment.
The impact this has on your writedata function is that when R looks for baskets.df in the function and can't find it, R then turns to the Global Environment, finds baskets.df there, and then uses it in rbind.  However, the result of rbind gets saved to a baskets.df in the function environment, and does not update the object of the same name in the global environment.
To address this, I added an argument to writedata that is simply named data. We can then use this argument to pass a data frame to the function's environment and do everything locally.  By not making any assignment at the end, we implicitly tell the function to return it's result.
Then, in your loop, instead of simply calling writedata, we assign it's result back to baskets.df to replace the previous result.
for(i in 1:length((user_data)))
{
  for(j in i:length(user_data))
  {
    if(user_data$challenge_sequence[i] == user_data$challenge_sequence[j] &&
       user_data$challenge[i] == user_data$challenge[j])
    {
     baskets.df <- writedata(baskets.df,
                             user_data$challenge_sequence[i],
                             user_data$challenge[i])

    }

  }

}

writedata=function(data, seqnn,challng)
{

  #print(seqnn)
  #print(challng)
  newRow <- data.frame(Sequence = seqnn,
                       Challenge = challng,
                       countno = 1)
  rbind(data, newRow)

}

A: I'm not sure what you're programming background is, but your loops will be very slow in R because it's an interpreted language.  To get around this, many functions are vectorized (which simply means that you give them more than one data point, and they do the looping inside compiled code where the loops are fast).
With that in mind, here's what I believe will be a much faster implementation of your code
user_data=read.csv("train_5.csv")

# challenge_indices will be a matrix with TRUE at every place "challenge" and "challenge_sequence" is the same
challenge_indices <- outer(user_data$challenge_sequence, user_data$challenge_sequence, "==") &
  outer(user_data$challenge, user_data$challenge, "==")

# since you don't want duplicates, get rid of them
challenge_indices[upper.tri(challenge_indices, diag = TRUE)] <- FALSE

# now let's get the indices of interest
index_list <- which(challenge_indices,arr.ind = TRUE)

# now we make the resulting data set all at once
# this is much faster, because it does not require copying the data frame many times - which would be required if you created a new row every time.
baskets.df <- with(user_data, data.frame(
  Sequence = challenge_sequence[index_list[,"row"]],
  challenge = challenge[index_list[,"row"]]
)


text:
Q: Как заменить один символ в sql таблице? Нужен запрос, чтобы например заменить в одном поле все встречающиеся буквы С, например, на П. Как это сделать?
A: Функция REPLACE:
UPDATE `users` SET `firstname` = REPLACE( `firstname`, 'С', 'П');


text:
Q: fullcalendar.js, cannot navigate through periods I'm using fullcalendar.js for the first time, I implemented it successfully, I managed to retrieve and display my events, and I'm now working on the design of my calendar.
However, my calendar started to act weird, and now, for instance, I cannot navigate through weeks after I've loaded my page, the only way, I can is by changing the calendar view, by clicking month or day view button, then I'll be able to navigate and go back to week view to navigate through weeks. This happens regardless of the default view (if it's month view, I won't be able to go to next or previous months without changing the selected view first), the dates in the header change, but the content doesn't.
As it has worked previously, I tried to restart with simpler code (I tried to initialize my calendar with only the licence key, and as I was working on the design, I removed all the css), I get no error in the browser console, I tried with both Firefox and Chrome, I also wiped browser cache, but it hadn't improved anything.
I'm quite sure there's nothing to do with my ajax call (worked fine with it before, now doesn't work even without it) so I don't provide my controller code.
I'm using fullcalendar.3.9.0.
Here is my js (not in $(document).ready() but I tried and it did not change anything) :
    $('#calendar').fullCalendar({
        schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
        themeSystem: 'bootstrap4',
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'agendaDay,agendaWeek,month'
        },
        bootstrapFontAwesome: {
            close: 'fa-times',
            prev: 'fa-chevron-left',
            next: 'fa-chevron-right',
            prevYear: 'fa-angle-double-left',
            nextYear: 'fa-angle-double-right'
        },
        defaultView: 'agendaWeek',
        firstDay: 1,
        allDaySlot: false,
        editable: false,
        droppable: false,
        columnFormat: 'ddd DD/MM',
        timeFormat: 'HH:mm',
        nowIndicator: true,
        events: function (start, end, timezone, callback) {
            Post('/Incident/GetInterventionList',
                {
                    start: start.format('YYYY-MM-DD'),
                    end: end.format('YYYY-MM-DD')
                },
                function (response) {
                    var events = [];

                    for (var i = 0; i < response.length; i++) {
                        let e = response[i];
                        events.push({
                            id: e.ActivityId,
                            title: e.SANumber + " | " + e.Subject,
                            start: moment(e.MorningStart ? e.MorningStart : e.EveningStart).toISOString(),
                            end: moment(e.EveningEnd ? e.EveningEnd : e.MorningEnd).toISOString(),
                            color: (e.StateCode == 0 ? '#ffc107' : (e.StateCode == 1 ? '#28a745' : (e.StateCode == 3 ? '#dc3545' : '#007bff')))
                        });
                    }

                    callback(events);
                });
        }
    });

And here is my css (I'm using bootstrap.sass) :
table {
    /*overflow: hidden;*/ /* blocks event display in fullCalendar */
    border: none !important;
    border-radius: 0.25rem !important;
}

table td, th {
    border: none !important;
}

table thead {
    border-radius: 0.25rem 0.25rem 0 0 !important;
}

table thead th:first-child, table thead th:first-child {
    overflow: hidden;
    border-radius: 0.25rem 0 0 0 !important;
}

table thead th:last-child, table thead th:last-child {
    overflow: hidden;
    border-radius: 0 0.25rem 0 0 !important;
}

table tfoot {
    border-radius: 0 0 0.25rem 0.25rem !important;
}

table tfoot td {
    min-height: 9px;
}

table tfoot tr:last-child td:first-child {
    overflow: hidden;
    border-radius: 0 0 0 0.25rem !important;
}

table tfoot tr:last-child td:last-child {
    overflow: hidden;
    border-radius: 0 0 0.25rem 0 !important;
}

.fc-scroller {
    max-height: 60vh;
    height: 60vh !important;
}

#calendar .btn {
    margin:3px;
}

.fc-event {
    box-shadow: 0px 1px 4px black;
}

table table {
    box-shadow: none !important;
    border: none !important;
}

table tfoot td {
    height: 9px;
}

.fc-row {
    border: none !important;
}

Thanks for reading, help would be really appreciated.

A: Hope this could help, the issue wasn't in the code provided here, actually there were something silently interfering with fullCalendar in my code (as suggested @ADyson, see comments), I was modifying the fullCalendar main table (dynamically adding a <tfoot> tag) after pageload and this was the source of the problem.


text:
Q: QRemoteObjectNode::remoteObjectAdded signal does not fire While learning how to use QtRO tech preview module, I tried a simple 3 node network ( A registry node, a source object remoting node, and a client node).
registry node main.cpp:
#include <QCoreApplication>
#include <QRemoteObjectRegistryHost>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QRemoteObjectRegistryHost host(QUrl("tcp://127.0.0.1:5557"));

    return a.exec();
}

source node main.cpp:
#include <QCoreApplication>
#include <QRemoteObjectHost>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QTimer timer;
    timer.start(10000);

    QRemoteObjectHost host;
    if(!host.setHostUrl(QUrl("tcp://127.0.0.1:5556"))) qDebug() << "Host url " << host.lastError();
    if(!host.setRegistryUrl(QUrl("tcp://127.0.0.1:5557"))) qDebug() << "Reg url " << host.lastError();

    if(!host.enableRemoting(&timer, "HostTimer")) qDebug() << "Remoting error " << host.lastError();

    return a.exec();
}

client node main.cpp:
#include <QCoreApplication>
#include <QRemoteObjectNode>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QRemoteObjectNode node(QUrl("tcp://127.0.0.1:5557"));

    QObject::connect(&node, &QRemoteObjectNode::remoteObjectAdded,
                     [](const QRemoteObjectSourceLocation& info){
        qDebug() << "New source added : " << info;
    });

    qDebug() << "Waiting for registry ";
    node.waitForRegistry(10000);

    qDebug() << "Already here sources : " << node.registry()->sourceLocations();

    QTimer timer;
    timer.start(5000);

    QObject::connect(&timer, &QTimer::timeout,
                     [&](){
        qDebug() << "New sources list : " << node.registry()->sourceLocations();
    });

    return a.exec();
}

I begin by starting the registry node, then the client node and finally the source node, with this launch sequence I expect to get the remoteObjectAdded fired up, but It didn't.
Your help will be highly appreciated.

A: I answer my question.
I used the wrong signal source in the connect method call.
the client node will be as :
#include <QCoreApplication>
#include <QRemoteObjectNode>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QRemoteObjectNode node(QUrl("tcp://127.0.0.1:5557"));

    QObject::connect(node.registry(), &QRemoteObjectRegistry::remoteObjectAdded,
                     [](const QRemoteObjectSourceLocation& info){
        qDebug() << "New source added : " << info;
    });

    qDebug() << "Waiting for registry ";
    node.waitForRegistry(10000);

    qDebug() << "Already here sources : " << node.registry()->sourceLocations();

    QTimer timer;
    timer.start(5000);

    QObject::connect(&timer, &QTimer::timeout,
                     [&](){
        qDebug() << "New sources list : " << node.registry()->sourceLocations();
    });

    return a.exec();
}

It is the registry who fire the signal not the node, It sound logic after all the source nodes are connected to the registry, so it fire the remoteObjectAdded signal.


text:
Q: Firebird lock and select unlocked fields I have a query
SELECT FIRST 10 * FROM FP_TASKS WITH LOCK

but I have multiple clients using a table, and I need for each selected client 10 rows that are not locked..
Is there any way to do something like below?
SELECT FIRST 10 * FROM FP_TASKS
 WHERE ROW NOT LOCKED
WITH LOCK

A: If you hold a lock a row, then another select .. with lock in another transaction will either wait for the lock to be released or raise an exception (depending on the transaction configuration).
There is no way to ignore or skip locked rows when selecting. The Firebird documentation also explicitly says:

WITH LOCK provides a limited explicit pessimistic locking capability
  for cautious use in conditions where the affected row set is:
a. extremely small (ideally, a singleton), and
  b. precisely controlled by the application code.

Your query is neither 'extremely small' nor 'precisely controlled' by your application.
You should consider allocating a row using a short transaction that updates the row with some type of connection-specific claim, or maybe a single producer or resource manager that allocates rows to a specific client.


text:
Q: Send files with Connect:Direct from HP NonStop (OSS) to UNIX Have you have worked with Connect:Direct HP NonStop?
I wish to make the transmission of a file located in 'OSS' HP NonStop to UNIX.
Connect:Direct run it through NDMCOM in GUARDIAN90 but can not interpret my route home from OSS, they will have some idea of missing my script to reconnoitre the route of OSS?
Below I add my script and messages received from the execution of the process.
my process:
SEND PROCESS SNODE=TEST.HPTEST SNODEID=(user,passwd)
STEP01 COPY FROM (FILE=/home/sat/origen.txt -
                  SYSOPTS=":datatype=binary:" –
                  PNODE) -
            TO   (FILE='/home/user/destino.txt' -
                  SYSOPTS=":datatype=binary:" -
                 DISP = RPL SNODE)

messages:

**XSMG622I: (RC=8, FDBK="0")
  An exception response was received during process exec.
  An exception response was received from the remote node
  during process execution.
SYSTEM ACTION: The copy step was aborted.
  RESPONSE:      Check the condition of the copy step
                 and resubmit the copy step.
**SFLH055I: (RC=8, FDBK="13")
  source DSN can only be a disk/ spooler file : \DESA.$OSS./home/sat/origen.txt


text:
Q: D difference between z-index's auto and inherited in CSS3 I am gong through the z-index property of CSS3 and it has got four properties , auto , number , inline and inherit. I understand number and inline but auto and inherit confuse me as auto mean "sets the value as parent's value as it's default value" and inherit means "inherits the value from parent". I googled but didn't really understand it.

A: z-index is not inherited; the default value for every element is auto. If you change it to be inherit then it will grab the value from its parent directly.
The key is that auto does not create a new local stacking context, while inherit, if the parent had any numerical value, will indeed.
Please check this example to get a better understanding. You can see the same DOM structure is duplicated. On the first scenario, div auto comes before inherit and on the other one; it's inverted.
You can see that the inherit value works equally as actually setting z-index: <number> equal to the parent, while auto is the default value that does not create a new stacking order and will simply display on the default z order as per determinated on the DOM. If you make the parent's value -1, then the inheritance will be exactly as if you set z-index: -1 on .inherit making it display behind .auto on both divs.

$('#button0').click(function(e){
  $('.parent').css('z-index', '0');
});
$('#button1').click(function(e){
  $('.parent').css('z-index', '1');
});
$('#button-1').click(function(e){
  $('.parent').css('z-index', '-1');
});
.parent{
  position: relative;
  z-index: 1;
}
.parent > div{
  position: absolute;
}
.auto{
  z-index: auto; /* default value */
}
.inherit{
  z-index: inherit;
}

/* --------------------- */
/* presentational styles */
.auto{
  background: green;
}
.inherit{
  top: 100px;
  background: red;
}
.parent{
  width: 200px;
  height: 200px;
  opacity: 1;
  margin: 10px;
  background: yellow;
  display: inline-block;
}
.parent > div{
  width: 100px;
  height: 100px;
  opacity: 0.95;
  color: #fff;
}

  first auto and then inherit on DOM

auto

inherit

  first inherit and then auto on DOM

inherit

auto

  Change z-index of parent
  <button id="button-1">To -1</button>
  <button id="button0">To 0</button>
  <button id="button1">To 1</button>

More information on MDN https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

A: If an element 'a' is child of element 'b', then element 'b' is called the parent.If z-index of element 'b' is 5.0 and z-index of element 'a' is set to inherit, element 'a' will also have z-index 5.0.That's what inheritance means.


text:
Q: Evaluate the following definite integral $\int_{-\infty} ^\infty \frac{x^2-3x+2}{x^4+10x^2+9}dx$ Evaluate the following definite integral: $$\int_{-\infty} ^\infty \frac{x^2-3x+2}{x^4+10x^2+9}dx$$
I have factored top and bottom and notice nothing factors out. I thought this would be an easy integration but i am in need of guidance.

A: Try integrating the indefinite integral by partial fractions.
That is, find $A,B,C,D$ such that
$$
\dfrac{Ax+B}{x^2+9}+\dfrac{Cx+D}{x^2+1}=\dfrac{x^2-3x+2}{x^4+10x^2+9}
$$
It should be easy to integrate the individual $\dfrac{Ax+B}{x^2+9}$ and $\dfrac{Cx+D}{x^2+1}$

A: We can use the residue theorem:
$$\int_{-\infty}^{\infty}\frac{x^2+3x+2}{x^4+10x^2+9}\,dx = 2\pi i\left(\mathop{\rm Res}_{x=i}\frac{x^2+3x+2}{(x^2+1)(x^2+9)}+\mathop{\rm Res}_{x=3i}\frac{x^2+3x+2}{(x^2+1)(x^2+9)}\right) = 2\pi i\left(\frac{-1+3i+2}{2i\cdot8}+\frac{-9+9i+2}{-8\cdot6i}\right) = \frac{5\pi}{12}$$


text:
Q: Constructor not called on extended PHP DOMElement When extending DOMElement in PHP, the constructor of the child class is not called. Nothing jumped out at me in the docs as far as that being expected behavior, but maybe I'm missing something. Here's a simple test case....
 class SillyTestClass extends DOMElement{
    public $foo=null;
    public function __construct($name,$value=null,$namespace=null){
        echo "calling custom construct....";
        $this->foo="bar";
        parent::__construct($name,$value,$namespace);
    }
    public function sayHello(){
        echo "Why, hello there!";
    }
}

$doc=new DOMDocument();
$doc->registerNodeClass('DOMElement','SillyTestClass');
$doc->loadHTML("

Sample

");
//THIS WORKS! CUSTOM CLASS BEING USED
$doc->documentElement->firstChild->sayHello();

//THIS IS STILL NULL:( Never set by construct, no message saying construct was called either
echo $doc->documentElement->firstChild->foo;

Of course if I instantiate it myself it's fine...
$elm=new SillyTestClass("foo","Hi there");
//WORKS! Outputs "bar";
echo $elm->foo;

Why when I register the node class with the DOMDocument does it not call the __construct even though it gives me proper inheritance in every other way?
UPDATE For really curious people or people who know C
=======================================================================
Investigation....
This is the DOM extension source taken from PHP src on github
If you were to create an element, this is the chain of events that happens::
document.c :: dom_document_create_element
    |  //uses libxml to generate a new DOMNode
    | node = xmlNewDocNode(docp, NULL, (xmlChar *) name, (xmlChar *) value);

    // that node is then sent to
  php_dom.c :: php_dom_create_object
   |
   |  //the node type is used to figure out what extension class to use
   |     switch (obj->type) {...
   |
   |     //that class is used to instance an object
   |     if (domobj && domobj->document) {
   |          ce = dom_get_doc_classmap(domobj->document, ce);
   |     }
        object_init_ex(return_value, ce);

It appears that you do NOT get true inheritance from extending DOMNode or it's built in extension classes (DOMElement, DOMText) if the DOMDocument instances them. In that case, the libxml node is created first and our class properties tacked on second.
This is unfortunate and impossible to get around it seems, because even when you importNode into a document, it instances a new node. Example
class extendsDE extends DOMElement{
   public $constructWasCalled=false;
    public function __construct($name){
       parent::__construct($name);
       $this->constructWasCalled=true;
   }
}

 class extendsDD extends DOMDocument{

    public function __construct(){
        parent::__construct();
        $this->registerNodeClass("DOMElement","extendsDE");
    }
    //@override
    public function createElement($name){
        $elm=new extendsDE($name);
        echo "Element construct called when we create=";
        echo $elm->constructWasCalled?"true":"false";
        return $this->importNode($elm);
   }
}

$doc=new extendsDD();
$node=$doc->createElement("div");
echo "
";
echo "But then when we import into document, a new element is created  and construct called= ";
echo $node->constructWasCalled?"true":"false";

Now the debate- is this what the developers intended and the documentation is misleading, or is it a bug and true inheritance was supposed to take place?

A: I have figured a way around this in SOME circumstances so far. DOMNodes are kept in memory, so as long as you can get it into the document in one piece (your constructor called), then it will be okay no matter what you do with it or how you access it after that...
Here is an example where we can get the construct to call and still be okay with a document
class extendsDE extends DOMElement{
    public $constructWasCalled=false;
    public function __construct($name){
         parent::__construct($name);
          $this->constructWasCalled=true;
   }
  }

   $doc=new DOMDocument();
   $doc->registerNodeClass("DOMElement","extendsDE");
   $doc->loadHTML("

");

   //append a node we create manually rather than through createElement
   $node=$doc->getElementsByTagName('div')->item(0)->appendChild(new extendsDE("p"));
    $node->nodeValue="Was my construct called?";
     echo "
";
    echo "A new element was appended and construct called= ";
    echo $node->constructWasCalled?"true":"false";
    echo "
";
    echo "Okay but what happens if I retrieve that node some other way..";
    echo "
";
    echo "what if I get that element through selectors. Custom property still set from constructor=";
   echo $doc->getElementsByTagName('p')->item(0)->constructWasCalled?"true":"false";
  echo "
";
  echo "what if I get that element through relationships. Custom property still set from constructor=";
  echo $doc->getElementsByTagName('div')->item(0)->childNodes->item(0)->constructWasCalled?"true":"false";

THE CATCH:
That only works if you create all the elements. If you load HTML markup using $document->loadHTML($html), your extension constructors won't get called.  So far I can only think of hack ways around this like loading the markup and then looping each node to instance replicas and insert them. Definitely possible, but slow...


text:
Q: Numpy: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I know this error has been posted before but I am not sure how to proceed. I am wanting to write a function to return a square wave and then.
Here is my code:
def V_in(t):

    v  = np.floor(2*t)

    if v % 2 == 0
        V_in = 1
    else:
        V_in = -1

    return V_in

t = np.arange(0,10,1000)

square_wave = V_in(tpoints)

plt.plot(tpoints, square_wave);

When I run it I get this error message:

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

I have found I can get it to work if I create a loop over all values of t and store them in an array but that doesn't work when I try to use it within a second function.
def f(V,t):
    return (V_in(t) - V)

Where V is an initial value. This second function is then used in the RK4 algorithm to solve for the voltage.

A: Either you can use a for loop to change your array values or you can use a vectorized operation using np.where to make the changes all at once as follows. np.where(V%2==0, 1, -1) will assign 1 to the array values which are divisible by 2 and -1 to the values which are not.
def V_in(t):
    V  = np.floor(2*t)
    V = np.where(V%2==0, 1, -1)
    return V

t = np.linspace(0,10,100)

square_wave = V_in(t)

plt.plot(t, square_wave);


text:
Q: Dictionary KeyError when using a string read from serial device I am reading serial data that is the Key for a Python dictionary. When I read the serial data, it comes through as a byte stream which I convert to a string. When I use that string to search for a dictionary Key, I get a KeyError.
I have tried to search for the same Key by entering the Key manually, and that would perfectly returning the Value. My code is as follows, any help is appreciated!
plates_id = {'TestCylinder100umHard': 8, 'TestCube100umHard': 7, 'MotorMount100umHard': 6, 'InnerShaft100umHard': 5, 'DriveSleeve100umHard': 4, 'DrivePulley100umHard': 3, 'BearingSleeve100umHard': 2, 'Quad': 1, 'Auto Calibration Plate': 0}

s_bytes_new = ser.inWaiting()
s_new = str(ser.read(s_bytes_new))
printing_plate = plates_id[s_new]
print(printing_plate)

Which gives this error:
Traceback (most recent call last):
  File "C:/pythonProjects/nanoDLP/touchInterface/printTest.py", line 66, in <module>
  printing_plate = plates_id[s_new]
KeyError: "'Auto Calibration Plate'"

Let me know if you need more info. Thanks,
Dylan

A: Use .decode() instead of str, to convert of bytes to str
s_new  = ser.read(s_bytes_new).decode()


text:
Q: Sonar - reporting on most actively edited files? I'd like to create a report in Sonar for the most actively edited files. I've looked around but can't find a plugin to do this. Any suggestions would be appreciated.
If relevant, my team uses AccuRev for SCM, and Sonar v2.14
Thanks in advance

A: Unfortunately, there's currently no plugin that meets your need (at least none that I'm aware of).
I could have suggested you to develop your own plugin based on the metrics generated by the SCM Activity Plugin, but Accurev is not supported so you would have to start from scratch :-/


text:
Q: Can't read a column after pivoting pandas dataframe I have table that I came from a pivot table to eliminate missing values and too short value like city name, here's my code
company = pd.read_sql('SELECT user_id, address FROM company' , con=db_connection)
table = pd.pivot_table(company, index=['address'],aggfunc=np.sum)
table.reset_index()

Then I get his
    address                                             user_id
3   Jl. Raya Kranggan No. 7, Ruko Kav V No. 1 Jat...    65132
4   #ALAMAT atau LOKASI\r\nKota bengkulu perhubung...   15570
5   '--!>'</script/><Svg/Onload=confirm`alamat bis...   48721
6   (Rumah Bpk.RA'IS) Jl.Puskesmas RT.004/11 No.29...   20786

It seems OK when I check the colums
table.columns
Index(['user_id', 'address'], dtype='object')

Then I can't call a column
table['address']

When I call that column, this is happen
 KeyError                                  Traceback (most recent call last)
    C:\Users\asus\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
       2392             try:
    -> 2393                 return self._engine.get_loc(key)
       2394             except KeyError:

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)()

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)()

    pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)()

    pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)()

KeyError: 'address'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-46-eef3b78ea5fd> in <module>()
----> 1 table['address'] #.astype(str)

C:\Users\asus\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2060             return self._getitem_multilevel(key)
   2061         else:
-> 2062             return self._getitem_column(key)
   2063
   2064     def _getitem_column(self, key):

C:\Users\asus\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
   2067         # get column
   2068         if self.columns.is_unique:
-> 2069             return self._get_item_cache(key)
   2070
   2071         # duplicate columns & possible reduce dimensionality

C:\Users\asus\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   1532         res = cache.get(item)
   1533         if res is None:
-> 1534             values = self._data.get(item)
   1535             res = self._box_item_values(item, values)
   1536             cache[item] = res

C:\Users\asus\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath)
   3588
   3589             if not isnull(item):
-> 3590                 loc = self.items.get_loc(item)
   3591             else:
   3592                 indexer = np.arange(len(self.items))[isnull(self.items)]

C:\Users\asus\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2393                 return self._engine.get_loc(key)
   2394             except KeyError:
-> 2395                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2396
   2397         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)()

KeyError: 'address'

If you have other solution, it's fine as long as I can map the address to do keyword mapping

A: I think you need asign output of reset_index back, because address is index name, no column:
table = pd.pivot_table(company, index='address',aggfunc=np.sum).reset_index()

Another solutions if want define columns for aggregate sum:
table = company.groupby('address', as_index=False)['user_id'].sum()

Or:
table = company.groupby('address')['user_id'].sum().reset_index()

And for all columns:
table = company.groupby('address', as_index=False).sum()

table = company.groupby('address').sum().reset_index()

A: I don't think pivot is a proper choice here.
You can use this:
company.groupby('address').sum()


text:
Q: How to simulate a swipe on click? I am currently trying to develop an app with some card swipe actions (similar to the way Tinder works).
I found a boilerplate which works pretty well in my current code :
https://www.cssscript.com/card-carousel-tinder/
The problem is : swipe actions can be fairly sluggish on old mobile devices (probably due to the continuous touch detection of hammer.js)
So, I wanted to add in a functionnality to change cards simply by tapping the card.
The boilerplate has a tap detection function which is great, but I can't manage to simulate a swipe from a tap.
I have tried inputing custom finger coordinates from the function, but it just doesn't have any effect on the card (the fake touch is not detected)
https://www.cssscript.com/card-carousel-tinder/

A: This will not animate the cards, but it will add a "like" and "dislike" button. When a user makes a selection, the card disappears and shows the next one.
At the bottom of push(), add (used jQuery here):
            $('
Like
' +
              '
Dislike
').appendTo(card)

At the top of onTap(e), add:
            let clickedElementClass = e.target.className;
            if(clickedElementClass.includes('button')) {
                if(clickedElementClass.includes('swipe-right')){
                    alert('clicked swiped right button')
                    // do something
                }
                if(clickedElementClass.includes('swipe-left')){
                    alert('clicked swiped left button')
                    // do something
                }
                this.board.removeChild(this.topCard)
                this.push()
                this.handle()
            }

You can style your buttons how you please. Here's an example:
            .swipe-right-button{
                background-color: #d7e2b7;
                width:50%;
                float: left;
                text-align: center;
                padding: 10px 0 10px;
            }
            .swipe-left-button{
                background-color: #eab4b4;
                width:50%;
                float: left;
                text-align: center;
                padding: 10px 0 10px;
            }


text:
Q: how to set image width and height in vb.net In html I just do <img src="x.jpg" width="1px" height="2px"> how about in vb.net. Is there an easy way to do this. When you are viewing the image through the picture box

A: How do you display the image? If you load an image into the Image property of a PictureBox you can use the SizeMode property to stretch the image to the size of the PictureBox. You can then set the width and height of the PictureBox.
PictureBox1.Load("image.png")
PictureBox1.SizeMode = PictureBoxSizeMode.Stretch
PictureBox1.Size = New Size(width, height)


text:
Q: TypeScript – Visual Studio Code – Compiled Doesn´t Output 2 Spaces Tab this seems to be a less relevant problem, but I spent already 3 hours trying to figure this out and nothing.
Then basic setup:
I have a project in node / javascript and I'm currently trying to use TypeScript in order to output a cleaner production code. So tsconfig.json looks like this:
{
  "compilerOptions": {

    "target": "es6",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
     "lib": [
       "DOM",
       "es6",
       "DOM.Iterable",
       "ScriptHost"
     ], //default                                  /* Specify library files to be included in the compilation. */
    "sourceMap": true,                           /* Generates corresponding '.map' file. */
    "removeComments": true,                      /* Do not emit comments to output. */
    "strict": true,                                 /* Enable all strict type-checking options. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  },
  "files": [
    "app_js/functions-syncsystem.ts"
  ]
}

And my prettier .prettierrc file looks like so:
{
    "singleQuote": true,
    "tabWidth": 2
}

On top of that, I've changed all configuration for tab spaces in the visual studio code to 2 spaces (user and workspace), besides unchecking "Detect Indentation".
The problem:
On my editor, everything works fine with the 2 spaces tab. But when I run tsc on the terminal, the output file has tab sizes of 4 and I can't seem to change anywhere.
I've also tried many suggestions on this post:
How to change indentation in Visual Studio Code?
Like this one too:
https://stackoverflow.com/a/68082579/2510785
After each modification, I made sure I closed the editor and opened again and generated a another compiled file to be sure. Can anyone think of any other possibility that could fix this issue? The only thing I can think of is that it could be a specific problem in my OS / VS Code Instalation.
Thanks,
Jorge Mauricio

A: Changing the settings of VSCode won't have any effect on the tsc compiler.
At a quick glance, it doesn't seem to be possible to change the indentation style of tsc's output, see https://github.com/microsoft/TypeScript/issues/4042
This is likely because there seldom is a reason for a developer to edit the compiled output.
As a workaround, you could reformat the output files with something like prettier or using VSCode itself.


text:
Q: Assign different interfaces to the same object I have a Typescript project in which I want to pass the same object between several functions with a different interface
These are the interfaces:
export interface TestModel {
  fileName:string,
  year:number,
  country:string
}
export interface Test2Model {
  fileName:string,
  year:number
}

This is the first function that generates the object and calls the second function passing it the generated object:
function test1() {
  let fileData:TestModel = {
    fileName:'fileName',
    year:2022,
    country:'Spain'
  }

  test2(fileData)
}

test1();

This is the second function:
function test2(fileData:Test2Model) {
  console.log(fileData)
}

This is what I get in the second function:
{fileName: "fileName", year: 2022, country: "Spain"}

This is what I want to receive:
{fileName: "fileName", year: 2022}

My problem: is it possible to automatically generate the second object adapted to the Test2Model interface without creating a new object?

A: You need to delete the property, the type can't change the object. Use delete keyword like
delete fileData.country

//then pass it to test2 function


text:
Q: darts named optional parameters in subclass I am wondering is there is a way to use named optional parameters in subclass.
ex:
class A {
  num min;
  num max;
  A({min: 1, max: 10});
}

class B extends A {
  num step;
  B({min: 2, max, step: 1}) : super(min, max);
}

This does not work, so I am wondering what would.
The main idea is that I subclass a class and override the methods and maybe I have an additional optional parameter in the subclass, but I want to reuse the super-class parameters. How do I do that in Dart?

A: If it is a named optional parameter you must provide the name:
class A {
  num min;
  num max;
  A({min: 1, max: 10});
}

class B extends A {
  num step;
  B({min: 2, max, step: 1}) : super(min: min, max: max);
}


text:
Q: Javascript in Safari not always running Am having an issue with Safari. I have a basic script using jQuery that makes some changes to a form field and adds some behaviours to it. When I run this script on using the document ready method it's fine in Firefox but in Safari it doesn't always run the initial changes. I can hit refresh and get it running fine 4/5 times, but sometimes it just doesn't initialise like it should.
This is running on a local server so the refresh is pretty quick, I'm wondering if the javascript is executing before the page has finished loading. I've tried calling the script in the foot of the page rather then the header but that hasn't helped. I remember hearing about different browsers firing document ready at different times and thought this would help remedy it but it hasn't and I can't find any further information on that topic.
Anything I'm missing that could be the issue or a workaround? The script itself doesn't seem to be at fault. Am using the jQuery colours plugin, apart from that it's only jQuery and my script.
Help is always appreciated, thanks people!
Here is the code. initSearchBox() is run using the line below in the header.
$(document).ready(function() { initSearchBox() ; });
function randomFieldValue(){

var options = new Array(
    'Lorem',
    'Ipsum',
    'Dolor',
    'Sit',
    'Amet'
)

t = Math.floor(Math.random()*(options.length - 1));

return options[t] ;

}

function initSearchBox(){

instanceDefText = randomFieldValue() ;

$('#search-form-field')
    .attr('value',instanceDefText)
    .css('color','#fff')
    .animate({color:'#999'},1500)
    .focus(function(){
        if($(this).attr('value') == instanceDefText){
            $(this).attr('value','')
                .css('color','#000')
        }
    })
    .blur(function(){
        if($(this).attr('value') == ''){
            instanceDefText = randomFieldValue() ;
            $(this).attr('value',instanceDefText)
                .css('color','#fff')
                .animate({color:'#999'},1500)
        }
    });

}


text:
Q: subquery returned more than 1 value table join I am writing a course project (something like a program for the hotel manager) and I need a little help. I have tables Reservations and Rooms and I need to calculate the amount of payment after the client leaves the room ((End_date - Start_date) * price_per_day), but I'm having trouble getting the price_per_day from the table Rooms.
My query only works if there is one record in the Resertvation table, if there are 2 or more, I get an error "subquery returned more than 1 value" and I don't know how to fix it (the problem is in this part of the query SELECT price_per_day FROM Rooms AS ro JOIN Reservations AS re ON ro.room_id = re.room_id)
I'm using visual studio 2019 + SQL Server Express LocalDB.
I will be grateful for any help or hint!
UPDATE Reservations
SET Amount_payable = (
        DATEDIFF(day, CONVERT(datetime, Start_date, 104), CONVERT(datetime, End_date, 104)  * (SELECT price_per_day FROM Rooms AS ro JOIN Reservations AS re ON ro.room_id = re.room_id))
    )
WHERE Status = 'Archived'

Table Reservations
reservation_id   customer_id   room_id   start_date   end_date   status   Amount_payable
      1               3           3      12.04.2020  05.06.2020  Archived        0
      2               2           4      11.04.2020  30.05.2020   Active         0

Table Rooms
reservation_id   room_id   number_of_persons   room_type   price_per_day
      0               1           3             Double          300
      0               2           4             Triple          600
      0               3           3             Studio          400
      2               4           2             Single          444

A: you need slightly different approach to resolve the issue.
try the following:
UPDATE re
  SET
      Amount_payable = (DATEDIFF(day, CONVERT(DATETIME, Start_date, 104), CONVERT(DATETIME, End_date, 104)) * price_per_day)
FROM Reservations re
     JOIN Rooms AS ro ON ro.room_id = re.room_id
WHERE STATUS = 'Archived';


text:
Q: Summing bootstrap-derived confidence intervals? I have a couple things to add together- two different pools of material, and I need to know the total material.  Because of various things related to the sampling, I would like to bootstrap the sampling data from each pool.  So I generate a list of 100 masses for one pool, and 50 masses for the second pool.  Plus, I get the confidence intervals built off the bootstrap.  I can just add the mean, to get the mean total mass, but what about the CIs?
I'm still learning bootstrapping, obviously, so sorry if it's a simple question.  At first, I figured I could combine them similar to SD's, like sqrt(x^2 + y^2), but that doesn't work.  Does simple addition work?  Or do I need to build the CI's from scratch using the standard errors from each pool?

A: Correct me if i am wrong but it sounds to me like your problem is simply to get a confidence interval for the sum of two random variables $X$ and $Y$ with $X$ is the total mass from the sample for the first pool and Y is the total mass for the sample from the second pool.  I think for this problem you can use either the sum or the average.  To get a confidence interval for X+Y you would need to get the sampling distribution of $Z=X+Y$.  For a normal distribution a $95\%$ confidence interval for the population mean equates to the
$$\overline{x} \pm 1.96 \cdot s$$
where $\overline{x}$ denotes the sample mean and $s$ is the standard deviation.  But this relationship between confidence level does not hold for other distributions.  If you assume that $X$ and $Y$ are independent with a known parametric distribution then you can solve the problem without bootstrapping.  If you don't you can generate a bootstrap confidence interval for $Z$.  Get a bootstrap sample from the sample that generated $X$ and do the same for $Y$.  Take the bootstrap estimate for $X$ and add it to the bootstrap estimate for Y to get a bootstrap estimate for $Z$.  Repeat this say 10000 times and you will be able to construct a histogram of the $Z$s.  The percentile method bootstrap is one simple way to generate approximate confidence intervals.  Let $Z_1$ be the value at which $25$ values are at it or below and let $Z_2$ be the values at which $25$ values are at it or above. Then $[Z_1, Z_2]$ is an approximate $95\%$ bootstrap confidence interval for the mean of the distribution for $Z$.
The interval is approximate and there are other types of bootstrap confidence intervals that can be more accurate for the given sample size.


text:
Q: Accessing private virtual functions within same class I was asked, using this code and only writing in the extractMultAdd() function, to return variable.x variable.y variable.add() and variable.multiply. I understand that the basic concept of virtual tables and when they are created, but despite my best efforts, I'm not quite sure how to leverage them to access the private virtual functions. Any help would be appreciated.
#include <cstdio>
#include <iostream>
class MultAdd
{

private:
    int x;
    int y;
    virtual int add()   //virtual fuction so vtable created for Thing class
    {
            return x+y;
    }
    virtual int multiply()
    {
            return x*y;
    }
public:
    MultAdd(){
            x = 2;
            y = 10;
    }
};

int extractMultAdd(void* math)
{
    return 0;
}

int main()
{
    MultAdd variable;
    printf("%d\n", extractMultAdd(&variable));
    return 0;
}

A: I give you two versions to choose. They do not follow the standard, and are by no means portable, but both work on MSVC 2013, GCC 4.9, and clang 3.5 as I test it. The second version is relatively safer and more portable than the first one. In fact, I expect it to be rather robust.
Version 1:
#include <iostream>

class MultAdd {
private:
  int x;
  int y;
  virtual int add() { return x + y; }
  virtual int multiply() { return x * y; }
public:
  MultAdd() {
    x = 2;
    y = 10;
  }
};

struct MultAddCracker: MultAdd {
  int add();
  int multiply();
};

void extractMultAdd(MultAdd& v) {
  char* p = (char*)&v;
  std::cout << *(int*)(p + sizeof(void*)) << '\n';
  std::cout << *(int*)(p + sizeof(void*) + sizeof(int)) << '\n';
  MultAddCracker* pcracker = (MultAddCracker*)&v;
  std::cout << pcracker->add() << '\n';
  std::cout << pcracker->multiply() << '\n';
}

int main() {
  MultAdd v;
  extractMultAdd(v);
}

Version 2:
#include <iostream>

class MultAdd {
private:
  int x;
  int y;
  virtual int add() { return x + y; }
  virtual int multiply() { return x * y; }
public:
  MultAdd() {
    x = 2;
    y = 10;
  }
};

struct MultAddCracker {
  int x;
  int y;
  virtual int add();
  virtual int multiply();
};

void extractMultAdd(MultAdd& v) {
  MultAddCracker& w = (MultAddCracker&)v;
  std::cout << w.x << '\n';
  std::cout << w.y << '\n';
  std::cout << w.add() << '\n';
  std::cout << w.multiply() << '\n';
}

int main() {
  MultAdd v;
  extractMultAdd(v);
}

A: Well, if you're looking for a portable way, I could offer the following, which a C++ compiler must support. It is discussed further here. In short, it leverages the fact that access checking rules are bypassed in explicit template instantiations as per 14.7.2p8:

14.7.2p8 The usual access checking rules do not apply to names used to specify explicit instantiations. [Note: In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) may be private types or objects which would normally not be accessible and the template may be a member template or member function which would not normally be accessible.]

It does almost what you want to do; the only caveat with this is that template declarations cannot be at the function scope as per 14.2:

A template declaration can appear only as a namespace or class scope declaration

This might break the spirit of the question though the way it is phrased.
I don't know of any way to weasle the template structs into the function scope, but if there is a similar trick, this could do 100% what you want.
////////////////////////////////////////////////////////////////////////////////////////
//// The template classes can unfortunately not be declared inside extractMultAdd ()
////////////////////////////////////////////////////////////////////////////////////////

#define ROB_PRIVATE_MEMBER_INST(CLASS, TYPE, MEMBER)    \
template<typename T>                                    \
struct CLASS##_##MEMBER##_rob_tag {                     \
  typedef T CLASS::*type;                               \
  friend type get(CLASS##_##MEMBER##_rob_tag);          \
};                                                      \
template<typename Tag, typename Tag::type M>            \
struct CLASS##_##MEMBER##_rob_private                   \
{                                                       \
    friend typename Tag::type get(Tag) { return M; }    \
};                                                      \
template struct CLASS##_##MEMBER##_rob_private<         \
CLASS##_##MEMBER##_rob_tag<TYPE> , &CLASS::MEMBER>;     \

#define ROB_PRIVATE_MEMBER_INST_FN(CLASS, TYPE, MEMBER) \
template<typename T>                                    \
struct CLASS##_##MEMBER##_rob_tag {                     \
  typedef T type;                                       \
  friend type get(CLASS##_##MEMBER##_rob_tag);          \
};                                                      \
template<typename Tag, typename Tag::type M>            \
struct CLASS##_##MEMBER##_rob_private                   \
{                                                       \
    friend typename Tag::type get(Tag) { return M; }    \
};                                                      \
template struct CLASS##_##MEMBER##_rob_private<         \
CLASS##_##MEMBER##_rob_tag<TYPE> , &CLASS::MEMBER>;     \

#define ROB_PRIVATE_MEMBER_ACCESS(CLASS, INSTANCE, TYPE, MEMBER) \
    (INSTANCE.*get(CLASS##_##MEMBER##_rob_tag<TYPE>()))          \

////////////////////////////////////////////////////////////////////////////////////////
//// Actually use the macros
////////////////////////////////////////////////////////////////////////////////////////

ROB_PRIVATE_MEMBER_INST(MultAdd, int, x);
ROB_PRIVATE_MEMBER_INST(MultAdd, int, y);
ROB_PRIVATE_MEMBER_INST_FN(MultAdd, int(MultAdd::*)(), add);
ROB_PRIVATE_MEMBER_INST_FN(MultAdd, int(MultAdd::*)(), multiply);

////////////////////////////////////////////////////////////////////////////////////////

//ROB_PRIVATE_MEMBER_INST_FN(MultAdd, int(__thiscall *)(), add);
int extractMultAdd(void* math)
{
    // No need to pass as void*
    MultAdd *pMA(reinterpret_cast<MultAdd*>(math));

    // ROB_PRIVATE_MEMBER_INST(MultAdd, int, x); // Note that unfortunately this isn't possible

    // The 4 values, retrieved in a portable way
    int robbed_x = ROB_PRIVATE_MEMBER_ACCESS(MultAdd, *pMA, int, x);
    int robbed_y = ROB_PRIVATE_MEMBER_ACCESS(MultAdd, *pMA, int, y);
    int robbed_add = ROB_PRIVATE_MEMBER_ACCESS(MultAdd, *pMA, int(MultAdd::*)(), add)();      // Note we're calling function with ()
    int robbed_mul = ROB_PRIVATE_MEMBER_ACCESS(MultAdd, *pMA, int(MultAdd::*)(), multiply)(); // Note we're calling function with ()

    return 0;
}

Ignore the friend declaration warnings and scroll to output:
Run example
Of course "only writing in the extractMultAdd() function" might leave some room for this semantic trickery:
int extractMultAdd(void* math)
{
    return extractMultAdd_impl(math);
}

// structs

int extractMultAdd_impl(void* math)
{
    // original code ...
} // <== Original brace :)


text:
Q: Increase iBeacon range So I am currently using one device as a transmitter with a specific major and minor value and its broadcasting with
self.peripheralData = [[[CSMBeaconRegion alloc] initAsTransmitter] peripheralDataWithMeasuredPower:nil];
[self.peripheralManager startAdvertising:self.peripheralData];

And I am having a receiver that starts ranging and displays the major and minor value of the transmitter.
Everything works well. But when i start walking away from the device, and go beyond 10 meters, I lose connection.   When i walk back, i still do not have connection.  I can only restart the connection when I am less than 1m from the transmitter.
How can i increase the range of transmitter to its MAX?
Should I set some value to peripheralDataWithMeasuredPower?

A: The power of the iBeacon signal is based on BLE, you can't change it. The peripheralDataWithMeasuredPower is just use to calibrate ranging on the beacon.
Regarding your beacon not connecting when you come back in range, this is internal to the iBeacon system. It should work but sometimes there is a delay after you come in range of a beacon before your device detects it.

A: Something is wrong here.  When using an iPad or iPhone as a transmitter, you should be able to detect its iBeacon transmission beyond 10m, even if you can't reach the 50m nominal range.  Are you testing in an area with many obstructions?
And even if it does drop off at 10m, you should not have to return to 1m to detect it again (is that a typo?).  If you simply wait at 10m away, are you sure it won't detect it again?
While @Patrick-Tescher is correct that you cannot change the transmit power of an iOS device acting as an iBeacon, some hardware iBeacons like Radius Networks' RadBeacon do allow you to configure their transmitter power.  But you typically change the transmitter power with a proprietary mechanism that is specific to the beacon, and not with iOS APIs.
Also, while your iOS device may have a short range, dedicated hardware iBeacons often have a range that exceeds the 50m nominal range of Bluetooth LE.
Full disclosure:  I am an employee of Radius Networks.


text:
Q: checkScreenSharingCapability in Chrome 76 returns extensionRequired: "chrome" The TokBox documentation is confusing because it clearly states:
Important: As of Chrome 72+ and Firefox 52+, an extension is no longer needed for screen sharing. The browser prompts the end user for access to the screen as it would for access to the camera.

However, the sample code has:
OT.checkScreenSharingCapability(function(response) {
  if(!response.supported || response.extensionRegistered === false) {
    // This browser does not support screen sharing
  }
});

And chrome version 76 returns:
extensionInstalled: false
extensionRegistered: false
extensionRequired: "chrome"
supported: true

So Chrome 76 will say it's unsupported.  Firefox v68 returns extensionRegistered = undefined so it passes.  If I ignore the error and try to do screensharing in Chrome anyway, it fails and says the extension is required.

A: Fixed by updating @opentok/client from 2.15.1 to 2.16.2


text:
Q: Bad Token on line 1 with print statement I couldn't find anything online that would help so I'm asking here.  I want to format my print statement like this:
print("
1.)It really do be like that sometimes
2.)ok
3.)uhhhhhhhh
")

When I try to run it however, it says "SyntaxError: bad token on line 1 in main.py" and I don't know what I did wrong.  Any advice?

A: You can't have linebreaks in a string literal like that. Try replacing your code with this:
print("\n1.)It really do be like that sometimes\n2.)ok\n3.)uhhhhhhhh\n")

A: Use triple-quote string syntax:

print("""
1.)It really do be like that sometimes
2.)ok
3.)uhhhhhhhh
""")

For extra clarity couple it with textwrap.dedent():

import textwrap
print(textwrap.dedent("""
    1.)It really do be like that sometimes
    2.)ok
    3.)uhhhhhhhh
    """))


text:
Q: libstdc++ error trace unable to understand I am trying to enable informatica Integration Service which is failing to initialize. The core dump file traces to some libstdc++ error which we are not able to identify.
We have tried to check the libstdc++ version if that is an old version but it points to latest version.
Please see lines #2 through 8.
0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
1  0x00007f355b906d41 in __GI_abort () at abort.c:79
2  0x00007f355c064305 in __gnu_cxx::__verbose_terminate_handler () at ../../../../libstdc++-v3/libsupc++/vterminate.cc:95
3  0x00007f355c061ef6 in __cxxabiv1::__terminate (handler=<optimized out>) at ../../../../libstdc++-v3/libsupc++/eh_terminate.cc:47
4  0x00007f355c061f41 in std::terminate () at ../../../../libstdc++-v3/libsupc++/eh_terminate.cc:57
5  0x00007f355c062184 in __cxxabiv1::__cxa_throw (obj=obj@entry=0x7f353c042e70, tinfo=0x7f355c34e368 <typeinfo for std::ios_base::failure[abi:cxx11]>, dest=0x7f355c094a30 <std::ios_base::failure[abi:cxx11]::~failure()>) at ../../../../libstdc++-v3/libsupc++/eh_throw.cc:93
6  0x00007f355c08cea3 in std::__throw_ios_failure (__s=__s@entry=0x7f355c115f67 "basic_ios::clear") at ../../../../../libstdc++-v3/src/c++11/ios.cc:50
7  0x00007f355c0cb54d in std::basic_ios<char, std::char_traits<char> >::clear (this=<optimized out>, __state=<optimized out>) at /usr/src/debug/gcc-7.3.1-20180303/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/basic_ios.tcc:48
8  0x00007f355c0d00aa in std::basic_ios<char, std::char_traits<char> >::setstate (__state=<optimized out>, this=<optimized out>) at /usr/src/debug/gcc-7.3.1-20180303/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/basic_ios.h:158
9  std::istream::_M_extract<unsigned int> (this=0x7f3543ffe440, __v=@0x7f3543ffe85c: 0) at /usr/src/debug/gcc-7.3.1-20180303/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/istream.tcc:114
10 0x00007f3565c90266 in PmProcessStatsManager::fetchCPUStats() () from /obin/informatica/10.2/server/bin/libpmuti.so
11 0x00007f3565c90e59 in PmProcessStatsManager::collect() () from /obin/informatica/10.2/server/bin/libpmuti.so
12 0x00007f3565c9168a in PmMetricsCollector::collect() () from /obin/informatica/10.2/server/bin/libpmuti.so
13 0x00007f35660145a5 in SFOSMonitor::doMonitorProcesses() () from /obin/informatica/10.2/server/bin/libpmsf.so
14 0x00007f3566014e98 in SFOSMonitor::runImpl() () from /obin/informatica/10.2/server/bin/libpmsf.so
15 0x00007f356601caf8 in SFRunnable::run() () from /obin/informatica/10.2/server/bin/libpmsf.so
16 0x00007f356601cb81 in SFRunnable::run(void*) () from /obin/informatica/10.2/server/bin/libpmsf.so
17 0x00007f3562498a35 in ACE_Thread_Adapter::invoke_i() () from /obin/informatica/10.2/server/bin/libACE.so.6.3.3
18 0x00007f3562498ab1 in ACE_Thread_Adapter::invoke() () from /obin/informatica/10.2/server/bin/libACE.so.6.3.3
19 0x00007f3566c7354b in start_thread (arg=0x7f3543fff700) at pthread_create.c:465
20 0x00007f355b9c62ff in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95


text:
Q: How to prevent that rowSelector's clickAction method is fired when using any button on the page? I have a ice:dataTable with a ice:rowSelector in one column, and a ice:selectBooleanCheckbox in another column. The ice:rowSelector has toggleOnInput set to false.
If I select a checkbox (with a click) in one row, the clickAction is not fired (because of toggleOnInput - so far, so good).
But If I click on a button on the same page after this, regardless of what action bindings they have, the rowSelector's clickAction is fired. Why?
Any ideas to prevent this?
Here is my page definition:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ice="http://www.icesoft.com/icefaces/component"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html">
    <f:view>
        <ice:form>
            <ice:commandButton value="Test" />

            <ice:dataTable id="dataTable"
                       value="#{PageBean.data}"
                       var="entity">
                <ice:column>
                    <ice:selectBooleanCheckbox />
                </ice:column>
                <ice:column>
                    <ice:outputText value="#{entity.name}" />
                    <ice:rowSelector clickAction="#{PageBean.clickAction}" toggleOnInput="false" />
                </ice:column>
            </ice:dataTable>
       </ice:form>
    </f:view>
</html>

A: You can try making different forms for other buttons in the page and the data table, we should not have nested forms but can have multiple forms
Also I would suggest to use selectionAction attribute if you are performing an Action method to call when the respective row is clicked.
Hope this could help you

A: I can see that you are using a command button which is specified as:
ice:commandButton

The ice:commandButton tag displays a button which can be linked to an action in
a backing bean method by specifying the bean and the method in the actionListener
attribute. The button can be replaced by an image by specifying the URL of the
image in the image attribute.

Where I clearly see that it's backed by a bean method. Check your code thoroughly.


text:
Q: How to compile so file from Mongodb c++ 2.2 source codes? Today I try to upgrade my driver for mongodb 2.2. But only get libmongoclient.a file.
The download url is:
http://downloads.mongodb.org/cxx-driver/mongodb-linux-x86_64-v2.2-latest.tgz
Here is my way:
scons --prefix=/usr install


text:
Q: Return false is not working AJAX I have got this in my index.htm
<form>
<input onkeyup="firstnamecheck(this.value)" type="text" name="firstname" id="Start" class="Inputs" />
<button type="submit" name="Murad"  id="tester"title="Register" >Register</button>
</form>

And this in reg.js
function firstnamecheck(str) {
    if (str.length == 0) {
        document.getElementById("firster").innerHTML = "";
        return false;
    }else if(3>str.length>0){
        document.getElementById("firster").innerHTML = "Firstname should be more than 3 charachters";
        return false;
    }else if(str.length>30){
        document.getElementById("firster").innerHTML = "Firstname should be less than 30 charachters";

       return false;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("firster").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("POST", "era.php?f=" + str, true);
        xmlhttp.send();
    }
}

But even when it gives error i can still submit form even though there is return false.

A: Compound range comparisons like
if(3>str.length>0)

don't work in JavaScript, or most (but not all!) other languages whose syntax derives from B (C, C++, C#, D, Java, JavaScript, etc.).
Instead, you have to list the two comparisons separately:
if (3 > str.length && str.length > 0)

A: In addition to @TJCrowder's answer, there's something possibly even more important:
Your return false; is going to the onkeyup event of the input element, not the submit event of the form!
In fact, there is nothing that attempts to stop the form submitting.


text:
Q: Bit operations on an arbitrarily large bit-array or number I have a very simple question: In C++, is there an in-built or straightforward way to group a large (~1000) number of bits (or bools) in a single label such that the inbuilt bit operators function as they do for fundamentals?
e.g. for a long you might write:
unsigned long maximum = ~0;

or one might use:
somenum>>;

Is there an analogous way to do this for a block of memory of arbitrary size?
If not, what are some good alternatives ? I have thought of bit <vectors>, a C union, etc., but these all seem to require handwritten routines for the various bit operations.

A: Yep!  It's called std::bitset and does just that.
Hope this helps!

A: Also, boost::dynamic_bitset might be useful depending on the requirements. I wish it was standard instead of the hack that std::vector<bool> is


text:
Q: GCP Mysql instance is not taking VARCHAR limit more than 3072 We are using GCP based mysql server for our application. For one of the column we need to increase the limit for varchar from default 255.
Please see below query and error :-
ALTER TABLE data_key MODIFY COLUMN key VARCHAR(8000);
ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes

This is working as expected on local mysql DB but not on mysql of GCP. Do we have restriction on GCP for limits else how can limit be increased or change of data type is possible (last option).
Output of show create table data_key :
data_key table
CREATE TABLE data_key (
    id int(11) NOT NULL,
    key varchar(255) DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY US_mypr3ns15fjs031li0iwa6sdf4nk` (key )
)  ENGINE=InnoDB DEFAULT CHARSET=latin1

A: The reason why this error occured is InnoDB engine[1]. If you use MySQL Second Generation on Google Cloud, InnoDB is the only storage engine supported [2]. For MySQL First Generation instances, the InnoDB storage engine is recommended.
In InnoDB innodb_large_prefix is enabled by default, the index key prefix limit is 3072 bytes for InnoDB tables that use DYNAMIC or COMPRESSED row format. This was introduced in MySQL 5.5 to disable large index key prefixes for compatibility with earlier versions of InnoDB that do not support large index key prefixes. It was deprecated and removed in future releases [3].
In your case you can create a First Generation MySQL instance[4], but be aware that support for First Generation instances ends January 30, 2020 and set up another storage engine[5].

[1] https://en.wikipedia.org/wiki/InnoDB
[2] https://cloud.google.com/sql/docs/mysql/faq#innodb
[3] https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html#innodb-maximums-minimums
[4] https://cloud.google.com/sql/docs/mysql/create-instance#create-1st-gen
[5] https://dev.mysql.com/doc/refman/5.7/en/storage-engines.html


text:
Q: nestedscroolview doesn't scroll well inside another nestedscrollview I have a bottom sheet dialog with 2 nestedscrollview, the outer one wrap the entire view, the inner one wrap a single textview, I have 2 problems:
1.
the the inner one can scroll only down, as you can see in the gif:

I need to make the inner nestedscrollview scrollable in both direction and the outer nestedscrollview scrollable when I drag outside the inner one, how can I do it?
2.
I need to make the inner nestedscrollview to wrap text, tried with constraints but not working, wrap_content make the entire textview to be shown, making the scrollview a simple textview.
How can I do it?
This is my XML code:
<androidx.core.widget.NestedScrollView
    android:id="@+id/outer_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ViewSwitcher
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/inner_scrollview"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="200dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                    android:textColor="@color/white"
                    android:textSize="25dp"
            </androidx.core.widget.NestedScrollView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"></TextView>

        </ViewSwitcher>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

A: After Some R&D at my End I have Finalised the XML Layout, Its Working For Me.
Actually the issue was the Wrong layout Designing. Grab the Latest Changes from Below.
<androidx.core.widget.NestedScrollView
    android:id="@+id/outer_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ViewSwitcher
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/inner_scrollview"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="200dp"
                android:nestedScrollingEnabled="true"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                    android:textColor="@color/white"
                    android:textSize="25dp"></TextView>

                </LinearLayout>

            </androidx.core.widget.NestedScrollView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"></TextView>

        </ViewSwitcher>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

Apply this layout XML and Let me know if anything Required more.

A: the problem simply is you are using scrolling view inside scrolling view so
I suggest you to make text scrollable in another way like making it read only edit text android:editable="false" or Edittext.setEnabled(false);  and play with colors
or
give enough space to text view
or
adjust text size
or you can give focus when you tab on scrolling view like

A:  ViewCompat.setNestedScrollingEnabled(listRecyclerView, false);

You might try this to fix the scrolling problem.


text:
Q: Offline Sentiment Analysis Lib with java I have an offline tweets corpus. I am trying to do sentiment analysis on it offline classifying each tweet to 'Positive', 'Negative', 'Neutral'.
Is there a java lib that I can use ?

A: There is the sentiment analysis implementation by the Stanford NLP group (http://stanfordnlp.github.io/CoreNLP/). You can find some source code here: https://blog.openshift.com/day-20-stanford-corenlp-performing-sentiment-analysis-of-twitter-using-java/
Another alternative is to use a word-emotion association lexicon as found here: http://saifmohammad.com/WebPages/NRC-Emotion-Lexicon.htm.
A simple approach is tidying the tweet and counting the negative and positive words as found in the lexicon.


text:
Q: Python thread with queue duplicates items inside queue I am trying to implement a worker thread to go through a queue and add the items inside to a sql db.
But I am experiencing this weird issue where even though I am definetly putting in different statements to the queue, they all become copies of each other inside the queue if I am putting them in the queue within 2 seconds.
This is the worker thread with the queue:
class DBWriterThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.q = queue.Queue()
        self.put = self.q.put

        self.start()

    def run(self):
        db_conn = None
        while True:
            statements = [self.q.get()]
            try:
                while self.q.empty() is False:
                    statements.append(self.q.get(), block=False)
            except queue.Empty:
                pass
            try:
                if statements[0] is None:
                    return
                if not db_conn:
                    db_conn = connect_to_db()
                try:
                    cursor = db_conn.cursor()
                    for statement in statements:
                        print(statement)
                        if statement is None:
                            return

                        work_order = statement[0][0]
                        data = statement[0][1]

                        if work_order == 'insertTick':
                            print(f"GOT ORDER TO INSERT DATA OF SYMBOL {data['symbol']}")
                            insertDataRow(data, cursor)
                        elif work_order == 'insertTrade':
                            insertTradeSignal(data, cursor)
                        else:
                            print("Unknown work order")
                            print(work_order)
                finally:
                    db_conn.commit()
            finally:
                for _ in statements:
                    self.q.task_done()

I instantiate this thread class inside my main program (which is also a class) where I in the init method is defining it as
self.db_writer = DBWriterThread()

and then throughout the program I am doing
self.dbWriter.put((['insertTick', self.peopleTick],))

to insert data in the queue.
I believe what is happening is that I am getting multiple peopleTicks within a very short span (practically simultaneously), where after I am calling the self.dbWriter.put((['insertTick', self.peopleTick],)) with the two different peopleTicks directly after each other.
This is where I am experiencing that even though I input two different peopleTicks into the queue, when the worker thread retrieves the queue, the items inside are duplicates of the same tick.
This can be stopped if I do a time.sleep(2) (not less) between I call the self.dbWriter.put but that would not work for my program and defeats the whole point of a queue. How do I solve this?
I have tried figuring out locks if that could help, but I don't know how to implement it and if that would be the solution.


text:
Q: an i-drop  tag seems to deviate from the parent div on Internet Explorer I am working on AutoDesk's iDrop indicator in Internet explorer and the object file seems to deviate from the parent .
How can I fix it to enforce the object image to fit to  box.
Preview of the idrop image at top and it's parent at the bottom