text:
Q: Ambient Light Sensor + Comparator So I've been looking at options to create a way of controlling whether a flash will fire based on the amount of light in the surrounding environment.
Early note: Everything has to be surface mount and tiny
One of the companies I contacted about an ambient light sensor says an ALS would work to turn the circuit on\off only if I used a comparator.
I threw together a quick circuit, except with a phototransistor, and this is what I have, but the problem is I feel the amperage really sucks. I can't pull more than 14mA for a single LED (I need closer to 50mA), and about 8mA for two in parallel. So I must have something wrong, or maybe a comparator just can't source more than that?

Option 2 is using Transistors, which this circuit shows to source more, but still a bit under what I'd like.

So I'd like to know what you guys think. Do you think either of these will work with something like this? Is there a better way to do this? As always, thank you guys a ton!

A: Connect a transistor after the comparator to amplify the current.

simulate this circuit – Schematic created using CircuitLab
If you are using a push-pull comparator (which LM311 is not) then you may be able to remove R2 if the comparator is powered from V+ and its high output is very close to V+.
And yes, the current output of the LM311 is in the single-digit mA. This additionally means that you may need a Darlington transistor for Q1.


text:
Q: Error message "invalid escape sequence near "\%" when tex.sprint is inside a \chapter command The error message "invalid escape sequence near "\%"" occurs only when a \luaexec tex.sprint is placed inside a \chapter command: why ?
\documentclass{book}
\usepackage{luacode}
\begin{document}

\def\CalculusResult{
\luaexec{Calculus = 1/3 tex.sprint (string.format("\%0.5f", Calculus))}}%

\chapter{\huge When placed inside a chapter command, the  CalculusResult \CalculusResult ~  prints well but produces an error message: invalid escape sequence near "\%" }%

\huge No error message if the CalculusResult \CalculusResult ~ is in the text.

\end{document}

A: It's not much different from things like \chapter{abc \eqref{def}} (\eqref is one of the few fragile commands).
The macro \luaexec is fragile, so it should be protected; burying it into another command is not sufficient, unless the other command is protected.
\documentclass{book}
\usepackage{luacode}

\newcommand\CalculusResult{%
  \luaexec{Calculus = 1/3 tex.sprint (string.format("\%0.5f", Calculus))}%
}

\begin{document}

\tableofcontents

\chapter{When placed inside a chapter command, the
  CalculusResult \protect\CalculusResult{} prints
  well but produces an error message: invalid escape sequence near "\%"}

No error message if the CalculusResult \CalculusResult{} is in the text.

\end{document}

Note that I have used % in the correct places. You had two in useless ones and missed one in an important place.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add number of days in Date in javascript I want to add +1 if the date is sunday. Below code works for the rest dates. But when I pass 30 sept 2012 I gives me 1 Sept 2012 instead of 1 Oct 2012 in dateMsg. What is wrong with the code?. Please guide.  I guess I'l face same problem in all last date of the month.How to add 1 to whole date rather than just the day?
var monthName=convertMnthNoToName(freeLookEndDt.getMonth()+1);

    if (freeLookEndDt.getDay()==0) {

      var date=new Date(freeLookEndDt.getFullYear(),freeLookEndDt.getMonth(),
      freeLookEndDt.getDate()+1);
      var newmonthName=convertMnthNoToName(date.getMonth()+1);
      var dateMsg = date.getDate() + '-' + monthName + '-' + freeLookEndDt.getFullYear();

      document.forms[0].flEndDt.value=dateMsg;

    }

and convertMnthNoToName()
function convertMnthNoToName(val)
{
    if(val==01 || val==1)
    {
      val1="Jan";
    }
    if(val==02 || val==2)
    {
      val1="Feb";
    }
    if(val==03 || val==3)
    {
      val1="Mar";
    }
    if(val==04 || val==4)
    {
      val1="Apr";
    }
    if(val==05 || val==5)
    {
      val1="May";
    }
    if(val==06 || val==6)
    {
      val1="Jun";
    }
    if(val==07 || val==7)
    {
      val1="Jul";
    }
    if(val==08 || val==8)
    {
      val1="Aug";
    }
    if(val==09 || val==9)
    {
      val1="Sep";
    }
    if(val==10)
    {
      val1="Oct";
    }
    if(val==11)
    {
      val1="Nov";
    }
    if(val==12)
    {
      val1="Dec";
    }

    return val1;
}

where freeLookEndDt = Sun Sep 30 00:00:00 UTC+0530 2012

A: DEMO
This is more efficient. Also you need to take the monthname AFTER you add the day
Please note your date in your example is resolving to Saturday in my country!!!
var monthNames ="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",")

if (freeLookEndDt.getDay()==0) {
  freeLookEndDt.setDate(freeLookEndDt.getDate()+1);
  var dateMsg = freeLookEndDt.getDate() + '-' + monthNames[freeLookEndDt.getMonth()] + '-' + freeLookEndDt.getFullYear();
  document.forms[0].flEndDt.value=dateMsg;
}

or if you need to keep freeLookEndDate:
if (freeLookEndDt.getDay()==0) {
  var date = new Date(freeLookEndDt.getTime());
  date.setDate(date.getDate()+1);
  var dateMsg = date.getDate() + '-' + monthNames[date.getMonth()] + '-' + date.getFullYear();
  document.forms[0].flEndDt.value=dateMsg;
}

A: u define newmonthName but use monthName. Thus it is using old month name. newmonthNameshould have changed
you should just be able to do  freeLookEndDt.setDate(freeLookEndDt.getDate()+1)

A: Instead of

var date=new Date(freeLookEndDt.getFullYear(), freeLookEndDt.getMonth(),
                  freeLookEndDt.getDate()+1);

use

var date = new Date();
date.setFullYear(freeLookEndDt.getFullYear());
date.setMonth(freeLookEndDt.getMonth());
date.setDate(freeLookEndDt.getDate()+1);

That way, you'll be setting day at the last step, and Date will recalculate stored month and year to correct values. Note that year also can change, if you have Dec.31.
Also, the function convertMnthNoToName can be modified to have more compact implementation and be able to handle also string input values, such as "03".
Complete code:

var monthName=convertMnthNoToName(freeLookEndDt.getMonth()+1);

if (freeLookEndDt.getDay()==0) {

    var date = new Date();
    date.setFullYear(freeLookEndDt.getFullYear());
    date.setMonth(freeLookEndDt.getMonth());
    date.setDate(freeLookEndDt.getDate()+1);
    var newmonthName=convertMnthNoToName(date.getMonth()+1);
    var dateMsg = date.getDate() + '-' + newmonthName + '-' + freeLookEndDt.getFullYear();

    document.forms[0].flEndDt.value=dateMsg;
}

/**
 * Converts month (1-based) to its string representation
 * @param {Number|String} val    Month index (from 1-January to 12-December)
 * @return {String}    String representation of month or empty string for invalid input parameter
 */
function convertMnthNoToName(val)
{
    val = parseInt(val); // string "01" will be converted to 1
    if(val>=1 && val<=12)
    {
        var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        return monthNames[val-1];
    }
    return "";
}


text:
Q: Kubernetes CKAD Preparation Question: Exposed port is not working This is what i am trying to do:Get nginx pod's ip created in previous step, use a temp busybox image to wget its '/'
Find the link for your reference:
https://github.com/dgkanatsios/CKAD-exercises/blob/main/a.core_concepts.md#get-nginx-pods-ip-created-in-previous-step-use-a-temp-busybox-image-to-wget-its-
Now my question is when I run this command it works:
kubectl run busybox --image=busybox --rm -it --restart=Never -- wget -O- $(kubectl get pod nginx -o jsonpath='{.status.podIP}:{.spec.containers[0].ports[0].containerPort}')

but when I do this it does not work. Cam someone explain me why is that ?
kubectl get po -o wide # get the IP, will be something like '10.1.1.131'
# create a temp busybox pod
kubectl run busybox --image=busybox --rm -it --restart=Never -- wget -O- 10.1.1.131:80

A: You have to first create an Nginx pod. This is what is referred as "previous step".
$ kubectl run nginx --image=nginx --restart=Never --port=80

pod/nginx created

You can then run wget inside a BusyBox pod:
$  kubectl run BusyBox --image=busybox --rm -it --restart=Never -- wget -O- $(kubectl get pod nginx -o jsonpath='{.status.podIP}:{.spec.containers[0].ports[0].containerPort}')

Connecting to 10.42.0.52:80 (10.42.0.52:80)
writing to stdout
<!DOCTYPE html>

<title>Welcome to nginx!</title>

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.

For online documentation and support please refer to
nginx.org.

Commercial support is available at
nginx.com.

Thank you for using nginx.

-                    100% |********************************|   615  0:00:00 ETA
written to stdout
pod "busybox" deleted


text:
Q: SendEmail pipeline showing "Could not resolve type name error" while adding pipeline- sitecore emailcampaign I have created a class
public class ECMSendMessageProcessor
{
    public void Process(SendMessageArgs args)
    {
    }
}

And added a pipeline on "SendEmail"
<SendEmail>
  <processor type="Namespace.ClassName.Method,Assembly" />

While i send email am facing
Could not resolve type name "Namespace.ClassName.Method,Assembly"
Reference link http://www.craigtaylor.us/2014/10/injecting-tracking-pixel-into-sitecore-ecm.html
I tried changing the pipeline, class etc. But always showing this error.

A: When specifying your custom processor, don't include the method name. Change your example to this:
<SendEmail>
  <processor type="Namespace.ClassName,Assembly" />

A: You should just use just the ClassName in your declaration rather than adding the method on the end e.g
 <SendEmail>
      <processor type="Namespace.ClassName, Assembly" />

The process() method is the default method for a pipeline processor. If you wanted to use another method other than process you can add Method="yourmethod" to the declaration.


text:
Q: Updating the table by multiple where conditions in codeigniter I have to update the table if only the three values gets matched. I get a syntax error on trying this. What could be the reason?
 $sql1="update target set updvalue='".$val3."'  where Id ='".$b."'" AND MId ='".$c."'" AND DID ='".$f."'";
 $res1=$this->db->query($sql1);

A: $sql1="update target set updvalue='".$val3."'  where Id ='".$b."' AND MId ='".$c."' AND DID ='".$f."'";
$res1=$this->db->query($sql1);

