text:
Q: arduino button doesn't work So I got a program, that must turn on/off the light by a press of a button, but it just doesn't work. It doesn't show anything in the console and the light doesn't turn off/on. It just stays on for a moment of time and then turns off
const int buttonPin = 3;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
int incoming = 0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  attachInterrupt(0, blink, CHANGE);

}

void blink()
{
  digitalWrite(ledPin, !digitalRead(buttonPin));
  if (!digitalRead(buttonPin)) {
    Serial.println("LED lights");
  } else {
    Serial.println("LED is off");
  }
}

void loop() {

  if (Serial.available() > 0) {
    incoming = Serial.read() - 48;
    analogWrite(ledPin, incoming * 29);
    Serial.print("LED brightness = ");
    Serial.println(incoming*29);

  }
}

A: In Arduino Uno, which you are using according to comments, the interrupt 0 is responsible for pin number 2 according to the docs. But you are using pin 3 as your input, so according to the same page it should use interrupt 1.

A: Why do you use the interrupt? I would suggest to use a simple state pattern by comparing the previous button state like in this code example from http://www.multiwingspan.co.uk
int ledPin = 13;
int buttonPin = 3;
int lastButtonState = HIGH;
int ledState = HIGH;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop()
{
  // read from the button pin
  int buttonState = digitalRead(buttonPin);
  // if the button is not in the same state as the last reading
  if (buttonState==LOW && buttonState!=lastButtonState)
  {
    // change the LED state
    if (ledState==HIGH)
    {
      ledState = LOW;
    }
    else
    {
      ledState = HIGH;
    }
  }
  digitalWrite(ledPin, ledState);
  // store the current button state
  lastButtonState = buttonState;
  // add a delay to avoid multiple presses being registered
  delay(20);
}


text:
Q: Hibernate Criteria is returning same value for different Restrictions in two consecutive calls Surprisingly I am getting same value for different Restrictions in two consecutive Criteria calls.
I am using Hibernate 4.2.20 final. Please refer my maven dependency.
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.2.20.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.2.20.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>

    <dependency>
       <groupId>org.hibernate.javax.persistence</groupId>
       <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
     </dependency>

My DAO code:
  public List<StockQuote> retrieve(final Date startDate, final Date endDate, final String companyName)
        throws StartDateAfterEndDateException
{

    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(StockQuote.class).createAlias("company", "c")
            .add(Restrictions.eq("c.name", companyName)).add(Restrictions.between("date", startDate, endDate))
            .addOrder(Order.asc("date"));

    return criteria.list();

}

If the above code is executed with the following:
  DateTime endDate = new DateTime(2016, 4, 24, 0, 0, 0);
    List<StockQuote> quotes;
    quotes = stockService.retrieve(endDate.toDate(), endDate.toDate(), "S&P CNX Nifty", org.technical.analysis.common.Period.DAILY );
    quotes = stockService.retrieve(endDate.toDate(), endDate.toDate(), "Associated Cements", org.technical.analysis.common.Period.DAILY );

Then both the cases I am getting same list of StockQuotes. Please note I have called my DAO method retrieve by different company name.
@Entity

@Table(name = "stockdata")
public class StockQuote {
private Company company;
private Date date;
private double open;
private double high;
private double low;
private double close;
private long volume;

/**
 * Empty constructor
 */
public StockQuote() {
}

/**
 * Constructor with arguments
 *
 * @param company The company
 * @param date Date of the quotation
 * @param open Open quote
 * @param high High quote
 * @param low Low quote
 * @param close Close quote
 * @param volume Volume of data
 */
public StockQuote(Company company, Date date, double open, double high, double low, double close, long volume) {
    this.company = company;
    this.date = date;
    this.open = open;
    this.high = high;
    this.low = low;
    this.close = close;
    this.volume = volume;
}

@ManyToOne
@JoinColumn(name = "companyId")
public Company getCompany() {
    return company;
}

public void setCompany(Company company) {
    this.company = company;
}

@Id
@Column(name = "date", nullable = false)
public Date getDate() {
    return this.date;
}

public void setDate(Date date) {
    this.date = date;
}

@Column(name = "open", nullable = false)
public double getOpen() {
    return this.open;
}

public void setOpen(double open) {
    this.open = open;
}

@Column(name = "high", nullable = false)
public double getHigh() {
    return this.high;
}

public void setHigh(double high) {
    this.high = high;
}

@Column(name = "low", nullable = false)
public double getLow() {
    return this.low;
}

public void setLow(double low) {
    this.low = low;
}

@Column(name = "close", nullable = false)
public double getClose() {
    return this.close;
}

public void setClose(double close) {
    this.close = close;
}

@Column(name = "volume", nullable = false)
public long getVolume() {
    return this.volume;
}

public void setVolume(long volume) {
    this.volume = volume;
}

@Override
public String toString() {
    return "StockQuote [" + company + ", date=" + date + ", open=" + open
            + ", high=" + high + ", low=" + low + ", close=" + close + ", volume=" + volume + "]";
}

@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    long temp;
    temp = Double.doubleToLongBits(close);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result + ((company == null) ? 0 : company.hashCode());
    result = prime * result + ((date == null) ? 0 : date.hashCode());
    temp = Double.doubleToLongBits(high);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    temp = Double.doubleToLongBits(low);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    temp = Double.doubleToLongBits(open);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result + (int) (volume ^ (volume >>> 32));
    return result;
}

@Override
public boolean equals(Object obj)
{
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    StockQuote other = (StockQuote) obj;
    DateTime otherDateTime = new DateTime(other.date);
    DateTime dateTime = new DateTime(date);
    if (Double.doubleToLongBits(close) != Double.doubleToLongBits(other.close))
        return false;
    if (company == null)
    {
        if (other.company != null)
            return false;
    }
    else if (!company.equals(other.company))
        return false;
    if (date == null)
    {
        if (other.date != null)
            return false;
    }
    else if (!(dateTime.getDayOfMonth() == otherDateTime.getDayOfMonth() &&
               dateTime.getMonthOfYear() == otherDateTime.getMonthOfYear() &&
               dateTime.getYear() == otherDateTime.getYear()))
        return false;
    if (Double.doubleToLongBits(high) != Double.doubleToLongBits(other.high))
        return false;
    if (Double.doubleToLongBits(low) != Double.doubleToLongBits(other.low))
        return false;
    if (Double.doubleToLongBits(open) != Double.doubleToLongBits(other.open))
        return false;
    if (volume != other.volume)
        return false;
    return true;
}

}
Please help me to resolve this issue.

A: After some research I have found that there was issue with @Id in StockQuote as per the first comment. So I have added a id column in the table of stockdata and made it as a Primary Key also updated StockQuote class. Now it is wokring fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kendo UI Treeview with check-boxes, Hierarchical Data Source not fully loaded Using the example at Kendo-ui Demo page I now have the following code
<script>
    var dataSource = new kendo.data.HierarchicalDataSource({
        data: [
            {
                id: 1, text: "Useraccess", expanded: true, items: [
                    { id: 2, text: "Roles", items: [
                        { id: 3, text: "Access", checked: true },
                        { id: 4, text: "Edit", checked: true }
                    ]},
                    { id: 5, text: "Users", items: [
                        { id: 6, text: "Access" },
                        { id: 7, text: "Edit" }
                    ]}
                ]
            },
            {
                id: 8, text: "Customer", expanded: true, items: [
                    { id: 9, text: "Customer", items: [
                        { id: 10, text: "Access" },
                        { id: 11, text: "Edit", checked: true }
                    ]},
                    { id: 12, text: "Account", items: [
                        { id: 13, text: "Access" },
                        { id: 14, text: "Edit" }
                    ]}
                ]
            }
        ]
    });

    $("#treeView").kendoTreeView({
        checkboxes: {
            checkChildren: true
        },
        dataSource: dataSource
    });

    // function that gathers IDs of checked nodes
    function checkedNodeIds(nodes, checkedNodes) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].checked && !nodes[i].hasChildren) {
                checkedNodes.push(nodes[i].id);
            }

            if (nodes[i].hasChildren) {
                checkedNodeIds(nodes[i].children.view(), checkedNodes);
            }
        }
    }

    function refreshResult() {
        var checkedNodes = [],
            treeView = $("#treeView").data("kendoTreeView"),
            message;

        checkedNodeIds(treeView.dataSource.view(), checkedNodes);

        if (checkedNodes.length > 0) {
            message = "IDs of checked nodes: " + checkedNodes.join(",");
        } else {
            message = "No nodes checked.";
        }

        $("#result").html(message);
    }

    // show checked node IDs on datasource change
    $("#treeView").data("kendoTreeView").dataSource.bind("change", function() {
        refreshResult();
    });

    refreshResult();
</script>

