text:
Q: Filtering of javascript object I am having an object listing as following
{
  "ACCOUNT": "Accountant",
  "ART": "Artist/Entertainer",
  "BIZ": "Business Owner",
  "CIVIL": "Civil Servant",
  "CLERK": "Clerk/Executive",
  "CONSULT": "Consultant",
  "EDU": "Educationist",
  "ENGINEER": "Engineer",
  "FACTORY": "Factory Worker",
  "FARMER": "Farmer",
  "FINANCE": "Finance Professional",
  "FREELANCER": "Freelancer",
  "GM": "General Manager/Director",
  "GWORKER": "General Worker",
  "HOUSEWIFE": "Housewife",
  "MANAGER": "Manager",
  "OTHERS": "Others",
  "POLICE": "Police/Army/Fireman",
  "PROF": "Professional",
  "RETIREE": "Retiree",
  "SALES": "Salesman/Marketer",
  "TECH": "Technician",
  "UNEMPLOY": "Unemployed"
}

How can i filtering object and return obj when user type specific character. For example when user type 'A'. Only return
  {
      "ACCOUNT": "Accountant",
      "ART": "Artist/Entertainer",
}

A:

const List_X =
  { ACCOUNT   : "Accountant"
  , ART       : "Artist/Entertainer"
  , BIZ       : "Business Owner"
  , CIVIL     : "Civil Servant"
  , CLERK     : "Clerk/Executive"
  , CONSULT   : "Consultant"
  , EDU       : "Educationist"
  , ENGINEER  : "Engineer"
  , FACTORY   : "Factory Worker"
  , FARMER    : "Farmer"
  , FINANCE   : "Finance Professional"
  , FREELANCER: "Freelancer"
  , GM        : "General Manager/Director"
  , GWORKER   : "General Worker"
  , HOUSEWIFE : "Housewife"
  , MANAGER   : "Manager"
  , OTHERS    : "Others"
  , POLICE    : "Police/Army/Fireman"
  , PROF      : "Professional"
  , RETIREE   : "Retiree"
  , SALES     : "Salesman/Marketer"
  , TECH      : "Technician"
  , UNEMPLOY  : "Unemployed"
  }

let List_filter = Object
                    .keys(List_X)
                    .filter(k=>/^A/.test(k))
                    .reduce((a,c)=>{a[c]=List_X[c];return a},{})

console.log( List_filter )
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Qt : QImage load data from memory I am new to StackOverFlow and wish there are experts to my problem, which consumed me a week time!
I embedded my JPEG files into a single data file, and need to load them on demand to avoid memory problem in mobile phone.
I wrote something like:
char *imageBuffer = getBytes(sourceFilename, offset, length);

to get a JPEG file data from a sourceFile  with offset and length. I saved the bytes to file and it works.
My problem is how can I construct a QImage from the (char *) data? I tried many methods and haven't any success.
Wishing that there is experienced members to solve my problem. Thanks!!!

A: Yes, you can load using QImage::loadFromData().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error "WebView.Context" when running WebView I'm learning how to make a webview from youtube, however i followed every step of their code, however my code got an error while their code did not. I can't run but they can. Error said "Cannot convert value of type 'WebView.Context' (aka 'UIViewRepresentableContext') to expected argument type 'URLRequest'"
Can someone point out the problem? Thank you.
import SwiftUI
import WebKit
import UIKit
import SwiftUI

struct ContentViewww: View {
 var body: some View {
    NavigationView {
        NavigationLink {
            WebView(url: URL(string: "https://www.youtube.com")!)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
        } label: {
            Text("open website")
                .padding(10)
                .background(.black)
                .foregroundColor(.white)
        }
        .navigationBarHidden(true)
    }
   }
   }

struct WebView: UIViewRepresentable {

 var url : URL
 func makeUIView(context: Context) -> some UIView {
     let web = WKWebView()
    let request = URLRequest(url: url)
    web.load(context)
    return web

 }

 func updateUIView(_ uiView: UIViewType, context: Context) {
    let web = WKWebView()
    let request = URLRequest(url: url)
    web.load(request)
 }

}

A: You are supposed to load request not context.
func makeUIView(context: Context) -> some UIView {
  let web = WKWebView()
  let request = URLRequest(url: url)
  web.load(request) //modified
  return web

}


text:
Q: Why Run-time error '3061'. Too few parameters. Expected 1? Access 2010 I have researched all the STACKOVERFLOW questions on this but cannot make it work.  I have a simple table:

And a form:

I want to extract the fields from the table T:ActityRoster and the "Activity Date" from the form and "add" them to a table T:ActivityHistory.

A STACKOVERFLOW expert helped me with some code, but it won't even set the first recordset:rsIn
Dim ActID As Integer, actDate As Date, val1 As Long, val2 As Long, val3 As Boolean, val4 As Currency

Dim db As Database, rsIn As Recordset, rsOut As Recordset

Dim strSQL As String

Set db = CurrentDb

ActID = Me.cboActivityName.Column(0)

strSQL = "SELECT * FROM T:ActivityRoster WHERE [ActivityID] = ActID"

Debug.Print strSQL

Set rsIn = db.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)

rsIn.MoveLast

Set rsOut = db.OpenRecordset("T:AttendanceHistory", dbOpenDynaset, dbEditAdd)

rsOut.MoveLast

actDate = Me.ActivityDate.Value  ' retrive the date from the form

With rsIn
    .MoveFirst
    Do
    val1 = !ActivityID
    val2 = !MemberID
    val3 = !Attended
    val4 = !AmtSpent

           With rsOut
               .AddNew
               !ActivityDate = actDate
               !ActivityID = val1
               !MemberID = val2
               !Attended = val3
               !AmtSpent = val4
               .Update
           End With

    .MoveNext
    Loop Until .EOF
    .Close

End With

rsOut.Close
Set rsIn = Nothing
Set rsOut = Nothing
Set db = Nothing

End Sub

I have verified that all field names are correct and are consistent data types. When I put the query back into Access, it gives what is expected.

A: The SELECT statement includes the name of a VBA variable (ActID):
strSQL = "SELECT * FROM T:ActivityRoster WHERE [ActivityID] = ActID"

Unfortunately, the db engine doesn't know anything about that variable.  So, when it sees ActID, it presumes that is the name of a parameter for which you haven't supplied a value.
Include the variable's value instead of its name when you build the SELECT statement.  Use one of these 2 examples: the first if [ActivityID] is text datatype; or the second if it's numeric datatype:
strSQL = "SELECT * FROM [T:ActivityRoster] WHERE [ActivityID] = '" & ActID & "'"
strSQL = "SELECT * FROM [T:ActivityRoster] WHERE [ActivityID] = " & ActID

I enclosed the table name in square brackets because that name includes punctuation.  However, I would rename the table if possible.  Same for T:AttendanceHistory.  Choose object names which do not include punctuation and spaces and which do not match VBA or SQL keywords.
Alternatively you could use a parameter query and supply the parameter value with ActID:
strSQL = "SELECT * FROM [T:ActivityRoster] WHERE [ActivityID] = [which_ActivityID]"
Dim qdf As DAO.QueryDef
Set qdf = db.CreateQueryDef(vbNullString, strSQL)
qdf.Parameters("which_ActivityID").Value = ActID
Set rsIn = qdf.OpenRecordset(dbOpenSnapshot)

A: My source was a query and it had criteria in it referencing a field on a form. Got rid of that and all is now okay.  All my fields in the query were the right name, etc.

A: A little old, but I ran into this issue today and required a different solution. So hopefully this helps out anyone who runs into this in the future.
I had this error pop up when I created a new query and tried to reference it in VBA:
Set rst = CurrentDb.OpenRecordset("SELECT * FROM qry_New WHERE [Field]='" & [RptField] & "'")

Compiling the project seemed to resolve the error. Debug > Compile [Project Name] in the VB Editor.
This was also in Access 2013, not Access 2010, so I'm not sure if it applies in this exact scenario.


text:
Q: add font to Ghostscript 9.15 when compiling When building ghostscript from scratch, without compiling in in the fonts / resources, etc., it is fairly straightfoward to add a font - you simply edit the Fontmap.GS and add the appropriate .pfa, .pfb, and .afm files to ghostscript's installation font folder.
Ghostscript allows you to build an 'embedded' version of it, where the fonts, etc. and compiled right into the executable.
My question is, how do you add a font to the source tree such that the new font will be embedded along with the default ones?
I tried modifying the Fontmap.gs in the Resource/Init source folder, but the resulting gs executable didn't have the font I wanted to add.

A: In addition to adding the font to the font map, you will need to put the font file somewhere in ghostpdl/Resource, normally in the Font sub-folder.
Ghostscript doesn't need, and isn't interested in, .afm files by the way.
The ROM File system is built by the mkromfs tool, so you can debug that to see what's going on. Eventually that should produce a C file called gsromfs1.c which you can open and read. You won't find it terribly interesting, but there are comments which include the filename of all the files which are embedded in there.
If you still can't get that to work we will need considerably more information; a copy of the modified font map, the name of the font file, and its type, the location where you are storing it, what platform you are using and the make invocation you are using.
You are also using a somewhat out of date version of Ghostscript, the current version is 9.19.


text:
Q: Show that if $(a,n)=d>1$ and $k$ is any positive integer, then $a^k\not\equiv 1\pmod{n}.$ So I know that if $(a,n)=1$, then $a^{\phi(n)}≡1\pmod{n}$ by Euler's Theorem. I also know that $d \mid a^k$ and obviously $d \mid n$. I know I probably need to use this in the proof, but I just don't know how to get started.

A: Given $(a,n) = d > 1$, suppose for the sake of contradiction that for some $k > 0$, $a^k \equiv 1 \pmod{n}$. Rewrite the equivalence as $(a/d)^kd^k \equiv 1 \pmod{n}$. This implies that $d^k$ is the multiplicative inverse of $(a/d)^k$ modulo $n$. Such an inverse exists if and only if $d^k$ is relatively prime to $n$; however, since $d \mid n$, we know $d^k$ and $n$ share a factor of $d > 1$. Therefore, $d^k$ is not relatively prime to $n$, so we have a contradiction.

A: Suppose $a^k \equiv 1\bmod{n}$. Write $a=da',n=dn'$.
Then $n' \equiv n' a^k = n' a a^{k-1} =n'da' a^{k-1} = na' a^{k-1} \equiv 0 \bmod n$.
This contradicts $0< n' < n$.

A: If $\gcd(a,n) = d > 1$ then $d \mid a^k, \forall k\in \mathbb{Z^+}$ and $d \mid n$.
Now let $a^k=(d\cdot x)^k$ and $n=d\cdot y$ then:
$$(d\cdot x)^k \equiv b \pmod {d\cdot y} \Rightarrow (d\cdot x)^k = d\cdot y\cdot q + b$$
$$(d\cdot x)^k - d\cdot y\cdot q = b \Rightarrow b \mid d(d^{k-1}x^k-y\cdot q)$$
Thus $gcd(d,b)=d$ and since we said $d>1 \cdots$


text:
Q: Reading variable length real values in fortran I have a file with the following text:
-1.065211      246.0638 xlo xhi
-0.615       245.385 ylo yhi
-10 10 zlo zhi

I want to read the numerical values on the lines into a 3*2 real matrix.
Is it possible to read only two inputs of a record and go to the next line? Something like:
read(1,'(2F?.?/)') (matrix(i,1:2),i=1,3)
I've put question marks in F?.? because the length of my numbers are variable. In other words, I need to read only two items of the record in free-format. I understand that you can do this by a loop. I'm wondering if an elegent one-liner is possible.

A: You can achieve what you want with
do i = 1, 3
   read(fd,*) matrix(i,:)
end do

where it is assumed that fd is connected to the file containing your data.

A: The code in @Steve's answer is the simplest one that can accomplish what you want.  If you want it in one line, you can simply
do i=1,3 ; read(fd,*) matrix(i,:) ; end do