use this

A: I think there are to many " between where Id and AND, that is, you have made a typo.

A: You can use Codeigniter query builder.
$this->db->where('Id',$b);
$this->db->where('MId',$c);
$this->db->where('DID',$f);
$upd_data['updvalue'] = $val3;
$res1=$this->db->update('target',$upd_data);

Let me know if it not works.


text:
Q: Comparison of image with csv column in loop python Gretings,
Problem:
I am stuck in a loop. I want the loop to pick image and compare it with csv column(name) if it exists then move further to resizing. Images were in a zip, first I took them out of zip;

from zipfile import ZipFile
file_name = "human_detection_images.zip"
with ZipFile(file_name, 'r') as zip:
   zip.extractall()
print('Done')

PATH_TO_TEST_IMAGES_DIR = pathlib.Path('/content/human_detection_images')
TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob("*.jpg")))
TEST_IMAGE_PATHS

Then I upload csv, which has labels and names of images (same as folder but not in sequence).

import pandas as pd
import numpy as np
data1 = pd.read_csv('/content/csvnew.csv')
df = pd.DataFrame(data1)
df.shape,df.columns

Now I need to run a loop which pick 1 by 1 images and compare it with names in csv. If similar it resize the image. resize code is available,

for image_path in TEST_IMAGE_PATHS:
   if TEST_IMAGE_PATHS == df['names']:
     print("done") #error here: it prints nothing
  #  return False
     imgs = read_given_images("./",TEST_IMAGE_PATHS)
     points = df['labels']
     points = np.array(points)

# resizing starts

I need help with the loop. if anyone please..

A: Its easy. First pick name from csv and find it in folder.
your code:
     imgs = read_given_images("./",TEST_IMAGE_PATHS)
 points = df['labels']
 points = np.array(points)

change it to:

imgs = read_given_images("/content/human_detection_images",df.names.values)
points = df['labels'].values
points = np.array(points)

this way images and points will be picked together.


text:
Q: Lombok's @Builder and Javadoc Creation In one of my projects, I'm handling some POJOs that may have 20+ fields. I'm using the Builder Pattern to make object creation less cumbersome. Lombok's @Builder annotation really removes a lot of boilerplate code and speeds up my process. Thing is that I want to add Javadoc to the 'setter'-like methods in the various builders of my project. I've tried to put the Javadoc to the fields just like Lombok's recommendation on @Getter/@Setter but it doesn't seem to work. Is there any possible method to achieve what I want?

A: You can also use @Accessors(chain = true) instead of @Builder.
Your Getter and Setter will return your instance and you can also use Method-Chaining like in Builder Pattern.
The syntax will be like
Model model = new Model().setId(23L).setTitle("test");

We always use this instead of @Builder.
Lomboks recommendation should work with this solution


text:
Q: What happened to WinFS? The most interesting feature that was ever connected to what eventually became Vista was WinFS, a revolutionary (so it seemed, at least back then) new way of storing and accessing information on a computer.
This feature was cut despite actually reaching a closed alpha/technical preview release. There was a smoke and mirrors blog post from MS about the technology living on in an upcoming SQL server release, but to me it just felt like it was axed, hard.
Does anyone have any idea what happened to it? Is it killed, or just on the backburner? Was it just impossible to implement, too expensive, or did someone think of a better idea?
Are there any projects (From MS or anyone else) that have similar goals?

A: It became part of SQL server 2008.
I worked on a team that had a partnership with microsoft to demonstrate the feature by integrating it with our product's data storage. there's a white paper floating about on the MS site (and frequently appears on the register) outlining the Marketing Bulls... uhh.. technology integration involved. if you look at my profile, that might give you a clue what to look for...
edit:
I believe this is the feature it became

A: Hal Berenson, the General Manager of what would become WinFS wrote an excellent four-part blog series after Bill Gates disclosed in 2013 that his biggest regret from his time at Microsoft was the failure to deliver WinFS:

*

*WinFS, Integrated/Unified Storage, and Microsoft – Part 1 (archive)

*WinFS, Integrated/Unified Storage, and Microsoft – Part 2 (archive)

*WinFS, Integrated/Unified Storage, and Microsoft – Part 3 (archive)

*WinFS, Integrated/Unified Storage, and Microsoft – Part 4 (archive)
From thisisbillgates:

Q. What one Microsoft program or product that was never fully developed or released do you wish had made it to market?
A. We had a rich database as the client/cloud store that was part of a Windows release that was before its time. This is an idea that will remerge since your cloud store will be rich with schema rather than just a bunch of files and the client will be a partial replica of it with rich schema understanding.

The short version is that it while it difficult to pull off, the challenge was to get the Exchange team to use it. They were going to be the test case. Except Object File System (OFS, aka Integrated Storage, aka Cairo, aka WinFS) wasn't ready yet. Microsoft had just bought SQL Server from Sybase, and were also creating an entirely new database engine internally from scratch: Jet Blue. Does the Exchange team wait for Cairo? Do they move to SQL Server? Do they switch to Jet Blue?

In a meeting with Bill to decide the direction for Integrated Storage he had to choose between two options.  One was the technology base that he thought was the right one for the long-term vision of Integrated Storage, but it was a store with no one committed to use it.  The other was a solid plan and commitment to deliver something that unified the unstructured and semi-structured worlds within Microsoft.  Bill chose to let the Exchange-based plan proceed, but also encouraged us to continue to work on SQL Server as the basis for a future Integrated Storage solution.

Exchange team went ahead and used JetBlue. The free database engine that ships with Windows, and has a publicly supported API. JetBlue, aka Extensible Storage Engine, is the database that powers:

*

*Exchange

*Outlook

*Windows Search

*Active Directory

*Windows Updates

Bonus Reading
And in a vein similar to WinFS and data storage, Hal also had an excellent blog on the history of OLEDB, the visions, the promises, and how OLEDB really does solve problems that exist:

*

*OLE DB and SQL Server: History, End-Game, and some Microsoft "dirt" (archive)
Along with SQL Server team's announcement that they're ending support for the OLEDB native client.

A: Just for the record, an excellent ZDNet overview from 2013 (titled "Bill Gates' biggest Microsoft product regret: WinFS"), with lots of relevant links, references and insider quotes like:

... no two members of the WinFS team seemed to be able
  to answer the question "What is it?" in a succinct, cohesive way. He
  noted:
"Some people would say that it (WinFS) was the database embedded in
  the operating system. Others would say that it was XML in the
  database. Other answers included a SQL-based file system, an
  object/relational mapping layer, rich storage for Office apps, a file
  system metadata indexer, .NET in the database, etc. It's not that
  these weren't useful technologies (many of them shipped outside the
  WinFS project), it's that there wasn't a singular vision driving the
  project to completion. Because no one could identify the essence of
  the project, it made it really hard to make any decisions about what
  should or shouldn't be included."

In his referenced blog post Welcker continued:

... it provides a barometer for other projects that may be headed
  towards certain doom. If you can't boil down what your project is
  about (and everyone is be able to say what it is) then it's probably
  not going to be successful. I would argue that even a single,
  incorrect goal is better than a wide variety of semi-correct goals.
  You can always change the course of a team headed in a unified
  direction but trying to corral a team headed in every direction is
  pretty much impossible.

A: I don't think anyone really knows.
The most up to date information I can find is an interview with Quentin Clark in which he says that "most of WinFS either already has shipped, or will ship" just in other forms, such as part of SQL server or the ADO.net entity framework.
I personally suspect it was one of those projects that was poorly defined from the start. It was all things to all people and consequently could never fully realise all it's goals. It seems that all the research that went into the various different aspects of WinFS eventually grew into separate projects and became parts of other things.
You can see from this development timeline that it's been an ongoing project since 1990. that makes it one of the few software projects that actually been in development longer than Duke Nukem Forever
[Edit: For completeness, here is some other info I found - WinFS Blog - Last updated June 2006. The last entry basically says WinFS was not dead but is no longer a separate product, it was planned to incorporate the tech into other products like SQL server and ado.net]

New information (May 2010):
I found this article which talks about the features of WinFS that have survived and live on in some form in Windows7.

A: Other reasons WinFS never appeared could be due to marketing and profit. The only area Microsoft can increase profits is the sale of Vista to someone already running XP. Vista licenses for new PCs are instead of XP licenses and don't increase profit. So, you need to convince people they need to upgrade XP to Vista. Outside of users of this site, the idea of a new file system is nowhere near enough to fork out the cash for a new OS. A new, shiny GUI is a much easier sell and more likely to make those additional sales.


text:
Q: jQuery on click function not working in Android mobile browsers This jQuery onclick function works perfectly in all computer browsers but when run on Android mobile devices' default browser it doesn't. It does work in Chrome mobile browser.
html
<input type="button" value="Add" id="submit" class="btn btn-primary"/>

        #
        code
        credit
        Grade