When the page is loaded, the result text is "No nodes checked.", even though there are indeed 3 nodes checked. While debugging, I noticed that even though the "Roles" node has the attribute hasChildren = true, the children array is empty. In the example in the Demo page, the data source is defined inside the TreeView:
 $("#treeview").kendoTreeView({
        checkboxes: {
            checkChildren: true
        },

        dataSource: [
            {
                id: 1, text: ....

When I define the data source inside the Treeview, the result text shows the correct nodes as selected. Is there a way to simulate that behaviour? I am planning to use remote data in the future.

A: I have found the answer in the TreeView API. The answer is here:
loadOnDemand TreeView configuration
So what I need to do is set loadOnDemand: false inside the TreeView:
$("#treeView").kendoTreeView({
loadOnDemand: false, ...


text:
Q: Ubuntu 12.04 running from an external hard drive freezes frequently I have the late-2009 model of the iMac (with the latest version of Lion) and I use a rEFIt CD frequently to switch from OS X to Ubuntu and vice versa.  Ubuntu 12.04 is installed on a partition of an external hard drive and the rest is used as a Time Machine.
I've noticed recently that at times, Ubuntu will suddenly freeze everything on the desktop except for the mouse.  When this happens, I can unplug the external hard drive and nothing happens; the mouse (Bluetooth) continues to function, but clicking or hovering over anything makes it useless. At this point, I have to manually hold down the Mac's power button and reboot to the rEFIt CD. I've installed the graphics driver it needs and at this point, I can't see what could cause it to freeze like this.  Should I just file a bug, or does anyone have any workaround suggestions to unresponsiveness?  Thanks in advance.
EDIT it appears that after installing 'nvidia-current,' I have not experienced freezing issues.  I'll update this post if it freezes again.

A: If the driver re-installation seems to provide a long-term fix, please disregard this; but external devices can sometimes be unreliable because of cabling problems. If the cable connectors (on the cable, the computer, or the disk) are worn, the connection may be a bit loose, causing unreliability. A cable's wires could also be damaged because of a heavy object having been placed on it, a pet nibbling on it, or whatnot. Thus, as a general rule, replacing the cable should be one of the first things you try when you have problems with an external disk. Similarly, taking any USB hubs or extension cables out of the equation is generally worthwhile.

A: It seems that installing the NVIDIA drivers from their website has provided the fix for this problem.  Thank you for your help!
If you need help installing NVIDIA drivers, it's worth starting here: How to install drivers for NVIDIA GeForce FX 5200 on Precise
Thanks again!


text:
Q: About audits in Oracle 11g I need to do the auditing in database, but different the normal process that administrator use, (active audit in first installation or alter ) I don't have time window for this.
My scenario:
tree users with select grant just. But, for others users in same place, using the global user whit delete, update grant.
And I don't simply change the grant these users, because others applications use in font the same user and password.
Exist other form that I take a report with , what each one user does in database?

A: You're right, excuse any errors or agreement error.
My question is a concept so much, but explain.
I have users who have their logins, but there is a login that has some privileges that also and the same User used in important processes in the environment and is in source code.
At one point in the past knew the password for this login, and the more I say to access the environment with their respective login and password in some cases, they use this login with privileges.
As I have not, by default, a native audit Oracle configured in my environment, I wonder if through tables and views I can map out what such User made using a PL SQL DEVELOPER.
The worst and I have no time available to make this change, let offline the database, adjust and available.


text:
Q: What's the most efficient way of querying the database based on a list of values? I have a list of record Id's that I want to retrieve from Sql Server. I'm trying to figure out what the most performant way doing this would be. For example in code I have this:
var recordsToFind = new List<long>{ 12345, 12346, 45756, 42423 ... }

I want to create a stored proc that does this:
Select * From Puzzles where ID = {any of the integers passed in}

I know there are several options like, table value parameters, converting the list into a comma seperated string and using CharIndex, created a temp table and splitting the string etc...
What would be the best approach keeping in mind this will be used A LOT!
Thanks!

A: Several must read articles about this can be found here: http://www.sommarskog.se/arrays-in-sql.html  Performance considerations are addressed in those articles.

A: Micah,
is it out of the question to just do the simple sql 'in()' function?? (with obviously your array being used as a parameter, rather then the hardcoded values)
select * From Puzzles where ID in (12345, 12346, 45756, 42423)

maybe i've misunderstood the question mind you :)
[edit] - i notice that this is being used in .net. would it be possible to use linq against the database at all?? if so, then a few well crafted linq (over EF or subsonic for example) methods may do the trick. for example:
var idlist =  new int[] { 12345, 12346, 45756, 42423 };
var puzzleids = Puzzles.Where(x =>
                       idlist.Contains(x.ID));

A: Do you have the ability to change the code and the stored procedure or are you bound to some limit?  If you have the ability to change both, I've seen this done before:
//Convert array/list to a comma delimited string using your own function (We'll call string strFilter)
//Pass strFilter into stored procedure (varchar(1000) maybe, we'll call parameter @SQLFILTER)

DECLARE @SQL AS VARCHAR(2000) --Or VARCHAR(MAX)
SET @SQL = "SELECT * FROM PUZZLES WHERE ID IN (" + @SQLFILTER + ")"
EXEC (@SQL)

I apologize if my syntax is off.  My job unfortunately uses Oracle and I haven't used SQL Server a lot in 8 months.  Hope this helps.


text:
Q: Control Flow Exception I am getting the following exception in the server application. What could be the reason for the issue and how can I debug the issue. I am getting the exception from different points of the thread
ICC_SequenceService_SequenceReportService.NotifyEventRecived]-Exception Occured :The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it has been Aborted.-
Server stack trace:

   at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposedOrNotOpen()
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

A: That's probably because your client don't abort the channel when it is failed and try to Close it instead.  That's unfortunately the default behavior if you are using a client proxy generated by wsdl.exe and a using statement.


text:
Q: Keyboard Shortcuts in Tooltips in macOS Calculator Is there something that can be done so that the tooltip text indicates the keyboard shortcut associated with each button in the macOS calculator? It's frustrating to have to look it up online every time.
Currently, the tooltip text contains only a description of the button, not its shortcut.
I'm on Calculator Version 10.14 (123) on Catalina 10.15.1.

A: Tooltip text (presented on hovering the mouse cursor over the Calculator app buttons) does show the keyboard shortcut. The following is a screenshot from Calculator app version Version 10.14 (123), running in macOS Catalina 10.5.1.


text:
Q: How to disable link in javascript This is actually a 2 part question.
1) I'm having trouble at the moment looping through my links and disabling it with javascript. I need to grab the links from a div id called "bottom" and any link with "nhl" in it needs to be disabled or just won't work however you want to word it. So far i've got: External js file.
onload = function() {
    var links = document.getElementById("bottom").getElementsByTagName("a");

    for(i = 0; i < links.length; i++) {
        if (links[i].indexOf("nhl") >= 0) {
            links[i].onclick = function() {
                 return false;
            }
        }
    }
}

html file:

www.nhl.com
www.youtube.com
www.w3schools.com

2) My js file at the moment contains a couple functions like:
function changeColorOnMouseIn() {
    this.style.color = "red";
}

function changeColourOnMouseOut() {
    this.style.color = "black";
}

onload = function() {
    var divClasses = querySelectorAll(".change p");

    for(i = 0; i < divClasses.length; i++) {
        divClasses[i].onmouseover = changeColorOnMouseIn;
        divClasses[i].onmouseout = changeColorOnMouseOut;
    }
}

My question is should I continue to do it this way or doing something like this instead:
onload = function() {
    var divClasses = document.querySelectorAll(".change p");

    for(i = 0; i < divClasses.length; i++) {
        divClasses[i].onmouseover = function() {
            this.style.color = "red";
        }
    }
}

Or should I just make a function that does all that with the for loops and just call "myFunctionName()" in the onload function? What are the differences? And in what situation would you do one over the other?
Thank you!

A: For the first part I found a small mistake in your loop, you need to write links[i].href.indexOf("nhl")
onload = function() {
var links = document.getElementById("bottom").getElementsByTagName("a");

    for(i = 0; i < links.length; i++) {
       if(links[i].href.indexOf("nhl") >= 0) {// CHANGE
           links[i].onclick = function() {
                return false;
               }
           }
    }
 }

For the second part you can easily do it by CSS
.change p {
  color: black;
}
.change p:hover{
  color: red;
}

If you still want to do it in javascript then this approach is better
function changeColorOnMouseIn() {
    this.style.color = "red";
}

function changeColourOnMouseOut() {
    this.style.color = "black";
}

onload = function() {
    var divClasses = querySelectorAll(".change p");

    for(i = 0; i < divClasses.length; i++) {
        divClasses[i].onmouseover = changeColorOnMouseIn;
        divClasses[i].onmouseout = changeColorOnMouseOut;
    }
}

The reason here why this approach is better to the approach is because below code will create n number of anonymous function, so if loop is going for 10 items there will be 10 anonymous function, whole in above approach it will have single function declaration.
divClasses[i].onmouseover = function() {
    this.style.color = "red";
}


text:
Q: Recover files that were added to the index but then removed by a git reset I added some files to the index but then by mistake I deleted them with git reset --hard.  How do I recover them?
Here's what happened:

*

*I added all files using git add .

*I then committed

*When I checked the status, there were still files that weren't included in the commit from the add, which was strange

*I added the untracked files again and it worked this time

*But I wanted everything to be in 1 single commit so I looked up how to unstage what I just committed

*I used git reset --hard HEAD^ — bad idea obviously, all files were deleted

*so then I used git reflog to find where I left off

*then I used git reflog ______ to go back to my last commit.

*then I used git reset HEAD to unstage the commit (what I should have originally done) but the files I added (see above) after the commit were still gone.

How do I get those files back?

A: First, make a full backup of your Git repository!
When you git add a file, git will create a blob out of this file's content and add it to its object database (.git/objects/??/*).
Let's look at your commands, one by one:

I added all files using git add .

$ git add .

This will add all files contained in the current directory and its subdirectories to Git's object database. Untracked files matching patterns from .gitignore files will not be added. Tree files will also be written. Please see the end of my answer.

I then committed

$ git commit -m'added all files'

This will write a new commit object to the object database. This commit will reference a single tree. The tree references blobs (files) and other trees (subdirectories).

When I checked the status, there were still files that weren't included in the commit from the add, which was strange

$ git status

I can think of two scenarios where this happens: something modified your files or new files were added behind your back.

I added the untracked files again and it worked this time

$ git add .

I assume you used the same add command again, as in step 1.

But I wanted everything to be in 1 single commit so I looked up how to unstage what I just committed

I will tell you a better way at the end of this answer, which does not require the user to issue a potentially dangerous reset

I used git reset --hard HEAD^ — bad idea obviously, all files were deleted

$ git reset --hard HEAD^

This command will set your current working tree and index to be exactly at the commit HEAD^ (the second-last commit). In other words, it will discard any local uncommitted changes and move the branch pointer back one commit. It does not touch untracked files.

so then I used git reflog to find where I left off

$ git reflog

This shows the last commits that were recently checked out (identical to git reflog HEAD). If you specify a branch name, it will show you the last commits that this branch pointed to recently.

then I used git reflog __ to go back to my last commit.

Not sure about this one. git reflog is (mostly) a read-only command and cannot be used to "get back" to commits. You can only use it, to find commits a branch (or HEAD) pointed to.

then I used git reset HEAD to unstage the commit (what I should have originally done) but the files I added (see above) after the commit were still gone.
      $ git reset HEAD

This will not unstage this commit, but it will unstage all staged (but uncommitted) changes from the index. Originally (1st step), you wanted to say git reset HEAD^ (or git reset --mixed HEAD^) – this will leave your working tree untouched, but set the index to match the tree pointed to by the commit named by HEAD^.

Now, to get back your files, you have to use git fsck --full --unreachable --no-reflog. It will scan all objects in Git's object database and perform a reachability analysis. You want to look for blob objects. There should also be a tree object, describing the state after your second git add .
git cat-file -p <object hash> will print the files content, so you can verify that you have the right objects. For blobs, you can use IO redirection to write the content to the correct file name. For trees, you have to use git commands (git read-tree). If it's only a few files, you are better off writing them directly to files.

A few notes here:
If you want to add files to the last commit (or edit its commit message), you can simply use git commit --amend. It's basically a wrapper around git reset --soft HEAD^ && git commit -c HEAD@{1}.
Also, it's almost never a good idea to use git add .. Usually, you only want to use it the first time, when you are creating a new repository.
Better alternatives are git add -u, git commit -a, which will stage all changes to tracked files. To track new files, better specify them explicitely.

A: I had a similar issue but I had a lot of dangling blobs and trees in my repo so I ended up filtering with grep the output of all the dangling blobs and printing the ones that matched.  Assuming ${UNIQUE_CODE} is some code that is unique to the files you had in the index, then this should give you the hashes of the blobs you are looking for:
for b in $(git fsck --lost-found | grep blob | awk '{print $3}'); do git cat-file -p $b | grep -q ${UNIQUE_CODE} && echo $b; done


text:
Q: Can Windows security protect a stolen hard drive? I am aware of hard drive encryption options like TrueCrypt and other tailor-made solutions, but I am curious as to whether Windows security provides any kind of protection for a drive that is removed or stolen from a PC. If I grant read-access to a directory only to members of one group, can any user access that directory after the drive is moved to another PC? What about accessing the drive from a Mac or Linux box?

A: Permissions alone can't protect a stolen drive. Linux and Mac won't honor NTFS permissions and you will be able to do what you want (provided you have the ntfs-3g driver). However, if you use NTFS encryption or the new Bitlocker (Vista Ultimate+), you'll be better off.

A: Windows Encrypted File System (look at the efs tag here) will lock away your data quite good.
But, like John points out, permissions are not the answer.
Permissions and related access control will only prevent users defined by the windows 'administrator' from accessing across their ownerships (that too within the limits of system stability and vulnerability).
Both TrueCrypt and EFS will protect your data within the limits of the encryption technology similarly. It would need someone to know your password (by whatever means) to reach your data.
But, having said that, I would prefer using TrueCrypt over EFS.


text:
Q: Why is parameter for onChange(of:perform:) captured? I was using the onChange(of:perform:) SwiftUI modifier. I then wanted to get the old value, to compare it with the new value. I read the documentation, which says:

The previous value may be captured by the closure to compare it to the new value.

With an example:
.onChange(of: playState) { [playState] newState in
    model.playStateDidChange(from: playState, to: newState)
}

My question is why in the example is playState captured in the [ ]? The playState value could easily be accessed without passing it in. In addition, this isn't part of a class, so I assume there is no way to create a strong reference by capturing self of some sort.
Why is the example written like this?

A: Under "normal" circumstances, a closure defined inside an immutable value-type (e.g. a struct) captures its value, which doesn't change, so all is good.
struct Foo {
  var a = "original"

  func makeFn() -> () -> Void {
     return { print(a) }
  }
}

var foo = Foo()
let fn = foo.makeFn()
foo.a = "changed"

fn() // "original"

But with @State, the actual value is stored in some global storage that SwiftUI maintains, so it basically behaves as if it's having reference semantics.
When the closure is called, the state value has already changed, so doing print(a) as above accesses a value through the @State property wrapper, which retrieves the then-updated value.
To counter that, you can capture the property into the closure's local variable with a capture list:
return { [a] in print(a) }

This is of course a simplified example, and SwiftUI might be doing other things behind the scenes, but I think it conveys the point.

To see the difference in SwiftUI, try the following:
.onChange(of: playState) { [playState] newState in
    print(playState, self.playState, newState)
}

The output would be something like this:
original new new

playState is the captured local variable at the time the closure was defined (i.e. when body was computed), self.playState accesses the value via @State, which has changed, and newState is obviously the passed-in parameter with the new value.


text:
Q: JS - why touchEvent.identifier in Chrome is always zero? i'm playing with touch events and i realized a demo that creates and moves a circle for each finger. No problem on iOS Safari, but Android Chrome returns always "0" as identifier of the touch ( https://developer.mozilla.org/en-US/docs/Web/API/Touch/identifier ). Is it a bug, an "anti-user-tracking" privacy choice, or what else? Is there a workaround to identify the touches?
Thanks.

A: This seems to be due to a different reading of the W3C spec than that used by Apple in iOS Safari.
Android Chrome gives an identifier of 0 for a touch when only one finger is touching the screen. When two fingers are touching, it gives them identifiers of 0 and 1 and so on. This actually conforms to the wording of the W3C spec:
identifier of type long, readonly
An identification number for each touch point. When a touch point becomes active, it must be assigned an identifier that is distinct from any other active touch point. While the touch point remains active, all events that refer to it must assign it the same identifier.
Note it only has to be unique relative to any other active touch point, which means that it can be the same as for previous touch points that are no longer active. This is much less useful than the Apple implementation.


text:
Q: Android nfcA.transceive(byte[] command), what is the sequence of commands to fetch data from nfc device? I have a few questions regarding nfcA. I am integrating a NFC device with my android application to fetch the data from the device. I am successful in connecting the NFC device using nfcA.connect(). Card is NXP MIFARE Ultralight. This is my NFC device info:

QUESTION: What should be the byte[] commands to send to nfcA.transceive(byte[] commands) to fetch the data from the device. When i try to read the pages by using the following command:
 byte[] commands = new byte[]{
                    (byte) 0x30,  // READ
                    (byte) 0x04,  // page address
                   };

I succeed, but it's showing only empty bytes (00,00,00,00). So, i have a protocol document on how to get the data. The screenshot is below:

So, considering this request structure, i tried staring by byte command with
byte[] commands = new byte[]{
                    //NFCCmd
                    (byte) 0x06,

                    //Manufacture Code
                    (byte) 0x39,
                    (byte) 0x02,

                    //Card Identification Number
                    (byte) 0x00,
                    (byte) 0x00,
                    (byte) 0x01,
                    (byte) 0x80,
                    (byte) 0xD9

                    //Number of Service
                    (byte) 0x01,

                    //Service Code
                    (byte) 0x00,
                    (byte) 0x0B,

                    //Cnt
                    (byte) 0x02,

                    //BlockList Commands
                    (byte) 0x06,
                    (byte) 0x02,
                    (byte) 0x10,
                    (byte) 0x40
                  };

PROBLEM:  The ID consists of 7 bytes using the mTag.getId() or TagInfo android app(ref. Image below).
When i send commands, i get exception Tag is lost. I know, it's happening because of invalid commands. Can you help me out what will be proper byte commands[] sequence considering my device info.(cannot use Ndef so need to send raw commands only to fetch data)
Any help will be really appreciated.


text:
Q: Increment + auto-update variable value in JS I'm a beginner at JS and PHP, so please forgive my ignorance and bear with me :)
I'm trying to implement a live counter on my website. This counter should display the number of translated words up to now, and I'd like this number to update "live" to reflect the number of translated words (based on my yearly average).
To simplify, I set a variable $wordsPerYear with an average of words translated per year, say 1,000. I also set the start date to 10 years ago (2004), so that it returns roughly 10,000.
So here's my code so far:
<!DOCTYPE html>

    <title>Live Word Count</title>

    <?php
    $now = time();
    $start = mktime(0, 0, 0, 1, 01, 2004);
    $wordsPerYear = 1000;
    $totalDays = (($now - $start) / 86400); // number of a seconds in a day
    $count = $totalDays / 365 * $wordsPerYear;
    $count = round($count);
    ?>

                Loading Word Count...

I just need to be able to make this figure update "live" with the real value of words translated instead of a "fake" live incrementation using setInterval('updateCounter()', 1000).
So yeah, I really just need to update the function to update that word count value to the ratio of the current time against my start date.
Could anyone help me achieve this? I'm sure it's something really simple to do but I'm racking my brains to no avail. Let me know if clarifications are needed to explain what I want to do!
Thanks in advance

A: There's no need for both PHP and Javascript for this, since you're not actually getting any values from your server - it's all being calculated in a vacuum.
Fundamentally, this is a math problem. Javascript calculates the differences in dates in milliseconds, so you first need to know the number of words per millisecond you translate: words per year / days per year / milliseconds per day. I used 31556900 as the words per year value to test, since that's the number of seconds in a year.
Next, you have to apply that total to the current date - the start date, and set that as your starting total.
Finally, create an interval function that adds the number of words to the total.
This should do it:
;(function() {
    // Constants
    var   wpm = (31556900 / 365) / 86400000 // Words per year / days per year / milliseconds per day
    ,   start = new Date('January 1, 2004');

    var now = new Date()
    , total = Math.round((now - start) * wpm);

    var dom = {
        counter: document.getElementById('counter')
    };
    dom.counter.textContent = total;

    setInterval(function() {
        total += Math.round((new Date() - now) * wpm)
        dom.counter.textContent = total;
        now = new Date();
    }, 1000)
}())

http://jsfiddle.net/PjmwD/

A: you can try this, i just translate your PHP code in javascript and calculate your "totalWords" base on the server time.

                Loading Word Count...

FIDDLE DEMO


text:
Q: Yocto find the recipe or class that defines a task I am a yocto noob, trying to decipher how the device tree is built from a Xilinx hardware definition (.hdf) file. But my question is more general.
Is there a yocto way to find the source of task?
Given a task name is it possible to find where the tasks source code lives? (presumably in a recipe or class)
As an example, where is the source for the Python task do_create_yaml which is called by recipes in the meta-xilinx-bsp layer that compile the device tree blob?
bitbake -e device-tree

Will dump the python source for do_create_yaml (amongst the rest of it prodigious output) but how can I find where that is coming from?

A: Device tree is part of Linux Kernel. In Yocto, this is compiled from KERNEL_DEVICETREE variable value either defined as part of Linux Kernel recipe or machine configuration.
For example, for cubieboard7 as defined here,
KERNEL_DEVICETREE = "s700_cb7_linux.dtb"

instructs the compilation to use this dts file for compilation. This is done by yocto by using various classes.
In our example, we inherit kernel.bbclass which in turn inherits kernel-devicetree.bbclass, in this class (copied from kernel-devicetree.bbclass),
do_compile_append() {
        for dtbf in ${KERNEL_DEVICETREE}; do
                dtb=`normalize_dtb "$dtbf"`
                oe_runmake $dtb
        done
}

do_install_append() {
        for dtbf in ${KERNEL_DEVICETREE}; do
                dtb=`normalize_dtb "$dtbf"`
                dtb_ext=${dtb##*.}
                dtb_base_name=`basename $dtb .$dtb_ext`
                dtb_path=`get_real_dtb_path_in_kernel "$dtb"`
                install -m 0644 $dtb_path ${D}/${KERNEL_IMAGEDEST}/$dtb_base_name.$dtb_ext
        done
}

do_deploy_append() {
        for dtbf in ${KERNEL_DEVICETREE}; do
                dtb=`normalize_dtb "$dtbf"`

this appends tasks to compile, install and deploy tasks. So defining KERNEL_DEVICETREE enables the automatic build of dtb.

A: I found that the datastore contains the filename for tasks as a VarFlag,
from a devpyshell
pydevshell> d.getVarFlags("do_create_yaml")

gives
{'filename': '.....yocto/sources/core/../meta-xilinx-tools/classes/xsctyaml.bbclass', 'lineno': '61', 'func': 1, 'task': 1, 'python': '1', 'deps':   ['do_prepare_recipe_sysroot']}

So for the example in my question the active definition for the do_create_yaml task is in xsctyaml.bbclass.


text:
Q: Applescript: Using one list to weed out another list So I have this list of words:
{{"YOU"}, {"KNOW"}, {"BETTER"}, {"THAN"}, {"TO"}, {"PARK"}, {"YOUR"}, {"CAR"}, {"IN"}, {"UNASSIGNED"}, {"SPOTS"}}

and I also have this list:
{{"0", "<SIL>"}, {"269", "YOU"}, {"389", "<SIL>"}, {"439", "KNOW"}, {"509", "BETTER"}, {"829", "THAN"}, {"969", "TO"}, {"1059", "PARK"}, {"1350", "YOUR"}, {"1449", "CAR"}, {"1839", "IN"}, {"2059", "<SIL>"}, {"2089", "UNASSIGNED"}, {"2659", "SPOTS"}}

I would like to weed out all the extraneous sublists (the ones that do not contain the words in the first list) leaving something like this:
{{"269", "YOU"}, {"439", "KNOW"}, {"509", "BETTER"}, {"829", "THAN"}, {"969", "TO"}, {"1059", "PARK"}, {"1350", "YOUR"}, {"1449", "CAR"}, {"1839", "IN"}, {"2089", "UNASSIGNED"}, {"2659", "SPOTS"}}

I'm new to applescript so this is really difficult for me.
Any help would be greatly appreciated!

A: This script cycles one at a time through the list pairs, and for each of them, checks each word from the original list to see if it's in that pair, and if so, add that pair to the resulting list.
set L1 to {{"YOU"}, {"KNOW"}, {"BETTER"}, {"THAN"}, {"TO"}, {"PARK"}, {"YOUR"}, {"CAR"}, {"IN"}, {"UNASSIGNED"}, {"SPOTS"}}

set L2 to {{"0", "<SIL>"}, {"269", "YOU"}, {"389", "<SIL>"}, {"439", "KNOW"}, {"509", "BETTER"}, {"829", "THAN"}, {"969", "TO"}, {"1059", "PARK"}, {"1350", "YOUR"}, {"1449", "CAR"}, {"1839", "IN"}, {"2059", "<SIL>"}, {"2089", "UNASSIGNED"}, {"2659", "SPOTS"}}

set L3 to {} -- initiate the resulting list
repeat with wordPair in L2 -- cycle through each list pair in L2
    repeat with wordSingle in L1 -- check each source word to see if found in the list pair
        if wordSingle is in wordPair then
            copy (wordPair as list) to end of L3
            exit repeat
        end if
    end repeat
end repeat
return L3


text:
Q: An image side by side in latex I would like to have two figures side by side in my document. I found an example on here with the following code
\begin{figure}
\centering
\begin{minipage}{.5\linewidth}
\centering
\includegraphics[width=.4\linewidth]{image}
\captionof{figure}{A figure}
\label{fig: test1}
\end{minipage}%
\begin{minipage}{.5\linewidth}
\centering
\includegraphics[width=.4\linewidth]{image}
\captionof{figure}{Another figure}
\label{fig: test2}
\end{minipage}
\end{figure}

However when I try to compile it it comes up with the following errors:

template.tex  error  line 195   Argument of \caption@ydblarg has an
  extra } \end{figure}
template.tex  error  line 195   Paragraph ended before \caption
  @ydblarg was complete \end{figure}

How can I fix this to make it work?

A: try to use subfigure instead of minipage.
How about this code :
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}

\begin{figure}
        \centering
        \begin{subfigure}[b]{0.5\textwidth}
                \includegraphics[width=\textwidth]{pic1}
        \end{subfigure}
        \begin{subfigure}[b]{0.5\textwidth}
                \includegraphics[width=\textwidth]{pic2}
        \end{subfigure}
        \caption{two pictures side by side}
\end{figure}

A: This compiles fine for me:
\documentclass{article}

\usepackage{graphicx}
\usepackage{caption}

\begin{document}

\begin{figure}
\centering
\begin{minipage}{.5\linewidth}
\centering
\includegraphics[width=.4\linewidth]{image}
\captionof{figure}{A figure}
\label{fig: test1}
\end{minipage}%
\begin{minipage}{.5\linewidth}
\centering
\includegraphics[width=.4\linewidth]{image}
\captionof{figure}{Another figure}
\label{fig: test2}
\end{minipage}
\end{figure}

\end{document}

A: You can try my answer and the examples provided here:
side by side minipage figures


text:
Q: credential id not work with jenkins ansible plugin adhoc class I am using step([$class: 'AnsibleAdHocCommandBuilder']): Invoke Ansible Ad-Hoc Command to invoke adhoc command in my pipeline, but somehow, it gives error when use credentialsId to pass the private key variable.
step([
  $class: 'AnsibleAdHocCommandBuilder',
  ansibleName: 'Run cvWatchBuilder',
  inventory: [$class: 'InventoryPath', path: "myhost,"],
  hostPattern: "all",
  module: 'shell',
  disableHostKeyChecking: true,
  command: 'ls',
  forks: 1,
  credentialsId: 'ssh-private-key'
  ]);

When this step run, it gives error for private key.
Running on k8s-6930a022-327d-44a2-9065-cae0fde58c14-s8pbx-70c8d in /home/jenkins/agent/workspace/k8s-e2e
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Run shell)
[Pipeline] container
[Pipeline] {
[Pipeline] step
Executing sh script inside container ansible of pod k8s-6930a022-327d-44a2-9065-cae0fde58c14-s8pbx-70c8d
Executing command: "ansible" "all" "-i" "myhost," "-m" "shell" "-a" "ls" "-f" "1" "--private-key" "/tmp/ssh11730288813016418676.key" "-u" "devops"
exit
myhost | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added 'myhost,172.17.203.19' (ECDSA) to the list of known hosts.\r\n\n\n__________                __                                     __                 _________ .____    .___\n\\______   \\_____    ____ |  | ____ ________   ____  ____   _____/  |_  ___________  \\_   ___ \\|    |   |   |\n |    |  _/\\__  \\ _/ ___\\|  |/ /  |  \\____ \\_/ ___\\/ __ \\ /    \\   __\\/ __ \\_  __ \\ /    \\  \\/|    |   |   |\n |    |   \\ / __ \\\\  \\___|    <|  |  /  |_> >  \\__\\  ___/|   |  \\  | \\  ___/|  | \\/ \\     \\___|    |___|   |\n |______  /(____  /\\___  >__|_ \\____/|   __/ \\___  >___  >___|  /__|  \\___  >__|     \\______  /_______ \\___|\n        \\/      \\/     \\/     \\/     |__|        \\/    \\/     \\/          \\/                \\/        \\/\n\n\n\nno such identity: /tmp/ssh11730288813016418676.key: No such file or directory\r\ndevops@myhost: Permission denied (publickey,password).",
    "unreachable": true
}
FATAL: command execution failed
hudson.AbortException: Ansible Ad-Hoc command execution failed
    at org.jenkinsci.plugins.ansible.AnsibleAdHocCommandBuilder.perform(AnsibleAdHocCommandBuilder.java:224)
    at jenkins.tasks.SimpleBuildStep.perform(SimpleBuildStep.java:123)
    at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:100)
    at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:70)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

But when use same key with sh function, it works.
withCredentials([sshUserPrivateKey(credentialsId: 'ssh-private-key', keyFileVariable: 'keyfile')]) {
                    sh("ANSIBLE_HOST_KEY_CHECKING=False ansible all -i myhost, -m shell -a ls --private-key $keyFile -u devops")
                }

This works and print output as below.
Running on k8s-8f822fb4-b0bf-4c8d-9df2-9fa3da5e4a55-v9j9n-kdbtg in /home/jenkins/agent/workspace/k8s-e2e
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Run shell)
[Pipeline] container
[Pipeline] {
[Pipeline] withCredentials
Masking supported pattern matches of $keyfile
[Pipeline] {
[Pipeline] sh
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
         Affected argument(s) used the following variable(s): [keyfile]
         See https://jenkins.io/redirect/groovy-string-interpolation for details.
+ ANSIBLE_HOST_KEY_CHECKING=False ansible all -i myhost, -m shell -a ls --private-key **** -u devops
myhost | CHANGED | rc=0 >>

EDIT
I debug little more, then sees that, it complain about /tmp/ssh11730288813016418676.key: No such file or directory, then I was thinking to see where this file is :)
We are using Jenkins-operator on kubernetes cluster to run the jenkins instance. What it will do is, it create 2 container in pod. One for jnlp to connect to jenkins master, and second to use for the execution.
My full pipeline is as below.
$ cat cicd/pipelines/k8s.jenkins
#!/usr/bin/env groovy

def label = "k8s-${UUID.randomUUID().toString()}"
def home = "/home/jenkins"
def workspace = "${home}/workspace/build-jenkins-operator"
def workdir = "${workspace}/src/github.com/jenkinsci/kubernetes-operator/"

podTemplate(label: label,
        containers: [
            containerTemplate(name: 'ansible', image: 'my registry/ansible', ttyEnabled: true, command: 'cat'),
//          containerTemplate(name: 'ansible', image: 'python', ttyEnabled: true, command: 'cat'),
        ],
        ) {
    node(label) {
        stage('Run shell') {
            container('ansible') {
//              withCredentials([sshUserPrivateKey(credentialsId: 'ssh-private-key', keyFileVariable: 'keyfile')]) {
//                  sh("ANSIBLE_HOST_KEY_CHECKING=False ansible all -i myhost, -m shell -a ls --private-key $keyFile -u devops")
//              }
//              sh 'pip install ansible'
                step([
                    $class: 'AnsibleAdHocCommandBuilder',
                    ansibleName: 'Run command',
                    inventory: [$class: 'InventoryPath', path: "myhost,"],
//                  inventory: [$class: 'InventoryPath', path: "localhost,"],
                    hostPattern: "all",
//                  module: 'shell',
                    module: 'pause',
                    disableHostKeyChecking: true,
                    command: 'minutes=5',
//                  command: 'ls',
                    forks: 1,
                    additionalParameters: '-vvv',
                    credentialsId: 'ssh-private-key'
                ]);
                sleep time: 60
            }
        }
    }
}

When I check the jenkins console log, it shows that which pod it created and what it runs under which container.
Running on k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn in /home/jenkins/agent/workspace/k8s-e2e
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Run shell)
[Pipeline] container
[Pipeline] {
[Pipeline] step
Executing sh script inside container ansible of pod k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn
Executing command: "ansible" "all" "-i" "myhost," "-m" "pause" "-a" "minutes=5" "-f" "1" "--private-key" "/tmp/ssh6159272872640967836.key" "-u" "devops" "-vvv"
exit
ansible 2.10.11
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.8/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.8.8 (default, Mar 31 2021, 12:38:11) [GCC 8.3.0]
Using /etc/ansible/ansible.cfg as config file
Parsed myhost, inventory source with host_list plugin
Skipping callback 'default', as we already have a stdout callback.
Skipping callback 'minimal', as we already have a stdout callback.
Skipping callback 'oneline', as we already have a stdout callback.
META: ran handlers
Pausing for 300 seconds
(ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort)
myhost | SUCCESS => {
    "changed": false,
    "delta": 300,
    "echo": true,
    "rc": 0,
    "start": "2021-12-15 19:45:35.186293",
    "stderr": "",
    "stdout": "Paused for 5.0 minutes",
    "stop": "2021-12-15 19:50:35.186787",
    "user_input": ""
}
META: ran handlers
META: ran handlers
[Pipeline] sleep
Sleeping for 1 min 0 sec
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // podTemplate
[Pipeline] End of Pipeline
Finished: SUCCESS

from above message, it created k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn pod in our kubernetes cluster. When I did describe on that pod, I see there are 2 containers running in this pod.
# kubectl describe pod k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn -n jenkins
Name:         k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn
Namespace:    jenkins
Priority:     0
...
...
Status:       Running
IP:           192.168.221.84
IPs:
  IP:  192.168.221.84
Containers:
  ansible:
    Container ID:  containerd://400d9360a9b3a1415335d6e57148a58d2e64576649323e203a9b66a0de2b048a
    Image:         myrepo/ansible
    Image ID:      myrepo/ansible@sha256:6b797d6f80c7ec8c209bec8bde363b84c910a68b4b608c9db6a0411acff3b515
    Port:          <none>
    Host Port:     <none>
    Command:
      cat
    State:          Running
      Started:      Wed, 15 Dec 2021 19:45:30 +0000
    Ready:          True
    Restart Count:  0
    ...
    ...
    Mounts:
      /home/jenkins/agent from workspace-volume (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-mrww8 (ro)
  jnlp:
    Container ID:   containerd://f592bf372bf8fde5baca8a28918b275125fea9b66c9d6ea422172adb29c688ac
    Image:          jenkins/inbound-agent:4.3-4-jdk11
    Image ID:       docker.io/jenkins/inbound-agent@sha256:2ee9fb7405f135e15ea3c5efaa605b7c19bc0a93a306deec7a0826a489c1a364
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Wed, 15 Dec 2021 19:45:31 +0000
    Ready:          True
    Restart Count:  0
    Requests:
      cpu:     100m
      memory:  256Mi
    Environment:
      JENKINS_SECRET:                                      0e0f75a0d4e42f0b6c0964f12a1bd1d331d75b0578d8b0e1fd2a7fd9d1175b9d
      JENKINS_TUNNEL:                                      jenkins-operator-slave-jenkins-instance.jenkins.svc.cluster.local:50000
      JENKINS_AGENT_NAME:                                  k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn
      JENKINS_NAME:                                        k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn
      JENKINS_AGENT_WORKDIR:                               /home/jenkins/agent
      ...
      ...
    Mounts:
      /home/jenkins/agent from workspace-volume (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-mrww8 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  workspace-volume:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  kube-api-access-mrww8:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Burstable
Node-Selectors:              kubernetes.io/os=linux
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age    From               Message
  ----    ------     ----   ----               -------
  Normal  Scheduled  3m13s  default-scheduler  Successfully assigned jenkins/k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn to myworker
  Normal  Pulled     3m13s  kubelet            Container image "stepladder-docker-local.artifacts.rackspace.net/ansiblelint:latest" already present on machine
  Normal  Created    3m13s  kubelet            Created container ansible
  Normal  Started    3m13s  kubelet            Started container ansible
  Normal  Pulled     3m13s  kubelet            Container image "jenkins/inbound-agent:4.3-4-jdk11" already present on machine
  Normal  Created    3m13s  kubelet            Created container jnlp
  Normal  Started    3m12s  kubelet            Started container jnlp

In the console log it has log line as Executing sh script inside container ansible of pod k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn means ansible command will run in ansible container of pod.
When I check the /tmp directory in ansible pod, I didn't see any files in that.
# kubectl exec -i -t k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn -c ansible -n jenkins -- ls -al /tmp/
total 8
drwxrwxrwt 1 root root 4096 Dec 15 19:45 .
drwxr-xr-x 1 root root 4096 Dec 15 19:45 ..

While as per the ansible command, there should be file /tmp/ssh11730288813016418676.key exists in the /tmp folder. Then I check the jnlp container.
# kubectl exec -i -t k8s-d83c8383-beca-4cfb-ac61-5b8df98d76e7-t4s7w-chmhn -c jnlp -n jenkins -- ls -al /tmp/
total 20
drwxrwxrwt 1 root    root    4096 Dec 15 19:45 .
drwxr-xr-x 1 root    root    4096 Dec 15 19:45 ..
drwxr-xr-x 2 jenkins jenkins 4096 Dec 15 19:45 hsperfdata_jenkins
drwxr-xr-x 2 root    root    4096 Mar 31  2020 hsperfdata_root
-r-------- 1 jenkins jenkins 3243 Dec 15 19:45 ssh11730288813016418676.key

I can see the sshXXXX.key file is created in jnlp container.
When ansible command runs on ansible container, it is not able to find the sshXXXXX.key file on that container, and it gives error that no such file or directory.


text:
Q: Can a Sql statement be encapsulated into a sub function for better readability? I try to implement a table function by following Tony Andrews example. But my Sql statement will be several lines long (>20) and will also contain parameters. Is it possible to encapsulate the Sql statement somewhere else and to refer to it from the main function to keep everything more readable?
In traditional programming languages I would assign the raw Sql into a string and replace the parameters as required.

A: Yes, you can:
--declare variables
TYPE curref is REF CURSOR;
c1 curref;

q VARCHAR2(2000);

--save query to string variable
q:='<insert 20 line query here>';

--open cursor
OPEN c1 FOR q;

--then, work on cursor rows, one by one

Notice that 'q' can be quite complex, with concatenated parameter values (or subqueries that can be stored as separate varchar variables):
q:='
    select distinct
        fn.BASENAME as name
        ,h.PARENT_ID as "admin_place_id"
        ,h.lev as "admin_level"
    FROM (
        SELECT CHILD_ID, PARENT_ID, level lev
        from '||schema||'.NT_ADMIN_GRAPH
        START WITH CHILD_ID='||q_sub2||'
        CONNECT BY CHILD_ID=PRIOR PARENT_ID
    UNION ALL
        SELECT null, '||q_sub2||', 0
        FROM DUAL
    ) h
    '
    ||q_sub||
    '
    ORDER BY h.lev asc
';

See Oracle's documentation for more examples of how to implement this.

A: Inspired by drapkin11 I found a solution using a cursor:
CREATE OR REPLACE Function TotalIncome( name_in IN varchar2 )
RETURN varchar2
IS
    total_val number(6);

    cursor c1 is
      select monthly_income
      from employees
      where name = name_in;

BEGIN
    total_val := 0;
    FOR employee_rec in c1
    LOOP
        total_val := total_val + employee_rec.monthly_income;
    END LOOP;
    RETURN total_val;
END;


text:
Q: Item is not getting selected on spinner when used in recyclerview I have a weird problem when using spinner widget inside a recyclerview. So the story is like this I have a recyclerview which has the spinner and I am passing list which needs to be inflated from fragment to the recyclereview where I am creating adapter if the data is not null and setting it into the spinner, but it works sometimes and most of the times not. It also works when getting focus or typing in edit text below it.
Note: I have already checked the other questions related this and yes I am using a white background with black text color layout which is basically a custom layout for the spinner. I am having a hard time figuring out what is going on.
This is my code for setting spinner in onBindViewHolder()
 @Override
public void onBindViewHolder(FamilyMemberAdapter.ViewHolder holder, int position) {
    FamilyMemberRecyclerViewModel familyMemberModel = familyMemberRecyclerViewModelList.get(holder.getAdapterPosition());

    if (familyMemberModel.getRelationTypeModelList()!=null){
        relationTypeModelArrayAdapter = new ArrayAdapter<RelationTypeModel>(context,R.layout.item_spinner,familyMemberModel.getRelationTypeModelList());
        holder.spnRelationType.setAdapter(relationTypeModelArrayAdapter);
        if (familyMemberModel.getRelationTypeAdapterModel()!=null){
            int positionRelation = relationTypeModelArrayAdapter.getPosition(familyMemberModel.getRelationTypeAdapterModel());
            holder.spnRelationType.setSelection(positionRelation);
        }
    }

}
spinner onItemSelectedListener()
spnRelationType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //here differentiate between different doc and relation
                uploadDocumentItemsClickListener.onSpinnerChangeListener(spnRelationType,getAdapterPosition(),adapterView.getSelectedItemPosition());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

Here is snapshot of what is going on.
This is I am selecting item from the spinner

This is after selecting an item from the spinner.

Please let me know if more code needed.

A: I believe this is because the edit text still has the focus and not on the spinner. Try something like this.
spinner.setFocusableInTouchMode(true);
spinner.setOnFocusChangeListener((v, hasFocus) -> {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (spinner.getWindowToken() != null) {
                spinner.performClick();
            }
        }
    }
});


text:
Q: scipy spectrogram with logarithmic frequency axis? Playing with scipy.signal.spectrogram. Works fine for what it is.
from scipy.io import wavfile
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt

sf, audio = wavfile.read('serious.wav')
sig = np.mean(audio, axis=1)
f, t, Sxx = signal.spectrogram(sig, sf, scaling='spectrum')

plt.pcolormesh(t, f, np.log10(Sxx))
plt.ylabel('f [Hz]')
plt.xlabel('t [sec]')
plt.show()

This is the result:

But the frequency axis is linear. For audio this is not often desirable - at any rate, it's not what I want.
Is there a way to coax scipy.signal.spectrogram to output a logarithmic frequency scale?
If this is not doable with scipy, could you recommend an equally simple approach to obtain this result?

EDIT: The problem is not in the way the image is displayed. The problem is in the way the data is generated by signal.spectrogram()
I've changed the code like this:
plt.pcolormesh(t, f, np.log10(Sxx))
plt.ylabel('f [Hz]')
plt.xlabel('t [sec]')
plt.yscale('log')
plt.savefig('spec.png')
plt.show()

And now the image looks like this:

The f vector (generated by signal.spectrogram()) looks like this:
array([    0.      ,   172.265625,   344.53125 ,   516.796875,
         689.0625  ,   861.328125,  1033.59375 ,  1205.859375,
        1378.125   ,  1550.390625,  1722.65625 ,  1894.921875,
        2067.1875  ,  2239.453125,  2411.71875 ,  2583.984375,
...
       19982.8125  , 20155.078125, 20327.34375 , 20499.609375,
       20671.875   , 20844.140625, 21016.40625 , 21188.671875,
       21360.9375  , 21533.203125, 21705.46875 , 21877.734375,
       22050.      ])

That's a linear distribution. I need far more points in the lower end, and far fewer at the top end.

A: I've found the problem. FFT is linear. My image is logarithmic. The default interval between frequencies is too big in the lower part of the frequency spectrum.
So I just upped the number of frequency samples via the nperseg parameter. In this example, the distance between successive frequencies is 1 Hz, which is pretty good resolution. Also, symlog scaling is best.
npts = int(sf)
f, t, Sxx = signal.spectrogram(sig, sf, nperseg=npts)
plt.yscale('symlog')

Of course, then there's too many frequencies at the top of the range, so some pruning is required within the f and Sxx arrays (dimensions must match, so prune them both the same way). Also, the range of displayed frequencies must be limited to 10 - 20000 or some reasonable values. All these optimizations are beyond the scope of this answer.
But I brought the script to the point where it's usable and I put it on GitHub:
https://github.com/FlorinAndrei/soundspec
Here's an example of a working spectrogram:


text:
Q: Keep Mac mini on Wi-Fi (for screen-sharing), but disable internet access... How? I have a Mac mini, running El Capitan, which I use as a media server. I access/control it and control it via screen-sharing. The Mac Mini has no display attached, so it must remain connected to my Wi-Fi or I can't access/control it.
There is however no need for it to be permanently connected to the internet. Beyond the security risk, it also uses up bandwidth for background tasks which I have no use for.
I would like to disable web access, while keeping Wifi connectivity. Possible? How?

A: There are a couple of things you can do, but by far the easiest is to just manually configure your IP address (don't use DHCP) and leave the router field blank.  See below...

Before you select "Manually" in the drop down, take note of the IP address that was assigned to it by DHCP.  Then when you select "Manually" just re-enter that same IP address.
With the Router field empty, your Mac Mini will not know how to get out to the Internet.
Update:  As pointed out by user3439894 in the comments, reusing the IP address from the DHCP pool could pose a problem.  To avoid this, assign it an address outside the pool.
Most routers will have a starting address (Netgear's typically start their addressing at 192.168.1.100 and assign 50 or 100 address).  So you either have addresses up to 192.168.1.49 or .199.  To make sure you don't cause conflict, just assign it an address either higher than or lower than the pool (i.e. 192.168.1.30 or 192.168.1.210)

A: Remove the default gateway from its routing table, so that it can't route outside your local network. It will probably be set by DHCP, so you'll need to run a script regularly to delete it again.


text:
Q: Getting coverage from jest testing with mocks I seem unable to get jest coverage for reporting when I try to use mocks.  Scenario is:

// file.js

export func1 () {}; // there are many named exports in this file

export apifunc () {}; // this is the function I have mocked

// __mocks__/file.js

export apifunc () {}; // mocked version of apifunc for testing

// file.test.js
import {func0, /*apifunc*/} from './file.js';

// jest.mock('./file.js) - this did not work due to only one mocked function from file.js in a sea of named exports.  It would cause all my other tests to fail.

import { apifunc } from './__mocks__/file.js; // this is what I ended up having to do

test('test the apifunc here', () => {
  // tests all pass
});

I have not been able to get code coverage on the apifunc and have not been able to find a good answer


text:
Q: Time series data adding a gap between dates
I have a data set that I want to plot with a line graph. I have two "sets" of dates from 2006-2008 and then from 2015-2019. Ggplot keeps adding a line between these two points from 08-15 because technically there aren't any data gaps, it just spans over the two time periods. I don't want a line drawn between these two periods. How do I do this? I've tried adding a fake date between these two periods to trick R into adding a line break.

library(lubridate) # for working with dates
library(ggplot2)  # for creating graphs
library(scales)   # to access breaks/formatting functions
library(gridExtra) # for arranging plots

# Create Dataset

attach(TP)
df=data.frame(Site,Date,TP)
df %>% na.omit()
df$Date= as.Date(df$Date)
df$Site = factor(df$Site, levels = c("Site 1", "Site 2", "Site 3", "Site 4", "Site 5"))

ggplot(df, aes(x=Date, y=TP, group=Site)) +
  geom_line(aes(color=Site))  +
  scale_y_continuous( limits = c(0, 0.5))+
  theme_classic() +
  labs(x="", y=(expression(TP~ (mg-P~L^{-1})))) +
  scale_x_date(limits = as.Date(c("2006-01-01","2019-12-30")),
               labels = date_format("%Y"))


text:
Q: Excel return text stopping at character I have a excel extract which I need to use to do a VLOOKUP, my problem is that the names between the two spreadsheet are not perfect matches.. for example on the main spreadsheet:
|File|
|-|
Test File 1|
Test File 2|
Test File 3|
Test File 4|
Dummy File 59|
Dummy File 21|
Ostrich|

But the table I am looking up against has the following:
|File|
|-|
DRIVE/FOLDER LOCATOIN/Test File 1|
ROOT/DESTINATION FOLDER/Test File 2|
DRIVE/FOLDER LOCATOIN/Test File 3|
DRIVE/Test File 4|
FOLDER LOCATOIN/Dummy File 59|
DRIVE/FOLDER/LOCATOIN/Dummy File 21|
DRIVE/FOLDE- LOCATOIN/Ostrich|

I am curious if their is a way to pull just the text from the right stopping at the first "/"
Normally I would just use a =RIGHT formula but since each line has a different amount of characters I need this is a little impossible

A: combine what you have done with a find("/", cell_number)

A: Use wild-card to find the match that ends with your lookup_value
eg:  =VLOOKUP("*" &A1,$O$1:$O$10,1,FALSE)


text:
Q: how to reduce Flutter launch_background.xml display time? I have set an image in launch_background.xml file for splash screen. it takes around 5sec to switch to next page. how to reduce display time.
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <!--   <item android:drawable="@android:color/white" />-->

    <!-- You can insert your own image assets here -->
  <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/splash_screen" />
    </item>
</layer-list>

Please suggest how to reduce display time?

A: I think you are running app in debug mode so it will take time. I will suggest you run the app in release mode. by running this command in terminal.
flutter run --release

By default, flutter run compiles to debug mode. Your IDE supports this mode. Android Studio, for example, provides a Run > Debug… menu option, as well as a green bug icon overlayed with a small triangle on the project page.

Read more about Flutter's build modes here


text:
Q: Appending matrices Suppose I have a matrix. I delete an entire row and after doing so, I want to append the deleted row to the reduced matrix. How can I do this?
import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
A1=np.delete(A,1,0)
A2=A[1,:]
np.append(A1,A2,0)

But this is showing error.
Any suggestion?

A: You can try vstack instead: Stack arrays in sequence vertically (row wise).
http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html
In [33]: np.vstack([A1, A2])
Out[33]:
array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])

A: When you do np.delete it returns the array without the deleted row, not the deleted row. So your A1 has actually two rows instead of one, and that's why it's failing.
To achieve what you want, this should do it:
A1 = A[1]
A = np.delete(A, 1, 0)
result = np.append(A, A1[np.newaxis, :], 0)

and this result will contain:
array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])

