text:
Q: SQL Network Name owned by Available Storage OwnerGroup in Server 2012 FCI I did a simple get-clusterresource and noticed the 'owner group' is 'available storage'.  Not SQL Server (instance)for the SQL Server Network Name (instance).  I want to fix this ASAP but I'm having a hard time finding out how to move a owner group only.
Or actually from what I can tell the SQL Network Name (instance) isnt even supposed to be a 'network name'.  It's a instance.  I think this is a extra line I don't need and should remove this:
SQL IP Address 1 (clsnwname... Online                        SQL Server (I1)             IP Address
SQL IP Address 1 (clsnwname2... Online                        SQL Server (I2)              IP Address
SQL Network Name (clsnwname... Online                        SQL Server (I1)             Network Name
SQL Network Name (clsnwname2... Online                        SQL Server (I2)              Network Name
SQL Network Name (I1)       Failed                        Available Storage             Network Name
SQL Server (I2)              Online                        SQL Server (I2)              SQL Server
SQL Server (I1)             Online                        SQL Server (I1)             SQL Server
SQL Server Agent (I2)        Online                        SQL Server (I2)              SQL Server Agent
SQL Server Agent (I1)       Online                        SQL Server (I1)             SQL Server Agent

I was testing a new server that will be released at some point and noticed the Windows Updates were not installing SQL updates.  It stated it cannot update because the IP is offline.
I tested failover repeatedly and it always has worked, and continues to work as shown in the GUI with no issues and IP is up.  Replication and all connections are working fine.

A: It looks like a rogue client access point was added or someone manually moved/changed something.
Your two instances are as such:
SQL Server (I2)              Online                        SQL Server (I2)
SQL Server (I1)             Online                        SQL Server (I1)

They have corresponding network names in the proper groups:
SQL Network Name (clsnwname... Online                        SQL Server (I1)
SQL Network Name (clsnwname2... Online                        SQL Server (I2)

Each client access point also has at least one online IP:
SQL IP Address 1 (clsnwname... Online                        SQL Server (I1)
SQL IP Address 1 (clsnwname2... Online                        SQL Server (I2)

The outlier (failed) client access point:
SQL Network Name (I1)       Failed                        Available Storage

Which you've stated isn't part of any of the SQL Resource Groups, isn't online (failed) doesn't have an IP associated with it (as far as we can tell from your output).
This leads me to believe:

*

*Someone attempted to make this and didn't know what they were doing

*Incorrect automated setup was run (with DSC, powershell, or other tooling [chef, puppet,etc])

*Testing was done and not cleaned up properly

I doubt it was malicious. In any event, check out the dependency report - which I'm guessing will be blank. If it is, feel free to remove it and the associated computer object in AD. If it isn't blank, update the post with more information please.


text:
Q: Samba accessible from same machine but not from external network So I got samba configured on a remote Ubuntu 16.04 server but whenever I try to access it from either windows 10 or another ubuntu machine remotely, I get an error that the folder could not be found. It's worth noting that I'm trying to connect directly using the IP and not the hostname
When I try to connect using smbclient or list the folders from the same server, it connects just fine and I can see the shares.
root@hostname:~# smbclient -L //<ip is here>/home -U user
WARNING: The "syslog" option is deprecated
Enter user's password:
Domain=[WORKGROUP] OS=[Windows 6.1] Server=[Samba 4.3.11-Ubuntu]

    Sharename       Type      Comment
    ---------       ----      -------
    home            Disk      home
Domain=[WORKGROUP] OS=[Windows 6.1] Server=[Samba 4.3.11-Ubuntu]

When I try the same command from the remote ubuntu machine, it doesn't work.
See below my /etc/samba/smb.conf
    [global]

    ## Browsing/Identification ###

    # Change this to the workgroup/NT-domain name your Samba server will part of
       workgroup = WORKGROUP

    # server string is the equivalent of the NT Description field
            server string = %h server (Samba, Ubuntu)

    # Windows Internet Name Serving Support Section:
    # WINS Support - Tells the NMBD component of Samba to enable its WINS Server
      wins support = yes

    # WINS Server - Tells the NMBD components of Samba to be a WINS Client
    # Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
    ;   wins server = w.x.y.z

    # This will prevent nmbd to search for NetBIOS names through DNS.
       dns proxy = no

#### Networking ####

# The specific set of interfaces / networks to bind to
# This can be either the interface name or an IP address/netmask;
# interface names are normally preferred
interfaces = eth0 lo
guest account= nobody

# Only bind to the named interfaces and/or networks; you must use the
# 'interfaces' option above to use this.
# It is recommended that you enable this feature if your Samba machine is
# not protected by a firewall or is a firewall itself.  However, this
# option cannot handle dynamic or non-broadcast interfaces correctly.
;   bind interfaces only = yes

#### Debugging/Accounting ####

# This tells Samba to use a separate log file for each machine
# that connects
   log file = /var/log/samba/log.%m

# Cap the size of the individual log files (in KiB).
   max log size = 1000

# If you want Samba to only log through syslog then set the following
# parameter to 'yes'.
#   syslog only = no

# We want Samba to log a minimum amount of information to syslog. Everything
# should go to /var/log/samba/log.{smbd,nmbd} instead. If you want to log
# through syslog you should set the following parameter to something higher.
   syslog = 0

# Do something sensible when Samba crashes: mail the admin a backtrace
   panic action = /usr/share/samba/panic-action %d

####### Authentication #######

# Server role. Defines in which mode Samba will operate. Possible
# values are "standalone server", "member server", "classic primary
# domain controller", "classic backup domain controller", "active
# directory domain controller".
#
# Most people will want "standalone sever" or "member server".
# Running as "active directory domain controller" will require first
# running "samba-tool domain provision" to wipe databases and create a
# new domain.
   server role = standalone server

# If you are using encrypted passwords, Samba will need to know what
# password database type you are using.
   passdb backend = tdbsam

   obey pam restrictions = yes

# This boolean parameter controls whether Samba attempts to sync the Unix
# password with the SMB password when the encrypted SMB password in the
# passdb is changed.
   unix password sync = yes

# For Unix password sync to work on a Debian GNU/Linux system, the following
# parameters must be set (thanks to Ian Kahan <<kahan@informatik.tu-muenchen.de> for
# sending the correct chat script for the passwd program in Debian Sarge).
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .

# This boolean controls whether PAM will be used for password changes
# when requested by an SMB client instead of the program listed in
# 'passwd program'. The default is 'no'.
   pam password change = yes

# This option controls how unsuccessful authentication attempts are mapped
# to anonymous connections
   map to guest = bad user

############ Misc ############

# Allow users who've been granted usershare privileges to create
# public shares, not just authenticated ones
   usershare allow guests = yes

#======================= Share Definitions =======================

[home]
 comment=home
 path=/home/myhome/share
 browseable=Yes
 read only = yes
guest ok=yes

What am I doing wrong?

A:
interfaces = eth0 lo

Well ... for one  ... unless you went out of your way to rename it you don't have an interface named eth0. You may have one labelled something like enp0s3.
Run the following command to find out:
ifconfig

Or just leave the entire line out of smb.conf. Samba will figure this out by itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript setProperty only seems to works for first element? I am creating a timer countdown function for a webshop.
Preview:

It's using the (Tailwind) DaisyUI countdown element (https://daisyui.com/components/countdown/) and counts down from a dynamic datetime value.
This is working fine for one countdown, but not for multiple on the same page. I've changed all javascript triggers to classes, and created a for-loop for the javascript function, but still only works for the first one found.
What is causing this? Im using the javascript setProperty function to change the time values with a timeout of 1 second. Below my code:

let timerCounter = jQuery('.timer-counter');
    if (typeof timerCounter !== undefined) {
        var datetime = timerCounter.closest('div').find('.timer-item').attr('data-counter-date');
        if (datetime == undefined) {
            return;
        }

        for (let key = 0; key < timerCounter.length; key++) {
            const value = timerCounter[key];
            startTimer(key, datetime);
        }
    }

function startTimer(timerCounter, countDown) {
    var countDownDate = new Date(countDown).getTime();
    var interval = setInterval(function() {

        // Get today's date and time
        var now = new Date().getTime();

        // Find the distance between now and the count down date
        var distance = countDownDate - now;

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.querySelector('.timer-hours').style.setProperty('--value', hours);
        document.querySelector('.timer-minutes').style.setProperty('--value', minutes);
        document.querySelector('.timer-seconds').style.setProperty('--value', seconds);

        // If the count down is over, write some text
        if (distance <= 0) {
            clearInterval(interval);
            location.reload();
        }
    }, 1000);
}

And the PHP component:
<?php
$offset = !empty($args['offset']) ? $args['offset'] : die('offset not definded');
$hours = date_i18n('H', $offset);
$minutes = date_i18n('i', $offset);
$seconds = date_i18n('s', $offset);
$date = date_i18n('Y/m/d H:i:s', $offset);
?>

<div class="timer-item inline-flex flex-col" data-counter-date="<?php echo $date; ?>">
    <?php echo __('Shipping today?', 'qore'); ?>

            <span class="timer-hours" style="--value:<?php echo $hours; ?>;">:
            <span class="timer-minutes" style="--value:<?php echo $minutes; ?>;">:
            <span class="timer-seconds" style="--value:<?php echo $seconds; ?>;">

        <?php echo __('remaining', 'timer') ?>

I hope anyone will know the answer for what I am doing wrong.
Thanks in advance!

A: With some help of ADyson and a small tweak in my code, I managed to get this working.I replaced querySelector with querySelectorAll, and have send the correct key in my startTimer function.
This way I could use:
document.querySelectorAll('.timer-hours')[key].style.setProperty('--value', hours);
document.querySelectorAll('.timer-minutes')[key].style.setProperty('--value', minutes);
document.querySelectorAll('.timer-seconds')[key].style.setProperty('--value', seconds);

Inside my countdown script file.
Hope this will help others in the future.


text:
Q: How do I align the text and accompanied image horizontally? Here is the result of the code below:

If I make the first image bigger then I have this one (The text goes far below the image) :

Now the question is:
How do I align each text and image horizontally?
(I want the text on the middle of the image not on the lower edge)

Diamonds: {valueY.value}

Performance: {Performance}

A: Just Convert the image vertical-align property from bottom to top.
It's better to divide your structure into divs that will make controlling of elements designs much easier.

A: To make the text horizontally centered comparing to the images you can make it's position absolutely & push it 50% from top and push it back of it's own height. So it will be vertically centered comparing to the left image/icon. Here is what I mean:

    Diamonds: {valueY.value}

    Performance: {Performance}

I have wrapped each block within a div element so I can make the div position relatively.
Here is the css:
.wrapper { position: relative; }
img {
  vertical-align: bottom; margin-right: 10px;
  width:32px; height:30px;
}
span {
  font-size:14px; color:#000000; display: inline-block;
  position: absolute;
/*  push it by 50% from top  */
  top: 50%;
/*  push it back of it's own height  */
  transform: translateY(-50%);
}

Here is the live preview


text:
Q: iron router add parameter to string as well as add a query Just started playing around with meteor and I'm trying to use iron-router for the routing. Here is my data structure:
team
  _id
  name
  tags:[{name,counter}]

And here is the linking I'm trying to use in the template
{{#each team.tags}}
   #{{this.name}} {{this.counter}}
{{/each}}

And my router has:
route('/team/:_id')  // And I get the search through the GET property... this.params.query

So:

*

*How do I get the parent team _id in the template?

*How can I pass the _id and the search parameter in the pathFor?

Thanks in advance.

A: You can make use of ../ to step back to the parent scope, which in this case appears to be teams
{{#each team.tags}}
   #{{this.name}} {{this.counter}}
{{/each}}


text:
Q: ERR_CONNECTION_REFUSED after dockerizing Vuejs app I'm trying to dockerize my frontend and I've followed this tutorial https://v2.vuejs.org/v2/cookbook/dockerize-vuejs-app.html
Here's my dockerfile
FROM node:lts-alpine

# install simple http server for serving static content
RUN npm install -g http-server

# make the 'frontend' folder the current working directory
WORKDIR /frontend

# copy both 'package.json' and 'package-lock.json' (if available)
COPY package*.json ./

# install project dependencies
RUN npm install

# copy project files and folders to the current working directory (i.e. 'app' folder)
COPY . .

# build app for production with minification
RUN npm run build

EXPOSE 8080
CMD [ "http-server", "dist" ]

When I go to localhost:8000 it says the site cannot be reached and ERR_CONNECTION_REFUSED


text:
Q: CSS sprites and IE6 Does IE6 support css-sprites?

A: You can also use Glue http://gluecss.com/
It's an open-source command line tool to generate sprites.

A: CSS sprites is a general solution using backround-position, which is avaible even in IE5.
A good tutorial about them is located here: http://www.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/

A: I have encountered the IE6 CSS sprites problem myself - I blogged it here:
There's a really easy fix - I quote myself here...

Luckily, the solution wasn't too bad. Internet Explorers passim seem to ignore overflow:hidden when a child element is set to position:relative. Not good news... but the solution is easy - set the element with overflow:hidden to also be position:relative and then change the position:relative declaration on the child to be position:absolute... the jobs a goodun.

The full details can be found on that link.

A: Yes IE 6 supports sprites but doesn't support 24 bit PNG transparency.
I use this css hack for giving IE < 7 a gif file and everything else a 24 bit png with transparency.
background-image:url(/images/sprites/icons-sprite.png);
_background-image:url(/images/sprites/icons-sprite.gif); /* IE<7 gets the crappy icons */

A: Yes.
CSS sprites is just a technique to use offset on background images to display different parts of the same image in different elements.
I use CSS sprites on for example the main menu on the website of the company I work for, and the flags on my own web site. I started using it before it was even called CSS sprites...

A: Browsers which support background-position property will support CSS sprites also.
CSS Sprites: What They Are, Why They're Cool, and How To Use Them
Please take a look at the following questions also
CSS Sprites images rendered with bad quality in IE
CSS Sprite Help

A: Yes. If you're using PNGs though you should consider a few things. Here is a decent summary of IE 6 PNG issues:
http://24ways.org/2007/supersleight-transparent-png-in-ie6

A: You could just use an online sprites generator. There are so many of them available for free and most of them support all browsers.

A: Sprites can work perfectly in ie6. But a png image will not work, so use a gif. If you process a gif with Smush.it to losslessly remove overhead, you might get a file size smaller than the corresponding png.


text:
Q: RPG/DB2 Cursor as a resultset being cleared I have an RPG program/stored procedure that returns a resultset to a .net program. Everything is working fine until the RPG is added some code after
... RETURN to CLIENT CURSOR C1...

// New Line Of code
... DELETE FROM <FILE>...

Why is the resultset empty when it is deleted from the FILE?  Shouldnt the resultset already be in the cursor C1?
What I am trying to do is call a RPG stored procedure and have the procedure return me a resultset from a FILE then delete the records int the file. I thought by setting it to a resulset it would retain the data after I delete the actuall data in the db. but it looks like if I delete the records the resultset is cleared

A: You could put the chosen records in a temp table, delete them from the original file, then return a result set of the temp table.


text:
Q: SQL Error Code: 1172 on update not insert I have a very basic query here
UPDATE leads
SET created = NOW()
WHERE id IN(
    4142429,
    4142430,
    4142431,
    4142432,
    4142433,
    4142434,
    4142435,
    4142436,
    4142437
);

But whenever i try to run it in sqlYOG, I get the error:
Error Code: 1172
Result consisted of more than one row

I did some research to the error, and that turned up this question:
Error 1172 : Result consisted more than one row (in SQL)
which has already been answered, but the answer is not clear. I'm not inserting anything into the table either.
I have also tried doing the query
UPDATE leads SET created = NOW() - INTERVAL 1 DAY WHERE ID = 4142432;

But I still get the same error.
Why does this happen when I am only updating one row?


text:
Q: How to get cookie after login using mechanize import mechanize
import json
import re
from bs4 import BeautifulSoup
import requests

browser = mechanize.Browser()
class login:
    def __init__(self):
        email = "aaaa"
        password = "bbb"
        url = "https://app.propertymeld.com/login/?next=/"
        self.email = email
        self.password= password
        self.url = url
    def login_url(self):
        try:
            browser.open(self.url)
            browser.select_form(nr=0)
            browser.form['email'] = self.email
            browser.form['password'] = self.password
            result = browser.submit().read()
            print(result)
            print("Login Successfully")
        except Exception as e:
            print("Unable to login successfully",e)

def main():
    web_login = login()
    web_login.login_url()
if __name__ == "__main__":
    main()

I need to get the cookies after logging in a webpage, using a particular email and password with mechanize. How can I get the browser's cookies in a particular login session?

A: You can get the cookies from browser._ua_handlers['_cookies'].cookiejar.
This returns a mechanize._clientcookie.CookieJar object which can be iterated through and there are names and values for each of the cookies in it.
For instance, the first cookie's name and value are:
browser._ua_handlers['_cookies'].cookiejar[0].name
browser._ua_handlers['_cookies'].cookiejar[0].value


text:
Q: Transform is not applied on Embedded SVGs Chrome I am new to using SVGs, but everything was fine until I tried my code on chrome and found that it doesn't work properly, all transform attributes are neglected. Firefox gets it done as expected.
My problem is that the transform attribute is not working when I assign it to embedded SVG (SVG inside an SVG). This problem doesn't occur in Firefox.
Here is a sample code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" type="text/css" />

    <title>Document</title>
  </head>
  <body>
    <svg
      viewBox="0 0 300 100"
      xmlns="http://www.w3.org/2000/svg"
      stroke="red"
      fill="grey"
    >
      <circle cx="50" cy="50" r="40" />
      <circle cx="150" cy="50" r="4" />

      <svg transform="translate(0,50)" viewBox="0 0 10 10" x="200" width="100">
        <circle cx="5" cy="5" r="4" />
      </svg>
    </svg>
  </body>
</html>

You will notice that the circle with the thick red border moves a little bit downward when this code runs in Firefox, but it stays in its place when the code runs in chrome.
Why does this happen and how to solve it?
Thank you so much! <3

A: transform attributes on <svg> elements are a feature added with the SVG 2 spec. Its implementation is still a bit uneven.
Just set the attribute y="50" to achieve the same effect, or, if for some reason you are not able to do so, wrap the <svg> element in a <g> and apply the transform there.


text:
Q: How to avoid blocking thread during some heavy processing in c++? I'm a beginner of c++ multi threading program. I created a dummy code for my question. Hoge class is communication class which is connected socket and I assume Hoge::update() is data receiving class via the socket. And if specific data has arrived, Hoge instance pass the data to Fuga instance for specifigc processing.
So my questions are,

*

*I don't want to block Hoge::update(). So after storing data, I don't want to use th_process_data.join(). Are there any better solution for this?

*After processing data in another thread, how to return this processed data to Hoge instance. Some callback class is solution?

Hoge.cc
Fuga fuga;
Hoge::update() {
  while(true) {
    if(check_something()) {
      auto data = get_data();
      fuga.push_data(data);
    }
  }
}

Hoge::on_received(const Data& data) {
  std::cout << "received: " << data.id << std::endl;
  // do something...
}

Fuga.cc
std::vector<Data> data_list;
std::mutex mtx;

Fuga::push_data(const Data& data) {
  {
    std::lock_guard<std::mutex> lock(mtx);
    data_list.push_back(data);
  }
  std::thread th_process_data([&]{ do_processing(); });
  // Q1. I don't want to block this thread for Hoge::update()
}

Fuga::do_processing() {
  Data data;
  {
    std::lock_guard<std::mutex> lock(mtx);
    data = data_list.pop();
  }

  // heavy task for data...
  std::this_thread::sleep_for(std::chrono::seconds(3));

  // Q2. How to pass this processed data to Hoge::on_received(const Data& data)
}

A: Part of your Q is not very clear to me as it seems open ended many possibilites. However your 2 queries are objective, hence I am trying to answer from my recent experience with sockets.

"1. I don't want to block Hoge::update(). So after storing data, I don't want to use th_process_data.join(). Are there any better solution for this?"

In such case, you may do:
th_process_data.detach();

This will save you from blocking on .join(). You may also use std::future and std::promise combo if your design allows. More information can be found in this post.

"2. After processing data in another thread, how to return this processed data to Hoge instance. Some callback class is solution?"

I don't see a big deal in simply calling Hoge::on_received() method and pass the data. The thread will be still the th_process_data only. If you are worried about providing the time slicing and using sleep_for() method for it, then you may also look for std::yield as an alternative.

According to your current design you have put 2 std::mutex in 2 methods. I feel, it's not required.
Also, remember that you are creating a thread every time the Fuga::push_data() is invoked. If this method is invoked frequently and you don't want to load the CPU with the expense of multiple threads creation, then better to create single thread once and wait in it for the data to be received. But that will require a change of design.


text:
Q: how to update and post the value of checkbox from ajax call i retrieved data from mysql table into html page i.e
$query="select * from student";
$result=mysql_query($query)or die(mysql_error());
while($rs=mysql_fetch_array($result))
{
?>

      <?php echo $rs['st_id']; ?>
<?php echo $rs['name']"; ?>
<input type="checkbox" name="checked[]" <?php if($rs['checked']==1){echo "checked"; } ?> />

this is gives me the output

assume that checkbox of id 1 is checked and retrieved from mysql table.
 Now what i want to do is that when i checked the remaing two checkbox into this table and a function is called to ajax which goes to php page and update the value of checked field according to the given id (i.e 2 and 3 in this case). Not refreshing the whole page nor updating the whole record just the value of check box. i am new to ajax so
any help would be greatly appreciated.

A: Yes, exploring jqGrid isn't a waste of time at all. However, since you want to update only on change of checkbox value. Here's what you can do..
<input type="checkbox" name="check1"  />

And..
$().ready(function(){
  var st_id = <?php echo $rs['st_id']; ?>;
  //Or you could use a hidden field in the form

  $(':checkbox').click(function(){
    var chkName = $(this).attr('name');
    var checkVal = $(':checkbox[name='+chkName+']').attr('checked');//true or false
    $.ajax({
      url: 'MyApp/update.php?checboxName=' + checkVal,//Do update on server-side
      success: function(data) {
        alert('Updated successful.');
      }
    });
  });
});

Also, you can do a $('formID').serialize() wihch returns name=value pairs of all form elements that can then be appended in the call to your php script.


text:
Q: bash shell display first part of file using BSD head Here's the file:
line1
line2
⋮
line10
Total
Update time

I want to have the first part of file except for the last 2 lines.
The output should look like this:
line1
line2
⋮
line10

How can i achieve this using BSD head? or other oneliner?
Thanks!

A: using awk, this will print all the lines except last two lines.
  awk '{a[j++]=$0}END{for(i=0;i<j-2;i++){print a[i]}}' filename

A: Another awk option:
cat <<file>> | awk -v len=$(wc -l <<file>> | awk '{print $1}') 'NR < len - 2 { print $0 }'

A: reverse the file, delete the first 2 lines, then reverse back:
tac file | sed 1,2d | tac

A: The concept of this doesn't use much buffers and is useful even for extremely large files or endless streams in pipes. It should be better than any other solution provided so far. You also don't have to wait to get to the end before it starts printing the lines.
awk 'BEGIN{X = 2; getline; a[NR % X] = $0; getline; a[NR % X] = $0}{print a[NR % X]; a[NR % X] = $0}'

NR could also be replaced with another counter that resets itself to 0 if limit of NR is concerned. Also it would depend on the implementation of awk how it cleans itself up and reuse memory on every N lines of input
 but the concept is there already.
awk 'BEGIN{X = 2; for(i = 0; i < X; ++i)getline a[i]}{i %= X; print a[i]; a[i++] = $0}'

A: Something like
head file.txt -n -2

should work, provided your head version allows the -2 argument.  My version of GNU's head works

$ head --version
head (GNU coreutils) 5.97
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License .
There is NO WARRANTY, to the extent permitted by law.

Written by David MacKenzie and Jim Meyering.

A: This might work for you:
[root@gc-rhel6-x64 playground]# cat file
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
[root@gc-rhel6-x64 playground]# head -`expr \`wc -l < file\` - 2` file
line1
line2
line3
line4
line5
line6
line7
line8

A: This will get the file except last 2 lines

cat file.txt | head -$(expr $(wc -l file.txt | cut -c-8) - 2)

change the bold part for modification.


text:
Q: How can I eliminate the bad anti-aliasing or blending on the left side of my SVG layers? Sorry for the garish colors, but it most clearly shows the bad blending with this combination.
On the left side of the inner circle, there is a dark line where the blue meets the red. But on the right half of the inner circle, there is not. This is happening in Chrome, FF, and IE11.
Any idea why?

<svg viewBox="0 0 500 500" width="500" height="500">
  <circle fill="red" cx="250" cy="215" r="165"/>
  <circle fill="#2994FF" cx="250" cy="215" r="100"/>
</svg>

Picture version:

A: What you think you are seeing is not actually real.  It is an optical illusion caused mostly by the contrast change between the two colours.  Dark to light and then light to dark.
The layout of the subpixels on your monitor may be contributing as well - I'm not sure on that.
If we create a magnified version of the two edges next to one another, you should see that those strong dark and light borders are not actually there.


text:
Q: Configure port 1935 in iptables for media On CentOs 6.4 I cannot connect to the media server from port 1935 only 5080. I have read you can edit the iptables files with following.

*

*Open flle /etc/sysconfig/iptables:
$ sudo vi /etc/sysconfig/iptables

*Append rule as follows:
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport XY -j    ACCEPT

*Save and close the file. Restart iptables:
$ sudo /etc/init.d/iptables restart

How would I specifically configure port 1935? The above seems to be open to all ports, is this correct? Do I replace XY with 1935?

A: It just opens port XY, i.e., there you should put your 1935.
I'd advise to use the command your distribution uses to configure the firewall (on Fedora, RHEL and clones it is system-config-firewall). Easier on the brain, less likely to screw everything up, takes care of ancilliary tasks like reloading rules and saving them away for later boots).


text:
Q: Rewrite URL with just company name with current htaccess file First I like to say I feel so privileged being here.  I have used the answer given here for many years and it has saved me many many hours.  I have searched for the answer to my current question with no luck.  I believe the answers didn't work because I am adding it to my current .htaccess file which is required.  I have asked in my current software program (phpfox) forum but they said it could not be done.  I will leave it to stackoverflow experts to tell me whether it can be done or not. Here is my current .htaccess file
Options -Indexes
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase  /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(file)/(.*) PF.Base/$1/$2
RewriteRule ^static/ajax.php index.php
RewriteRule ^themes/default/(.*) PF.Base/theme/default/$1
RewriteRule ^(static|theme|module)/(.*) PF.Base/$1/$2
RewriteRule ^(Apps|themes)/(.*) PF.Site/$1/$2

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

</IfModule>

Here are three examples of the URL for this business page.
DomainName/directory/detail/302/name-of-business/overview/
DomainName/directory/detail/302/name-of-business/aboutus/
DomainName/directory/detail/302/name-of-business/contactus/
I think you get the picture but just in case here is a different business.
DomainName/directory/detail/303/name-of-business/overview/
Now for this business page the /directory/details never changes.  The 302 is the primary id of the record in the database table for this business.  In that same record is the name-of-business.  So if I type in the browser URL DomainName/directory/detail/302 it will still bring me to main overview page even without "name-of-business/overview" at the end of the URL.  So I am assuming the php code throws that at the end of the url from the database depending on what menu you click on this specific business.
My dream hope is getting it down to
DomainName/name-of-business/overview
DomainName/name-of-business/contact etc...
But I would even be happy to get rid of at least directory/detail (I am guessing the id "302" is needed since it is the main identifier...just guessing).
DomainName/302/name-of-business/overview
I have tried many different answers here but I feel I also may be putting it on the wrong line in my current .htaccess file.  Thank you in advance for any help and your time.

A: Try with:
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase  /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(file)/(.*) PF.Base/$1/$2
RewriteRule ^static/ajax.php index.php
RewriteRule ^themes/default/(.*) PF.Base/theme/default/$1
RewriteRule ^(static|theme|module)/(.*) PF.Base/$1/$2
RewriteRule ^(Apps|themes)/(.*) PF.Site/$1/$2

# Rewrite DomainName/303/... to DomainName/directory/detail/303/...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\d+)(/.*|$) index.php?q=directory/detail/$1$2 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

</IfModule>

Rewrite DomainName/303/... to DomainName/directory/detail/303/...
but only for external links or once fixed in your pages


text:
Q: Find out if a variable is a martingale (discrete time) Let X be a stochastic variable on a finite, filtered probability space.
If
$$
M_1(t) = E(X| \mathcal{F}_t)
$$
Is $M_1(t)$ a martingale?
I have a lot of trouble checking if variables are martingales or not. I know about the $(\Omega, \mathcal{F}, P)$ notation, and I am allowed to use this to answer the question.
I am pretty sure you need to use the tower law to solve this problem, which says that
$$
E(E(X_u|\mathcal{F}_t)|\mathcal{F_d}) = E(X_u|\mathcal{F}_d)\text{ } whenever\text{  } d \leq t \leq u
$$
But I just dont see how its done? Can someone help me out? What is the general method to find out if a variable is a martingale or not?

A: For $s\le t$, we have by the tower rule :
$$\mathbb E[M_1(t)\mid \mathcal F_s]=\mathbb E[\mathbb E[X\mid \mathcal F_t]\mid\mathcal F_s]=\mathbb E[X\mid\mathcal F_s]=M_1(s)$$
Furthermore, since for all $t$ we have  $\mathbb E[M_1(t)]=\mathbb E[X]$ and $X$ is integrable because the probability space is finite, then $(M_1(t))_t$ is integrable and hence a martingale. This form of martingale is called a closed martingale.


text:
Q: Allow anonymous upload for Vsftpd? I need a basic FTP server on Linux (CentOS 5.5) without any security measure, since the server and the clients are located on a test LAN, not connected to the rest of the network, which itself uses non-routable IP's behind a NAT firewall with no incoming access to FTP.
Some people recommend Vsftpd over PureFTPd or ProFTPd. No matter what I try, I can't get it to allow an anonymous user (ie. logging as "ftp" or "anonymous" and typing any string as password) to upload a file:
# yum install vsftpd

# mkdir /var/ftp/pub/upload

# cat vsftpd.conf
listen=YES
anonymous_enable=YES
local_enable=YES
write_enable=YES
xferlog_file=YES

#anonymous users are restricted (chrooted) to anon_root
#directory was created by root, hence owned by root.root
anon_root=/var/ftp/pub/incoming
anon_upload_enable=YES
anon_mkdir_write_enable=YES

#chroot_local_user=NO
#chroot_list_enable=YES
#chroot_list_file=/etc/vsftpd.chroot_list
chown_uploads=YES

When I log on from a client, here's what I get:

500 OOPS: cannot change directory:/var/ftp/pub/incoming

I also tried "# chmod 777 /var/ftp/incoming/", but get the same error.
Does someone know how to configure Vsftpd with minimum security?
Thank you.

Edit: SELinux is disabled and here are the file permissions:
# cat /etc/sysconfig/selinux
SELINUX=disabled
SELINUXTYPE=targeted
SETLOCALDEFS=0

# sestatus
SELinux status:                 disabled
# getenforce
Disabled

# grep ftp /etc/passwd
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

# ll /var/
drwxr-xr-x  4 root root 4096 Mar 14 10:53 ftp

# ll /var/ftp/
drwxrwxrwx 2 ftp ftp 4096 Mar 14 10:53 incoming
drwxr-xr-x 3 ftp ftp 4096 Mar 14 11:29 pub

Edit: latest vsftpd.conf:
listen=YES
local_enable=YES
write_enable=YES
xferlog_file=YES

#anonymous users are restricted (chrooted) to anon_root
anonymous_enable=YES
anon_root=/var/ftp/pub/incoming
anon_upload_enable=YES
anon_mkdir_write_enable=YES

#500 OOPS: bad bool value in config file for: chown_uploads
chown_uploads=YES
chown_username=ftp

Edit: with trailing space removed from "chown_uploads", err 500 is solved, but anonymous still doesn't work:
client> ./ftp server
Connected to server.
220 (vsFTPd 2.0.5)
Name (server:root): ftp
331 Please specify the password.
Password:
500 OOPS: cannot change directory:/var/ftp/pub/incoming
Login failed.
ftp> bye

With user "ftp" listed in /etc/passwd with home directory set to "/var/ftp" and access rights to /var/ftp set to "drwxr-xr-x" and /var/ftp/incoming to "drwxrwxrwx"...could it be due to PAM maybe? I don't find any FTP log file in /var/log to investigate.

Edit: Here's a working configuration to let ftp/anonymous connect and upload files to /var/ftp:
listen=YES
anonymous_enable=YES
write_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES

A: You have created a dir called pub/upload:
# mkdir /var/ftp/pub/upload

But then you configured uploads to go to pub/incoming:
anon_root=/var/ftp/pub/incoming

So it's a simple path mismatch, all the rest seems OK.

A: *

*For anonymous logins, change the "ftp" users home directory in /etc/passwd.
ftp:x:119:131:ftp daemon,,,:/var/ftp/pub/:/bin/false

*And add this to your /etc/vsftpd.conf file.
allow_writeable_chroot=YES

*And make sure that the ftp user has access (chmod 755) to enter every directory up to the location /var/ftp/pub/
I was fighting this problem for hours. vsftpd doesn't give clear help or suggestions for errors.

A: You probably have SE linux enabled. Rather than disable the whole thing you can use
/usr/sbin/setsebool -P ftp_home_dir 1
to allow ftp to work correctly.
EDIT
Looking over this again, if the commands above are what you really typed then /var/ftp/pub/incomming doesn't exist so make sure it does then try again.

A: You probably have userlist_deny=NO in your conf file. Change it to YES and make sure that the username you're using isn't in /etc/vsftpd/user_list or in /etc/vsftpd/ftpusers.

A: here is what worked for me (he said, while mentally strangling a developer)
vsftpd.conf:
anonymous_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_root=/var/ftp/

create/chown Directories
mkdir /var/ftp
chown nobody:nogroup /var/ftp
mkdir /var/ftp/uploads
chown ftp:ftp /var/ftp/uploads
#edit for good measure also (gave me grief with pure-ftpd)
chmod 777 /var/ftp/uploads

change homedir in
/etc/passwd:

    ftp:x:116:124:ftp daemon,,,:/var/ftp:/usr/sbin/nologin

(default home dir on debian is /srv/ftp so you can make yo life
easier sticking to that dir)
uploads are possible to /var/ftp/uploads
SElinux/Apparmor is disabled on this system, debian 10.3
Note: vsftp will throw an errormessage if the initial homedirectory
has rw rights (aka chown ftp:ftp) on /var/ftp directly
Edit note: with the faint hope, this whole text is somewhat understandable.
Klaus

A: Is SE linux enabled. Folks in that forum were able to resolve the issue by disabling SE linux.
http://rackerhacker.com/2007/06/14/500-oops-error-from-vsftpd/


text:
Q: Javascript to enable, disable drop down menu in JSP file having Java code only, no HTML directly Let me introduce the design.
Each field in a JSP is made by a Map.
The label name, the input type (drop down or other), the input values, the default values, etc are added to the Map, say Map nameAttributes.
There is another class, GeneralWriter writer, to which I do not have access, which takes the values from Map, parses them and writes the proper HTML code.
After writing the Map, writer.writeSelectBox(nameAttributes); is called.
Now, the requirement is:
There is a drop-down menu, depending upon its selected value, some other drop-down menus are disabled (shown in UI, but not modifiable) or enabled.
Since, I am not writing HTML code for the added field, I can not write the function call events to do my job.
I have observed that a JS function is called on onMouseOut event from the fields, as seen in "View Source".
So I thought I might write my code there to check the field value and impact other drop-down menus.
But if I write alert in the JS function (just to check), it won't alert me, means the function is not called and I can not write the enable/disbale code.
Is there any way to achieve the job. The enabling and disabling should depend on what user selects in one of the drop downs.
Sample code:
<%
Map nameAttr = new HashMap();
nameAttr.put(GeneralConst.INPUT_MESSAGE, Const.MSG_FIELD_NAME);
//.....

writer.writeAllSelectBox(nameAttr);
%>

Urgent help needed, thanks.

A: In View Source of the JSP page, its clear that for some fields onChange and onMouseOut events etc. were added, and in the GeneralWriter class, those things were being written out to the out stream as follows
out.println("<td nowrap><select name=" + strName);
out.println(" style=\"width:" + strWidth + "px\"");
out.println(" onChange ="+onChange);

So, I added my own method there rather than using existing code and introduced the onChange event. The "onChange" variable that you see (the right one) is of java.lang.String type and this had to be passed from the JSP itself, as to what behavior I want or which particular function to call for a particular JSP.
Now I added the following in JSP
<body>
  <script>
    window.onload = setModeForPara2('MEMBERTYPE','MEMBERSTATE','CKSTATUS') ;
    function resetevent(uri){
      setModeForPara2('MEMBERTYPE','MEMBERSTATE','CKSTATUS') ;
    }
  </script>
</body>

where the parameters are the names of the drop down menus, and setModeForPara2() is a JS function to disable/enable as my requirement was stated in original post. It checks if MEMBERTYPE is 0, then render disabled state and gray color to MEMBERSTATE and CKSTATUS drop-down menus, else enable them and remove gray color.
The resetevent(uri) is also a JS function called when the Reset button is clicked to render the disabled state to the State and Status fields.
So that way, setModeForPara2() function is called whenever:
1. the page is loaded,
2. the value of first drop-down (MEMBERTYPE) is changed, and
3. the Reset button is clicked.
Resolved.


text:
Q: Does Differences-in-Differences linear regression 'forget' the pairing between before and after data points? Differences-in-differences regression can be used to test the impact of a treatment on a metric of interest. It works by comparing the metric before and after, both for a treatment group and for a control group. For example, I might want to measure whether an educational intervention improves students' grades.  To do this, I would measure grades before and after the intervention, both for the participating group and for a control group (who didn't participate).
The input data might have the following form:

Student
Treated/Control
Before grade (%)
After grade (%)

Student A
Treated
40
60

Student B
Treated
45
55

Student C
Control
30
50

Student D
Treated
75
80

$\vdots$
$\vdots$
$\vdots$
$\vdots$

If I understand correctly, the linear model underlying the differences-in differences-method is as follows:
$Y_i=\alpha+\beta T_i+\gamma A_i+\delta T_i A_i+\epsilon_i$,
where $Y_i$ is the $i^\textrm{th}$ grade, $T_i$ is a dummy variable which takes the value 1 if the $i^\textrm{th}$ data point was from the treated group,  $A_i$ is a dummy variable which takes the value 1 if the $i^\textrm{th}$ data point was taken after the intervention, and  $\epsilon_i$ is a normal random variable with mean 0.  The Greek letters are parameters to be estimated.  If we want to test whether the treatment has an effect, we will test the null hypothesis $\delta=0$ (because $\delta$ tells us how much extra the treatment group gained from before to after vs the control group).
The above data doesn't match the form of this model.  To use the linear model, we need to have only one grade measurement per row, and to introduce variable telling us whether each data point was before or after.

Student
Treated? ($T_i$)
After? ($A_i$)
Grade ($Y_i$)

Student A
1
0
40

Student A
1
1
60

Student B
1
0
45

Student B
1
1
55

Student C
0
0
30

Student C
0
1
50

$\vdots$
$\vdots$
$\vdots$
$\vdots$

I understand how to run the linear regression on data in this form.

The question
My question is whether reformatting this data was the right thing to do.  In particular, by running the analysis on this data, we have lost the information that the first two data points belonged to Student A.  The data below would give equivalent results - the after grades of Student A and Student B have been swapped.

Student
Treated? ($T_i$)
After? ($A_i$)
Grade ($Y_i$)

Student A
1
0
40

Student A
1
1
55$\leftarrow$

Student B
1
0
45

Student B
1
1
60$\leftarrow$

Student C
0
0
30

Student C
0
1
50

$\vdots$
$\vdots$
$\vdots$
$\vdots$

Intuitively, it seems that this information was important.  On the other hand, perhaps it is not: by using a linear model (and holding all the information about the model in the four Greek variables), we have produced a set up where four means (before/after for treatment/control) are a set of sufficient statistics for the model.  Switching the final grades of Student A and Student B doesn't change these means, so perhaps the two situations should be regarded as equivalent.

A: The first data frame includes multiple $i$ students and their associated test scores measured at two distinct time periods $t$. The before-and-after scores (i.e., pre- versus post-test) are juxtaposed side-by-side, giving the data frame a wide display. You then propose the following model which I reproduced below:
$$
Y_i = \alpha + \beta T_i + \gamma A_i + \delta (T_i \times A_i) + \epsilon_i,
$$
which includes the appropriate variables but the wrong subscripts! For instance, every variable is $i$-subscripted, indicating you observe individual grades in one time period. $T_i$ is appropriately subscripted; it should index students in your treatment group, 0 otherwise. $A_i$, on the other hand, is devoid of a $t$-subscript despite denoting the post-intervention period. It should equal 1 in the "after" period in both treatment and control groups. The $i$-subscript appended to $A$ does not account for the simple passage of time between tests. If applied to your first data frame which only includes one observation per student, then a linear model run in standard software cannot disambiguate between pre- and post-test grades unless it is stacked. It will not return a difference-in-differences estimate.
Here is the appropriate model, which is estimable if used on your second (stacked) data frame:
$$
Y_{it} = \alpha + \beta T_i + \gamma A_t + \delta (T_i \times A_t) + \epsilon_{it},
$$
where you observe students $i$ in time periods $t$. By stacking observations, you do not lose the second time period as your question suggests. $A_t$ is a column vector and distinguishes between pre- and post-test values. In most software packages, the data must be formatted in this manner (i.e., long format). I hope it is obvious how the wide display might become unwieldy in settings with serial observations before-and-after treatment. Suppose you sample multiple $i$ students at a university and observe a series of outcomes for each student over 100 consecutive days. Now suppose you also adjusted for a series of time-varying covariates at the student level. Would you organize your data in a wide display in this setting? In my opinion, the stacked display is the way to go.
Even though I don't particularly advise it, you can certainly structure your data where each row corresponds to one student. In the classical case with two discrete groups (i.e., treatment group versus control group) and two discrete time periods (i.e., pre-treatment versus post-treatment), simply organize your data in a 2x2 table. Calculate the average grade in both groups before-and-after your exposure of interest. You can then perform the basic difference-in-differences calculation by hand. But again, I wouldn't recommend the extra effort. If you have many $i$ students and the data is stacked, simply estimate the foregoing regression. It is easier and you also obtain your standard errors—for free.
In the psychological sciences, it is common to observe applied researchers use the change score approach:
$$
Y_2 - Y_1 = \gamma + \beta T_i + \epsilon_i,
$$
where the differences between two grades (i.e., $t_2 - t_1$) is regressed on a treatment dummy. This is yet another approach where you can keep your data in your desired structure (i.e., one individual $i$ per row). Your estimate of $\beta$ in the foregoing example should equal the coefficient on your interaction term in the stacked difference-in-differences regression. For more information on this approach, peruse this paper  by Lüdtke and Robitzsch (2020), or review this post which also references the paper.
To conclude, you correctly note that swapping two students' grades in your treatment group should not affect your estimate in the simple 2x2 case with four cell means. I hasten to add that you shouldn't use a regression model on your "grouped" data frame which only includes four observations. Even though software may spit out coefficients, you have no residual degrees of freedom! Thus, you have no hope of calculating statistics in this setting. As a final word, I encourage you to stack your observations and estimate the second model outlined above. Let software do the work for you! This structure is handy once you start adding more students—and more time periods.


text:
Q: notifyDataSetChanged on CustomAdapter not Working I have a Dialog which is used to add project. Dialog(Addproject.java) is an activity which is called on another activity(Projects_list.java).
In Projects_list.java .I have a listview which uses customadapter (Custom_projectList_adapter.java).
After i add any project in dialog i want to refresh the content of listview .
I called notifyDataSetChanged but it is not working.
Here is my Code:
Projects_list.java
public class Projects_list extends ActionBarActivity {
    public String[] itemname ={"Safari","Camera","Global","FireFox","UC Browser","Android Folder", "VLC Player","Cold War"};
    Custom_projectList_adapter adapter;
    ListView list;
    final ArrayList<String> projectlist = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.projects_list);

        for (int i = 0; i < itemname.length; ++i) {
            projectlist.add(itemname[i]);
        }

        CircleButton addproject = (CircleButton) findViewById(R.id.addproject);
        adapter = new Custom_projectList_adapter(this,projectlist);
        list = (ListView) findViewById(R.id.projectlistView);
        list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        list.setAdapter(adapter);

        addproject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent addproject = new Intent(Projects_list.this, AddProject.class);
                startActivity(addproject);
            }
        });
    }

    public void additem(String item) {
        projectlist.add(item);
        adapter.notifyDataSetChanged();
    }
}

This is my AddProject.java
public class AddProject extends Activity {
    EditText newProjectname;
    String project_name;
    Button add_project;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_project);

        newProjectname = (EditText) findViewById(R.id.add_project_name);
        add_project = (Button) findViewById(R.id.btn_add_project);

        add_project.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String add = newProjectname.getText().toString().trim();
                Projects_list pl = new Projects_list();
                pl.additem(add);
            }
        });
    }

}

And this is my Custom_projectList_adapter.java
public class Custom_projectList_adapter extends ArrayAdapter<String>{

    private final Activity context;
//    private final String[] projectName;
    ArrayList<String> projectName;
    int selectedoption = 0;
    public Custom_projectList_adapter(Activity context, ArrayList<String> projectName) {
        super(context, R.layout.custom_project_list,projectName);
        this.context = context;
        this.projectName = projectName;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.custom_project_list, null, true);

        RadioButton radio_project = (RadioButton) rowView.findViewById(R.id.radio_project);
        radio_project.setText(projectName.get(position));
        radio_project.setChecked(position == selectedoption);
        radio_project.setTag(position);
        radio_project.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectedoption = (Integer) view.getTag();
                notifyDataSetChanged();
                Toast.makeText(context, projectName.get(position), Toast.LENGTH_SHORT).show();
            }
        });
        return rowView;
    }

}