If what you are looking for is a way to "read only two inputs of a record and go to the next line" with only one statement, that is, to my knowledge, not possible: Since your real values have different formats, you need to use list-directed input (an asterisk in the format) in order to read multiple lines with the same statement (all other formats for reals require a positive width for input, and since your reals have different widths any specification of a width would result in a runtime error).
If you want to only use one statement, you will need to explicitly tell the program to read the two strings at the end of each line, even if they are discarded (otherwise the program will try to run a string into a real number, and this will result in a runtime error):
character(len=10) :: r
read(1,*) (a(i,:),r,r,i=1,3)

This is less general than @Steve's code (requires that you have exactly 2 character strings per line), and actually requires the additional declaration of the character variable.
Finally, note that you are not reading the array in element sequence order: in Fortran, the order of the elements of the array in the memory is a(1,1), a(2,1), a(3,1), a(1,2), etc.  If the actual arrays you are planning on manipulating are much bigger, the order of the indices may dramatically affect performance, since your consecutive memory accesses may address distant parts of the memory rather than contiguous parts of it.  When you are writing a program in Fortran, as in any other language (which may use a different ordering), you need to give some thought to the order of the indices of arrays.


text:
Q: jQuery .clone(true, true) not cloning events I'm working on this piece of code and as I'm not really good with jQuery, I found myself stuck.
var row_clone_index = 1;
function Row_clone() {
    var cloned_row = $(this).parent().parent().clone(true, true);
    cloned_row.css('display', 'none');
    cloned_row.delay(100).queue(function(next){
        cloned_row.css('display', '');
        next();
    });
    $(this).removeClass("row-clone");

    var html = cloned_row.html().replace(/new/g, "new" + row_clone_index);
    cloned_row.html(html);

    cloned_row.find("select,input").each(function() {
        if (!$(this).hasClass("preserved")) {
            if (!$(this).attr("id")) {
                $(this).val("");
            } else {
                match = $(this).attr("id").match(/((start|stop)holiday_new)[0-9]*_(calendar(month|year))/);
                if (match) {
                    id = match[1] + "_" + match[3];
                    $(this).val($("#" + id).val());
                } else {
                    if ($(this).attr("type") == "checkbox") {
                        $(this).removeAttr("checked");
                    } else if ($(this).attr("id").match(/(start|stop)holiday_new.*/)) {
                        $(this).val("");
                    } else if ($(this).attr("id").search(/day/) == -1) {
                        $(this).val("");
                    }
                }
            }
        }
    });
    $(this).parent().parent().after(cloned_row);
    row_clone_index = parseInt(row_clone_index) + 1;
};