Was this what you wanted?
Note the use of np.newaxis is necessary to make the single-row array A1 of the same shape as the array to append (because np.append requires arrays to have the same number of dimensions).

A: How about:
def move_row_to_end(A, row):
  return A[range(row) + range(row + 1, A.shape[0]) + [row]]

A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print move_row_to_end(A, 1)

A: when appending keep the arrays in the same dimension
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
A1=np.delete(A,1,0)
#a2 must be the same dimension as a1
A2=[A[1,:]]
print(np.append(A1,A2,axis=0))

output:
[[1 2 3]
 [7 8 9]
 [4 5 6]]


text:
Q: How do i set up an Alert that tells me when a replication of data failed? I've got Database Mail setup and tested fine.  Alerts do work when I stop and start the replication agent job, but I cannot get it to throw any alerts when data moves from a publisher db to a subscriber db successfully or unsuccessfully.  Ultimate goal is to notify me if something doesn't go right with a data replication.

A: You can set up SQL Server Agent Alerts to trap specific error numbers and respond to them by sending email notifications, or running jobs. In Management Studio, drill down to SQL Server Agent, Alerts. You might have a few defaults in there. If you don't have "Replication: agent success" and "Replication: agent failure", you can create them to watch for error numbers 14150 and 14151, respectively.
HOWEVER, since the agent success message isn't written to the SQL Server error log, you won't be able to have alerts on it by default. I just went through this trying to get email alerts for permission denied errors. You can use sp_altermessage to enable logging for a specific error message, but be careful that it isn't a frequent message, or you'll have some serious error log bloat on your hands. You don't need to do this to enable the agent failure message, which is logged by default.
EXEC sp_altermessage 14150, 'WITH_LOG', 'true'