As i am a beginner .I am very confused with it. Help me out please.

A: add_project.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String add = newProjectname.getText().toString().trim();
            Projects_list pl = new Projects_list();
            pl.additem(add);
        }
    });

Here you instantiate a new Projects_list, thus pl.additem(add); won't update the data of the adapter. And it is not recommended to instantiate an Activity manually.
I suggest you use Dialog rather than start another Activity to add project.


text:
Q: Where clause causing cannot compare elements error I have two tables, Doctors and DoctorShifts, The relation between two table is one(Doctor) to many(DoctorShifts).
In the DoctorShifts I saved the days of week for each doctor that work on.
What I need is to display the list of the Doctors that work today, I tried the following expression but it does not work :
IQueryable<Doctor> TodayDoctorsQuery = _context.Doctors.Where(s => s.DoctorShifts.Where(s2 => s2.DayOfTheWeek == _todayNumber) != null);

The error is :

Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1[[MedCare_Software.EDM.DoctorShift, MedCare-Software, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported."}

How can I get the list of doctor that works today?

A: The inner where clause returns a IEnumerable<DoctorShift> which can't be compared to null.
Anyway, you're better off using Any as in:
var TodayDoctorsQuery = _context.Doctors.Where(
    s=> s.DoctorShifts.Any(s2 => s2.DayOfTheWeek == _todayNumber));

and make sure that DayOfTheWeek and _todayNumber are the same type.


text:
Q: JavaScript редактирование JSON данных на сервере Задача: использовать ТОЛЬКО javascript (или ajax) для реализации сбора данных.
На сервере находится файл pickingdata.json (структура не имеет значения). Для получения данных используется функция readTextFile().
function readTextFile(file, callback) {
        var rawFile = new XMLHttpRequest();
        rawFile.overrideMimeType("application/json");
        rawFile.open("GET", file, true);
        rawFile.onreadystatechange = function() {
            if (rawFile.readyState === 4 && rawFile.status == "200") {
                callback(rawFile.responseText);
            }
        }
        rawFile.send(null);
    }

Данные успешно редактируются. Далее и возникает проблема. Если использовать ajax с php, то файл перезаписывается:
$.ajax({
                    type: "POST",
                    url: "savefile.php",
                    data: {'file':"pickingdata.json", 'data':datasend},
                    success: function(result){
                        if (result==1){
                            alert("Данные добавлены!");
                            window.location.href="index.html";
                        }
                        else {
                            alert("Ошибка на сервере! Обратитесь к администратору!");
                        }
                    }
                });

НО по заданию использовать PHP НЕЛЬЗЯ!
На просторах интернета нашла вариант использования XMLHttpRequest. Но метод POST не возвращает данные типа .json, а только File, txt и др.
var url  = "/example";
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", url, true);
                    xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
                    xhr.onload = function () {
                        var users = JSON.parse(xhr.responseText);
                        if (xhr.readyState == 4 && xhr.status == "201") {
                            console.table(users);
                        } else {
                            console.error(users);
                        }
                    }
                    xhr.send(datasend);

Возможно ли использование node.js для реализации данной задачи? Есть ли еще какие-либо варианты решения вышеописанной проблемы? HELP=(


text:
Q: Getting Error com.jnetdirect.jsql.JSQLException: Invalid parameter index:2 Valid range is 1 to 1 While inserting in to database? i am using sql server 2005 and jdbc. Trying to insert values in to table ContentModification with below code
  java.sql.Date date= new java.sql.Date(Calendar.getInstance().getTimeInMillis());
  sql = "insert into ContentModification values(?,?)";
         pc.setString(1, space);
         pc.setDate(2, date); // line 3
     pc.executeUpdate();//line 4

At line 3 i am getting error  com.jnetdirect.jsql.JSQLException: Invalid parameter index:2 Valid range is 1 to 1
           i am not getting whats the reason for this?
My create table script is below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ContentModification](
[XWC_NAME] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[XWC_LASTUPDATE] [datetime] NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

A: Using JSQLConnect(5.95) Trial license, jdk 1.6 and SQL Express 2008 your code executes successfully. This exception generally occurs when you have miss-match between the number of '?' marks in PreparedStatement and the index of setDate() / setString()
You might try changing this line :
 sql = "insert into ContentModification(XWC_NAME, XWC_LASTUPDATE) values(?,?)";


text:
Q: How to convert local time to UTC? I need to convert local time to UTC using a function. The inputs I have is the local time, timezone of the local time (e.g. 'Pacific/Auckland'). What I need to get from the procedure is the UTC time for the local time based on given timezone.
Can someone please help?
I am using version 8.3

A: This is covered in the manual, but it's not always obvious how to actually work with dates/times. The SQL spec is a bit bizarre.
In the case of your question it isn't clear whether you want to store the time in UTC but display it in the server's local time (TimeZone), or whether you wan to ignore TimeZone and always display it as UTC. I'll assume the latter.
For timestamps you'd just use AT TIME ZONE twice, like:
SELECT TIMESTAMP '2013-08-13 00:00:00' AT TIME ZONE 'Australia/Sydney' AT TIME ZONE 'UTC';

You need to use AT TIME ZONE twice. Once to convert the input timestamp to timestamptz according to the argument timezone, then another to convert that to a timestamp at UTC.
Unfortunately because of the (IMO insane) way the SQL spec defines AT TIME ZONE for TIME, you can't do the same thing for TIME. You'll have to manipulate the TimeZone variable instead:
SET TimeZone = 'UTC';
SELECT TIME '07:00' AT TIME ZONE 'Australia/Sydney';

This still leaves you with a timetz not a time. So its display value changes with the timezone setting.

A: You can use select now() at time zone 'UTC' for postgresql.


text:
Q: Get/Display all results from Array that matches condition New to power automate. I've created a flow that gets specific rows from an html_to_text output. That one works fine, but the requirement is that I also need to display rows that contain "FAIL"
What I did was to create an array and then a condition where "Current item contains FAIL". If "yes", then it will display the current item + the initial output for the other string.
I have 240 rows of html_to_text data.
The apply_to_each and its condition works, but I don't know how to display ALL of the outputs that had 'FAIL' string in them in one Compose.

A: If you want to filter and the data is an array I would suggest to use the Filter Array action.
Try something like below

A: Found this: https://blog.thenetw.org/2022/06/27/compose-in-apply-to-each/ and did the steps to combine all outputs.


text:
Q: Correlation between $XY$ and $Y$ Let $X$ and $Y$ be independent random variables with means $\mu_X$ and $\mu_Y$ and variances $\sigma_X^2$ and $\sigma_Y^2$. Find an expression of correlation of $XY$ and $Y$ in terms of these means and variances.
When I follow the definition for correlation, I get a zero in the denominator, which does not make sense. Please help.

A: The denominator is $\sigma_{XY}\sigma_Y$.
Let us compute $\sigma_{XY}$, since that is undoubtedly the source of the problem. We get
$$\sigma_{XY}^2=E((XY)^2)-(E(XY))^2.$$
By independence,
$$E((XY)^2)=E(X^2)E(Y^2)=(\sigma_X^2+\mu_X^2)(\sigma_Y^2+\mu_Y^2).$$
And $(E(XY))^2=\mu_X^2\mu_Y^2$. Subtract. We get
$$\sigma_{XY}^2=\sigma_X^2\sigma_Y^2+\mu_X^2\sigma_Y^2+\mu_Y^2 \sigma_X^2.$$
The calculation for the numerator is quite a bit easier.

A: The correlation is given by:
$$
\mathrm{Corr}(XY,Y)=\frac{\mathrm{Cov}(XY,Y)}{\sqrt{\mathrm{Var}(XY)\mathrm{Var}(Y)}}.
$$
Now you just have to use that for any random variable $Z_1$ and $Z_2$ we have
$$
\mathrm{Var}(Z_1)=E[Z_1^2]-E[Z_1]^2,\qquad \mathrm{Cov}(Z_1,Z_2)=E[Z_1Z_2]-E[Z_1]E[Z_2]
$$
along with the fact that $X$ and $Y$ are independent (in particular this implies that $X^2$ and $Y^2$ are independent and also $X$ and $Y^2$ are independent, which you will have to use).


text:
Q: View layout after setvisibility I've got problem with setting visibility to relative layout. I have part of big layout in relativelayout and below that next TextView. But in my code, when           myRelativeLayout.setVisibility(View.GONE);
is called, TextView which is below that did not appear. I tried several ways to rearange layout, but i need that textview under it. Thanks
My XML:
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
    <ScrollView
        android:id="@+id/scrollView_liab_ra_flipper_04"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <RelativeLayout
            android:id="@+id/linearLayout_liab_ra_flipper_04"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/someTextView"
                android:text="Something" />

            <!-- This relative layout should be removable -->
            <RelativeLayout
                android:id="@+id/vg_liab_ra_04_flipper_car_container_visible"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/someTextView" >

                <TextView
                    android:id="@+id/tv_1"
                    style="@style/WhiteFormText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="2dp"
                    android:text="@string/licence_plate_counter" >
                </TextView>

                <EditText
                    android:id="@+id/et_1"
                    style="@style/WhiteFormField"
                    android:layout_below="@+id/tv_1"
                    android:hint="@string/licence_plate_hint" >
                </EditText>
            </RelativeLayout>

            <!-- This textview is not visible if relative layout is gone -->
            <TextView
                android:id="@+id/tv_liab_ra_04_flipper_mandat"
                style="@style/WhiteFormTextHint"
                android:layout_below="@+id/vg_liab_ra_04_flipper_car_container_visible"
                android:layout_marginBottom="15dp"
                android:text="@string/mandatory_field" >
            </TextView>
        </RelativeLayout>

    </ScrollView>
</merge>

Java Code:
 private void hideCar() {

   if (!accident.getParticipant(0)) {
        rlCarContainer.setVisibility(View.GONE);

    } else {
        rlCarContainer.setVisibility(View.VISIBLE);

    }

}

A: The easiest way to do what you want is to use LinearLayout instead of your root RelativeLayout.. the child views will get realigned after you hide the RelativeLayout just the way you want.. if you don't want that, you can use android:layout_alignWithParentIfMissing on the TextView see here the documentation. That won't work exactly how you want but it might help you to solve the problem :).


text:
Q: Receiver type for instance message is a forward declaration popToRootViewController I've seen similar questions on this error.
But I'm not sure how it applies in this instance
This is the error
Receiver type for instance message is a forward declaration

And this is my code.
MyAppDelegate *appDel = (MyAppDelegate*)
    [[UIApplication sharedApplication] delegate];
[appDel.secondTabNavController popToRootViewControllerAnimated:NO];

What's the problem here and how do I fix it ?
I clarified my usage of this code was correct, as a different navigation controller for each of my tabs in my tab controller. I do this as I push views within each controller.
Several UINavigation controllers, one for each tab, as an outlets from my app delegate?

A: Try to import the appdelegate.h and it should work fine.
A better way of implementing this would be to use notifications.
1. Send a notification when you reach the condition
2. Handle the notification in the appropriate view controller. (You can handle it in the app delegate too but it is not a clean way)


text:
Q: Python - appending to multiple arrays If I wanted to perform something like Levene's test of equal variances via scipy stats, which produces two outputs (the test statistic and p-value) for all the data in a dictionary, how would I append the outputs for each test to two different lists? I tried the code below:
test_stat[]
p_value[]
for i in range(0, n_data):
    for j in range(1, n_name):
        test_stat[i], p_value[i] = scipy.stats.levene(data[i][name[j-1]],
                                                      data[i][name[j]],
                                                      center='median')

But this clearly isn't the way to go about it, as I keep getting anIndexError because the list assignment index out of range.
Any suggestions would be greatly appreciated. Thanks!

A: Not everything needs to be in a single line... This should work fine:
test_stats = []
p_values = []
for i in range(0, n_data):
    for j in range(1, n_name):
        test_stat, p_value = scipy.stats.levene(data[i][name[j-1]],
                                                data[i][name[j]],
                                                center='median')
        test_stats.append(test_stat)
        p_values.append(p_value)

Though of course this will add n_data * n_name rows.


text:
Q: How do I find the difference in hours between two time zones? I have this code here that can find the time in two different timezones at the moment. I want to calculate the difference in hours, between the two timezones.
def time_caluclator(timezone1, timezone2):

    dt_utcnow = datetime.datetime.now(tz=pytz.UTC)

    dt_1 = dt_utcnow.astimezone(pytz.timezone(timezone1))
    dt_2 = dt_utcnow.astimezone(pytz.timezone(timezone2))

    print(dt_1, dt_2)

This is the code, and it will print this:
2022-05-15 00:44:22.031149+00:00 2022-05-15 01:44:22.031149+01:00

(First timezone is Zulu, and the other is WET).

A: I would do two nested for loops to separate your times into sections by both spaces and ":" so that you can get the individual numbers. Then its just subtraction and maybe a dictionary if you would like to say specifically timezone codes like "EST"

A: def time_caluclator(timezone1, timezone2):
    off1 = pytz.timezone(timezone1).utcoffset(datetime.datetime.now())
    off2 = pytz.timezone(timezone2).utcoffset(datetime.datetime.now())
    return (off2 - off1).seconds // 3600

Works correct for pytz timezones such as "US/Eastern", "Europe/Moscow".


text:
Q: How to find which flags were applied to git merge It appears that a git merge commit clobbered changes I made on one parent. Specifically, one parent contained a change (removing some lines from a file, and removing another file) and the other parent did not contain those changes. The result of the merge does not contain the changes. git show on the merge commit shows the removed lines being added into the file instead of removing those lines. git show does not show any change to the file which was removed.
I'm trying to understand why the merge result does not contain the changes. The merge commit message doesn't indicate any conflicts about the affected files.
My question is: Is there some way to discover what flags were applied to a merge? (Is there any flag that would not bring in the change from the parent that contains them? There wasn't a conflict about the affected files, so would --ours or --theirs have any effect?)
I'm worried that there might be other files for which changes were clobbered. I guess I will try some permutations of git diff to try to find those. Any advice on this point is welcome.

A:
My question is: Is there some way to discover what flags were applied to a merge?

The short answer is no.  When the merge is complete, the only things recorded as a result are in the commit object itself, which like any other commit, records your name and email address and time-stamp (as author and committer), the parent commit hashes (the two main inputs—the third input, the merge base commit, is computed automatically from these), your log message, and of course the final snapshot.

(Is there any flag that would not bring in the change from the parent that contains them?

Yes.

There wasn't a conflict about the affected files, so would --ours or --theirs have any effect?)

The git merge command itself doesn't have --ours and --theirs; instead, it has this very confusing set of options:

*

*-s ours: ignore the other commit(s) entirely; don't find a merge base; just make a merge commit that uses the current index contents.  (There will never be any conflicts this way, since Git doesn't even look at their changes.)

*-X ours: wherever there are conflicts, automatically resolve them using our changes.  If there are other unconflicted changes to the same file, use their changes to that file.

*-X theirs: wherever there are conflicts, automatically resolve them using their changes.  As with -X ours this only affects conflicted regions within a file; unconflicting changes are merged as usual.

If there are any unresolved conflicts at all, though, git merge stops in the middle of the merge, and gives you (the person doing the merge) full control.  At this point there are --ours and --theirs options, to git checkout.

I'm worried that there might be other files for which changes were clobbered. I guess I will try some permutations of git diff to try to find those. Any advice on this point is welcome.

That's possible; note that you can run git show -m to split the merge into two separate virtual commits, one with parent #1 as its single parent (so that git diff will diff that parent vs the merge result), and one with parent #2 as its single parent (so that a second git diff, run by git show -m, will diff the other parent vs the merge result).

To see what the inputs to the merge were, run:
git merge-base --all <hash of first parent> <hash of second parent>

The output is the hash ID of the merge base(s).  Ideally there's only one hash ID here (if there are two or more, look up "virtual merge base").  Save that hash ID, then run:
git diff --find-renames <merge base hash> <hash of first parent>

and:
git diff --find-renames <merge base hash> <hash of second parent>

and you'll see what Git saw for the three inputs.

One other thing you can do pretty easily is repeat the merge.  If you get yourself a detached HEAD, pointing to parent #1, then run git merge <hash ID of parent #2>, you'll be repeating the same merge (maybe with different flags, since we have no idea what flags were used the first time).  Be sure you have disabled git rerere before this, otherwise Git will re-use the recorded resolutions. You can now re-resolve conflicts manually and commit.  The new commit will be a new detached HEAD, and you can now diff the contents of this commit vs the contents of the original merge commit:
git diff HEAD <other merge commit ID>

to see if you resolved things differently.


text:
Q: 'Error -5 while decompressing data' in Spark, in PyPDF2 lib Does anybody know why this occurs:
Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 1089.0 failed 4 times, most recent failure: Lost task 0.3 in stage 1089.0 (TID 1951, ip-10-0-208-38.ec2.internal): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/home/ubuntu/databricks/spark/python/pyspark/worker.py", line 101, in main
    process()
  File "/home/ubuntu/databricks/spark/python/pyspark/worker.py", line 96, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/home/ubuntu/databricks/spark/python/pyspark/serializers.py", line 236, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "<ipython-input-762-e1c8f006c3c2>", line 4, in getPdfData
  File "<ipython-input-762-e1c8f006c3c2>", line 85, in extractData
  File "./addedFile3142227314340912289bfddea6e_2a71_413e_b077_a4493987f9d9_PyPDF2-12df7.egg/PyPDF2/pdf.py", line 2566, in extractText
    content = ContentStream(content, self.pdf)
  File "./addedFile3142227314340912289bfddea6e_2a71_413e_b077_a4493987f9d9_PyPDF2-12df7.egg/PyPDF2/pdf.py", line 2644, in __init__
    stream = BytesIO(b_(stream.getData()))
  File "./addedFile3142227314340912289bfddea6e_2a71_413e_b077_a4493987f9d9_PyPDF2-12df7.egg/PyPDF2/generic.py", line 837, in getData
    decoded._data = filters.decodeStreamData(self)
  File "./addedFile3142227314340912289bfddea6e_2a71_413e_b077_a4493987f9d9_PyPDF2-12df7.egg/PyPDF2/filters.py", line 346, in decodeStreamData
    data = FlateDecode.decode(data, stream.get("/DecodeParms"))
  File "./addedFile3142227314340912289bfddea6e_2a71_413e_b077_a4493987f9d9_PyPDF2-12df7.egg/PyPDF2/filters.py", line 111, in decode
    data = decompress(data)
  File "./addedFile3142227314340912289bfddea6e_2a71_413e_b077_a4493987f9d9_PyPDF2-12df7.egg/PyPDF2/filters.py", line 49, in decompress
    return zlib.decompress(data)
error: Error -5 while decompressing data: incomplete or truncated stream

I process PDF files on workers using PyPDF2, creating a PyPDFpdfObject, calling getDocumentInfo() and calling extract_text() on the pageObjects. Im not explicitly using the zlib module where this 'compression' error usually occurs according to the oracle called the internet.
My code runs perfectly fine for smaller number of PDF's (around 500 or so) stored in an RDD (3 workers), but when I scale it up to 5000 or higher it goes wrong. Any ideas?


text:
Q: Deleting android app from Firebase problem I faced a problem that my app can't connect to firebase any more I just deleted my app from firebase project and added it to another project, after that my application can't connect to firebase and I have this message loading

Checking if the app has communicated with our servers. You may need to uninstall and reinstall your app.

and when I try to send FCM notification it not send I have this error message

"error": "MismatchSenderId"

A: Your app must communicate first with your Firebase project before you start sending any FCM notifications and start using other services.
I recommend you to read this documentation:
https://firebase.google.com/docs/android/setup?authuser=0

Make sure that you enter the package name that your app is actually using. You cannot add or modify this value after you register your app with your Firebase project.

And please make sure that you deleted old google-services.json file from your app directory and replaced it with the new one. You can find documentation on this here: https://support.google.com/firebase/answer/7015592?authuser=0
After all these changes, it is recommended that you uninstall your app from the emulator/physical device first, then install it again. Open it a few times, wait for a few minutes and the app should be connected to your firebase project.

A: I had the exact problem. Google JSON was fine, had uninstalled the app and updated the fcm server key but it didn't work.
In the end, all I did was to:
-uninstall the app again
-restart my device
-clean project
-invalidate caches and restart
and it started working.


text:
Q: Unable to display JavaScript widget I'm trying to add a JustGiving widget to my website but it doesn't display at all. I had other scripts in the file which I thought might be interfering so I ended up testing in a new plain html file and it still wouldn't work.
Interestingly enough if I copy/paste it into a W3 schools code editor it works! It's the same exact code and I cannot work out why it doesn't load in an html file.
    <!DOCTYPE html>

123

A: Why do you just not use something like this? Didn't test but I assume it works.

';
    document.getElementById("scripts").innerHTML = script;
</script>

And jQuery has html and append functions for this.


text:
Q: npm Warning: config production; Use --omit=dev Instead Every time I run any kind of npm command, I get the following error before the actual output:
npm WARN config production Use `--omit=dev` instead.

Of course I've come across similar issues regarding the -g flag, and I updated npm to avoid that problem. Some of the workarounds describe editing the npm and npm.cmd in the program files for node to remove these flags, but for this error in particular, the word production occurs nowhere in those configuration files. Unhelpfully, npm's warnings don't include a reference to the file that contains this irksome configuration setting.
Can anyone offer advice on where to search for this configuration, or at least how to silence this redundant warning message?

A: And of course, as soon as I ask, I find an answer somewhere else:
I created an error log because of a different npm crash, and when I search the log, I found the config file that was causing the error:
C:\Users\Chris\AppData\Roaming\npm\etc\npmrc

Sure enough, I open the file, find production=false, delete the necessary line, and now the error has disappeared.

A: You can try to install production by npm --production and install --omit=dev by npm --omit=dev or check you version properly then run a command.

A: I removed the line production=false at the address below and the warning didn't appear anymore.
C:\Users\[username]\.npmrc


text:
Q: scaling the navigation bar - responsive design I'm trying to make my website fully responsive, and I'm stumbling upon the navigation bar; I cannot seem to make it responsive. My coding is as following:

Collectie

Zomercollectie

Wintercollectie

Kerstcollectie

Over ons

Contact

And the CSS as following:
.navbar
{
height: 50px;
width: 920px;
max-width:100%;
background-color:#2d2d2d;
margin-left:auto;
margin-right:auto;
}

/* NAVBAR CSS */

nav ul ul
{
display: none;

}

nav ul li:hover > ul
{
display: block;
}
nav ul {
background:#2d2d2d;
color:ffffff;
font-size:30px;
padding: 0 20px;
list-style: none;
position: relative;
display: inline-table;
margin-top: 0;

}

nav ul:after
{
content: "";
clear: both;
display: block;
}

nav ul li
{
float: left;
}

nav ul li:hover
{
background: #4b545f;
}

nav ul li:hover a
{
color: #fff;
}

nav ul li a {
display: block;
padding: 7px 93px;
color: #757575;
text-decoration: none;
}

nav ul ul
{
background: #5f6975;
padding: 0;
position: absolute;
top: 100%;
}

nav ul ul li
{
float: none;
border-top: 1px solid #6b727c;
border-bottom: 1px solid #575f6a;
position: relative;
}
nav ul ul li a
{
padding: 15px 40px;
color: #fff;
}

nav ul ul li a:hover
{
background: #4b545f;
}

/* END of NAVBAR CSS */

I would like to make it scale the whole thing, including fonts when they are too big, and without the buttons stacking vertically.
Any idea?

A: Allright, i've fixed it. It was in the height element. I shouldn't have used them at all.


text:
Q: How to show multi-choice answer key at the end of the document? I want to show the answer keys at the end of the (multiple-choice) exam page. I have a bank of questions and answers (always the first answer in the bank is assumed to be the right choice), and some macros to shuffle the questions and their answers. All files are attached (here). The output is also shown bellow. the problem is that I cannot show the correct answers at the end of the page.

A: There are various packages out there to help you build exams and quizzes.  I'm not really familiar with them because I've built my own.  Here's a very simplified version of what I use:
\documentclass{article}

\makeatletter

\newcounter{ae@prob@cnt}
\let\ae@answer@key\relax

\newcommand\problem[1][a]{%%
  \stepcounter{ae@prob@cnt}%%
  \edef\ae@tmp{\theae@prob@cnt/#1}%%
  \ifx\relax\ae@answer@key
    \edef\ae@answer@key{\ae@tmp}%%
  \else
    \edef\ae@answer@key{\ae@answer@key,\ae@tmp}%%
  \fi
  Problem \theae@prob@cnt\hspace{1em}%%%
  }

\newcommand\presentanswerkey{%%
  \expandafter\ae@present@answers\ae@answer@key,\relax\@nil}

\def\ae@present@answers#1,#2\@nil{%%
  \def\ae@continue{}%%
  \ae@parse@pair#1\@nil
  \ifx\relax#2
  \else
    \def\ae@continue{\ae@present@answers#2\@nil}%%
  \fi
  \ae@continue}

\def\ae@parse@pair#1/#2\@nil{%%
  #1\hspace{0.25cm}#2\par}

\makeatother

\begin{document}

\problem[a] This is a question

\problem[b] This is another question

\problem[d] This is the penultimate question

\problem[c] My favorite question.

\presentanswerkey

\end{document}

UPDATE
Here's a modified version of the above:
\makeatletter
\let\ae@answer@key\relax
\newcommand\buildanswerkey[2]{%%
  \typeout{===>#1:#2}%%
  \edef\ae@tmp{#1/#2}%%
  \ifx\relax\ae@answer@key
    \xdef\ae@answer@key{\ae@tmp}%%
  \else
    \xdef\ae@answer@key{\ae@answer@key,\ae@tmp}%%
  \fi}

\newcommand\presentanswerkey{%%
  \typeout{===>\detokenize\expandafter{\ae@answer@key}}%%
  \expandafter\ae@present@answers\ae@answer@key,\relax\@nil}

\def\ae@present@answers#1,#2\@nil{%%
  \def\ae@continue{}%%
  \ae@parse@pair#1\@nil
  \ifx\relax#2
  \else
    \def\ae@continue{\ae@present@answers#2\@nil}%%
  \fi
  \ae@continue}

\def\ae@parse@pair#1/#2\@nil{%%
  #1\hspace{0.25cm}#2\par}

\makeatother

Save it in a file called buildanswerkey.tex and load it in your commandsPerm.tex file.
In commandsPerm.tex, I've rewritten a few of the lines as follows:
%%-----------------------------------------
\pgfmathrandomitemwithoutreplacement\j{tmp}
\sbox\answera{\ifx\j\correctAnswer * \expandafter\buildanswerkey\expandafter{\thequestion}{a}\fi\ifcase\j\relax\or#1\or#2\or#3\or#4\fi}%
\ifx\j\javab \questionhaspoints{\thequestion = 1} \fi
%%-----------------------------------------
\pgfmathrandomitemwithoutreplacement\j{tmp}
\sbox\answerb{\ifx\j\correctAnswer * \expandafter\buildanswerkey\expandafter{\thequestion}{b}\fi\ifcase\j\relax\or#1\or#2\or#3\or#4\fi}%
\ifx\j\javab \questionhaspoints{\thequestion = 2} \fi
%%-----------------------------------------
\pgfmathrandomitemwithoutreplacement\j{tmp}
\sbox\answerc{\ifx\j\correctAnswer * \expandafter\buildanswerkey\expandafter{\thequestion}{c}\fi\ifcase\j\relax\or#1\or#2\or#3\or#4\fi}%
\ifx\j\javab \questionhaspoints{\thequestion = 3} \fi
%%-----------------------------------------
\pgfmathrandomitemwithoutreplacement\j{tmp}
\sbox\answerd{\ifx\j\correctAnswer * \expandafter\buildanswerkey\expandafter{\thequestion}{d}\fi\ifcase\j\relax\or#1\or#2\or#3\or#4\fi}%
\ifx\j\javab \questionhaspoints{\thequestion = 4} \fi

Then when you compile your file, you get an answer key.  I didn't bother to figure out how you intended to create your answer key, but by calling \presentanswerkey before exiting your mcquestions environment, then you'll get a correct key:


text:
Q: When run an infintie loop why int or char gives negative value at the end #include <stdio.h>

int main()
{
    signed char x = 0;
    for (; x >= 0; x++);
    printf("%d\n", x);
    return 0;
}

The output of this code is -128. Can anyone explain why?

A: Implementation-defined behavior
signed char x = 0; for (; x >= 0; x++); iterates x from 0 up to 127 (SCHAR_MAX), all OK so far.
On the next iteration, x++ acting like x = x + 1;, attempts to assign 128 to the signed char x.  As that is out of signed char range:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
(C spec relating to conversions to a signed type)

A common implementation-defined result is to wrap around to -128 or SCHAR_MIN.  Other results could have happened, like assigning a max value of 127 resulting in an infinitive loop.
There is no signed integer overflow, just an out of range assignment.

Code is not highly portable and should be avoided.

A: It is implementation-defined behaviour.
on x86 platform all known to me compilers, when x is 127 and you add 1 it performs unsigned addition and the result is 0b10000000 which in two's complement signed integer format is -128
As x is -128 the loop terminates and -128 is printed out


text:
Q: How to execute JavaScript on UserControl PostBack in asp.net? We have an asp.net page that consists of multiple user controls, many of which have the visible attribute set to false.
By selecting a radio button, one of the user controls is shown by setting the visible attribute to true in the code-behind. When this happens, we want a JavaScript function to be run. The script has been registered using ScriptManager.RegisterStartUpScript in the Page_Load method of the page.
How can we make this work?
Things we've tried:

*

*Register script in the user control (both code-behind and markup)

*Trying some of the other methods available on the ScriptManager

*Using jQuery $(document).ready()
But in all cases the script is only executed when the page is loaded/reloaded.
The only hack that seems to work, is calling the function inside the pageLoad() function as this function gets called after every PostBack.

A: I suggest you to include the user control inside an updatePanel and add your ScriptManager.RegisterStartUpScript inside the updatePanel load event:
<asp:UpdatePanel runat="server" ID="UpdatePanel1"
OnLoad="UpdatePanel1_Load">

c#
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
  //your code to fire the javascript
}

A: You can try the server side: ClientScriptManager.RegisterClientScriptBlock() with client side: setTimeout()
For example:
protected void Page_Load(object sender, EventArgs e)
{
    Page page = (Page)HttpContext.Current.CurrentHandler;
    string script = "<script type=\"text/javascript\">setTimeout(function(){alert("Hello World")},3000);</script>";

    if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
    {
            page.ClientScript.RegisterClientScriptBlock(typeof(PageFunctions), "alert", script);
    }
}

This will register a script block on page_load and after 3 secs the alert will be displayed see more about setTimeout @ Window setTimeout() Method


text:
Q: Unable to ntp query host that I have connection to So I have an ethernet point to point connection from my PC to a device running NTP on UDP port 123.
This is what nmap shows:
root@kali:~# nmap -sU mydevice
PORT    STATE         SERVICE
123/udp open|filtered ntp

Now when i start ntp and check its status this is what I'm getting:
root@kali:~# sudo service ntp start
root@kali:~# sudo service ntp status
● ntp.service - Network Time Service
   Loaded: loaded (/lib/systemd/system/ntp.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2019-12-06 10:31:22 CET; 1s ago
     Docs: man:ntpd(8)
  Process: 4203 ExecStart=/usr/lib/ntp/ntp-systemd-wrapper (code=exited, status=0/SUCCESS)
 Main PID: 4209 (ntpd)
    Tasks: 2 (limit: 4915)
   Memory: 2.2M
   CGroup: /system.slice/ntp.service
           └─4209 /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 105:111

Dec 06 10:31:22 kali ntpd[4209]: Listen normally on 2 lo 127.0.0.1:123
Dec 06 10:31:22 kali ntpd[4209]: Listen normally on 3 eth0 10.96.104.97:123
Dec 06 10:31:22 kali ntpd[4209]: Listen normally on 4 wlan0 192.168.1.126:123
Dec 06 10:31:22 kali ntpd[4209]: Listen normally on 5 lo [::1]:123
Dec 06 10:31:22 kali ntpd[4209]: Listen normally on 6 eth0 [fe80::868a:75a:e3ad:2cbc%2]:123
Dec 06 10:31:22 kali ntpd[4209]: Listen normally on 7 wlan0 [fe80::cbd2:c686:502d:d0d0%3]:123
Dec 06 10:31:22 kali ntpd[4209]: Listening on routing socket on fd #24 for interface updates
Dec 06 10:31:22 kali ntpd[4209]: kernel reports TIME_ERROR: 0x41: Clock Unsynchronized
Dec 06 10:31:22 kali ntpd[4209]: kernel reports TIME_ERROR: 0x41: Clock Unsynchronized
Dec 06 10:31:23 kali ntpd[4209]: Soliciting pool server 162.159.200.123

And this is the response from ntpq -npcrv
root@kali:~# ntpq -npcrv
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 10.96.104.98    .STEP.          16 u    -   64    0    0.000    0.000   0.000
 0.debian.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 1.debian.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 2.debian.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 3.debian.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
*83.168.200.199  192.36.143.130   2 u   76   64    1    3.652   -0.742   0.646
 193.182.111.143 194.58.202.20    2 u   40   64    1    2.206   -0.768   4.768
-213.199.225.30  212.160.106.226  2 u   46   64    3   44.320    0.156   4.717
+213.251.52.202  195.66.241.10    2 u   11   64    3   19.966   -1.813   1.371
-109.201.133.100 151.80.124.104   3 u   44   64    3   31.114    1.118   0.964
+147.78.228.41   193.11.166.36    2 u   11   64    3    3.708   -1.263   0.946
 193.182.111.14  192.36.143.130   2 u   40   64    1    2.196   -0.488   0.677
+193.182.111.13  194.58.202.20    2 u   47   64    3    2.062   -1.249   4.331
+27.124.125.250  85.199.214.98    2 u   45   64    3   31.547   -1.261   1.389
 218.186.3.36    .GPS.            1 u   38   64    1  307.278   37.465  11.156
 162.159.200.1   10.128.8.119     3 u   41   64    1    1.660   -0.669   0.295
+62.201.225.9    62.201.214.162   2 u   45   64    3   84.179   -1.641   0.768
-45.231.168.6    23.31.21.163     3 u   46   64    3  170.302  -27.169   0.945
 193.182.111.141 194.58.202.20    2 u   42   64    1    2.567   -0.554   2.066
 102.130.49.223  85.199.214.98    2 u   42   64    1  186.493   -1.765   0.277
 176.9.241.107   130.149.17.8     2 u   40   64    1   36.654   -0.853   0.272

associd=0 status=0618 leap_none, sync_ntp, 1 event, no_sys_peer,
version="ntpd 4.2.8p13@1.3847-o (1)", processor="x86_64",
system="Linux/5.3.0-kali2-amd64", leap=00, stratum=3, precision=-22,
rootdelay=4.995, rootdisp=219.827, refid=83.168.200.199,
reftime=e19b727a.eb1b269c  Wed, Dec 11 2019 14:49:46.918,
clock=e19b72c6.3c2e95c2  Wed, Dec 11 2019 14:51:02.235, peer=1791, tc=6,
mintc=3, offset=-1.425931, frequency=-5.187, sys_jitter=0.437287,
clk_jitter=0.668, clk_wander=0.017, tai=37, leapsec=201701010000,
expire=202006280000

It says Listen Normally on 3 eth0, which is my remote device.b
Now with wireshark I can see incoming and outgoing NTP packets to/from this host.
Wireshark trace
EDIT: This is a google drive folder containing, screenshots of two requests, one client and one server, aswell as the complete .pcap from wireshark:
https://drive.google.com/drive/folders/1PbvjJugtpRJKN0YrvX5VbI9iJfnJxdYH
So far so good, there seems to be NTP communication between my PC and the device.
However, when I try to ntp query the device:
root@kali:~# ntpdate -q mydevice
29 Nov 12:59:17 ntpdate[9599]: no server suitable for synchronization found
root@kali:~# ntpq -p mydevice
10.96.104.98: timed out, nothing received
***Request timed out

Why am I unable to manually query the remote host, when my wireshark clearly shows me that I'm having "automatic ntp communications" with it?
Is it because the remote host is only running a ntp client and not a ntp server? If so, what kinda ntpq commands can I use to communicate with it?

A: Based on your packet capture, the local clock of 10.96.104.98 was set to 1 Jan 1997 00:00 when you started NTP.  For the first 4 polls, the clock was still set to that time, which would mean that you weren't synchronised (because the offset was too large).  By the time of the 5th poll, 10.96.104.98 had changed its clock to the right time, and by the 6th poll it was showing 10.96.104.97 as its reference clock.
The ntpq -npcrv output you captured was showing a maximum of 3 successful polls to any time server.  So that suggests the output was captured before the 5th poll.  If you try it again now (or any time after that 6th poll), it should show successful synchronisation.
Please note that if you don't control 10.96.104.97, it's normal for it to refuse to respond to ntpq -p, and ntpdate wouldn't have selected it because your time was too far out.
Double check that your ntpd is being started with the -g or -G flags so that it sets the clock correctly on initial startup.


text:
Q: How to request JVM garbage collection (not from code) when run from Windows command-line how could I request Java garbage collection externally, starting the program from JAR (Windows BAT used)?

*

*From the Java code I can do it with System.gc()

*When running a JNLP distribution, I get this "Java console" turned on from Control Panel / Java / ... and this Java console provides manual garbage collection.

But... When I'm running the jar from command-line / bat the java console doesn't seem to open. Couldn't find help with a brief googling, maybe somebody here?

A: If you use the very latest java 6 you also have jvisualvm which complements and extend the jconsole functionality.  They are both very useful tools.

A: For a purely command-line approach, you should be able to use jcmd.  I believe jcmd has been part of the standard JDK install since at least Java 1.7.  The command would be something like this:
jcmd <process-id> GC.run

You can get a list of available diagnostic commands that jcmd provides for a particular process like this:
jcmd <process-id> help

A: You can use jconsole to connect to a JVM that is running locally - This provides a "Perform GC" button on the GUI.
You'll need to specify -Dcom.sun.management.jmxremote when you kick off your java process.

A: You normally should not have any reason to force garbage collection. Doing so, messes up the garbage collector algorithms (mainly their performance). It will also slow down the program while garbage is being collected. If there is a memory issue, you should use memory tracing tools to find out where references are being held? (Are listeners unregistered?)
As in the other answers, you can use jconsole or jvisualvm. You can also use jmx to do it programmatically.


text:
Q: What is a regular expression for removing spaces between uppercase letters, but keeps spaces between words? For example, if I have a string like "Hello I B M", how do I detect the space between the uppercase letters but not between the "o" and the "I"?
Basically "Hello I B M" should resolve to "Hello IBM"
So far, I have this:
value = "Hello I B M"
value = value.replace(/([A-Z])\s([A-Z])/g, '$1$2')

But it only replaces the first instance of a space between two uppercase letters like: "Hello IB M"
--EDIT--
Solution Part 1:
 value = value.replace(/([A-Z])\s(?=[A-Z])/g, '$1')

Thanks to Renato for the first part of the solution! Just found out if there is a capitalized word AFTER an uppercase letter, it swallows that space as well. How do we preserver the space there?
So "Hello I B M Dude" becomes "Hello IBMDude" instead of "Hello IBM Dude"

A: When the regex matches the first time (on "A B"), this part of the string in consumed by the engine, so it is not matched again, even though your regex has the global ('g') flag.
You could achieve the expected result by using a positive lookahead ((?=PATTERN)) instead, that won't consume the match:
value = "Hello I B M"
value = value.replace(/([A-Z])\s(?=[A-Z])/g, '$1')
console.log(value) // Prints "Hello IBM"

To make it not remove the space if the next uppercase letter is the first in a word, you can increment the lookahead pattern with using a word boundary \b to make that restriction:
value = "Hello I B M Dude"
value = value.replace(/([A-Z])\s(?=[A-Z]\b)/g, '$1')
console.log(value) // Prints "Hello IBM Dude"

Note: As @CasimirHyppolite noted, the following letter has to be made optional, or the second regex won't work if the last character of the string is uppercase. Thus, the pattern ([^A-Za-z]|$), which can be read as "not a letter, or the end of the string".
Edit: Simplify lookahead  from (?=[A-Z]([^A-Za-z]|$)) to (?=[A-Z]\b) as suggested by @hwnd