What I'm trying to do is clone an element when it changes (the Row_clone function is called on a .change()). But the events that should happen when interacting with this element after being cloned don't happen.
I tried moving the .after at the end (it was previously at the beginning of the function but it didn't change anything).
Thanks for the help!

A: It looks like you're cloning it right, however afterwards, you're also changing the HTML of the element, which does most probably invalidate all your previously cloned bindings:
var html = cloned_row.html().replace(/new/g, "new" + row_clone_index);
cloned_row.html(html);

Don't adjust the HTML directly, use find() to change the sections you need to replace by whatever needs replacing.


text:
Q: Given a planar graph with minimum cycle length 8, show that $|E| \le \frac{4}{3}|V| - \frac{8}{3}$ Here's what I've got so far. I'm stuck on how to proceed. I believe I need to plug back into Euler's formula, but I'm not getting what I'm looking for by doing that. Where is the denominator of $3$ coming from in the result? Can you please check over my proof for any incorrect statements, and help me move forward?

Proof. Let $G$ be a connected planar graph with at least two edges, and a cycle with length $\ge 8$. Pick a crossing-free embedding of $G$; this embedding has $f$ faces. By Euler's formula, $$f = 2 - |V| + |E|\;.$$
  We calculate the sum of the degrees of the faces in this embedding. On the one hand, the sum of the face degrees is $2|E|$ by proposition. On the other hand, since there is a cycle of at least length $8$, the sum of the face degrees is at least $8f$.

That's where I'm stuck at. Any ideas?

A: If every cycle has length at least eight, then every face in your crossing-free embedding is bounded by at least eight edges, so $8f < 2|E|$, or simply $4f < |E|$. Combining this with Euler's characteristic formula,
$$\begin{align}
  |E|=f+|V|-2 &\implies 4|E| = 4f + 4|V| - 8 \\
              &\implies 4|E| \leq |E| + 4|V| - 8 \\
              &\implies 3|E| \leq 4|V| - 8 \\\\
              &\implies  |E| \leq \frac{4}{3}|V| - \frac{8}{3} \\
\end{align}$$


text:
Q: Change moverows script that checks blanks i a row to specific cells left blank in a row Got help with my script from Cooper yet i need some modification, the script basically moverows with a custom dialog if a cell in the row is left blank.
What i like to accomplish is that only the specific cells in a row will be checked.
e.g. row 1 and 4 are mandatory and row 2 and 3 are not.
This is the code what I've got so far.
    function Moverows57654() {

 var ss=SpreadsheetApp.getActive();
 var sourceSheet=ss.getSheetByName("sheet1");
 var targetSheet=ss.getSheetByName("sheet2");
 var sourceRange=sourceSheet.getRange("A2:T2");
 var values=sourceRange.getValues();
 var range0=sourceSheet.getRange("A2:B2");
 var range1=sourceSheet.getRange("D2:E2");
 var firstFreeRow=goToFirstRowAfterLastRowWithData(targetSheet, "A:AD");
 var noBlanks=true;
 var bA=[];
 var ro=sourceRange.getRow();
 var co=sourceRange.getColumn();
 for(var ri=0;ri<values.length;ri++) {
 for(var ci=0;ci<values[ri].length;ci++) {
  if(!values[ri][ci]) {
    noBlanks=false;
    bA.push(sourceSheet.getRange(ri+ro,ci+co).getA1Notation());
  }
   }
    }
 if(noBlanks) {

  targetSheet.getRange(firstFreeRow,1,values.length,values[0].length)
 .setValues(values);      targetSheet.getRange(firstFreeRow, 1, values.length, values[0].length)

    .setValues(values);
range0.clearContent();
range1.clearContent();

//createPdf()//function gets started
}else{
SpreadsheetApp.getUi().alert('Sorry there are blanks in the following cells: ' + bA.join(', '));
return;
 }

A: Try this:
function Moverows57654() {
  var ss=SpreadsheetApp.getActive();
  var sourceSheet=ss.getSheetByName("sheet1");
  var targetSheet=ss.getSheetByName("sheet2");
  var sourceRange=sourceSheet.getRange("A2:T2");
  var values=sourceRange.getValues();
  var range0=sourceSheet.getRange("A2:B2");
  var range1=sourceSheet.getRange("D2:E2");
  //var firstFreeRow=targetSheet.getLastRow() + 1;
  var firstFreeRow=goToFirstRowAfterLastRowWithData(targetSheet, "A:AD");
  var noBlanks=true;
  var bA=[];
  var skA=[1,2];//column -1
  var ro=sourceRange.getRow();
  var co=sourceRange.getColumn();
  for(var ri=0;ri<values.length;ri++) {
    for(var ci=0;ci<values[ri].length;ci++) {
      if(!values[ri][ci] && skA.indexOf(ci)==-1) {
        noBlanks=false;
        bA.push(sourceSheet.getRange(ri+ro,ci+co).getA1Notation());
      }
    }
  }
  if(noBlanks) {

    targetSheet.getRange(firstFreeRow,1,values.length,values[0].length)
    .setValues(values);      targetSheet.getRange(firstFreeRow, 1, values.length, values[0].length)

    .setValues(values);
    range0.clearContent();
    range1.clearContent();

    //createPdf()//function gets started
  }else{
    SpreadsheetApp.getUi().alert('Sorry there are blanks in the following cells: ' + bA.join(', '));
    return;
  }
 }


text:
Q: EPUB, combining all xml documents in a single xml file Is it possible to combine all the xml documents in an EPUB in a single xml file?

A: You might want yo look at Sigil e-book editor link. I know you can do it by hand, but may be there is a batch processing capabilities.

A: You can do it relatively fast by using XSLT 2.0 :
See document() and collection() functions for reading the files.
Use the identify template for copying the content of each documents.
One of the advantage of using XSLT is that you are sure to obtain a well-formed XML.
I will try to post a sample soon.


text:
Q: how can I show progressbar in WPF for DB actions? I want to show my application user a progressbar for following actions:

*

*when they provide login information in WPF and hit submit/OK whatever.

*when they request any information from DB (select command execution).

Thank You

A: A login to the database is an atomic operation.  So you can't really show a progress bar.  You can show a waiting indicator (hour glass), or an indeterminate progress bar (which is really just a waiting indicator that looks like a progress bar).
For a query that gets data, you can show progress by paging the result set.  There are multiple ways to do this depending on the database/ORM you use.  The general principle is to set up a worker thread and grab data one page at a time.  After you grab a page, switch context to the UI thread and update the screen to show how much data you grabbed.


text:
Q: A parallel RL circuit being energized by a sinusoidal a.c. voltage of \$v=100\sin(1000t+36°)\$. Find total current in RMS value The question is as follows:

\$\bullet\$In my book it is done as:
\$\begin{align}\\
i_R &=\frac{V_m}{R}\sin(1000t+36°)\\
&=10\sin(1000t+36°)A\\
&=10\cos(1000t-54°)....(a)\\
\end{align}\\\$
\$\begin{align}\\
i_L&=\frac{V_m}{\omega L}\sin(1000t+36°-90°)\\
&=10\sin(1000t-54°)\\
&=10\cos(1000t-144°)....(b)\\
\end{align}\\\$
From (a) and (b) we get, \$I_R=10\angle-54°\$ and \$I_L=10\angle-144°\$
\$\therefore\$ net r.m.s. current
\$\begin{align}\\
I&=I_R+I_L =10\angle-54°+10\angle-144°\\
&{\begin{aligned}\\
=10(\cos54°-j\sin54°)&+10(\cos144°-j\sin144°)\\
\end{aligned}\\}\\
&=5.88-j8.1-8.1-j5.88\\
&=(-2.22-j13.97)A\\
\end{align}\\\$
i.e.\$I=14.14\angle-99°\$A
\$\bullet\$I did it like:
\$\begin{align}\\
i_R &=\frac{V_m}{R}\sin(1000t+36°)\\
&=10\sin(1000t+36°)A....(a)\\
\end{align}\\\$
\$\begin{align}\\
i_L&=\frac{V_m}{\omega L}\sin(1000t+36°-90°)\\
&=10\sin(1000t-54°)....(b)\\
\end{align}\\\$
From (a) and (b) we get, \$I_R=10\angle36°\$ and \$I_L=10\angle-54°\$
\$\therefore\$ net r.m.s. current
\$\begin{align}\\
I&=I_R+I_L =10\angle36°+10\angle-54°\\
&{\begin{aligned}\\
=10(\cos36°+j\sin36°)&+10(\cos54°-j\sin54°)\\
\end{aligned}\\}\\
&=8.1+j5.88+5.88-j8.1\\
&=(13.98-j2.22)A\\
\end{align}\\\$
i.e.\$I=14.15\angle-9.02°\$A
I don't know why the angle is different (though the magnitude is same). Please check this which method is faulty.

A: There is no difference it is just because you have chosen to consider another reference axis rotated by 90 degrees from the reference taken in the book.
By subtracting 90 degrees of any of your angles you will get the corresponding angle in the book:

*

*36-90 = -54

*-54 -90 = -144

*-9.02 - 90 = -99.02


text:
Q: Ubuntu login loop. Cannot fix My system recently had a problem, where I could not update the system because it kept on saying :
> E: Could not get lock /var/lib/dpkg/lock - open (11 Resource
 temporarily unavailable) E: Unable to lock the administration
directory (/var/lib/dpkg/) is another process using it?

So I followed these steps and removed the lock file. After a reboot, I cannot login. Its stuck in loop. I have already tried many answers on this forum like changing ownership of .Xauthority and even removing it. But nothing works, its still stuck in a loop.
Help me!


text:
Q: Reading From a File of Numbers Using RandomAccessFile Java I have an assignment to write some numbers in a text file using PrintStream and then reading from that same file using RandomAccessFile. While the writing part works as intended, I get the following output when running my code.
 807416096
840971040
874525984
Exception in thread "main" java.io.EOFException
908080928
941635872
at java.io.RandomAccessFile.readInt(RandomAccessFile.java:776)
at Problema4.main(Problema4.java:21)
Java Result: 1

Here is the code:
import java.io.*;
import java.util.*;

public class Problema4 {

public static void main(String[] args) throws IOException, FileNotFoundException
{
    PrintStream ps = new PrintStream(new FileOutputStream("fisiernou.txt"));
    int i=0;
    while (i<11)
    {
        ps.print(i);
        ps.print(" ");
        i++;
    }
    ps.close();
    RandomAccessFile raf = new RandomAccessFile("fisiernou.txt", "r");
    raf.seek(0);
    //System.out.println(raf.readInt());
    while (raf.getFilePointer()<raf.length())
        System.out.println(raf.readInt());
    raf.close();
}

}

A: You are writing integer as strings ( ps.print(i) ). If you write 1, in the file you are writting the ascii character of 1. Suposse this is the unique number we write, the file then have only one byte.
When reading, you are using raf.readInt(). This method reads 4 bytes and convert them to an integer. If now you try to read your file, this only contains one byte (the ascii character of 1), and then you get an EOF excepcion.
Use the same type of method for writting and reading. You can write with FileOutputStream.write(int).

A: RandomAccessFile.readInt() reads a binary 32-bit integer from the file. This means that it read 4 bytes and transform those 4 bytes into an int. It doesn't read the string representation of an int. Read its javadoc.

A: When your raf pointer is reading from the file, it is possible to hit an 'End of File' character. From the Java API:
"It is generally true of all the reading routines in this class that if end-of-file is   reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown."
http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html


text:
Q: How to get attribute values of HTML tags into a list? I want to extract the values of the "id" attribute from a list of table rows like this one:
<tr id="8LVPCRJGR" role="row" class="odd">, via BeautifulSoup4. In the case of this example tag, I want the "8LVPCRJGR" part.
I tried this block of code (yes, I did import bs4 and requests modules):
url = "https://brawlify.com/stats/club/V8GVVR0R"
result = requests.get(url).text
doc = BeautifulSoup(result, "html.parser")

tag = doc.find_all('tr')

attribute = tag['id']

print(attribute)

It's supposed to print out a list with all the values in it, but nothing prints. The console is blank.
What am I doing wrong here?

A: find_all will return a list
you should loop through this list and extract the id attribute something like this
Edit
following @chitown88 comment
you can id if statement to the loop
and for @Zaid Hussain comment
apparently you can't get the tr tag from the HTML page because  the javascript code didn't execute before loading requests.get(url).text to the BeautifulSoup I would recommend trying to inspect the return of requests.get(url).text and if this is the case I would recommend opening the page with selenium through for example chrome driver  and passing the HTML code to the BeatifulSoup or just doing the job with Selenium
tags=doc.find_all('tr')
attribute= [tag['id'] for tag in tags if tag['id'] ]
print(attribute)

A: Few issues. First, tag is list of elements, specifically all the <tr> tag elements. Secondly, not all the <tr> tags have an 'id' attribute.
So you need to put in some logic for that:
import requests
from bs4 import BeautifulSoup

url = "https://brawlify.com/stats/club/V8GVVR0R"
result = requests.get(url).text
doc = BeautifulSoup(result, "html.parser")

tag = doc.find_all('tr')

attribute = [x['id'] for x in tag if 'id' in x.attrs]

Output:
print(attribute)
['8LVPCRJGR', '29G9VJJC', '2YP08GUG8', 'UY8PVUPL', 'VV2RRRGG', '20RQQ08U9', 'VJ00J8Y8', '200PG2VLP', '28QV0RJVV', 'YRLPJ80J', 'PRLV99U89', '9QJLQGGU', '88UYYG0U', '9PG8RUVJ', 'YP9UQ8CQ', '9J8LRGQU2', '2LPGYQVV9', '8C8CJ0UJU', 'GUGJLLRG', '9Q0VCV2J', '2RVYVL8YL', 'JP0VGC2P', '280GY2R2C', '2PRLQPJJY', '8CGJGPYJ9', '89RYCVQJ0', '80GVU28CC', 'UV0CPU2Q', '9RGG9J08J', 'Y2PQ8090R']

A: Select a bit more specific - all <tr> with an id and iterate the result set to get each id:
[x['id'] for x in soup.select('tr[id]')]

Example
import requests
from bs4 import BeautifulSoup

r = requests.get('https://brawlify.com/stats/club/V8GVVR0R')
soup = BeautifulSoup(r.text, "html.parser")

attribute = [x['id'] for x in soup.select('tr[id]')]
print(attribute)

Output:
['8LVPCRJGR',
 '29G9VJJC',
 '2YP08GUG8',
 'UY8PVUPL',
 'VV2RRRGG',
 '20RQQ08U9',
 'VJ00J8Y8',
 '200PG2VLP',
 '28QV0RJVV',...]


text:
Q: Hadoop Error "Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1" mapper.py is working fine. I ran mapper.py on my cluster and stored its output in part-0.txt.
Excatly like a word-count job, I am trying to count the occurrences of every distinct key stored in part-0.txt file.
I tried copy-pasting the code from this link:
http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/
It worked but I was unable to understand it's reducer code, so I wrote my own reducer.
And here is the reducer code:
#!/usr/bin/env python
from numpy import *
import sys

arr = []
previous_printed_word = ''
#f=open('/home/nalin/Downloads/part-0.txt','r')

for line in sys.stdin:
    line = line.strip()
    current_word, current_count = line.split('\t',1)
    current_count = 0

    if(previous_printed_word != current_word):
        #f2 = open('/home/nalin/Downloads/part-0.txt', 'r')
        for line2 in sys.stdin:
            line2 = line2.strip()
            word, count2 = line2.split('\t', 1)
            count2 = int(count2)
            if current_word == word:
                current_count = current_count + count2
            else:
                continue
        print '%s\t\t\t%d' % (current_word, current_count-1)
        arr.append ( [current_word, current_count-1] )
        previous_printed_word = current_word

arr = sorted(arr, key=lambda row: row[1])
#print arr
length=len(arr)
print "LENGHT OF 2-D ARRAY IS = ",length
for i in range(1,11):
    print arr[length-i]

I keep getting this error:
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1

I tried looking up what this error means and I found out that this error comes up when there is something wrong with the code.
But if I uncomment out these 2 lines:
f = open('/home/nalin/Downloads/part-0.txt', 'r')

f2 = open('/home/nalin/Downloads/part-0.txt', 'r')

put f & f2 instead of sys.stdin(on both occurrences of sys.stdin) then it works like a charm.
It is working when I run it on mappers output file.
It is not working when I run it on my cluster.
Help me figure out what is wrong in the code.


text:
Q: What is the logic of reverse indexed slices in Python? Reverse indexing in python with the x[::-1] format is very handy, but what is the logic of reversed indexing on slices?  I understand that the idea is [high:low:-stride], but I find the following example confusing.  In particular, why is it not possible to slice so that the entire iterable is reversed (without using the implicit [high::-1] format)?
This Python 3.6 snippet:
s = 'abcde'
for i in reversed(range(0,6)):
    print(i, f'{s[6:(i - 1):-1]:>6}', f'{s[:i]:6}')

Returns:
5        abcde
4      e abcd
3     ed abc
2    edc ab
1   edcb a
0

Concretely, why isn't the 0 line edcba?

A: If i is 0, then s[6:(i - 1):-1] becomes s[6:(-1):-1], since there are only 5 characters, you take all chars from the 6th place to the last place. And because there are no chars between those two you get an empty string.
If i is 0, then s[:i] becomes s[0:0], since there are no charachters between 0 and 0, you get an empty string.
To print 'abcde' backwards, you use s[::-1]

A: What happened?
All magic in here, function PySlice_AdjustIndices:
if (*start < 0) {
    *start += length;
    if (*start < 0) {
        *start = (step < 0) ? -1 : 0;
    }
}
else if (*start >= length) {
    *start = (step < 0) ? length - 1 : length;
}

if (*stop < 0) {
    *stop += length;
    if (*stop < 0) {
        *stop = (step < 0) ? -1 : 0;
    }
}
else if (*stop >= length) {
    *stop = (step < 0) ? length - 1 : length;
}

if (step < 0) {
    if (*stop < *start) {
        return (*start - *stop - 1) / (-step) + 1;
    }
}
else {
    if (*start < *stop) {
        return (*stop - *start - 1) / step + 1;
    }
}

In your case,
start = 6, stop = -1, step = -1, length = 5

After calculated,
start = 4, stop = 4, step = -1

Sum up:
5         = s[4:4:-1]
4      e  = s[4:3:-1]
3     ed  = s[4:2:-1]
2    edc  = s[4:1:-1]
1   edcb  = s[4:0:-1]
0         = s[4:4:-1]

How to solve?
s = 'abcde'
length = len(s)
for i in reversed(range(length + 1)):
     print(i, f'{s[-1:i-length-1:-1]:>6}', f'{s[:i]:6}')

output:
5        abcde
4      e abcd
3     ed abc
2    edc ab
1   edcb a
0  edcba


text:
Q: A question about eigenvalues Let $v=\begin{pmatrix}v_1\\v_2\\v_3\\v_4\end{pmatrix}$ be a nonzero column vector in $\Bbb R^4$ and let $A=vv^T$. Find the eigenvalues of $A$
There must be a easier way rather than calculate it directly. But I couldn't think of that, could somebody help me? Many thanks

A: Note that for some vector $ w $, $ A w = v ( w \cdot v) $. If you choose an orthonormal basis $ \{ e_1 = \frac{v}{|v|}, e_2, e_3,e_4 \} $, then is it easier?

A: The eigenvalues are $\{\|v\|^2, 0, 0, 0\}$.  Consider
$$Av = (vv^T)v = v (v^Tv) = v \|v\|^2 = v\lambda .$$
So we conclude $v$ is an eigenvector and $\|v\|^2$ is an eigenvalue.
Now consider the mutually orthogonal $u_1$, $u_2$, $u_3$ such that $\mathrm{span}(u_1, u_2, u_3) \perp v$, then
$$Au_i = (vv^T)u_i = v (v^Tu_i) =0 = v\lambda .$$
So we likewise conclude that $u_1$, $u_2$, $u_3$  are engenvectors with eigenvalues of $0$.


text:
Q: Which architecture for Intel Atom CPU N270: amd64 or i386? I have and old netbook with 1gb of ram and an Atom N270 CPU.  I want to install Ubuntu 14.04.  Which one should I use amd64 or i386?
Thanks in advance

A: Intel Atom N270 does NOT have 64-bit support, so you have to install 32-bit (i386) version.
You can view that at Intel Webpage where it says:

Intel® 64:    No

You said your netbook has 1GB of RAM: When you download Ubuntu in the official Ubuntu webpage, they recommend installing the 32-bit version if your computer has less than 2GB of RAM.


text:
Q: Can't find sound app after installation (20.04) I made a clean upgrade from 18.04 to 20.04, then installed sound app (sonido really, spanish version). Everything works fine except that the sound app is not in the available apps (launcher?) you get down right corner, with app icons. I took the app and installed from ubuntu software, that says it is installed....

A: Often times, you have to reboot or log out and log back in before the app will show amongst your list of installed apps. Also, if you are referring to the launcher bar on the left side of the screen, you must pin apps to the launcher.
If you're still having trouble, use the following instructions:
First, select the show applications icon on the lower left hand side of the screen (six dots in a square).

Then, search for the application by name.
Once you start an app, the icon will appear on the launcher. To pin the app to the launcher, right click on the icon and select to pin.
Alternatively, you can move your mouse into the upper left corner of your screen to trigger the "Activities" menu. Then, search for the app by name from your Activities screen. Again, once you open the app, the icon will show on your launcher. To pin the app to the launcher, right click on the icon and select to pin.


text:
Q: Como usar where com filtro em C# entre duas tabelas (one to many)? Usando C# e EntityFramework:
Tenho duas tabelas com relacionamento entre elas de "um para muitos".
Gostaria de fazer dois Gets em uma controller:
O 1o que me trouxesse os dados da tabela que não tivessem ligação com a outra tabela.
O 2o que me trouxesse apenas os dados que tem ligação com a outra tabela.
Tendo a tabela abaixo como exemplo:
Gostaria que a 1a busca me trouxesse apenas o hulk e o pantera negra, pois estes não possuem armas.
Em seguida a outra busca me trouxesse o capitão américa e o thor.
tabela1

Id
Nome

1
Hulk

2
Capitão America

3
Pantera Negra

4
Thor

tabela2

Id
Nome
HeroiId

1
Escudo
2

2
Martelo
4

Para o 1o caso eu tentei abaixo:
public ActionResult<IEnumerable<Heroi>> Get()
{
    return _context.Herois.Where(c => c.Armas != null).ToList();
}

A: Você precisará usar operadores de consulta complexa: https://docs.microsoft.com/pt-br/ef/core/querying/complex-query-operators
Para trazer apenas "hulk" e "pantera negra", vocë precisa fazer um LEFT JOIN. O LINQ não possui um operador de LEFT JOIN nativo, mas você pode usar esse padrão para chegar ao mesmo resultado. Crie um GroupJoin entre as duas tabelas e depois nivele o grupo usando SelectMany com DefaultIfEmpty na origem do grupo para corresponder a nulo quando o interno não tiver um elemento relacionado. Segue o exemplo:
var Herois = from t1 in context.Set<Tab1>()
                 join t2 in context.Set<Tab2>()
                    on t1.Id equals t2.HeroiId into grouping
                 from t2 in grouping.DefaultIfEmpty()
                    where t2.HeroiId == null
                 select new { t1 };

A query gerada é:
SELECT [t].[id], [t].[name]
FROM [tab1] AS [t]
LEFT JOIN [tab2] AS [t0]
    ON [t].[id] = [t0].[heroi_id]
WHERE [t0].[heroi_id] IS NULL

Já para trazer "capitão américa" e "thor", você precisa fazer um JOIN simples entre as duas tabelas. Lembre-se que as tabelas envolvidas precisam ter PRIMARY KEY e FOREIGN KEY definidas no banco de dados.
var Herois = from t1 in context.Set<Tab1>()
                 join t2 in context.Set<Tab2>()
                    on t1.Id equals t2.HeroiId
                 select new { t1 };

A query gerada é:
SELECT [t].[id], [t].[name]
FROM [tab1] AS [t]
INNER JOIN [tab2] AS [t0]
ON [t].[id] = [t0].[heroi_id]

A: Neste cenário você pode utilizar o LINQ com uma propriedade de navegação do tipo ICollection, ficaria assim:
public class Heroi
{
    public int Id { get; set; }
    public string Nome { get; set; }

    // EF Navigation
    public ICollection<Arma> Armas { get; set; }
}

public class Arma
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public int HeroiId { get; set; }

    public Heroi Heroi { get; set; }
}

No controller você faz:
var herois = context.Herois.Include(x => x.Armas).ToList();

var heroisComArma = herois.Where(x =>  x.Armas.Any());
var heroisSemArma = herois.Where(x => !x.Armas.Any());


text:
Q: Remote debug with VSCode, go & nakama i have the following problem. I try to run a nakama gameserver in go with docker.
For the debugging purposes i want to use delve.
I am not really sure if i am proceeding right, so maybe my problem is actually a complete different. But i think my delve does not connect to the nakama build.
What have i done so far?
I created a new go project and put a bit code in the main.go. After that i created a Dockerfile and an docker-compose.yml.
I think in one of these two files is the mistake.
My Dockerfile looks like this:
FROM golang

ENV GOPATH /home/marc/go_projects
ENV PATH ${GOPATH}/bin:/usr/local/go/bin:$PATH

RUN go install github.com/go-delve/delve/cmd/dlv@latest

FROM heroiclabs/nakama-pluginbuilder:3.3.0 AS go-builder

ENV GO111MODULE on
ENV CGO_ENABLED 1

WORKDIR $GOPATH/gamedev

COPY go.mod .
COPY main.go .
COPY vendor/ vendor/

RUN go build --trimpath --mod=vendor --buildmode=plugin -o ./backend.so

FROM heroiclabs/nakama:3.3.0

COPY --from=go-builder /backend/backend.so /nakama/data/modules/
COPY local.yml /nakama/data/

An my docker-compose.yml
version: '3'
services:
  postgres:
    container_name: postgres
    image: postgres:9.6-alpine
    environment:
      - POSTGRES_DB=nakama
      - POSTGRES_PASSWORD=localdb
    volumes:
      - data:/var/lib/postgresql/data
    expose:
      - "8080"
      - "5432"
    ports:
      - "5432:5432"
      - "8080:8080"
  nakama:
    container_name: nakama
    image: heroiclabs/nakama:3.12.0
    entrypoint:
      - "/bin/sh"
      - "-ecx"
      - >
        /nakama/nakama migrate up --database.address postgres:localdb@postgres:5432/nakama &&
        exec /nakama/nakama --name nakama1 --database.address postgres:localdb@postgres:5432/nakama --logger.level DEBUG --session.token_expiry_sec 7200
    restart: always
    links:
      - "postgres:db"
    depends_on:
      - postgres
    volumes:
      - ./:/nakama/data
    expose:
      - "7349"
      - "7350"
      - "7351"
      - "2345"
    ports:
      - "2345:2345"
      - "7349:7349"
      - "7350:7350"
      - "7351:7351"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:7350/"]
      interval: 10s
      timeout: 5s
      retries: 5
volumes:
  data:

When i build and run the docker image, it runs with no complains. I can open the webinterface of nakama, so this is running fine.
But when i try to connect the debugger, it looks like he create a succesfull connection but closes it right away.
SO my launch.json config is the following:
 "name": "Connect to server",
 "type": "go",
 "request": "attach",
 "mode": "remote",
 "remotePath": "/home/marc/go_projects/bin/dlv",
 "port": 2345,
 "host": "127.0.0.1",
 "trace": "verbose"

This is what i get in /tmp/vs-code-debug.txt:
[07:24:05.882 UTC] From client: initialize({"clientID":"vscode","clientName":"Visual Studio Code","adapterID":"go","pathFormat":"path","linesStartAt1":true,"columnsStartAt1":true,"supportsVariableType":true,"supportsVariablePaging":true,"supportsRunInTerminalRequest":true,"locale":"de","supportsProgressReporting":true,"supportsInvalidatedEvent":true,"supportsMemoryReferences":true})
[07:24:05.882 UTC] InitializeRequest
[07:24:05.882 UTC] To client: {"seq":0,"type":"response","request_seq":1,"command":"initialize","success":true,"body":{"supportsConditionalBreakpoints":true,"supportsConfigurationDoneRequest":true,"supportsSetVariable":true}}
[07:24:05.883 UTC] InitializeResponse
[07:24:05.883 UTC] From client: attach({"name":"Connect to server","type":"go","request":"attach","mode":"remote","remotePath":"/home/marc/go_projects/bin/dlv","port":2345,"host":"127.0.0.1","trace":"verbose","__configurationTarget":5,"packagePathToGoModPathMap":{"/home/marc/go_projects/gamedev":"/home/marc/go_projects/gamedev"},"debugAdapter":"legacy","showRegisters":false,"showGlobalVariables":false,"substitutePath":[],"showLog":false,"logOutput":"debugger","dlvFlags":[],"hideSystemGoroutines":false,"dlvLoadConfig":{"followPointers":true,"maxVariableRecurse":1,"maxStringLen":64,"maxArrayValues":64,"maxStructFields":-1},"cwd":"/home/marc/go_projects/gamedev","dlvToolPath":"/home/marc/go_projects/bin/dlv","env":{"ELECTRON_RUN_AS_NODE":"1","GJS_DEBUG_TOPICS":"JS ERROR;JS LOG","USER":"marc","SSH_AGENT_PID":"1376","XDG_SESSION_TYPE":"x11","SHLVL":"0","HOME":"/home/marc","DESKTOP_SESSION":"ubuntu","GIO_LAUNCHED_DESKTOP_FILE":"/usr/share/applications/code.desktop","GTK_MODULES":"gail:atk-bridge","GNOME_SHELL_SESSION_MODE":"ubuntu","MANAGERPID":"1053","DBUS_SESSION_BUS_ADDRESS":"unix:path=/run/user/1000/bus","GIO_LAUNCHED_DESKTOP_FILE_PID":"6112","IM_CONFIG_PHASE":"1","MANDATORY_PATH":"/usr/share/gconf/ubuntu.mandatory.path","LOGNAME":"marc","_":"/usr/share/code/code","JOURNAL_STREAM":"8:44286","DEFAULTS_PATH":"/usr/share/gconf/ubuntu.default.path","XDG_SESSION_CLASS":"user","USERNAME":"marc","GNOME_DESKTOP_SESSION_ID":"this-is-deprecated","WINDOWPATH":"2","PATH":"/home/marc/.nvm/versions/node/v17.8.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/usr/local/go/bin:/usr/local/go/bin","SESSION_MANAGER":"local/mobile:@/tmp/.ICE-unix/1458,unix/mobile:/tmp/.ICE-unix/1458","INVOCATION_ID":"fe605ca56aa646859602b81e264bf01b","XDG_RUNTIME_DIR":"/run/user/1000","XDG_MENU_PREFIX":"gnome-","DISPLAY":":0","LANG":"de_DE.UTF-8","XDG_CURRENT_DESKTOP":"Unity","XAUTHORITY":"/run/user/1000/gdm/Xauthority","XDG_SESSION_DESKTOP":"ubuntu","XMODIFIERS":"@im=ibus","SSH_AUTH_SOCK":"/run/user/1000/keyring/ssh","SHELL":"/bin/bash","QT_ACCESSIBILITY":"1","GDMSESSION":"ubuntu","GPG_AGENT_INFO":"/run/user/1000/gnupg/S.gpg-agent:0:1","GJS_DEBUG_OUTPUT":"stderr","QT_IM_MODULE":"ibus","PWD":"/home/marc","XDG_DATA_DIRS":"/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop","XDG_CONFIG_DIRS":"/etc/xdg/xdg-ubuntu:/etc/xdg","_WSREP_START_POSITION":"","CHROME_DESKTOP":"code-url-handler.desktop","ORIGINAL_XDG_CURRENT_DESKTOP":"ubuntu:GNOME","VSCODE_CWD":"/home/marc","GDK_BACKEND":"x11","VSCODE_NLS_CONFIG":"{\"locale\":\"de\",\"availableLanguages\":{\"*\":\"de\"},\"_languagePackId\":\"b61d3f473b0358bc955527db7340fd23.de\",\"_translationsConfigFile\":\"/home/marc/.config/Code/clp/b61d3f473b0358bc955527db7340fd23.de/tcf.json\",\"_cacheRoot\":\"/home/marc/.config/Code/clp/b61d3f473b0358bc955527db7340fd23.de\",\"_resolvedLanguagePackCoreLocation\":\"/home/marc/.config/Code/clp/b61d3f473b0358bc955527db7340fd23.de/30d9c6cd9483b2cc586687151bcbcd635f373630\",\"_corruptedFile\":\"/home/marc/.config/Code/clp/b61d3f473b0358bc955527db7340fd23.de/corrupted.info\",\"_languagePackSupport\":true}","VSCODE_CODE_CACHE_PATH":"/home/marc/.config/Code/CachedData/30d9c6cd9483b2cc586687151bcbcd635f373630","VSCODE_IPC_HOOK":"/run/user/1000/vscode-432c1660-1.68.1-main.sock","VSCODE_PID":"6112","NVM_INC":"/home/marc/.nvm/versions/node/v17.8.0/include/node","LS_COLORS":"","NVM_DIR":"/home/marc/.nvm","LESSCLOSE":"/usr/bin/lesspipe %s %s","LESSOPEN":"| /usr/bin/lesspipe %s","NVM_CD_FLAGS":"","NVM_BIN":"/home/marc/.nvm/versions/node/v17.8.0/bin","GOPATH":"/home/marc/go_projects","VSCODE_AMD_ENTRYPOINT":"vs/workbench/api/node/extensionHostProcess","VSCODE_PIPE_LOGGING":"true","VSCODE_VERBOSE_LOGGING":"true","VSCODE_LOG_NATIVE":"false","VSCODE_HANDLES_UNCAUGHT_ERRORS":"true","VSCODE_LOG_STACK":"false","VSCODE_IPC_HOOK_EXTHOST":"/run/user/1000/vscode-ipc-8cf508cc-d427-4616-b6b5-61d3c3e5d99f.sock","APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL":"1","GOMODCACHE":"/home/marc/go_projects/pkg/mod","GOPROXY":"https://proxy.golang.org,direct"},"__sessionId":"1893ab9e-5a19-45e7-8b39-46db079cdbe3"})
[07:24:05.883 UTC] AttachRequest
[07:24:05.884 UTC] Start remote debugging: connecting 127.0.0.1:2345
[07:24:06.191 UTC] To client: {"seq":0,"type":"event","event":"initialized"}
[07:24:06.192 UTC] InitializeEvent
[07:24:06.192 UTC] To client: {"seq":0,"type":"response","request_seq":2,"command":"attach","success":true}
[07:24:06.194 UTC] [Error] Socket connection to remote was closed
[07:24:06.194 UTC] Sending TerminatedEvent as delve is closed
[07:24:06.194 UTC] To client: {"seq":0,"type":"event","event":"terminated"}
[07:24:06.201 UTC] From client: configurationDone(undefined)
[07:24:06.201 UTC] ConfigurationDoneRequest
[07:24:06.225 UTC] From client: disconnect({"restart":false})
[07:24:06.225 UTC] DisconnectRequest

I tried to change the remote path i the launch.json multiple times, try to math the paths in the docker files.
Maybe i have to change the implementation of delve in docker, but tbh i dont really know how. I dont really find a good documentation on how to do this.

A: I was having the same problem.
I solved it like this:
adding line: "debugAdapter": "dlv-dap" on my launch.json
{
  "version": "0.2.0",
  "configurations": [
      {
          "name": "Delve into Docker",
          "type": "go",
          "request": "attach",
          "debugAdapter": "dlv-dap",
          "mode": "remote",
          "substitutePath": [
              {
                  "from": "${workspaceFolder}/",
                  "to": "/app",
              },
          ],
          "port": 2345,
          "host": "127.0.0.1",
          "showLog": false,
          "apiVersion": 2,
          "trace": "verbose"
      }
  ]
}


text:
Q: How to open page in new tab using the response. redirect at asp.net I want to open a new tab or a new page by using Response.Redirect in a button click handler. I'm using a query string to pass some values. How can I open he page in a new tab?
protected void btnSave_Click(object sender, EventArgs e)
{
    ...//some code to insert records
    Response.Redirect("NewQuote.aspx?val=" + this.txtQuotationNo.Text);//displaying gridview in other page to print what needed
}

A: You can change your design element as below : OnClientClick
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"  OnClientClick ="document.forms[0].target = '_blank';"  />

Javascript code :
 Response.Write("<script>");
 Response.Write("window.open('NewQuote.aspx' ,'_blank')");
 Response.Write("</script>");

A: I encountered this same problem today.
Response.write didn't work for me, to solve it I used instead System.Web.UI.ScriptManager.RegisterClientScriptBlock.
This is how your btnSave click event should be:
protected void btnSave_Click(object sender, EventArgs e)
{
    ...//some code to insert records
    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "openModal", "window.open('NewQuote.aspx?val= "+ this.txtQuotationNo.Text+"' ,'_blank');", true);
}