js
 $(document).ready(function() {
        var i=0;
        var code;
        var credit=0;
        var grade=0;

        $('#submit').click(function (){
            i=i+1;
            code=$('input[name=codeInput]').val();
            credit=$('select[name=quantity]').val();
            grade=$('select[name=gradetInput]').val();
            $('.tableBody').append( '
'+'' + i +'	'+'' + code +'	'+'' + credit +'	'+'' + grade +'	'+'
');
        });
    });

A: try use touchstart, like this:
$('#submit').bind('touchstart click', function(){
    i=i+1;
    code=$('input[name=codeInput]').val();
    credit=$('select[name=quantity]').val();
    grade=$('select[name=gradetInput]').val();
    $('.tableBody').append( '
'+'' + i +'	'+'' + code +'	'+'' + credit +'	'+'' + grade +'	'+'
');
});

A: https://github.com/ftlabs/fastclick
$(function() {
    FastClick.attach(document.body);
});

profit, but hey what is i in your code?

A: Not sure why this is an issue, but try adding this rule:
.dropdown-backdrop {
 z-index: -1;
}


text:
Q: JavaScript - Check which child string occurs first in a parent string using string.indexOf() I have a really long "parent" string (about 2,000 characters).
I want to find out which of two "child" strings (or substrings) occur first.
So far I've been using string.indexOf():

/* VARIABLES */
var parentString = "Lorem foo ipsum dolor sit bar amet, consectetur adipiscing elit,..."

var firstSubstring = "foo"
var secondSubstring = "bar"

var firstSubstringLength = firstSubstring.length
var secondSubstringLength = secondSubstring.length

var searchIndex = 0
var continuationIndex = 0

/* SEARCH FOR SUBSTRINGS */

// Check if the substring exists
if (parentString.indexOf(firstSubstring, searchIndex) > -1) {
  console.log("firstSubstring occurred first in the ParentString")
  // Make the compiler continue its search from the end of firstSubstring"
  searchIndex = parentString.indexOf(firstSubstring, continuationIndex)
  continuationIndex = searchIndex + firstSubstringLength
}
// Check if the substring exists
if (parentString.indexOf(secondSubstring, searchIndex) > -1) {
  console.log("secondSubstring occurred second in the ParentString")
  // Make the compiler continue its search from the end of secondSubstring"
  searchIndex = parentString.indexOf(secondSubstring, continuationIndex)
  continuationIndex = searchIndex + secondSubstringLength
}

In a scenario where secondSubstring occurred in the parentString first, this code would still output that firstSubstring occurred first (because of the way this code is structured).
Is there a way to scan for both variables simultaneously and return the one which occurs first?.Thanks in advance!

A: You're printing that the first substring is first whenever the first substring is found, before comparing to the position of the second substring.
Use indexOf() for each of them, and then just compare their indexes.

/* VARIABLES */
var parentString = "Lorem foo ipsum dolor sit bar amet, consectetur adipiscing elit,..."

var firstSubstring = "foo"
var secondSubstring = "bar"

var firstSubstringLength = firstSubstring.length

/* SEARCH FOR SUBSTRINGS */

var firstIndex = parentString.indexOf(firstSubstring);
var secondIndex = parentString.indexOf(secondSubstring);

if (firstIndex > -1 && secondIndex > -1) {
  if (secondIndex >= firstIndex + firstSubstringLength) {
    console.log("secondSubstring occurred second in the ParentString");
  } else {
    console.log("secondSubstring did not occur second in the ParentString");
  }
} else if (firstIndex == -1) {
  console.log("firstSubstring was not found in the ParentString");
} else {
  console.log("secondSubstring was not found in the ParentString");
}

A: Use regex replacement to measure the position of first occurrence of each substring:

var parentString = "Lorem foo ipsum dolor sit bar amet, consectetur adipiscing elit,...";
var foo_index = parentString.replace(/^(.*?)foo\b.*$/, "$1").length;
var bar_index = parentString.replace(/^(.*?)bar\b.*$/, "$1").length;
if (foo_index < bar_index) {
    console.log("foo occurs first");
}
else {
    console.log("bar occurs first");
}

A: Hope it can help you,
var parentString = "Lorem foo ipsum dolor sit bar amet, consectetur adipiscing elit,..."

var firstSubstring = "foo"
var secondSubstring = "bar"

var firstStringIndex = parentString.indexOf(firstSubstring);
var secondStringIndex = parentString.indexOf(secondSubstring);

firstStringIndex>secondStringIndex ? console.log(secondStringIndex) : console.log(firstStringIndex);

A: While I believe the best answer has already been posted, another option would be to use positive lookahead regular expressions (though, in this case, they may prove slightly more computationally expensive -- but, might provide for more terse code -- verbosity is NOT a bad thing however, so I'd still stick with the indexOf).
For example,
const ss1index = parentString.indexOf(substring1);
const ss2index = parentString.indexOf(substring2);

const retest = new RegExp(substring1 +'(?='+ substring2 +')');
const ss1test = retest.test(parentString);

if (ss1index > -1) {
  if (ss2index > -1) {
  // substring 1 and 2 were both found in parent
    // You could rewrite the logic so you actually store the indexOf value if you need it.
    if (ss1test) // substring1 is first
    else substring2 is first
  }
}


text:
Q: Move and delete a file from two servers At work, we have a website on which we publish PDF files which are available for download (mostly user notices etc.). We also manage our internal database for updates and to generate CD's and USB Sticks with all PDF files on it, which are shipped out with the products.
So I build a platform where all plants that produce these PDF files can upload them. From time to time, a person will take care of updating the system (sync both servers).
I would like to have a link next to the files with a delete option. I already have that using a simple php script.
<?php
$deleter = new Deleter("./");
class Deleter {
    var $filename;
        var $ignorelist = array (
        '.',
        '..',
        'index.php',
        'del.php',
        'deletefile.php'
    );
    function Deleter($path="./") {
        $this->__construct($path);
    }
    function __construct($path="./") {

        $this->filename = basename(__FILE__);
        array_push($this->ignorelist, $this->filename);

        // insert page header
        $this->createHeader();

        // condition: create initial file list?
        if (isset($_GET['delete']) && !empty($_GET['delete'])) {

            // a path has been set, escape and use
            $path = basename($_GET['delete']);
            $path = urldecode($path);
            //$path = mysql_real_escape_string($path);

            // condition : Step 2: seek deletion confirmation?
            if (!isset($_GET['confirm']) || $_GET['confirm'] != 'aye') {
                $this->createConfirmationStep($path);

            // step 3: delete!
            } else {
                $this->createShowDelete($path);
            }

        // step 1: no files selected, create file list
        } else {
            echo '

These files are on the server:

            ';
            $this->createFileList($path);
            echo '
';
        }

        // insert page footer
        $this->createFooter();
    }

    /**
     * Step 1: Create a list of all files within a specific directory
     *
     * @param string $path The server path to look for files in
     * @return array $fileList Array of all files, with file/directory details
     * @access public
     */
    function createFileList($path) {

        // condition : if the path isn't set, assume one
        if (!isset($path)) {
            $path = "./";
        }

        // temporary arrays to hold separate file and directory content
        $filelist = array();
        $directorylist = array();

        // get the ignore list, in local scope
        $ignorelist = $this->ignorelist;

        // Open directory and read contents
        if (is_dir($path)) {

            // loop through the contents (PHP4 compat)
            $dh  = opendir($path);
            while (false !== ($file = readdir($dh))) {

                // skip over any files in the ignore list
                if (!in_array($file, $ignorelist)) {

                    // condition : if it is a directory, add to dir list array
                    if (is_dir($path.$file)) {

                        $directorylist[] = array(
                            "path" => $path,
                            "file" => $file,
                            "filetype" => 'directory',
                            "date" => date("M d Y, H:i", filemtime($path.$file."")),
                            "filecount" => $this->countRelevantFiles($path.$file),
                            "filesize" => 0
                        );

                    // file, add to file array
                    } else {

                        $filelist[] = array(
                            "path" => $path,
                            "file" => $file,
                            "filetype" => $this->getFileType($path.$file) . " file",
                            "date" => date("M d Y, H:i", filemtime($path.$file."")),
                            "filecount" => 0,
                            "filesize" => $this->getFileSize(filesize($path.$file))
                        );
                    }
                }
            }
        }

        // merge file and directory lists
        $finalList = array_merge($directorylist, $filelist);

        // loop through each file
        foreach ($finalList as $key => $value) {

            // condition : add trailing slash for directories
            $trailingslash = ($value['filetype'] == 'directory' ) ? '/' : '';

            // condition : if it is a directory, display count of subfiles
            if ($value['filetype'] == 'directory') {
                $fileending = ($value['filecount'] == 1) ? 'item' : 'items';
                $filedetails = ' (contains '.$value['filecount'].' '.$fileending.')';

            // else, if it is a file, display file size
            } else {
                $filedetails = ' ('.$value['filesize'].')';
            }

            // create the html for each project
            echo '

                        ' . $value['file'] . ' /

                        ';

            echo '

                    filename.'?delete='.urlencode($value['file'].$trailingslash).'">
                        Delete

            ';
        }
    }

    /**
     * count the number of files in a directory, not including the list of ignorable files
     *
     * @param string $path The server path to look for files in
     * @return int $count The number of relevant files
     * @access private
     */
    function countRelevantFiles($path, $count = 0) {

        // open the directory
        if (is_dir($path)) {

            // loop through all files, checking if we should count the current one
            $dh  = opendir($path);
            while (false !== ($file = readdir($dh))) {

                if (!in_array($file, $this->ignorelist)) {
                    $count++;
                    if(is_dir($path."/".$file)) {
                        $count = $this->countRelevantFiles($path."/".$file, $count);
                    }
                }
            }
        }

        // return the result
        return $count;
    }

    /**
     * list all sub-files of a directory
     *
     * @param string $path The server path to look for files in
     * @return void
     * @access private
     */
    function listFilesToDelete($path) {

        // open the directory
        if (is_dir($path)) {

            // loop through all files, checking if we should count the current one
            $dh  = opendir($path);
            while (false !== ($file = readdir($dh))) {

                if (!in_array($file, $this->ignorelist)) {

                    echo '
'.$path.'/'.$file.'
';

                    if(is_dir($path."/".$file)) {
                        $this->listFilesToDelete($path."/".$file);
                    }
                }
            }
        }
    }

    /**
     * Delete files
     *
     * @param string $path The server path to delete
     * @return void
     * @access private
     */
    function delete($path) {
        // Simple delete for a file
        if (is_file($path)) {

            echo '
deleting file: ' . $path . '
';

if (copy($path, "../trash/".$path)) {
  unlink($path);
}
        }

        }

    /**
     * Create a nice readable filesize from the number of bytes in a file
     *
     * @param int $size the size in bytes
     * @param string $retstring
     *
     * @return string the size in nice words
     */
    function getFileSize($size, $retstring = null)
    {
        $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        if ($retstring === null) { $retstring = '%01.2f %s'; }
        $lastsizestring = end($sizes);
        foreach ($sizes as $sizestring) {
                if ($size < 1024) { break; }
                if ($sizestring != $lastsizestring) { $size /= 1024; }
        }
        if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
        return sprintf($retstring, $size, $sizestring);
    }

    /**
     * Function to find a file type for a given filename
     *
     * @param string $file filename/path
     * @return string $extension file type
     */
    function getFileType($file="") {

        // get file name
        $filearray = explode("/", $file);
        $filename = array_pop($filearray);

        // condition : if no file extension, return
        if(strpos($filename, ".") === false) return false;

        // get file extension
        $filenamearray = explode(".", $filename);
        $extension = $filenamearray[(count($filenamearray) - 1)];
        return $extension;

    }

/* Page Building Methods */

    /**
     * Create page header
     */
    function createHeader(){
        echo '

        ';
    }

    /**
     * Create page footer
     */
    function createFooter(){
        echo '

        ';
    }

    /**
     * Create confirmation step
     */
    function createConfirmationStep($path){
        echo '

filename.'">� back to file list

Please confirm that you want to delete the following files:

filename.'?delete='.$path.'&confirm=aye">Delete

'.$path.'

        ';

        $this->listFilesToDelete($path);

        echo '

filename.'?delete='.$path.'&confirm=aye">Delete

        ';
    }

    /**
     * Show the files you're deleting
     */
    function createShowDelete($path){
        echo '

filename.'">� back to file list

The following items have been removed:

        ';

        $this->delete($path);

        echo '

Deletion complete.

filename.'">� back to file list

        ';
    }

}

?>

Now what I would like this to do is delete a file on one server e.g. server1.com/files/ and move the same file from server2.com/files/ to server2.com/trash/
I have full access to both servers. Is there any way to do that?

A: since you didn't tell us on what OS you're running you php script, I'm assuming you have a linux.
since you need to do that from one server, you'd need to have a passwordless ssh access to the other server. then you'd need to create a bash script that utilizes mv and rsync to do the file manipulations you need. and then you can use php's exec() function to execute and send the filename param to the shell script from a web page.

A: I think it's better to configure rsync over ssh with --delete option. Something like this
/usr/bin/rsync -avz --delete /path/files -e "ssh" userforsync@$SECONDARYSERVER:/path/files

where is $SECONDARYSERVER is dns name or ip. To make this work you should accept authentication by public key on secondary server and add public key to authorized keys


text:
Q: Rails 5 - what is the correct way to access this model structure from a single entity? I have a Product and Category model structure, however, the attributes that belong to each product are dependent upon which category they are in.
Please note that this is not about STI (single table inheritance) as I am not implementing specific classes that inherit from Product (eg like Book < Product, Bicycle < Product etc)
I have the following model classes (simplified to the pertinent code only):
class Product < ApplicationRecord
  # Relationships
  belongs_to :subcategory
  delegate :category, to: :subcategory, allow_nil: true
  has_many :product_category_attributes
end

class Category < ApplicationRecord
  # Relationships
  has_many :subcategories, dependent: :destroy
  has_many :products, through: :subcategories
  has_many :category_attributes, dependent: :destroy
end

class CategoryAttribute < ApplicationRecord
  # Relationships
  belongs_to :category
  has_many :product_category_attributes, dependent: :destroy
end

class ProductCategoryAttribute < ApplicationRecord
  # Relationships
  belongs_to :product
  belongs_to :category_attribute
end

This works but...bear with me here!
Here is the migrations for the category hierarchy:
class CreateCategories < ActiveRecord::Migration[5.1]
  def change
    create_table :categories, id: :uuid do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateCategoryAttributes < ActiveRecord::Migration[5.1]
  def change
    create_table :category_attributes, id: :uuid do |t|
      t.references :category, type: :uuid, foreign_key: true, index: true
      t.string :name
      t.string :value

      t.timestamps
    end
  end
end

class CreateProductCategoryAttributes < ActiveRecord::Migration[5.1]
  def change
    create_table :product_category_attributes, id: :uuid do |t|
      t.references :product, type: :uuid, foreign_key: true
      t.references :category_attribute, type: :uuid, foreign_key: true

      t.timestamps
    end
    add_index :product_category_attributes, [:product_id, :category_attribute_id], unique: true, name: 'index_product_category_attributes_on_fks'
  end
end

Imagine a category with the name 'Rugs'. Rugs have a size, so:
category_attribute.name would be 'size'
and
category_attribute.values would have 3 - 'small', 'medium', 'large'
So in the `category_attribute' table:
| id | name | value
| 1  | size | small
| 2  | size | medium
| 3  | size | large
But an individual Rug product might only be available in 'small'.
So that's the reason for the ProductCategoryAttribute -> I can assign only the attributes that applies to that particular product.
What I don't understand is how can I 'short-cut' the ActiveRecord associations created.
For example, if I load a Product in memory, how can I modify the associations so that I can do:
product.category_attributes or even
product.attributes
to return only those applicable to that product.
As an example, I know I can get a single attribute like this:
p.product_category_attributes.first.category_attribute
and that obviously only returns the first one (and is also quite unwieldy).
I believe there is a way to add a method or a scope - I'd like to call it 'attributes' - that could solve my problem, but I am a bit lost on how to proceed.
It seems that attributes is already reserved by ActiveModel?
Attempt 1
Barking up the wrong tree here but worth a try, eh?
Product.rb
  def cat_attributes
    self.product_category_attributes.each do |pca|
      return pca.category_attribute
    end
  end

Returns the product_category_attributes, not the category_attributes
Attempt 2
Product.rb
has_many :category_attributes, through: :product_category_attributes

This returns the data I want, but now how do I alias the name to something shorter?
Attempt 3
Product.rb
has_many :cat_atts, class_name: 'CategoryAttribute', through: :product_category_attributes, source: :category_attributes

Attempt 4
Delete *.*
ReturnTo C#

Thanks.

A: according to Rails Guide you can go with your attempt 3 version. Like:
# app/models/product.rb

  has_many :product_category_attributes
  has_many :cat_atts, through: :product_category_attributes, source: :category_attribute


text:
Q: 2 Layer power routing with mixed signals I am working on a BLE Gamepad project using a module based on the Nordic NRF51822. This is the first project I have done that is more complicated then an arduino project so I am likely to make some big mistakes. I am getting close to finishing it, but I have this aching feeling like I am doing the power rails completely wrong.
I currently have one long +3V3 trace running under all the circuitry that powers two LED's, two analog thumbsticks, and the microcontroller module. In a four layer board I would have separate traces for AVDD and VDD, but I am already beginning to feel a little cramped in the areas where power traces are needed. I might be able to separate them if I route VDD under the module itself, but I am worried that it might cause noise in the module if I do this. Essentially, I would like to know what I should do for power routing in such an environment.
For specifics check out the github project with pics, gerbers, and the source for the KiCad project files.
If you see things that are wrong with the design and are not related to this question then feel free to post about them at this reddit post

A: I haven't looked at your files. ...In general, for a two layer board I would put the bottom layer to be a ground plane and keep the power delivery traces short and wide on the top layer.
There will no doubt be places that the signals will need to cross, and it's fine to take them on to layer 2 but be careful not to make any copper Islands and not to break any continuous ground underneath the power delivery.
It is almost certain that you need to keep the copper away from the bluetooth module because it will mess with the antennae. Are there any impedance controlled nets in your design? If so this might be more difficult on a 2 layer board

Okay I have had a look at the png images on your github page and its not clear what you are asking. I can see 2 traces under the module: pin 38 bt_led and pin 28 select. Both of these can easily be moved onto L2 and I would suggest stitching vias on either side.
Your biggest problem is the chunk of signals on the right hand side passing directly underneath U2 and L4. These will pick up huge amounts of noise from the switcher. They must be routed somewhere else or move the psu to be above a ground plane
As for your specific question, the avdd is already separated from the rest because you have them joined at the smps output. D1 is the only thing that also uses this trace, but I don't imagine it will be particularly fast. So not a problem as it is. You should definitely decouple the other supply to the module at pin 14, and possibly add some lower value ceramics alongside c1. 10n perhaps


text:
Q: MFMailComposeViewController in iphone app hii every one
can we use  " MFMailComposeViewController "  with out using " presentModalViewController" , i mean i need to send email with out navigating to that mail composer page
i did a test project with following code
- (IBAction)buttonPressed {
    arrRecipients = [[NSMutableArray alloc]init];
    [arrRecipients addObject:@"xxxxxxx@gmail.com"];

    MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
    mailController.mailComposeDelegate = self;
    [mailController setSubject:@"Ravikiran test mail"];
    [mailController setToRecipients:arrRecipients];

    [mailController setMessageBody:@"this is my test app" isHTML:YES];
    [self presentModalViewController:mailController animated:YES];
    [mailController release];
}

it is sending mail but it is navigating to mail composer page  & then its sending but i need to send mail just on click of the button

A: No, you cannot use MFMailComposeViewController to send an email without user interaction.  There are probably 3rd parties libraries that let you do this, but the iOS SDK does not allow you to.
Also, you're leaking the arrRecipients array.

A: Best way for your needs is to have a web service  which sends the data to an email id.
its always to good to inform the user in some way before sending the mail.
Thanks!


text:
Q: Ruby Unit-testin, wrong numer of failures shown Situation is simple. I have a module like this(first.rb):
def ret_s(l)
  return "one" if l == 1
  return "twoe" if l == 2
  return "threee" if l == 3
end

def ret_l(str)
  return 1 if str == "one"
  return 2 if str == "two"
  return 4 if str == "three"
end

and a testing class(TestFist.rb):
require 'test/unit'
require './first'

class TestFirst < Test::Unit::TestCase

  def test_fist

    assert_equal("one",ret_s(1))
    assert_equal("two",ret_s(2))
    assert_equal("three",ret_s(3))
  end

  def test_second

    assert_equal(1,ret_l("one"))
    assert_equal(2,ret_l("two"))
    assert_equal(3,ret_l("three"))
  end

end

When running this test, why do I get an answer like this:
$ ruby TestFirst.rb
Run options:

# Running tests:

FF

Finished tests in 0.001000s, 2000.0000 tests/s, 5000.0000 assertions/s.

  1) Failure:
test_fist(TestFirst) [TestFirst.rb:9]:
<"two"> expected but was
<"twoe">.

  2) Failure:
test_second(TestFirst) [TestFirst.rb:17]:
<3> expected but was
<4>.

2 tests, 5 assertions, 2 failures, 0 errors, 0 skips

The last line makes me think that I'm doing something wrong. I would expect something like this:
2 tests, 6 assertions, 3 failures, 0 errors, 0 skips
not
2 tests, 5 assertions, 2 failures, 0 errors, 0 skips

A: The first test aborts after the first failed assertion, thus it never executes the line assert_equal("three",ret_s(3))


text:
Q: Make favorite tags to show on the left bar It would be nice to have your favorite/watched tags to show up on the left column. This way I can quickly go to the tags of interest when I visit a site.

A: You can add lists (and not just of your favorite tags) to the right sidebar (of the questions tab) by adding filters:


text:
Q: How can I toggle selected pulseeffects equalizer profile from command line? I have pulseeffects installed and running. I have created a few equalizer profiles.
How can I toggle (enable/disable) selected profile using command line options.
I know I can just click on the profile but I would like to bind that to some global key to toggle it when needed. How can I do that?
I know I can load selected preset by using (where v2 is a profile name):
   $ pulseeffects -l v2

But how can I disable (unload) this profile ?
Screenshot:

A: For example, if you have 3 profiles like V1, V2 & V3 and you would like to select profile V1, you can run the below command
gsettings set com.github.wwmm.pulseeffects last-used-preset 'V1'

If you dont want this, you can use below command
gsettings reset com.github.wwmm.pulseeffects last-used-preset

you can create a script with below content and call it with a shortcut you wish.
#!/usr/bin/env bash

key="com.github.wwmm.pulseeffects last-used-preset"
current=$(gsettings get "$key")

if [ "$current" == "'V1'" ]; then
  gsettings reset "$key"
else
  gsettings set "$key" "V1"
fi

Courtesy by @MichalPrzbylowicz for toggling on and off
dconf write /com/github/wwmm/pulseeffects/sinkinputs/equalizer/state true
dconf write /com/github/wwmm/pulseeffects/sinkinputs/equalizer/state false


text:
Q: How to prove that the weighted $l_1$ norm enhance the sparsity more than the traditional $l_1$norm The weighted $l_1$ norm minimization can enhance the sparsity performance in comparison with traditional $l_1$ norm minimization, that is $$ \min_{x\in \mathbb{R}^{n\times n}} ||wx||_1  > \min_{x\in \mathbb{R}^{n\times n}} ||x||_1, $$
where $A>B$ denotes that the entry $A$ has much more sparsity than the entry $B$.
How can I prove this in case the weights are from the derivative of the function $\phi(x)=\frac{x}{x+\epsilon}$, $\epsilon>0$?
Thank you.


text:
Q: What is the difference between loadingIndicatorSource and defaultSource props in react-native? The defination for loadingIndicatorSource and defaultSource properties are almost same for both.
Please, can anyone tell what is the difference between loadingIndicatorSource and defaultSource props in react-native?

A: Well as you said they are really similar but personally i would use
defaultSource for a placeholder image (A static image to display while loading the image source.)
while
loadingIndicatorSource you can use it to display a spinner while waiting the image is loaded
Not such an useful answer but hope it will help!
Bye!

A: On react native: "0.64.2", defaultSource and loadingIndicatorSource are not working.


text:
Q: How to record and playback with NAudio using AsioOut I'm trying to get the sound input and send output directly with less latency possible with C#.
I'm using the library NAudio that supports ASIO for better latency.
In particular, I use the AsioOut object for recording and another for playback initialized with a BufferedWaveProvider, which is filled in a Callback function: OnAudioAvailable, which allows me to use the ASIO buffers.
The problem is that I hear the sound with various glitches and with a bit of delay. I think the problem is in the function OnAudioAvailable where the buffer is filled with data taken as input from the sound card.
Declarations:
NAudio.Wave.AsioOut playAsio;
NAudio.Wave.AsioOut recAsio;
NAudio.Wave.BufferedWaveProvider buffer;

Play procedure:
if (sourceList.SelectedItems.Count == 0) return;

int deviceNumber = sourceList.SelectedItems[0].Index;

recAsio = new NAudio.Wave.AsioOut(deviceNumber);
recAsio.InitRecordAndPlayback(null, 2, 44100); //rec channel = 1

NAudio.Wave.WaveFormat formato = new NAudio.Wave.WaveFormat();
buffer = new NAudio.Wave.BufferedWaveProvider(formato);

recAsio.AudioAvailable += new EventHandler<NAudio.Wave.AsioAudioAvailableEventArgs>(OnAudioAvailable);

//Collego l'output col buffer
playAsio = new NAudio.Wave.AsioOut(deviceNumber);
playAsio.Init(buffer);

//Registro
recAsio.Play();
//Playback
playAsio.Play();

OnAudioAvailable():
//Callback
private unsafe void OnAudioAvailable(object sender, NAudio.Wave.AsioAudioAvailableEventArgs e)
{
    //Copio tutti gli elementi di InputBuffers in buf e li aggiungo in coda al buffer
    byte[] buf = new byte[e.SamplesPerBuffer];
    for (int i = 0; i < e.InputBuffers.Length; i++)
    {
        Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer);
        //Aggiungo in coda al buffer
        buffer.AddSamples(buf, 0, buf.Length);
    }
}

AsioAudioAvailableEventArgs definition:
public AsioAudioAvailableEventArgs(IntPtr[] inputBuffers, int samplesPerBuffer, AsioSampleType asioSampleType);
public float[] GetAsInterleavedSamples();

Does anyone know how to fix it?
Thank you all.

A: You should not be using two instances of AsioOut for the same device. I'm surprised this works at all. Just use the one, with InitRecordAndPlayback.
For absolute minimal latency for pass-through monitoring, in AudioAvailableEvent, copy directly to the OutputBuffers, and set WrittenToOutputBuffers = true. This means you don't need a BufferedWaveProvider.
Also remember that any glitches are simply due to you not managing to process the AudioAvailable event quickly enough. When you're working with ASIO, you can be at very low latencies (e.g. sub 10ms), and can be dealing with lots of data (e.g. 96kHz sample rates, 8 channels of input and output). So you need to do a lot of moving of data in a short time window. With .NET, you have to factor in the unfortunate  fact that the garbage collector could kick in at any time and cause you to miss a buffer from time to time.


text:
Q: Jenkins: Build when a branch is tagged (Git newcomer here) I'm trying to implement a system whereby a Jenkins build is triggered when a tag is pushed to a specific branch. Currently, my supervisor has installed a simple PoC where, on our API servers (which run node.js), a cron job is ran every 5 minutes that runs:
git checkout production
git pull
git checkout `git describe --abbrev=0 --tags`

So when a developer wants to push a change to production, they simply run npm version patch which tags the latest commit with a new version number, then pushes the change using git push origin --tags. Then, they run a script via Jenkins that restarts all API services on API boxes.
So, to emulate this and fully automate it, I want to have a Jenkins job that does all of this (plus some extras) when it detects our production branch has been tagged with a new version.
Is this possible? Most documentation I've found involves triggering a build on ANY tag pushed to a repo. I want to trigger on a tag pointing to a commit to a specific repo.
I'm fairly certain this is an advanced case, and I could write some script to do it instead, but I'm attempting to learn best practices for Jenkins and git, and I don't want to end up adhering to some anti-pattern.

A: I have no clue how Jenkins actually gets used, so this answer may be quite useless.
In Git, however, if you plan to use a detached HEAD like this, all you need is to run git describe twice, once before fetching, and once after:
otag=$(git describe --tags --abbrev=0 origin/production) ||
    die "help, no initial tag"
git fetch origin
ntag=$(git describe --tags --abbrev=0 origin/production) ||
    die "help, no new tag"
if [ "$otag" = "$ntag" ]; then
    echo the tag we would check out now is the same as the one
    echo we checked out last time, so we do nothing
else
    echo moving from tag: $otag to tag: $ntag
    git checkout $ntag
    ... build ...
fi

git describe allows you to specify the commit you want described, so there is no need to check out a branch, fetch, and merge-and-hope-it's-a-fast-forward.
Note that this allows the local branch production to get progressively more and more out of date, or even simply to not exist at all, because the local branch is never really used.  The only thing it is giving you in your example code is its upstream setting.


text:
Q: synproxy on a bridge I am trying to implement synproxy to my firewall, on a bridge interface (between eth1 and eth2). Here are my rules:
/usr/local/sbin/iptables -t raw -i PREROUTING -i br0 -m physdev --physdev-in eth1 -p tcp -m tcp --syn -j CT --notrack
/usr/local/sbin/iptables -A FORWARD -i br0 -m physdev --physdev-in eth1 -p tcp -m tcp -m state --state INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460
echo 0 > /proc/sys/net/netfilter/nf_conntrack_tcp_loose

I have a client connecting to eth1 and http server (192.168.0.1) connecting to eth2.
With these rules, when I try to run curl 192.168.0.1 from the client I got timeout. It seems that the normal tcp request would not pass through.
When I run tcpdump on br0 I don't see any syn-ack and ack packets. Seems all syn packets got lost in the synproxy target.
Any ideas?

A: While sending syn-ack replies synproxy module looks your route table.
You should add needed route so that it can send syn-ack replies based on given routes.


text:
Q: Why would bash variables not expand in while loop I have a little script that reads a json file:
{
    "path": "$HOME/Projects:$HOME/Github"
}

I want to read path value, split on colon : and then read out the two paths with $HOME expanded.
#!/bin/sh
path_list="$(jq -r '.path' < "$JSON_FILE" | tr ':' '\n')"
echo "$path_list" | while IFS= read -r line; do
    echo "$line"
done;

The output is not what I would expect:
$HOME/Projects
$HOME/Github

Yet when I run echo "$HOME/Projects" the $HOME parameter expands fine.
Initially, I thought that I needed double quotes around the variable so I tried echo "\"${line}\"" and that just prints "$HOME/projects". I am confused. Can anyone please shed some light on this for me or point to a good tutorial on bash parameter expansion?
Regarding another SO question addressing similar issue. I do not think this is the same because that OP was asking about expanding strings loaded from a file. I do not think that is the dominant concern in my question. Other responses to this question involve using eval which I would like to because users will be entering their own inputs. Other solutions rely on external packages like gettext. I believe there should be a straight forward answer here.

A: Solved by adding 'eval':
#!/bin/sh
path_list="$(jq -r '.path' < "$JSON_FILE" | tr ':' '\n')"
echo "$path_list" | while IFS= read -r line; do
    eval echo "$line"
done;

More info: https://unix.stackexchange.com/questions/23111/what-is-the-eval-command-in-bash


text:
Q: Ambiguous column name, yet use "." to specify table When the following query is sent to my database:
SELECT statemachines.statemachinename,
states.statename,
actionhandlers.actionhandler,
actions.value, actions.sourcename
FROM actions, actionhandlers, states, statemachines
INNER JOIN rules ON (actions.rule_id AND rules.rule_id)
INNER JOIN actionhandlers ON (actions.actionhandler AND actionhandlers.actionhandler)
INNER JOIN states ON (states.state_id AND actions.state_id)
INNER JOIN statemachines ON (states.statemachinename AND statemachines.statemachinename)
WHERE (rules.eventname = 'PIR') AND (statemachines.currentstate = states.state_id)

The following error is returned:
 android.database.sqlite.SQLiteException: ambiguous column name: statemachines.statemachinename (code 1): , while compiling:

I have no clue what to do, all my other queries work.

A: You use statemachines twice. Once in the JOIN clause and once in the FROM.
Name one of them:
...
FROM actions, actionhandlers, states, statemachines AS statemachines1
...

A: Simplify: FROM actions, actionhandlers, states, statemachines => FROM actions


text:
Q: Why is half the sum of positive roots equal to the sum of fundamental weights? Let $\mathfrak{g}$ be a semisimple lie algebra. Let $\alpha_1,.., \alpha_n$ form a simple root system, and let the corresponding system of fundamental weights be $\lambda_1,..,\lambda_n$. I have been told that $\frac{1}{2} \sum_{\alpha \in \Delta^+} \alpha = \lambda_1 + ... + \lambda_n$.
However, I have difficulty in seeing why this can be true. For example, in the sl(3) case, the positive roots are $e_1  - e_2, e_2 - e_3, e_1 - e_3$, where $e_i \in \mathfrak{h}^*$ is the functional which pulls out the $i$'th diagonal element. $\frac{1}{2} \sum_{\alpha \in \Delta^+} \alpha = e_1 - e_3$. However, in this case, if we take the simple root system $\alpha_1 = e_1 - e_2, \alpha_2 = e_2 - e_3$, then $\lambda_i = e_1 + .. + e_i$, and so $\lambda_1 + \lambda_2 = 2e_1 + e_2$. Where does my reasoning go wrong in the sl(3) case?
And why is it true that the sum of fundamental weights is equal to half the sum of positive roots?

A: Nothing is wrong with your reasoning for sl(3).  Remember that in sl(3), there is the additional relation $e_1 + e_2 + e_3 = 0$, because the trace of a matrix in sl(3) is 0. So $e_1 - e_3 = 2e_1 + e_2$.


text:
Q: leaflet.js:6 Uncaught TypeError: Cannot read property 'lat' of null
i develop example web page that view open street map  and read data from sql server database by Json (javascript)

and let me this error
leaflet.js:6 Uncaught TypeError: Cannot read property 'lat' of null
the function return data successfully from database

 Model file
here return data by json
        [HttpPost]
    public JsonResult GetMap()
    {
        var data1 = (from p in db.Map
                     select new
                     {
                         Name = p.Name,
                         Latitude = p.Latitude,
                         Logitude = p.Logitude,
                         Location = p.Location,
                         Description = p.Description,
                         Id = p.Id
                     }).ToList().Select(res => new Map
                {
                    Name = res.Name,
                    Latitude = res.Latitude,
                    Logitude = res.Logitude,
                    Location = res.Location,
                    Description = res.Description,
                    Id = res.Id

                });
        return Json(data1, JsonRequestBehavior.AllowGet);

    }

 View file
here get data from json function  and get data successfully

A: Actually it is a linq query and those are deferred execution which means it only gets executed when we are just going to consume it, so you are just passing the IQueryable object to JSON method and the time it returns back it is not materialized with result.
You need to materialize the result using ToList() method when passing to JSON method.
Just change your last line to:
return Json(data1.ToList(), JsonRequestBehavior.AllowGet);

Now the EF will execute the query on the database server and will fetch the result and populate in the List<T> object.
Hope it helps!


text:
Q: Keeping local temp table alive I need to pass data among a list of stored procedures. The way this needs to be done is by using a local temp table.
var createTempTableCommand = new SqlCommand("Create table #mytemptable ....", myconnection);

using (SqlDataReader dr = createTempTableCommand.ExecuteReader())
{
   // ...
}

foreach(command in listOfSqlCommands)
{
    using (SqlDataReader dr = command.ExecuteReader())
    {
        dtResults.Load(dr);
    }
}

How do I ensure that the temp table that has been created #mytemptable remains intact during the foreach iteration?


text:
Q: Browsing is slow on LAN but works fine on wireless Internet works perfectly on every other router, but browsing sucks at home (slow browsing and slow loading times). I changed DNS servers to 8.8.0.0, still doesn't help. And funnily, download speed is extremely high on this network (meaning torrents for example), but using browsers and loading websites is extremely slow (only on this network). Do I need to change something in router settings or what can I try? By the way, I use wired connection to router. Also, there's problem with the whole computer, it is much slower overall.
EDIT: There's no problem when using Windows.
EDIT:
$ ifconfig

 eth0      Link encap:Ethernet  HWaddr f2:4d:a0:c0:3f:4c
           inet addr:192.168.11.8  Bcast:192.168.11.255  Mask:255.255.255.0
           inet6 addr: fe80::f24d:a2ff:fec6:3f4c/64 Scope:Link
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:206798 errors:0 dropped:0 overruns:0 frame:0
           TX packets:219570 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000
           RX bytes:76680734 (76.6 MB)  TX bytes:21738160 (21.7 MB)

 lo        Link encap:Local Loopback
           inet addr:127.0.0.1  Mask:255.0.0.0
           inet6 addr: ::1/128 Scope:Host
           UP LOOPBACK RUNNING  MTU:65536  Metric:1
           RX packets:160 errors:0 dropped:0 overruns:0 frame:0
           TX packets:160 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:0
           RX bytes:11094 (11.0 KB)  TX bytes:11094 (11.0 KB)

$ ping -c 2 4.2.2.2

PING 4.2.2.2 (4.2.2.2) 56(84) bytes of data.

--- 4.2.2.2 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms

$ ping -c 2 google.com

PING google.com (213.159.32.147) 56(84) bytes of data. 64 bytes from
lan-213-159-32-147.kns.skynet.lv (213.159.32.147): icmp_seq=1 ttl=61
time=0.936 ms 64 bytes from lan-213-159-32-147.kns.skynet.lv
(213.159.32.147): icmp_seq=2 ttl=61 time=0.937 ms

--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.936/0.936/0.937/0.030 ms

A: Your symptoms do suggest your first DNS is invalid, so there's a timeout period, then your second DNS is able to resolve addresses correctly and you start seeing things loading.
Of course, once the connection is established, transfers are fast, as you noted.
Unless I'm missing something, 8.8.0.0 is NOT a valid DNS, which suggests this is your problem:
$ dig @8.8.0.0 yahoo.com

; <<>> DiG 9.9.5-3-Ubuntu <<>> @8.8.0.0 yahoo.com
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

If you meant to use Google DNS, the correct addresses are 8.8.8.8 and 8.8.4.4:
$ dig @8.8.8.8 yahoo.com

; <<>> DiG 9.9.5-3-Ubuntu <<>> @8.8.8.8 yahoo.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 32669
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;yahoo.com.         IN  A

;; ANSWER SECTION:
yahoo.com.      1205    IN  A   98.138.253.109
yahoo.com.      1205    IN  A   98.139.183.24
yahoo.com.      1205    IN  A   206.190.36.45

;; Query time: 32 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Sat Jun 07 21:20:40 EDT 2014
;; MSG SIZE  rcvd: 86

A: Your ISP is screwing with your connection. You cannot get directly to the internet as indicated by failed pings to 4.2.2.2 Then PING google.com (213.159.32.147) shows that your ISP is redirecting your DNS  213.159.32.147 is NOT google's IP but belongs tolan-213-159-32-147.vln.skynet.lt which is probably your router or local proxy/cache because latency is so low less than 1ms. So when you think you're pinging google, you're actually pinging some proxy owned by skynet.lv It's not a satellite internet is it? You might have a "fat pipe" can get a lot of data at a time (that would explain fast torrents and big file downloads) but high latency (meaning it takes a while for a packet to reach it's destination). So your big files download would seem "fast" but browsing VOiP and other activities that don't require much data but need fast response would seem slow. try ping -c 2 ir1.fp.vip.gq1.yahoo.com or some other odd domain you never visited and look at the time if it's > 100ms that would be your problem if it's < 3ms then it's your ISPs server. You can also try tracepath somedomain.com

A: You're probably on the right track to specify a name server.  The one you choose (8.8.0.0) doesn't resolve, and would end up adding lookup time to your browsing.  Try specifying (8.8.8.8) instead.
Also try using the resolveconf's header file function so that you can leave all the other default's from your dhcp untouched and just add a nameserver header.
Update your /etc/resolvconf/resolv.conf.d/head to:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN

nameserver 8.8.8.8

By the way, I don't know why the file defaults to saying do not edit by hand.  I believe the purpose of the file is to edit by hand.  It's really the /etc/resolv.conf file that is overwritten.


text:
Q: Liferay permissions on web content I have created role (content editor) who is able to edit journal articles.
In our application we have homepage with web-content(journal article) and we need to disable editing only this web content to all roles (except admin role).
How to achieve this scenario?


text:
Q: Changing a Vanilla Item in Minecraft Forge 1.18.2 So, I'm new to modding Minecraft, and I want to change the Grass Block. All the tutorials I have found so far, however, are for older versions, and what they suggest simply doesn't seem to work anymore. Right now I am trying to register a new Block like this:
public static final RegistryObject<Block> GRASS_BLOCK = registerBlock("minecraft:grass_block", () -> new SiltBlock(BlockBehaviour.Properties.copy(Blocks.DIRT)), CreativeModeTab.TAB_BUILDING_BLOCKS);

private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block, CreativeModeTab tab) {
    RegistryObject<T> toReturn = BLOCKS.register(name, block);
    return toReturn;
}

Interestingly, while my normal registrations work this way, this one doesn't just not work, it actually causes an error when loading the Mod. It seems like I'm on the right track, apparently already accessing the Vanilla Block, but I do not know what is going wrong.

A: i found out recently that it's very simple.
Simply create another DeferredRegister and replace your mod id with "minecraft". So the code should be like:
public static final DeferredRegister<Block> VANILLA_BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, "minecraft");

public static final RegistryObject<Block> GRASS_BLOCK = registerBlock("grass_block", () -> new SiltBlock(BlockBehaviour.Properties.copy(Blocks.DIRT)), CreativeModeTab.TAB_BUILDING_BLOCKS);

private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block, CreativeModeTab tab) {
        RegistryObject<T> toReturn = VANILLA_BLOCKS.register(name, block);
        return toReturn;
    }

And don't forget to registry the deferred register in the main file:
VANILLA_BLOCKS.register(eventBus);


text:
Q: All triplet combinations, 6 values at a time I am looking for an algorithm to efficiently to generate all three value combinations of a dataset by picking 6 values at a time.
I am looking for an algorithm to efficiently generate a small set of 6-tuples that cumulatively express all possible 3-tuple combinations of a dataset.
For instance, computing playing-card hands of 6 cards that express all possible 3 card combinations.
For example, given a dataset:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

The first "pick" of 6 values might be:
['a','b','c','d','e','f']

And this covers the three-value combinations:
('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'b', 'e'), ('a', 'b', 'f'), ('a', 'c', 'd'),
('a', 'c', 'e'), ('a', 'c', 'f'), ('a', 'd', 'e'), ('a', 'd', 'f'), ('a', 'e', 'f'),
('b', 'c', 'd'), ('b', 'c', 'e'), ('b', 'c', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'),
('b', 'e', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f'), ('c', 'e', 'f'), ('d', 'e', 'f')

It is obviously possible by:

*

*computing all triplet combinations

*picking 6 values

*computing all triplet combinations for those 6 values

*removing these combinations from the first computation

*repeating until all have been accounted for

In this example there are 2600 possible triplet combinations (26*25*24)/(3*2*1) == 2600 and using the "brute-force" method above, all triplet combinations can be represented in around 301 6-value groups.
However, it feels like there ought to be a more efficient way of achieving this.
My preferred language is python, but I'm planning on implementing this in C++.

Update
Here's my python code to "brute-force" it:
from itertools import combinations
data_set = list('abcdefghijklmnopqrstuvwxyz')

def calculate(data_set):
  all_triplets = list(frozenset(x) for x in itertools.combinations(data_set,3))
  data = set(all_triplets)
  sextuples = []
  while data:
    sxt = set()
    for item in data:
      nxt = sxt | item
      if len(nxt) > 6:
        continue
      sxt = nxt
      if len(nxt) == 6:
        break
    sextuples.append(list(sxt))
    covers = set(frozenset(x) for x in combinations(list(sxt),3))
    data = data - covers
    print "%r\t%s" % (list(sxt),len(data))
  print "Completed %s triplets in %s sextuples" % (len(all_triplets),len(sextuples),)

calculate(data_set)

Completed 2600 triplets in 301 sextuples

I'm looking for something more computationally efficient than this.

Update
Senderle has provided an interesting solution: to divide the dataset into pairs then generate all possible triplets of the pairs. This is definitely better than anything I'd come up with.
Here's a quick function to check whether all triplets are covered and assess the redundancy of triplet coverage:
from itertools import combinations
def check_coverage(data_set,sextuplets):
  all_triplets = dict.fromkeys(combinations(data_set,3),0)
  sxt_count = 0
  for sxt in sextuplets:
    sxt_count += 1
    for triplet in combinations(sxt,3):
      all_triplets[triplet] += 1
  total = len(all_triplets)
  biggest_overlap = overlap = nohits = onehits = morehits = 0
  for k,v in all_triplets.iteritems():
    if v == 0:
      nohits += 1
    elif v == 1:
      onehits += 1
    else:
      morehits += 1
      overlap += v - 1
    if v > biggest_overlap:
      biggest_overlap = v
  print "All Triplets in dataset: %6d" % (total,)
  print "Total triplets from sxt: %6d" % (total + overlap,)
  print "Number of sextuples:     %6d\n" % (sxt_count,)
  print "Missed  %6d of %6d: %6.1f%%" % (nohits,total,100.0*nohits/total)
  print "HitOnce %6d of %6d: %6.1f%%" % (onehits,total,100.0*onehits/total)
  print "HitMore %6d of %6d: %6.1f%%" % (morehits,total,100.0*morehits/total)
  print "Overlap %6d of %6d: %6.1f%%" % (overlap,total,100.0*overlap/total)
  print "Biggest Overlap: %3d" % (biggest_overlap,)

Using Senderle's sextuplets generator I'm fascinated to observe that the repeated triplets are localised and as the datasets increase in size, the repeats become proportionally more localised and the peak repeat larger.

>>> check_coverage(range(26),sextuplets(range(26)))
All Triplets in dataset:   2600
Total triplets from sxt:   5720
Number of sextuples:        286

Missed       0 of   2600:    0.0%
HitOnce   2288 of   2600:   88.0%
HitMore    312 of   2600:   12.0%
Overlap   3120 of   2600:  120.0%
Biggest Overlap:  11

>>> check_coverage(range(40),sextuplets(range(40)))
All Triplets in dataset:   9880
Total triplets from sxt:  22800
Number of sextuples:       1140

Missed       0 of   9880:    0.0%
HitOnce   9120 of   9880:   92.3%
HitMore    760 of   9880:    7.7%
Overlap  12920 of   9880:  130.8%
Biggest Overlap:  18

>>> check_coverage(range(80),sextuplets(range(80)))
All Triplets in dataset:  82160
Total triplets from sxt: 197600
Number of sextuples:       9880

Missed       0 of  82160:    0.0%
HitOnce  79040 of  82160:   96.2%
HitMore   3120 of  82160:    3.8%
Overlap 115440 of  82160:  140.5%
Biggest Overlap:  38

A: I believe the following produces correct results. It relies on the intuition that to generate all necessary sextuplets, all that is necessary is to generate all possible combinations of arbitrary pairs of items. This "mixes" values together well enough that all possible triplets are represented.
There's a slight wrinkle. For an odd number of items, one pair isn't a pair at all, so you can't generate a sextuplet from it, but the value still needs to be represented. This does some gymnastics to sidestep that problem; there might be a better way, but I'm not sure what it is.
from itertools import izip_longest, islice, combinations

def sextuplets(seq, _fillvalue=object()):
    if len(seq) < 6:
        yield [tuple(seq)]
        return
    it = iter(seq)
    pairs = izip_longest(it, it, fillvalue=_fillvalue)
    sextuplets = (a + b + c for a, b, c in combinations(pairs, 3))
    for st in sextuplets:
        if st[-1] == _fillvalue:
            # replace fill value with valid item not in sextuplet
            # while maintaining original order
            for i, (x, y) in enumerate(zip(st, seq)):
                if x != y:
                    st = st[0:i] + (y,) + st[i:-1]
                    break
        yield st

I tested it on sequences of items of length 10 to 80, and it generates correct results in all cases. I don't have a proof that this will give correct results for all sequences though. I also don't have a proof that this is a minimal set of sextuplets. But I'd love to hear a proof of either, if anyone can come up with one.
>>> def gen_triplets_from_sextuplets(st):
...     triplets = [combinations(s, 3) for s in st]
...     return set(t for trip in triplets for t in trip)
...
>>> test_items = [xrange(n) for n in range(10, 80)]
>>> triplets = [set(combinations(i, 3)) for i in test_items]
>>> st_triplets = [gen_triplets_from_sextuplets(sextuplets(i))
                   for i in test_items]
>>> all(t == s for t, s in zip(triplets, st_triplets))
True

Although I already said so, I'll point out again that this is an inefficient way to actually generate triplets, as it produces duplicates.
>>> def gen_triplet_list_from_sextuplets(st):
...     triplets = [combinations(s, 3) for s in st]
...     return list(t for trip in triplets for t in trip)
...
>>> tlist = gen_triplet_list_from_sextuplets(sextuplets(range(10)))
>>> len(tlist)
200
>>> len(set(tlist))
120
>>> tlist = gen_triplet_list_from_sextuplets(sextuplets(range(80)))
>>> len(tlist)
197600
>>> len(set(tlist))
82160

Indeed, although theoretically you should get a speedup...
>>> len(list(sextuplets(range(80))))
9880

... itertools.combinations still outperforms sextuplets for small sequences:
>>> %timeit list(sextuplets(range(20)))
10000 loops, best of 3: 68.4 us per loop
>>> %timeit list(combinations(range(20), 3))
10000 loops, best of 3: 55.1 us per loop

And it's still competitive with sextuplets for medium-sized sequences:
>>> %timeit list(sextuplets(range(200)))
10 loops, best of 3: 96.6 ms per loop
>>> %timeit list(combinations(range(200), 3))
10 loops, best of 3: 167 ms per loop

Unless you're working with very large sequences, I'm not sure this is worth the trouble. (Still, it was an interesting problem.)


text:
Q: core data invalid redeclaration of class So, I have a got a problem…
 when I intend to create a NSManagedObject Subclass.
As you can see this problem is really spread widely. Many people propose a solution by changing codegen block into Manual/None. But this did not help me, furthermore Class Definition and Category/Extension did not resolve too.
When I delete two files which were created by tapping in Product/Create NSManagedObject, the code is really works. I didn't why but I could use a NSManObject classes like they are lying somewhere I found a path where they are existing.

I thought If I delete them then I can recreate subclass again and use it successfully. But it is not. When I create again a subclass files these two files that were lying in unknown directory were recreated again! I ask the people who encountered to this problem and I need their help or solution

A: There's an annoying bug in the core data codegen settings, which means that updated settings aren't stored correctly.
If you change the codegen settings and then Build or Run, your changes will not be saved. For example, if you changed from Category/Extension to None and deleted the generated file, it will be recreated.
To solve this problem…

*

*Change your codegen settings

*Save the .xcdatamodel file.

*Close all project windows.

*Re-open the project.

A: I tested for different Core Data data model class codegen settings. When it's set to Class Definition or Category/Extension. The builder will generate subclass files automatically. So we don't need to add these files by ourselves. The following is files generated by builder.


text:
Q: Can d3 draw pfam domain Just a quick question.
Can I use d3 to draw protein domains like the following?
Image of a protein domain
My plan is to attach these little protein domains to a tree, which would look awesome.
Thanks a lot in advance!


text:
Q: A question about the proof of Ito's theorem (Metabelian)
Let $G = AB$, where $A$ and $B$ are abelian subgroups of $G$. Then
$G'$ is abelian.

That is the first part of Ito's theorem, of which the proof has always been well-known for its simplicity.
Ito's basic idea :
$(i)$ $[\,A, B~]=G'$.
$(ii)$ All elements of the form $a^{-1}b^{-1}ab\,(a\in A,\,b\in B\,)$ are commutative. That is, $[\,A, B~]$ is abelian.
My questions :
It is $(i)$ that confuses me. In the paper, Ito said that, for $(i)$, it suffices to show $[\,A, B~]$ is invariant under similarity transformations with all $a\in A$, $b\in B$, in the third paragraph of the first page.
Why? What does that mean? I can see something, though, the reason is still very much not clear to me.
Once in Jack Schmidt's answer it was mentioned that equation $(1)(2)$ help to show $$[\,A, B~]=[\,AB, AB~]~(=[\,G, G~]=G').$$
I believe so, but how can I manage to do it?
Any help will be welcome.
PS:
[1] An alternative link to the proof is here.

A: Write $[x,y] = x^{-1} y^{-1} xy$ and $x^y = y^{-1} xy$. Then we have the identities $[x, yz] = [x,z] [x,y]^z$ and $[xy,z] = [x,z]^y [y,z]$.
Now if $G = AB$, you see from the identities that each commutator in $G$ is a product of conjugates of some commutators $[a,b]$ or $[b,a]$ with $a \in A$ and $b \in B$.
Thus if you are able to show that the set $\{[a,b] : a \in A, b \in B\}$ is invariant under conjugation by elements of $A$ and $B$, it follows that $[G,G] = [A,B]$.

A: Mikko Korhonen's answer and Derek Holt's comments are perfect for my questions, and I'd like to sort out my thoughts by adding a fully-detailed one.

Define $[x,y] = x^{-1} y^{-1} xy$ and $x^y = y^{-1} xy$. It's easy to show the identities  $[x, yz] = [x,z] [x,y]^z$ and $[xy,z] = [x,z]^y [y,z]$.
Since $G =AB$, for all $g_1,\,g_2\in G$, there exist $a_1,\,a_2\in A $, $b_1,\,b_2\in B $ such that $g_1= a_1 b_1 $, $g_2= a_2b_2. $ Therefore, ( the result can vary according to the convention of writing $g=ab[\text{or } ba]$ and how we use the identities )
$$[g_1, g_2]= [a_1b_1, a_2b_2]=[a_1 b_1, b_2] [a_1 b_1, a_2]^{b_2}=\left([a_1,b_2]^{b_1}\cdot [b_1,b_2]  \right)\cdot\left([a_1,a_2]^{b_1}\cdot [b_1,a_2]\right) ^{b_2}=[a_1,b_2]^{b_1}\cdot[b_1,a_2]^{b_2}.$$
If we can show $[A,B]$ is invariant under conjugation by elements of $A$ and $B$, we will be able to get $G'=[A,B]$, since we have  $G'=[G,G]\subseteq [A,B]$.
That is "it suffices to show $[A, B]$ are invariant..." as Ito said.

That's for my first question. Next, let me add more details to the second one following Derek Holt's nice comment.

For all $a'\in A$, $b'\in B$, we now compute $[a,b]^{a'}$ and $[a,b]^{b'}$ with $A$, $B$ abelian:
\begin{align*}
[a,b]^{a'}=a'^{-1}(a^{-1}b^{-1}ab)\,a'&=a^{-1}a'^{-1}b^{-1}aba'\\&=a^{-1}a'^{-1}b^{-1}(a'a'^{-1})aba'=a^{-1}(a'^{-1}b^{-1}a')(a'^{-1}a)ba'\\&=a^{-1}(a'^{-1}b^{-1}a')\,a\,(a'^{-1}ba')=a^{-1}(a'^{-1}ba')^{-1}a\,(a'^{-1}b^{-1}a')=[a,b^{a'}]
\\&~\\
[a,b]^{b'}=b'^{-1}(a^{-1}b^{-1}ab)\,b'&=b'^{-1}a^{-1}b^{-1}ab'b\\&=b'^{-1}a^{-1}b^{-1}(b'b'^{-1})ab'b=b'^{-1}a^{-1}(b^{-1}b')(b'^{-1}ab')b\\&=(b'^{-1}a^{-1}b')b^{-1}(b'^{-1}ab')b=(b'^{-1}ab')^{-1}b^{-1}(b'^{-1}ab')b=[a^{b'},b]
\end{align*}
$G=AB=BA$, so there exist $\widetilde{a},\,\widehat{a}\in A $, $\widetilde{b},\,\widehat{b}\in B $ such that $b^{a'} =\widetilde{a}\widetilde{b}$, $a^{b'} =\widehat{b} \widehat{a} $. However, due to one of communicator identities, $$[a,b]^{a'}=[a,b^{a'} ]=[a,\widetilde{a} \widetilde{b}]=[a, \widetilde{b}][a, \widetilde{a}]^{\widetilde{b}}= [a, \widetilde{b}]\in [A,B]; $$ $$
[a,b]^{b'}=[a^{b'},b ]=[\widehat{b} \widehat{a},b]= [\widehat{b}, b]^{\widehat{a}}[\widehat{a},b] =[\widehat{a}, b]\in [A,B]. $$
That is, $[A,B]$ is invariant under similarity transformations.
QED.


text:
Q: SQL Server need required output I  have a table which is represented below:
Country_ID | Country_name
-----------+-------------
    1      | India
    2      | Srilanka
    3      | South Africa
    4      | Australia

I now need a query that will present this data as below:
Match ID | Match Details
---------+---------------------------
    1    | India V/s Srilanka
    2    | India V/s South Africa
    3    | India V/s Australia
    4    | Srilanka V/s South Africa
    5    | Srilanka V/s Australia
    6    | South Africa V/s Australia

A: I guess you want to self join table with higher IDs
select
    row_number() over (order by a.country_id, b.country_id)
    , a.country_name + ' v/s ' + b.country_name
from
    myTable a
    join myTable b on a.country_id < b.country_id


text:
Q: The Xcode service is disabled on this server I'm trying to use OS X Server Xcode service integration.
In OS X Server, I'm sure to switch Xcode Service ON.
In Xcode Preference, Account tab, I select + and choose Add Server. I can see my Server appear in the list box. Then I fill the username and password, click Add, but the error "The Xcode service is disabled on this server" appear !!!

Someone hints that I should use IP address instead of selecting the Server name when adding Server. This works, but I then have many problems when adding remote repository or creating bots. Either Xcode asks for certificate, or shows "Server is offline", or crashes (crashes frequently!), ... I think they all relate to the previous Adding Server process.
So how to deal with this ?

A: Via the OS X Server app, click "Xcode" in the left sidebar and then make sure the Xcode "service" has been turned on via the slider at the top right:


text:
Q: How can I implement a cooldown on enderpearls? I want to make a private pvp server with my friends, and I am the only one that sort of knows how to program things, and I would like to know how to make enderpearl cooldowns, so you can only throw an enderpearl every 10s.

A: 1) Enderpearl cooldown is a vanilla feature in 1.9. You cannot affect the time it takes for them to recharge though.
2) To rename items without them being italicized, you need to download a third-party application such as NBT explorer, and edit the data of the item with it. There are plenty of online guides to do this. Be warned, you will be using this symbol a lot! §


text:
Q: how can i fix initialized error in springboot on kotlin? im trying make filter about authorization token in springboot on kotlin, below code  is filter
@Slf4j
class TokenFilter : Filter {

    private val log = LoggerFactory.getLogger(javaClass)

    @Throws(IOException::class, ServletException::class)
    override fun doFilter(servletRequest: ServletRequest?, servletResponse: ServletResponse?, filterChain: FilterChain) {
        val req = servletRequest as HttpServletRequest
        val res = servletResponse as HttpServletResponse
        val temp =req.getHeader("Authorization").split(" ")
        val tokenService: TokenService = TokenService()

        if(tokenService.check(s =temp.last())){
            log.info("트루")
        } else {
            log.info("거짓")
        }

        log.info("==========First 필터 시작!==========")
        filterChain.doFilter(servletRequest, servletResponse)
        log.info("==========First 필터 종료!==========")
    }

}

tokenService.kt
class TokenService{
    fun check(s: String): Boolean {
        lateinit var tokenRepository: TokenRepository
        var result = tokenRepository.findByToken("123123123123")
        return true
    }
}

tokenRepository.kt
interface TokenRepository: JpaRepository<Token, Long> {
    fun findByToken(token: String): Token
}

Find the token's user on the server when recive a request on server
It doesn't work normally and returns an error like below.
My guess is that the repository doesn't init properly.
But I don't know which part is wrong or how to fix it.
Can you give me some advice?
error
kotlin.UninitializedPropertyAccessException: lateinit property tokenRepository has not been initialized
at com.example.temp.common.token.service.TokenService.check(TokenService.kt:11) ~[main/:na]
at com.example.temp.common.token.TokenFilter.doFilter(TokenFilter.kt:35) ~[main/:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter.doFilterInternal(DefaultLogoutPageGeneratingFilter.java:58) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:237) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:223) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:223) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1787) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

A: You need to put the lateinit outside of your function:
class TokenService{
  lateinit var tokenRepository: TokenRepository

  fun check(s: String): Boolean {
    var result = tokenRepository.findByToken("123123123123")
    return true
  }
}

A: This won't work as you are creating a new instance of tokenService in doFilter val tokenService: TokenService = TokenService().
Even by putting the lateinit outside of your function Spring won't know your bean and will not inject the TokenRepository into the service.
To solve this inject the TokenService into TokenFilter via constructor injection. As there is now no excuse to use field injection at all use constructor injection to inject the TokenRepository into TokenService.
TokenFilter, TokenService and TokenRepository must be marked as Spring beans with @Component or equivalent. The ctor does not need any annotations as recent Spring releases are able to figure this out automatically.
Best way to inject component in Spring with Kotlin