Then in the "Response" page for the alert, you can choose which operators to notify. Set them up under SQL Server Agent, Operators if you don't have any defined.

A: My favorite measurement for this is distributor latency.
If data is getting published but never hits the subscriber, the distributor will scream about the latency to deliver. Setting up this type of alert has also served me well in seeing other problems early (network probs for example).
To baseline it, set an alert for distributor latency and set the alert to fire @ 1 second of latency (this alert is in MS). Set your alert to fire no more frequently than every 15 minutes and watch it for a period of time. Then dial in the threshold to what is appropriate for your publication.
I'm not able to send a screenshot atm, but I did find this person's blog post with a script to set the type of alert I'm talking about:
http://sqlblog.com/blogs/linchi_shea/archive/2009/06/05/distribution-latency-in-transactional-replication-is-a-volume-surge-the-culprit.aspx

A: SSMS -> Connect to the subscriber -> SQL Server Agent -> Alerts -> Double Click "Replication: agent failure" -> Response -> Add your operator with the alert type(s) you wish. (I recommend security groups instead of individuals).


text:
Q: How to apply lazy loading in background images i'm trying to improve my page speed, in order to do that i have used many lazy loading plugin, they work for normal images but not for background images. i need to lazy load background images to improve my page speed please help!!!

A: That is nothing that can be installed by a plugin or, at least, would be necessary for you to work on it.
However, you can build this yourself.
Step 1: Enqueue the IntersectionObserver polyfill you can find here: https://github.com/w3c/IntersectionObserver/blob/master/polyfill/intersection-observer.js to get Support for older Browsers.
Step 2: Change the code of your HTML-Elements which use a Background Image. Add a class (let's say lazybg) and put the background-image into a data-attribute (let's say data-lazybg). So you change this:

into this:

Step 3: Write some javascript to load the background-image lazily:

Success! Your prepared divs will now load the background-image when they come into the viewport!


text:
Q: $p=a^2+ab+41b^2$ iff $-163$ is a quadratic residue Prove that a prime $p$ can be written as $p=a^2+ab+41b^2$ iff $-163$ is a quadratic residue modulo $p$.
What I have in mind is something like this: look at $\mathbb{Q}[\sqrt{-163}]$ which has the ring of integers $\mathbb{Z} \left [ \dfrac{1+\sqrt{-163}}{2} \right ]$. Now $p$ is of that form iff $p$ is the norm of an element in the ring of integers. It is well known that the ring of intergers in this case is a PID. However, I cannot tie the fact that -163 has to be a quadratic residue to all of this (in one direction, clearly if $p=a^2+ab+41b^2$ then $4p=(2a+b)^2+163b^2$ so $-163$ has to be a quadratic residue).  Could somebody help me complete a solution along these lines?

A: I love the form "$a^2 + ab + 41b^2$" because it helps confuse humans. The fact that $a$ and $b$ are integers is too small a benefit to make this confusion worthwhile.
Setting $$\theta = \frac{1}{2} + \frac{\sqrt{-163}}{2}$$ we see that $(a + b \theta)(c + d \theta) = p$ gives us two solutions to $a^2 + ab + 41b^2 = p$. For example, $\theta (1 - \theta) = 41$ tells us that $0^2 + 0 \times 41 + 41 + 41 \times 1^2 = 41$ and $1^2 + (1 \times -1) + 41 \times (-1)^2 = 41$. However, if we rewrite $a + b \theta$ as $$\frac{m}{2} + \frac{n \sqrt{-163}}{2},$$ the relationship between a number in this domain and its conjugate becomes much easier to see. In fact, $$\left(\frac{m}{2} - \frac{n \sqrt{-163}}{2}\right) \left(\frac{m}{2} + \frac{n \sqrt{-163}}{2}\right) = N,$$ which in this example is the prime $41$ if we set $m = n = 1$: $$\left(\frac{1}{2} - \frac{\sqrt{-163}}{2}\right) \left(\frac{1}{2} + \frac{\sqrt{-163}}{2}\right) = 41.$$