NOTE: I'm using ScriptManager.RegisterClientScriptBlock because the button is inside an UpdatePanel, if that's not your case you should try:
protected void btnSave_Click(object sender, EventArgs e)
{
    ...//some code to insert records
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "openModal", "window.open('NewQuote.aspx?val= " + this.txtQuotationNo.Text + "' ,'_blank');", true);
}

A: Try this. This works sure for me...
protected void btnSave_Click(object sender, EventArgs e)
{
    ...//some code to insert records
    Response.Write("<script>window.open ('NewQuote.aspx?val=" + txtQuotationNo.Text+"','_blank');</script>");
}

A: if you are using http
then use below code
Response.Write("<script>window.open ('URL','_blank');</script>");

this code cannot be used for https
for https do below
javascript in page
function shwwindow(myurl) {
    window.open(myurl, '_blank');
}

in c# code behind
 string URL = ResolveClientUrl("~") + "**internal page path**";
    ScriptManager.RegisterStartupScript(this, this.GetType(), "show window",
    "shwwindow('"+URL+"');", true);

this code cannot bybass the browser popup blocker. user must allow it to run.
for ie it opens in new window or new tab up to ie version
in firefox and chrome it opens new tab
enjoy it!!

A: Simple solution is here.
Edit your html button element and add attribute OnClientClick="target ='_blank';".
<asp:Button ID="myButton" runat="server" CssClass="btn1"
            OnClick="btnSave_Click" OnClientClick="target ='_blank';" />