A: Consider the decomposition of $p$ in $\mathcal{O} = \mathbb{Z} \left[\frac{1+\sqrt{-163}}{2} \right]$.
There exists an ideal in $\mathcal{O}$ of norm $p$ $\Longleftrightarrow$ $p$ splits in $\mathcal{O}$ $\Longleftrightarrow$ $-163$ is a quadratic residue mod $p$.
In fact, (since $p$ is unramified in $\mathcal{O}$), if $p$ is inert in $\mathcal{O}$ then the only ideal of $\mathcal{O}$ above $p$ is $(p)$ itself which is of norm $p^2$, hence there is no ideal of $\mathcal{O}$ of norm $p$.


text:
Q: jQuery count checked checkbox in next element My sample is counting every single checkbox on a page. How to count the checked checkboxes on next/sibling element with jQuery?
PS: I want this to work on multiple forms on a single page without calling the element(form) ID.

$(document).ready(function() {
  function countChecked() {
    var tCount = $("input:checked").length;
      $(".totalchecked").text( tCount + ' selected');
  }
  countChecked();
  var tCheck = $(".totalchecked");
  $(tCheck).next().find(":checkbox").click(countChecked);
});

form 1:

0 selected

    <input type="checkbox" class="class" name="1">
    <input type="checkbox" class="class" name="2">
    <input type="checkbox" class="class" name="3">

form 2:

0 selected

    <input type="checkbox" class="class" name="4">
    <input type="checkbox" class="class" name="5">
    <input type="checkbox" class="class" name="6">

/* Update */
I want something like this.

A: Check this working sample:

function checkTotalCheckedBoxes(){
$("div" ).each(function( ) {
  if(this.children.length === 3){
  var checked = 0;
 $(this.children).each(function() {
        this.checked ? checked++ : null;
        $("input[name="+this.name+"]").parent().siblings().closest('.totalchecked')[0].innerText = (checked) + " selected";

       });
  }
});
}

form 1:

0 selected

<input type="checkbox" class="class" name="1"  onclick="checkTotalCheckedBoxes()">
<input type="checkbox" class="class" name="2"  onclick="checkTotalCheckedBoxes()">
<input type="checkbox" class="class" name="3"  onclick="checkTotalCheckedBoxes()">

form 2:

0 selected

<input type="checkbox" class="class" name="4"  onclick="checkTotalCheckedBoxes()">
<input type="checkbox" class="class" name="5"  onclick="checkTotalCheckedBoxes()">
<input type="checkbox" class="class" name="6"  onclick="checkTotalCheckedBoxes()">

A: $('input[type=checkbox]').change(function() {
        var siblingsChecked = [];
           $(this).siblings().each(function(el){
                if($(this).is(':checked')) {
                    siblingsChecked.push(el);
                }
          });
        console.log(siblingsChecked.length);
    });

Hope this helps you !

A: Here is my own solution and I hope it helps someone.

$( document ).ready(function() {
    var $SelectCount = $("input:checkbox")
    $SelectCount.change(function(){
        var countChecked = $(this).parent().find("input:checkbox").filter(':checked').length;
        $(this).parent().siblings(".totalchecked").text(countChecked + " Selected");
    });
});

form 1:

0 selected

    <input type="checkbox" class="class" name="1">
    <input type="checkbox" class="class" name="2">
    <input type="checkbox" class="class" name="3">

form 2:

0 selected

    <input type="checkbox" class="class" name="4">
    <input type="checkbox" class="class" name="5">
    <input type="checkbox" class="class" name="6">

A:

$(document).ready(function() {
  function countChecked() {
    var tCount = $("input:checked").length;
      $(".totalchecked").text( tCount + ' selected');
  }
  countChecked();
  var tCheck = $(".totalchecked");
  $(tCheck).next().find(":checkbox").click(countChecked);
});

form 1:

0 selected

    <input type="checkbox" class="class" name="1">
    <input type="checkbox" class="class" name="2">
    <input type="checkbox" class="class" name="3">

form 2:

0 selected

    <input type="checkbox" class="class" name="4">
    <input type="checkbox" class="class" name="5">
    <input type="checkbox" class="class" name="6">


text:
Q: proud in vs pride of For the following sentence, which one of "be the greatest proud in my life" and "be the greatest pride of my life" is more idiomatic?

I believe being admitted into your university would be the greatest proud in my life

A: In OP's context, proud is completely unacceptable. It must be pride.
This particular use of pride ("thing of which one is proud") has declined massively over the past couple of centuries, but here's a chart showing the 10 most common adjectives used with it...

...and here's another chart showing just how rarely we include any adjectival modifier in constructions like She's the pride of our family...

I think the reason we tend to avoid modifiers (especially, superlatives) here is because this kind of "pride" already carries strong connotations of being uniquely highly valued. Consider the still-common usage have/take pride of place - if you're at the very top, you can't be more at the top.


text:
Q: unable to permit a param I'm trying to use active storage to to attach an image file to my photo model, but no matter what I try I get an error saying that the "image_file" is not permitted. I've found several other identical questions on Stack Overflow that are unanswered. Any advice would be greatly appreciated.

A: Create ActiveStorage tables
rails active_storage:install

Add to Model
class Photo < ApplicationRecord
  has_one_attached :image_file
end

Controller (permit :image_file)
def photo_params
  params.require(:photo).permit(:image_file)
end

Javascript for Direct Upload
//= require activestorage

Add Direct Upload to View
<%= f.file_field :image_file, class: 'form-control-file', direct_upload: true, required: true %>

A: When I hit the byebug I entered "params" which returned permitted: false but I should have entered "photo_params which returns permitted: true


text:
Q: Increasing OpenGL's far clip plane distance I'm trying to make a C++ OpenGL representation of our Solar System as a way to teach myself OpenGL, so please keep your answers simple.
The problem I have is that planets are very far away, so everything else is beyond the clipping plane when viewing from any given planet. How do I move the clipping of C++ OpenGL 3.1  plane to, say, 2000000000? I'd prefer a simple code snippet if you can.
I've looked up SO and forum posts about this, but they're either so old that nothing applies (using legacy APIs or just dead links), or so complex that I can't work out what they're saying.

A: Clipping planes are defined by the perspective projection matrix.
If you use glFrustum, change the last argument passed to it to 2000000000.0.
If you use your own matrix, set 10th element of your matrix array to:
(2000000000.0+nearClippingPlane)/(nearClippingPlane-2000000000.0)
(the formula is (far+near)/(near-far))
and 14th to:
(-4000000000.0*nearClippingPlane)/(2000000000.0-nearClippingPlane)
(the formula is (-2.0*near*far)/(far-near))
2000000000 is very big value, however, so Z-fighting may occur if you add details such as mountains.


text:
Q: What is the simplest function yielding Fibonacci numbers upon iteration? A while ago I asked a question on trigonometric functions that are iteratively periodic. That is, after a finite number of iterations (compositions of the function with itself) the function returns to its original form. In other words, for some $k \in \mathbb{Z}_{>1}$ we have $f^{[k]} (x) = f^{[1]}(x) =: f(x)$.
In the question, I also mentioned some counterexamples that are not iteratively periodic. In these instances, I found functions that yield Fibonacci numbers upon iteration:

*

*Consider $m(x) := m^{[1]}(x) = \cot(\arcsin(x)) = \frac{\sqrt{1-x^{2}}}{x}$. Then, $m^{[n]}(x) = \sqrt{ \frac{F_{n} - F_{n+1}x^{2}}{F_{n}x^{2} - F_{n-1}} \cdot (-1)^{n+1} } $ for $n >1$, where $F_{n}$ is the $n$'th Fibonacci number.