Then in btnSave_Click
protected void btnSave_Click(object sender, EventArgs e) {
    Response.Redirect(url);
}

A: A redirect is always in the same page as where you came from, you can't open a new window from a redirect call.
I would suggest to inject some javascript code in the client to open the new page on reload, or change to a control that can open to a new page, like a LinkButton with the right Target attribute.

A: You can use ScriptManager to do the needed:
private void Redirect_New_Tab(string url_To_Open)
{
    string modified_URL = "window.open('" + url_To_Open + "', '_blank');";
    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", modified_URL , true);
}

A: Worked for me when I left the Double Quotes off of target ='_blank';

A: Response.write didn't work for me, so I used instead System.Web.UI.ScriptManager.RegisterClientScriptBlock.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "openModal", "window.open('NewQuote.aspx?val= "+ this.txtQuotationNo.Text+"' ,'_blank');", true);

A: I spent quite some time on this, and while it does work to set the target on the form to _blank it will mean that every other control on that page will attempt to open in a new window afterwards. And you can't manipulate the form back server side, since the response will never reach the orginal tab.
So I made it work with a combination of setting the target to _blank when the button is clicked, and then shortly after reset the target back.
I put in this Javascript function on the page:
 <script type="text/javascript">
    function openInNewTab() {
        document.forms[0].target = "_blank";
        setTimeout(function () {
            document.forms[0].removeAttribute('target'); // After 500 ms revert back to normal mode so all other controls are not affected.
        }, 500);
    }

And on the control that needs to open in a new tab just add:
OnClientClick="openInNewTab();"


text:
Q: SMP affinity vs XPS on paired queues and TX queue selection control I have a solarflare nic with paired rx and tx queues (8 sets, 8 core machine real machine, not hyperthreading, running ubuntu) and each set shares an IRQ number. I have used smp_affinity to set which irqs are processed by which core. Does this ensure that the transmit (tx) interrupts are also handled by the same core. How will this work with xps?
For instance, lets say the irq# is 115, set to core 2 (via smp_affinity). Say the nic chooses tx-2 for outgoing tcp packets, which also happens to have 115 irq number. If I have an xps setting saying tx-2 should be accessible by cpu 4, then which one takes precedence - xps or smp_affinity?
Also is there a way to see/set which tx queue is being used for a particular app/tcp connection? I have an app that receives udp data, processes it and sends tcp packets, in a very latency sensitive environment. I wish to handle the tx interrupts on the outgoing on the same cpu (or one on the same numa node) as the app creating this traffic, however, I have no idea how to find which tx queue is being used by this app for this purpose. While the receive side has indirection tables to set up rules, I do not know if there is a way to set the tx-queue selection and therefore pin it to a set of dedicated cpus.

A: You can tell the application the preferred CPU by setting the cpu affinity (taskset) or numa node affinity, and you can also set the IRQ affinities (in /proc/irq/270/node, or by using the old intel script floating around 'set_irq_affinity.sh' which is on github). This won't completely guarantee which irq / cpu is being used, but it will give you a good head start on it. If all that fails, to improve latency you might want to enable packet steering in the rxqueue so you get the packets in quicker to the correct cpu (/sys/class/net//queues/rx-#/rps_cpus and tx-#/xps-cpus). There is also the irqbalance program and more....it is a broad subject and i am just learning much of it myself.