*Define $l(x) := l^{[1]}(x) = \cos(\arctan(x)) = \frac{1}{\sqrt{1+x^{2}}} $. In this case, $l^{[n]} (x) = \sqrt{\frac{F_{n} + F_{n-1}x^{2}}{F_{n+1} + F_{n}x^{2}}}$ for $n>1$.

Question: though $m(\cdot)$ and $l(\cdot)$ are not the most complex functions, I wonder whether there exist functions that are even simpler than these and generate fibonacci numbers as well upon iteration. On could consider a rigorous definition of function complexity, but if that's not your thing then a simple function from a more intuitive sense (as little operations and inputs as possible) suffices as well. The function does not have to be trigonometric.

A: Take $f(x) = 1+\frac{1}{x}$. Then $$f^{[n]}(x) = \frac{F_{n+1} x +F_n}{F_n x + F_{n-1}}$$
A related one is $g(x) = \frac{1}{1+x}$. Then $$g^{[n]}(x)=\frac{F_{n-1}x+F_n}{F_n x+F_{n+1}}$$
I doubt there are "simpler" functions that those two whose iterations involve Fibonacci numbers.
This functions also have other amusing properties, for example:
If you define $f^{[n]}(x)$ for $n<0$ as the iterations of the inverse function, and extend in the usual way the Fibonacci numbers to negative indices, the formula above remains valid.
We have $\displaystyle \lim_{n\to\infty} f^{[n]}(1) = \lim_{n\to\infty}\frac{F_{n+2}}{F_{n+1}}=\phi$, the golden ratio.


text:
Q: How do I return the pkgInfo object from this arrow function? I installed an npm library reiko parser and it shows the pkgInfo object using console log. I changed the code to return this pkgInfo object but it returns undefined. I'm new to arrow functions so I'm quite lost how to get the pkgInfo object unless I declare a static variable and assign it the value of pkgInfo object which is bad practice?
function get_icon(serverFilePath) {
    const readerPkg = new PkgReader(serverFilePath, 'apk', { withIcon: true });
    return readerPkg.parse((err, pkgInfo) => {

        if (err) {
            console.log(err);
        } else {
            console.log(pkgInfo); // works with console log but not return??
           return pkgInfo //undefined
        }
    });

}

EDIT: This is also the code that was given in the npm pg
const reader =

     new PkgReader(filePath, 'apk', { withIcon: true });
    reader.parse((err, pkgInfo) => {
      if (err) {
        console.error(err);
      } else {
        console.log(pkgInfo); // pkgInfo.icon is encoded to base64
      }
    });

A: should just be return pkgInfo same as a normal function


text:
Q: Tomcat 9 Azure Webapp - Edit the Connection in Server.xml I would like to edit the  <Connector connectionTimeout="xx" /> property in the server.xml of my Tomcat 9 Server.
However the app was deployed to an Azure WebApp (Serverless Instance) Directly from the Eclipse IDE and I am unable to find or edit that file.
Is there anyway to do this within the Azure Portal?
Is it possible to define the connectionTimout property another way?
Any help would be most appreciated.
This thread did not answer any questions : Increase azure web app request timeout


text:
Q: Using $_SESSION with OOP php I need to redesign the back-end of a website and need some help getting started. The original website uses OOP, there is a class "User" used to saved data when users log on. This is serialized and unserialized on each page as needed:
// login.php
$user = new User($iduser);
// ...
// At the end of the script
$_SESSION["user"] = serialize($user);

// Another page
$user = unserialize ($_SESSION["user"]);

Thus that data is available on every page that the user visits. Plus, in (almost) every page visited, $_SESSION["user"] is updated with new data (it's quite possible that page_a.php doesn't use data that page_b.php needs to show).
The new design should be fully object oriented. And the main problem I find is that I don't know how to store properly that $_SESSION["user"] in a class method.
I tried to use Codeigniter, but it uses session variables with cookies, and that is not what I need.
Any suggestion or link would be helpful. Thanks in advance.

A: I have no experience with Codeigniter, so I can't give any specific advise on that. I trust others will point you in the right direction if there are any specific tools available for this use case in this framework. I can give you some insights on how you could handle this with basic, vanilla PHP tough.
If you want to keep things simple, I would suggest working with some sort of App singleton (or Auth, or whatever you want to call it), that can handle static data like the active user. Consider the following (very basic and untested) code
class App {

    protected static $instance;
    public $user;

    final private __construct() {
        $user = unserialize($_SESSION['user']);
    }
    final private __clone() {}

    public static getInstance() {
        if (! self::$instance) {
            self::$instance = new static;
        }
        return self::$instance;
    }

    public function __destruct() {
        $_SESSION["user"] = serialize($this->user);
    }
}

This would allow you to do things like:
/* fetch the active user */
$user = App::getInstance()->user;

/* set the active user */
$app = App::getInstance();
$app->user = new User($iduser);

The destruct handler takes care of sending your data back to the session when you are done with the App object. And since we use the singleton pattern, there can only be one instance of it, no matter where you call it from. This ensures you are always talking to the same User.
Let me know if anything is unclear, or if you want me to explain further.


text:
Q: Entity Framework user select database target So here is my question. For my open source project it is essential that we allow the user to store the contents of the cache on the file system, we currently do this by serializing the cache into json and store it as plain text files.
Since we want to get away from this solution in future versions, we are now looking for way to store the cache in a database.
In our current plans the user has the possibility to decide which database he wants to use (e.g. SQL Server compact, an already existing database, etc.). Now my questions are:

*

*Can something like this be achieved with EF? Can I switch the database while the application is running, or do I need to recompile the application for a database switch?

*Would EF be the best way to do this, or am I overlooking better solutions?

A: Can something like this be achieved with EF? Can I switch the database while the application is running, or do I need to recompile the application for a database switch?

If you have different database like Oracle, MS SQL etc, then in EF you have to make different models for each of them and then distribute to the client depend on which database they are using.
Would EF be the best way to do this, or am I overlooking better solutions?

It totally depends, you can possibly achieve this by simple ado.net. But for sake of flexibility EF code first and T4 code generator from model gives you nice options in which your domain data , data access layer, bussiness rule will be same for different database. You just have to modify the connection in app. config file.
I hope this helps you.


text:
Q: A Curious Binomial Sum Identity without Calculus of Finite Differences Let $f$ be a polynomial of degree $m$ in $t$. The following curious identity holds for $n \geq m$,
\begin{align}
\binom{t}{n+1} \sum_{j = 0}^{n} (-1)^{j} \binom{n}{j} \frac{f(j)}{t - j} = (-1)^{n} \frac{f(t)}{n + 1}.
\end{align}
The proof follows by transforming it into the identity
\begin{align}
\sum_{j = 0}^{n} \sum_{k = j}^{n} (-1)^{k-j} \binom{k}{j} \binom{t}{k} f(j) = \sum_{k = 0}^{n} \binom{t}{k} (\Delta^{k} f)(0) = f(t),
\end{align}
where $\Delta^{k}$ is the $k^{\text{th}}$ forward difference operator. However, I'd like to prove the aforementioned identity directly, without recourse to the calculus of finite differences. Any hints are appreciated!
Thanks.

A: This is just Lagrange interpolation for the values $0, 1, \dots, n$.
This means that after cancelling the denominators on the left you can easily check that the equality holds for $t=0, \dots, n$.

A: I just ran across this question after working on this answer, and realized that the same method could be used here.
Notice that your equation is equivalent to
$$
\sum_{j=0}^n(-1)^{n-j}\binom{n}{j}\frac{f(j)}{t-j}=\frac{n!f(t)}{t(t-1)(t-2)\dots(t-n)}
$$
As long as $f$ is a polynomial of degree $n$ or less, apply the Heaviside Method for Partial Fractions to the right hand side to get the left hand side.
That is, to compute the coefficient of $\frac1{t-j}$ on the left hand side, multiply both sides by $t-j$ and set $t=j$. The right hand side becomes
$$
\frac{n!f(j)}{j(j-1)(j-2)\dots1(-1)(-2)\dots(j-n)}=(-1)^{n-j}\binom{n}{j}f(j)
$$

A: This can also be done with  complex variables. Observe that we have by
inspection that
$$\sum_{j=0}^n (-1)^j {n\choose j} \frac{f(j)}{t-j}
= (-1)^n \times n! \times
\sum_{k=0}^n \mathrm{Res}_{z=k}
\frac{f(z)}{t-z}\prod_{q=0}^n \frac{1}{z-q}.$$
This holds  even if  $f(t)$ vanishes at  some positive integer  in the
range.

Recall that the residues sum to zero, so the right is equal to
$$-(-1)^n \times n! \times
\sum_{k\in\{\infty,t\}} \mathrm{Res}_{z=k}
\frac{f(z)}{t-z}\prod_{q=0}^n \frac{1}{z-q}.$$
The residue at infinity of a function $h(z)$ is given by the formula
$$\mathrm{Res}_{z=\infty} h(z)
= \mathrm{Res}_{z=0}
\left[-\frac{1}{z^2} h\left(\frac{1}{z}\right)\right]$$
which in the present case yields
$$-\mathrm{Res}_{z=0} \frac{1}{z^2}
\frac{f(1/z)}{t-1/z}\prod_{q=0}^n \frac{1}{1/z-q}
\\ = -\mathrm{Res}_{z=0} \frac{z^{n+1}}{z^2}
\frac{f(1/z)}{t-1/z}\prod_{q=0}^n \frac{1}{1-qz}
\\ = -\mathrm{Res}_{z=0} z^n
\frac{f(1/z)}{zt-1}\prod_{q=0}^n \frac{1}{1-qz}.$$
Note however that  $f(z)$ has degree $m$ and we  require that $n\ge m$
which means $f(1/z) z^n$ has no  pole at zero and hence the residue at
infinity is zero as well.

That leaves the residue at $z=t$ for a total contribution of
$$-(-1)^n \times n! \times (-1)\times f(t)\times
\prod_{q=0}^n \frac{1}{t-q}
= (-1)^n f(t) \times n! \prod_{q=0}^n \frac{1}{t-q}
\\ = (-1)^n f(t) \times n! \times
\frac{1}{(n+1)!} {t\choose n+1}^{-1}
\\ = (-1)^n \frac{f(t)}{n+1} {t\choose n+1}^{-1}$$
which was to be shown, QED.


text: Q: error when Adding Fire Base Sdk for ios app in flutter Hi I am adding the firebase in my flutter app and create the app in the fire Base website for android and when adding it in the IOS he wants to do this and i do not know what he wants could anyone help me