text:
Q: Minimizing the distance between two points. I am reading Differential Geometry: A First Course in Curves and Surfaces and in Example 1a it asked me to prove that if $\alpha(t)$ is a function that goes through two points, then prove the line segment gives the smallest length. To prove this, I started with this: $$s=\int_a^b\sqrt{1+\alpha'(t)^2}dt$$To minimize $s$, we should minimize the integrand. So: $$\frac{d}{dt}\sqrt{1+\alpha'(t)^2}=\frac{\alpha'(t)\alpha''(t)}{\sqrt{1+\alpha'(t)}}=0$$Here we have two possibilities. Either $\alpha'(t)\alpha''(t)=0$ (either $\alpha'(t)=0$ or $\alpha''(t)=0$, both give straight lines, with one a constant function and the other a linear function respectively) or the denominator is infinitely large, which would mean that $\alpha'(t)$ is infinitely large. This means that $\alpha'(t)$ is a vertical line. Q.E.D.
I am skeptical that this proof is true, since in another post by another user (couldn't remember exactly) the proof was using Calculus of Variations and was very long and complicated.


text:
Q: Unable to Load Some Layers in QField I have configured a QGIS Project file in QGIS 3.22 and used the QFieldSync version 3.4.4 to create a QField Package Project File to be imported into my tablet. However, I encountered this error upon loading the QGS file in QField.
Some of my colleagues also encountered this error. As a workaround, they closed their QGIS project and then repackaged again the project using QFieldSync. They transferred the file to their tablets and luckily the error was fixed and the following layers were able to be loaded.
I did the same workaround but still encountered this error.
What could be the cause of this error?

A: I had the same problem. I turned my .shp files into GeoPackages and everything loaded fine.
(If you did what I did and spent hours working on styles and labels, you can copy and paste the entire formatting in one go by right clicking on the existing layer and choosing Styles>Copy Style>All Style Categories and then clicking the new GeoPackage file and and Styles>Paste Style>All Style Categories - it saved me HOURS!)

A: I am encountering the same issue (QGIS v3.22.4, QField v2.2.3). I have packaging projects for QField for at least a couple of years now and this error has only started to come up after updating QFieldSync yesterday (v4.1.1). As far as I'm aware, I am doing the same thing as I always have, using the same type of files and now I can't open a project successfully on QField, resulting in either:

*

*Shp layers load if saved as GPKGs, but the basemap (only the map canvas extent portion so I can use it offline) does not

*The online basemap loads in its entirety (and requires internet access), but the shp layers do not

*No layers load

This is really very frustrating as I have been wanting to implement QField as a data collector for work. Being able to work offline is important because I often work in remote areas with little to no internet connection. I don't want to have to rely on the Cloud-based storage if I have to work offline to make updates and changes.
It's worth noting that I have successfully loaded previously imported projects which were packaged with my previous version of QField Sync, so I think there is some disconnect somewhere in the packaging process.


text:
Q: ASP.NET web application cloud authentication sql dependency I have created a project in visual studio using the ASP.NET web application (.NET Framwork) VB.
If i run it from within VS it asks for my MS credentials and registers the app in Azure. It then gives me the home page showing as me logged in.
I then deploy this app to IIS on a VM server in Azure. i create a self signed certifcate in IIS and create a https binding using the certificate and port
when i browse to the site it goes through all the login procedure as expected, then i get an error "A network-related or instance-specific error occurred while establishing a connection to SQL Server"
What SQL server??
if i go into connected services in VS under connected services it shows 'SQL Server dependency is detected' and i have to configure it. what is this?
Thanks
Gareth


text:
Q: Trying to get the custom Post type category link in Wordpress for the current post as meta data of the post I am trying to place a link to the Artist of a video in a custom post type in WordPress. Everything is working but the term_id does not iterate.
<?php
$args = array(
    'post_type'      => 'video',
    'posts_per_page' => 4,
    'taxonomy' => $term->name,
    'number' => $term->term_id,
);

$q = new WP_Query( $args);

if ( $q->have_posts() ) {
    while ( $q->have_posts() ) {
    $q->the_post();
        //Your template tags and markup like:
        ?>

<img  alt="Norway" style="width:100%" src="<?php the_post_thumbnail( 'thumbnail' );?>

<?php the_title( ); ?>

<?php

  $terms = get_terms( $args );
    foreach( $terms as $term ){

        echo '
slug, 'band' ) ) . '">' . esc_html( $term->name ) . " ". $term->term_id . '
';

    }  ?>

A: As per your code, it seems that you are using the posts arguments for "get_terms" which is not correct and that's why you are not getting the correct term's data.
You can check the query parameter of terms over here to get the idea.


text:
Q: Where can I systematically study how to write Mac OS X device drivers? I'm looking for an exhaustive, university-level book or guide to study in order to
gain the ability of writing Mac OS X device drivers. I'm totally ignorant on this OS, but I'm already skilled on Linux.
Is there any Mac OS X counterpart for book "Linux Device Drivers"?
The best guide should introduce OS internals too, makes clear kernel space and userland differences and so on.
Thanks in advance

A: Amit Singh's wonderful book Mac OS X Internals: A Systems Approach has an extensive section on kernel extensions, the IOKit and drivers. It's the best general resource on OS X internals that I know of, but it doesn't cover the latest system updates; it only covers up to the 10.4 release (Tiger).

A: The Apple Developer Connection web site contains lots of documentation.  There is a whole section on Hardware & Drivers here in particular a Getting Started document here.  Probably the best overall introduction to OS X internals is Mac OS X Internals by Amit Singh.

A: Amit Singh's book is good but as other posters noted it needs to be updated. I'm getting up to speed on IOKit and opted for another newer book OS X and iOS Kernel Programming. It doesn't have the depth of Singh's book but it has many practical examples of driver code. It is perhaps a better choice if you want get going quickly.

A: I suggest the following as it is updated to Snow Leopard and Lion: Mac OS X and iOS Internals: To the Apple's Core by Jonathon Levine: http://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Dstripbooks&field-keywords=Mac+internals&rh=n%3A283155%2Ck%3AMac+internals
This is quite a good book regarding all aspects of Mac OS X internals.


text:
Q: Some css is not working in IE I am working on the application. Some of the css are not working in IE, whereas working in Firefox, such as Scrollbar,  input types, placeholder, required etc. All of the things are working fine in Firefox as well as Chrome, but not in IE. My IE version is 9.
My Firefox view is

whereas my IE view is -

My css code is -
        input[type="submit"]{

          background:#3399cc;
          width:100%;
          border:0;
          padding:4%;
          font-family:'Open Sans',sans-serif;
          font-size:100%;
          color:#fff;
          cursor:pointer;
          transition:background .3s;
          -webkit-transition:background .3s;
        }

        input[type="submit"]:hover{
          background:#EE2C2C;
        }

input[type="text"]{
  width:100%;
  background:white;
  margin-bottom:2%;
  margin-top:2%;
  border:1px solid #ccc;
  padding:4%;
  font-family:'Open Sans',sans-serif;
  font-size:95%;
  color:black;
}

input[type="password"]{
  width:100%;
  background:white;
  margin-bottom:2%;
  margin-top:2%;
  border:1px solid #ccc;
  padding:4%;
  font-family:'Open Sans',sans-serif;
  font-size:95%;
  color:black;
}

I tried to figure out the issue by so many ways such as change Compatibility View, try but unsucceed.
My html file is -
    <%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*" %>

<link rel="shortcut icon" href="images/imageIcon.png" />
<title> IETM Solutions </title>

<link rel="stylesheet" href="styles/ietmLogin.css" type="text/css"></link>
<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

System.out.println("session -- A1 - " + session);

 if(session != null)
{
    session.invalidate();
    session = null;
}
System.out.println("session -- A2 - " + session);
%>

IETM Document Management System

   <form action="Login" method="post">

        <input type="text" name="user" placeholder="UserName" required = "true"/>

        <input type="password" name="password" placeholder="Password" required = "true"/>

        <input type="submit" value="Login"/>

   </form>

<%

String error = (String) request.getAttribute("error");
//System.out.println("error : "+ error);
if(error != null)
{
    %>

Invalid User Name/Password

<% }

%>

Any suggestion/solution will be very helpful.
Thank you.

A: You have no doctype.
<!DOCTYPE html>

...

IE is rendering in Quirks Mode, which doesn't support most styles on <input> elements.

A: Seeing your HTML one question knocking me repeatedly. You drew a table only with
 and
 tags but where is  tag which is equally required for drawing table as well? I just simply rewrote your html and it worked fine for me:
<form action="Login" method="post">

                <input type="text" name="user" placeholder="UserName" required="true" />

                <input type="password" name="password" placeholder="Password" required="true" />

                <input type="submit" value="Login" />

</form>

IE9 is not smart enough to understand markup error. If this works fine in your case please don't forget to widen or style  and  for more room.


text:
Q: Dynamically instantiate object of the python class similar to PHP new $classname? How to instantiated a class if its name is given as a string variable (i.e. dynamically instantiate object of the class). Or alternatively, how does the following PHP 5.3+ code
<?php

namespace Foo;

class Bar {};

$classname = 'Foo\Bar';
$bar = new $classname();

can be spelled in python?
Also see
Does python have an equivalent to Java Class.forName()?

A: foo.py
class Bar(object):
    pass

test.py
from importlib import import_module

module = import_module('foo')
BarCls = getattr(module, 'Bar')
bar = BarCls()

A: Here is some code I use to go from a full class path (e.g. foo.bar.baz.TheClass) to the class itself:
def get_class(class_path):
    module_path, class_name = class_path.rsplit(".", 1)

    try:
        module = __import__(module_path, fromlist=[class_name])
    except ImportError:
        raise ValueError("Module '%s' could not be imported" % (module_path,))

    try:
        cls = getattr(module, class_name)
    except AttributeError:
        raise ValueError("Module '%s' has no class '%s'" % (module_path, class_name,))

    return cls

Usage:
>>> get_class('twisted.internet.nonexistant.Deferred')

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    get_class('twisted.internet.nonexistant.Deferred')
  File "<pyshell#1>", line 7, in get_class
    raise ValueError("Module '%s' could not be imported" % (module_path,))
ValueError: Module 'twisted.internet.nonexistant' could not be imported
>>> get_class('twisted.internet.defer.NoClass')

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    get_class('twisted.internet.defer.NoClass')
  File "<pyshell#13>", line 12, in get_class
    raise ValueError("Module '%s' has no class '%s'" % (module_path, class_name,))
ValueError: Module 'twisted.internet.defer' has no class 'NoClass'
>>> get_class('twisted.internet.defer.Deferred')
<class twisted.internet.defer.Deferred at 0x02B25DE0>

Note that this doesn't necessarily return a class, it just returns the attribute of the imported module:
>>> get_class('twisted.internet')
<module 'twisted.internet' from 'C:\Python26\lib\site-packages\twisted\internet\__init__.pyc'>


text:
Q: Central Difference to Approximate f'(x) So, Let $f(x) = \frac{1} {1 + x^2}$, $f'(x) = Af(x-2h) + Bf(x-h) + Cf(x) + Df(x+h) + Ef(x+2h)$, Use central difference scheme to approximate $f'(1)$ to show the order of convergence and the de-stabilization of the numerical methods of $h$.
So using central difference formula i've gotten this far, but im stuck as what to do next:
$f(x) = \frac{\frac{1}{1+(1+h)^2} - \frac{1}{1+(x-h)^2}}{2h}$
$f'(x) = \frac{\frac{2(x+h)}{((x+h)^2+1)^2} - \frac{2(x-h)}{((x-h)^2+1)^2}}{2h}$
do i plug in 1 for x? What do i have to do or use with the other equation? My notes on the matter just show scientific notation.
::::EDIT::::
I decided to take another approach, i expanded the taylor series and multiplied by $\frac{1}{1+x^2}$. So i get something link this: $ \frac{f(x)}{2h+2hx^2} + \frac{f'(x)}{2h+2hx^2} + \frac{f''(x)}{4h+4hx^2} + \frac{f'''(x)h^2}{6h + 6hx^2} - \frac{f'(x)}{2h+2hx^2} + \frac{f''(x)}{4h+4hx^2}-\frac{f'''(x)h^2}{6h + 6hx^2} $ Then we remove like terms and simplify: $ \frac{f'(x)}{h + hx^2} + \frac{f'''(x)h^2}{3h + 4hx^2} + \frac{f''''(x)h^4}{5h + 5hx^2} $ somehow $\frac{f'''(x)h^2}{3h + 3hx^2}$ is chosen to be $\frac{f(c)h^2}{3h+3hx^2}$ and is rewritten as $theta(h^2)$ and this makes it the central difference a scheme of order two.

A: To give the overall idea without completely solving your homework, change to the second derivative and another function.
I take it that the approximation formula has to make the best of all 5 function values. At first, forget about the specific form of $f$, only use that it is sufficiently often continuously differentiable. Then by combining Taylor series the normal central difference formula has error terms
$$
D_2(x,h)=\frac{f(x-h)-2f(x)+f(x+h)}{h^2}=f''(x)+\frac{2f^{(4)}(x)}{4!}h^2+\frac{2f^{(6)}(x)}{6!}h^4+\frac{2f^{(8)}(x)}{8!}h^6+...
$$
Now replace $h$ by $2h$ in that formula$$
D_2(x,2h)=\frac{f(x-2h)-2f(x)+f(x+2h)}{4h^2}=f''(x)+\frac{2\cdot 2^2f^{(4)}(x)}{4!}h^2+\frac{2⋅2^4f^{(6)}(x)}{6!}h^4+\frac{2⋅2^6f^{(8)}(x)}{8!}h^6+...
$$
Now it is easy to see what combination of both formulas will eliminate the leading quadratic error term
$$
4D_2(x,h)-D_2(x,2h)=3f''(x)-\frac{2⋅(2^4-4)f^{(6)}(x)}{6!}h^4+O(h^6)
$$
giving the formula
\begin{align}
D_4(x,h)=\frac{4D_2(x,h)-D_2(x,2h)}3
&=\frac{-f(x-2h)+16f(x-h)-30f(x)+16f(x+h)-f(x+2h)}{12h^2}\\
&=f''(x)-\frac{f^{(6)}(x)}{90}h^4+O(h^6)
\end{align}
For $f(x)=\sin(x)$ where we know $f''(x)=-\sin(x)=f^{(6)}(x)$, we can try to numerically confirm that picture

where the error is drawn together with the numerical error bound composed of bounds for the floating point evaluation and the leading error term
$$
\frac{64|f(x)|\epsilon}{12h^2}+\frac{|f^{(6)}(x)|}{90}h^4
$$
where $ϵ\simeq 10^{-16}$ is the floating point machine constant.
As to be expected from this formula, the error is minimal where the terms are equal, around $h\sim\sqrt[6]{500ϵ}\approx 0.006$.


text:
Q: Reference counting: how to make sure two linked objects keep existing when you own at least one? Let's say I have two objects: A and B.
Both objects have a reference count property.
A and B may be created independently. Their reference count is initialized to 1 on creation.
A may be associated to B. When this happens, A gets a reference to B (B's reference count is incremented), and B gets a weak reference to A (to avoid cycles).
If A is associated to B, and you own a reference to either A or B (or both), A and B must not be destroyed. Both objects need to be destroyed when all external references to them are lost.
Here's the problematic situation with typical strong and weak references:
A = createA()   # A's ref count: 1
B = createB()   # B's ref count: 1
associate(A, B) # B's ref count: 2
put(A)          # A's ref count: 0
  -> A is destroyed
  -> B is put by A (B's ref count: 1)
  -> B is notified that A was destroyed
    -> B's weak reference to A is reset

A should not be destroyed here because you still own a reference to B.
How can this be achieved?
Let me also tell you that createA(), createB(), and associate() are part of an existing API which cannot be broken. The internal structure of A and B may be changed, however.

A: The way that you've laid out this problem, it can't be solved.  That's why weak/strong schemes always have the concept of the "owner" or "parent" which is the one with the strong references and which must be the one that you keep alive the longest.
To have cyclic references between objects, no manual lifetime management, and lifetimes of the objects dependent upon the whole cycle, then you need a garbage collector.


text:
Q: Spring boot abstract auto configuration problems I have the following error while using spring boot to run activiti and web sockets together:
Parameter 0 of method springAsyncExecutor in org.activiti.spring.boot.AbstractProcessEngineAutoConfiguration required a single bean, but 4 were found:
- clientInboundChannelExecutor: defined by method 'clientInboundChannelExecutor' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]
- clientOutboundChannelExecutor: defined by method 'clientOutboundChannelExecutor' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]
- brokerChannelExecutor: defined by method 'brokerChannelExecutor' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]
- messageBrokerTaskScheduler: defined by method 'messageBrokerTaskScheduler' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

As spring boot uses abstract configuration, do I have to override some configurations?
Thanks for your help.

A: That's arguably a bug in Activiti's auto-configuration class. It's relying on their only being a single TaskExecutor bean in the application context or, if there are multiple beans, for one of them to be primary.
You should be able to work around the problem by declaring your own TaskExecutor bean and marking it as @Primary:
@Configuration
class SomeConfiguration {

    @Primary
    @Bean
    public TaskExecutor primaryTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // Customize executor as appropriate
        return executor;
    }

}


text:
Q: grep hangs when executed using execvp function in my C program I have written a bash like Linux shell in C.
(Link to my repository:https://github.com/oneiro-naut/wish
 .The file src/execute.c has the execute_pipeline function in it)
I am having problem implementing builtin commands which produce some output. Builtins which do not produce any output like cd and exit work just fine. External commands run smoothly. Shell has support for pipe constructs and I/O redirection as well. The problem is when I try to run a internal command( which is just printing a message). When I redirect builtin command's output to grep command using a pipe the grep child process hangs which I think is happening because grep never encounters the end of stream(or EOF) while reading from the pipe.
NOTE:This does not happen when the pipeline has only external commands in it.(I have taken care that no (external)command finishes before the next command has not yet started therefore it does not hang there)
Here is a simplified version of my problem
 `
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

int main()
{

int pipe_fd[2] = {-1,-1};
int EXIT_STAT = 0;

pipe(pipe_fd);//creating pipe

char* argv[]={"grep","Radiohead",NULL};

int std_out_dup = dup(1);
dup2(pipe_fd[1],1); // redirecting stdout to parent pipe's read end
//close(pipe_fd[0]);//closing parent pipe's write end

printf("Alice in Chains\n");
printf("Radiohead\n");
printf("Dinosaur Jr.\n");
printf("Pixies\n");
printf("Soundgarden\n");
printf("Porcupine Tree\n");
printf("Pain of Salvation\n");

pid_t pid = fork();
if(pid == 0)//child process
{
dup2(pipe_fd[0],0); //redirecting grep's stdin to parent pipe's write end
close(pipe_fd[1]);
execvp(argv[0],argv);//executing grep command
perror("\n");
exit(-1);
}

else if(pid > 0)//parent process
{

    int i;//closing pipes for parent
    for(i=0;i<2;i++)
        close(pipe_fd[i]);

    do{ // waiting for grep to exit
        waitpid(pid,&EXIT_STAT,WUNTRACED);
        //write(,"\x4",1);
    }while(!WIFEXITED(EXIT_STAT)&&!WIFSIGNALED(EXIT_STAT));
}
else ;//fork error

dup2(std_out_dup,1); // restore stdout fd for parent process

return 0;

}

`
Program hangs if I try to run it without printing anything.
But pressing ^D terminates the program producing the output:

    Alice in Chains
    Radiohead
    Dinosaur Jr.
    Pixies
    Soundgarden
    Porcupine Tree
    Pain of Salvation
So it seems grep is not able reads indefinitely because it's not receiving any EOF signal.
Please point out my mistakes I am really confused.
EDIT: Now even pressing ^D does not terminate so I have to just ^C the program.
PROGRAM AFTER CORRECTION:
int main()
{

    int pipe_fd[2] = {-1,-1};
    int EXIT_STAT = 0;

    pipe(pipe_fd);//creating pipe

    char* argv[]={"grep","Radiohead",NULL};

    int std_out_dup = dup(1);
    //printf("%d \n",std_out_dup);
    dup2(pipe_fd[1],1); // redirecting stdout to parent pipe's read end
    //close(pipe_fd[0]);//closing parent pipe's write end

    printf("Alice in Chains\n");
    printf("Radiohead\n");
    printf("Dinosaur Jr.\n");
    printf("Pixies\n");
    printf("Soundgarden\n");
    printf("Porcupine Tree\n");
    printf("Pain of Salvation\n");
    fflush(stdout);

    pid_t pid = fork();
    if(pid == 0)//child process
    {
    close(pipe_fd[1]);
    dup2(pipe_fd[0],0); //redirecting grep's stdin to parent pipe's write end
    dup2(std_out_dup,1); // restore stdout fd for parent process
    execvp(argv[0],argv);//executing grep command
    perror("\n");
    exit(-1);
    }

    else if(pid > 0)//parent process
    {

        int i;//closing pipes for parent

        for(i=0;i<2;i++)
           close(pipe_fd[i]);

        dup2(std_out_dup,1); // restore stdout fd for parent process

        do{ // waiting for grep to exit
            waitpid(pid,&EXIT_STAT,WUNTRACED);
        }while(!WIFEXITED(EXIT_STAT)&&!WIFSIGNALED(EXIT_STAT));
      }
          else ;//fork error

       return 0;
    }

A: You should
1. restore the stdout in the child; otherwise the grep child process will write to the write end of the pipe which is its stdin.
Add a dup2(std_out_dup,1) just after the if(pid == 0)//child process ... {
2. add a fflush(stdout) after all those .... printf("Pain of Salvation\n"); printfs; otherwise the stream will be flushed twice.
3. close all writing ends of the pipe in both the parent and the child; add either dup2(std_out_dup,1) or close(1) before the wait loop in the parent.


text:
Q: change the indicatorColor tabs Material UI v5
I add tabs in my project but I can not change the background indicator :
const theme = createTheme({
  MuiTabs: {
      root: {
        styleOverrides: {
          indicator: {backgroundColor: "red !important"},
        },

        indicator: {backgroundColor: "red !important"},

      },
      indicator: {backgroundColor: "red !important"},

      styleOverrides: {
        indicator: {backgroundColor: "red !important"},
      },
    },

})

this is my code but it does not work.
and this is my jsx code it might help :
import {TabContext, TabList, TabPanel} from "@material-ui/lab";
import Box from "@mui/material/Box";
import Tab from "@mui/material/Tab";
<TabContext value={value}>
                    <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                        <TabList onChange={handleChange} aria-label="lab API tabs example"
                                 textColor="primary"
                                 indicatorColor="primary"

                        >
                            <Tab label="Company Details" value="1" />
                            <Tab label="Admin Details" value="2" />
                        </TabList>
                    </Box>
                    <TabPanel value="1">
                        <FormSimple id={id}/>
                    </TabPanel>
                    <TabPanel value="2"><Admin id={id}/></TabPanel>
                </TabContext>

A: I found my mistake it works very well if
import {TabContext, TabList, TabPanel} from "@mui/lab";


text:
Q: Intel WiFi AX200 - MSI x570 ACE Trying to get Ubuntu up and running on my MSI x570 ACE.
Everything seems to be working fine except WiFi (Intel ax200) and Realtek network drivers. I tried downloading the latest firmware from Intel's website and copying it to /lib/firmware/. Rebooted, no result.
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:    19.10
Codename:   eoan

  ~$ lshw -C network
WARNING: you should run this program as super-user.
  *-network
       description: Ethernet interface
       product: I211 Gigabit Network Connection
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:26:00.0
       logical name: enp38s0
       version: 03
       serial: 00:d8:61:75:d9:1e
       size: 1Gbit/s
       capacity: 1Gbit/s
       width: 32 bits
       clock: 33MHz
       capabilities: bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=igb driverversion=5.6.0-k duplex=full firmware=0. 6-1 ip=192.168.1.144 latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s
       resources: irq:24 memory:f7800000-f781ffff ioport:e000(size=32) memory:f7820000-f7823fff
  *-network UNCLAIMED
       description: Ethernet controller
       product: Realtek Semiconductor Co., Ltd.
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:27:00.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: bus_master cap_list
       configuration: latency=0
       resources: ioport:d000(size=256) memory:f7700000-f770ffff memory:f7710000-f7713fff memory:f7720000-f778ffff memory:f7790000-f77abfff
  *-network UNCLAIMED
       description: Network controller
       product: Intel Corporation
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:28:00.0
       version: 1a
       width: 64 bits
       clock: 33MHz
       capabilities: cap_list
       configuration: latency=0
       resources: memory:f7600000-f7603fff
WARNING: output may be incomplete or inaccurate, you should run this program as super-user.

Added output as requested:
5.3.0-24-generic #26-Ubuntu SMP Thu Nov 14 01:33:18 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
[    6.183238] iwlwifi 0000:28:00.0: enabling device (0000 -> 0002)
[    6.505795] iwlwifi: probe of 0000:28:00.0 failed with error -110

 lspci -knn | grep Net -A3; rfkill list
26:00.0 Ethernet controller [0200]: Intel Corporation I211 Gigabit Network Connection [8086:1539] (rev 03)
    Subsystem: Micro-Star International Co., Ltd. [MSI] I211 Gigabit Network Connection [1462:7c35]
    Kernel driver in use: igb
    Kernel modules: igb
27:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. Device [10ec:8125]
--
28:00.0 Network controller [0280]: Intel Corporation Device [8086:2723] (rev 1a)
    DeviceName: RTL8111EPV
    Subsystem: Intel Corporation Device [8086:0084]
    Kernel modules: iwlwifi
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

After reinstall:
$ dmesg | grep iwl

    [    3.439381] iwlwifi 0000:28:00.0: enabling device (0000 -> 0002)
    [    3.456558] iwlwifi 0000:28:00.0: TLV_FW_FSEQ_VERSION: FSEQ Version: 43.2.23.17
    [    3.456561] iwlwifi 0000:28:00.0: Found debug destination: EXTERNAL_DRAM
    [    3.456562] iwlwifi 0000:28:00.0: Found debug configuration: 0
    [    3.456768] iwlwifi 0000:28:00.0: loaded firmware version 48.4fa0041f.0 op_mode iwlmvm
    [    3.479627] iwlwifi 0000:28:00.0: Detected Intel(R) Wi-Fi 6 AX200 160MHz, REV=0x340
    [    3.490548] iwlwifi 0000:28:00.0: Applying debug destination EXTERNAL_DRAM
    [    3.490903] iwlwifi 0000:28:00.0: Allocated 0x00400000 bytes for firmware monitor.
    [    3.639001] iwlwifi 0000:28:00.0: base HW address: 38:00:25:aa:90:33
    [    3.685024] iwlwifi 0000:28:00.0 wlo1: renamed from wlan0
    [   10.030351] iwlwifi 0000:28:00.0: Applying debug destination EXTERNAL_DRAM
    [   10.177348] iwlwifi 0000:28:00.0: FW already configured (0) - re-configuring

$ lspci -knn | grep Net -A3; rfkill list
        26:00.0 Ethernet controller [0200]: Intel Corporation I211 Gigabit Network Connection [8086:1539] (rev 03)
            Subsystem: Micro-Star International Co., Ltd. [MSI] I211 Gigabit Network Connection [1462:7c35]
            Kernel driver in use: igb
            Kernel modules: igb
        27:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. Device [10ec:8125]
        --
        28:00.0 Network controller [0280]: Intel Corporation Device [8086:2723] (rev 1a)
            DeviceName: RTL8111EPV
            Subsystem: Intel Corporation Device [8086:0084]
            Kernel driver in use: iwlwifi
        0: hci0: Bluetooth
            Soft blocked: no
            Hard blocked: no
        1: phy0: Wireless LAN
            Soft blocked: no
            Hard blocked: no

$ lshw -C network
WARNING: you should run this program as super-user.
  *-network
       description: Ethernet interface
       product: I211 Gigabit Network Connection
           vendor: Intel Corporation
           physical id: 0
           bus info: pci@0000:26:00.0
           logical name: enp38s0
           version: 03
           serial: 00:d8:61:75:d9:1e
           capacity: 1Gbit/s
           width: 32 bits
           clock: 33MHz
           capabilities: bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
           configuration: autonegotiation=on broadcast=yes driver=igb driverversion=5.6.0-k firmware=0. 6-1 latency=0 link=no multicast=yes port=twisted pair
           resources: irq:24 memory:f7800000-f781ffff ioport:e000(size=32) memory:f7820000-f7823fff
      *-network UNCLAIMED
           description: Ethernet controller
           product: Realtek Semiconductor Co., Ltd.
           vendor: Realtek Semiconductor Co., Ltd.
           physical id: 0
           bus info: pci@0000:27:00.0
           version: 00
           width: 64 bits
           clock: 33MHz
           capabilities: bus_master cap_list
           configuration: latency=0
           resources: ioport:d000(size=256) memory:f7700000-f770ffff memory:f7710000-f7713fff memory:f7720000-f778ffff memory:f7790000-f77abfff
      *-network
           description: Wireless interface
           product: Intel Corporation
           vendor: Intel Corporation
           physical id: 0
           bus info: pci@0000:28:00.0
           logical name: wlo1
           version: 1a
           serial: 38:00:25:aa:90:33
           width: 64 bits
           clock: 33MHz
           capabilities: bus_master cap_list ethernet physical wireless
           configuration: broadcast=yes driver=iwlwifi driverversion=5.3.0-24-generic firmware=48.4fa0041f.0 ip=192.168.1.139 latency=0 link=yes multicast=yes wireless=IEEE 802.11
           resources: irq:42 memory:f7600000-f7603fff
    WARNING: output may be incomplete or inaccurate, you should run this program as super-user.

Was able to get them all working, the realtek driver was installed from here: Link

A: With a working internet connection by ethernet, tethered or any means possible, open a terminal and do:
sudo apt-get update
sudo apt-get install linux-oem-osp1

Reboot and show us:
dmesg | grep iwl


text:
Q: Is this histogram considered bimodal? Is this histogram bimodal? Because when I google what a bimodal histogram looks like, I keep getting images that say histograms like these are considered bimodal.

Isn't it unimodal because the highest peak is the only mode? Am I misunderstanding something?

A: If you read "mode" literally then there is just one mode: the highest bar. But that's not what "bimodal" means. Your distribution is properly labelled bimodal since it has two distinct local modes, with a drop between them.
Here's an example that's close to a sum of two normal distributions (Hodgkin lymphoma diagnosis as a function of age).

A: The diagram is bimodal because it's a sort-of sum of two normal distributions.  This can occur, for instance, if there are two sub-populations, say the one on the left is males and the one on the right is females.  Then each of males and females is distributed normally, but when you combine them together, you get a composition of two normal distributions, hence "bimodal", instead of a single normal distribution.
Note that this definition is different from what is given in first-year statistics.  For first-year statistics, "bimodal" is the opposite of "unimodal", whereas for the definition I explained, "bimodal" is the opposite of "normal".


text:
Q: Dot in Range Box Plot I'm attempting to make a table that visually mimics the WSJ markets page. Specifically, I'm hoping that there's a simple way to implement the visual from the Range column:

It seems plausible to me that there's an established way to do this but I don't know how to describe what I'm looking for. The one option I can think of now would be to make it all in TikZ, but I'd rather avoid that complexity if possible.
Is there an easy way to put a bullet in a range box based on an input value?

A: Something like this?
\documentclass{article}
\usepackage{booktabs}
\usepackage{tikz}
\newcommand\Range[1]{%
  \begin{tikzpicture}[scale=0.2]
    \fill[gray!40](0,0) rectangle (8,1);
    \foreach \x in {2,4,6}\draw[white,very thick](\x,0)--+(0,1);
    \fill[black](0.4+#1/100*7.2,0.5) circle (0.4);
  \end{tikzpicture}
}
\begin{document}
\begin{tabular}{l}
  \toprule
  RANGE\\\midrule
  \Range{50}\\
  \Range{100}\\
  \Range{0}\\
  \Range{12}\\
  \Range{62}\\\bottomrule
\end{tabular}
\end{document}

A: Yet another approach.
\documentclass{elsarticle}
\usepackage{xcolor,stackengine}
\def\greybox{\textcolor{gray!50}{\rule{8pt}{1.2ex}}}
\def\backgrid{\greybox\kern1pt\greybox\kern1pt\greybox\kern1pt\greybox}
\setbox0=\hbox{\backgrid}
\edef\backgridwd{\the\wd0}
\newcommand\Range[1]{\stackengine{0pt}{\backgrid}{%
  \kern#1\dimexpr\backgridwd\makebox[0pt]{$\mkern.5mu\bullet$}}{O}{l}{F}{F}{L}}
\begin{document}
\begin{tabular}{c}
\hline
Range\\
\hline
  \Range{.50}\\
  \Range{1.00}\\
  \Range{0}\\
  \Range{.12}\\
  \Range{.62}
\\
\hline
\end{tabular}
\end{document}

A: I ended up using the sparklines package:
\documentclass{article}
\usepackage{sparklines,booktabs}

\begin{document}
\definecolor{sparkspikecolor}{gray}{1}
\setlength{\sparkspikewidth}{1pt}
\setlength{\sparkdotwidth}{2pt}
\newcommand{\rangebox}[1]{
    \begin{sparkline}{10}
    \sparkrectangle 0 1
    \sparkspike .25 1
    \sparkspike .5 1
    \sparkspike .75 1
    \sparkdot #1 0.5 black
    \end{sparkline}
}

\begin{tabular}{c}
  \toprule
  Range
  \\\midrule
  \rangebox{.2}\\
  \rangebox{1}\\
  \rangebox{0}\\
  \rangebox{.8}\\
  \rangebox{.95}\\\bottomrule
\end{tabular}

\end{document}


text:
Q: Expanding QTreeView Item From ModelIndex How can I expand a QTreeView item knowing it's modelIndex. I'm trying to call the following piece of code and it doesn't throw any errors but it does not expand the treeview item...
parentIndex = self.categoryModel.indexFromItem(parent)
if parentIndex.isValid():
    self.uiTreeView.setExpanded(parentIndex, True)

To test, select the first item in the list and click the Add button. When a user adds a new category i want it to expand the item it's being added to.

import os, sys
from Qt import QtWidgets, QtGui, QtCore

################################################################################
# Widgets
################################################################################
class CategoryView(QtWidgets.QWidget):

    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.resize(250,400)

        self.uiAdd = QtWidgets.QPushButton('Add')

        self.categoryModel = QtGui.QStandardItemModel()
        self.categoryModel.setHorizontalHeaderLabels(['Items'])

        self.categoryProxyModel = QtCore.QSortFilterProxyModel()
        self.categoryProxyModel.setSourceModel(self.categoryModel)
        self.categoryProxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.categoryProxyModel.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.categoryProxyModel.setDynamicSortFilter(True)

        self.uiTreeView = QtWidgets.QTreeView()
        self.uiTreeView.setModel(self.categoryProxyModel)
        self.uiTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder)
        self.uiTreeView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.setContentsMargins(0,0,0,0)
        self.layout.setSpacing(0)
        self.layout.addWidget(self.uiAdd)
        self.layout.addWidget(self.uiTreeView)
        self.setLayout(self.layout)

        # Selections
        self.categorySelection = self.uiTreeView.selectionModel()

        # Signals
        self.uiAdd.clicked.connect(self.slotAddNewCategory)

        parent = self.categoryModel.invisibleRootItem()
        parent.appendRow(QtGui.QStandardItem('Fruit'))

    # Methods
    def getSelectedItems(self):
        items = []
        for proxyIndex in self.categorySelection.selectedIndexes():
            sourceIndex = self.categoryProxyModel.mapToSource(proxyIndex)
            item = self.categoryModel.itemFromIndex(sourceIndex)
            items.append(item)
        return items

    def slotAddNewCategory(self):
        text, ok = QtWidgets.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')

        if ok:
            item = QtGui.QStandardItem(text)

            parent = self.categoryModel.invisibleRootItem()
            items = self.getSelectedItems()
            if len(items) == 1:
                parent = items[0]

            parent.appendRow(item)

            parentIndex = self.categoryModel.indexFromItem(parent)
            print parentIndex.data()
            if parentIndex.isValid():
                self.uiTreeView.setExpanded(parentIndex, True)

################################################################################
# Unit Testing
################################################################################
def test_CategoryView():
    app = QtWidgets.QApplication(sys.argv)
    ex = CategoryView()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    pass
    test_CategoryView()
    # test_PainterSettingsDialog()

A: Answer found here... How to expand top-level QTreeview items
parentIndex = self.categoryModel.indexFromItem(parent)
px = self.categoryProxyModel.mapFromSource(parentIndex)

if parentIndex.isValid():
    self.uiTreeView.setExpanded(px, True)


text:
Q: Mostrar texto sobre punto de google maps quien me ayuda en lo siguiente:
Tengo un proyecto en el cual desde winform abro el navegador con la url de google maps especificando latitud y longitus, pasando los parametros en la url (Ejemplo: "http://maps.google.com/maps?q=17.43%2C60.65"), todo funciona bien y lo muestra así:

Lo que me falta es que necesito que encima del punto del mapa me aparezca un texto, algo como "Dirección de Pepito Perez". Entonces la pregunta sera ¿Como adiciono texto encima del punto de google maps? ojo que esto debe sar pasando parametros en la url (como en el ejemplo la latitud y longitud). Gracias.

A: Aquí tienes tu respuesta según los docs de google.
No pego el código porque sin especificar la api de google, lo ejecutarías en SO i no funcionaría.
Regístrate en google maps para obtener tu API, es facilito. (https://developers.google.com/maps/documentation/javascript/examples/place-details)
Te dejo otra opción esta es con la url de la api de google pero sin una api key.
He sacado el código de una respuesta de SO en inglés:
https://stackoverflow.com/a/31548993/4955542
Es mejor usar la API Key es más seguro para ti que te funcione en todos los navegadores, sin problemas.

<!DOCTYPE html>

            <title>test sandbox 8</title>

A: Utilizando la url del google maps directamente NO se puede hacer lo que indicas.
Si quieres ver todo lo que se puede hacer sin la API (que es lo que estás haciendo) puedes mirar esta respuesta que te indica todos los parámetros con los que puedes trabajar.


text:
Q: Winsock - Best way to read, write, send, and receive from sockets What is the best way to read and write from multiple client sockets on a single thread? I've heard that select() is oldschool and there are better options available. Is the best option currently to use one of WSAAsyncSelect, WSAEventSelect?
Also, what is the difference between WSARecv() and recv(), and WSASend() and send()? Are the WSA versions the most modern way to send and recv data through winsock?

A: If your single thread is also implementing a GUI then WSAAsyncSelect is designed for this purpose: You get your socket notifications through messages in the Windows queue that your GUI thread must service anyway.
If your single thread is dedicated to the sockets and does not need a message loop, then WSAEventSelect might be more convenient, and a little faster.


text:
Q: SQL/Spark: get condition with group and null values I would need to get an if statement that
groups by a date field (named VALIDTO)
and returns just one null value if there are any nulls in the group
or returns the maximun in case there are not nulls in the group.
This should work but it is very tricky as MAX, MIN and COUNT
ignore null values:
test = sql_context.sql(""" select field1, field2,
                                  if(MIN(VALIDTO) is null, null, MAX(VALIDTO)) as VALIDTO
                                  from test_table
                                """)

Many thanks in advance!

A: You can check whether there are nulls by getting the maximum of VALIDTO is null in that group:
select
    field1, field2,
    case when max(VALIDTO is null) = False then max(VALIDTO) end as VALIDTO
from test_table
group by field1, field2

A: Hmmm . . . I think you want an aggregation function on validto to return NULL if any values are NULL.  If so,  you can use case:
(case when count(*) = count(validTo) then max(validTo)
 end)