text:
Q: Form Submission with JSP I'm trying to make a JSP that will insert a record submitted through a form. However, I'm trying to make sure it connects and by doing so using a mySQL select statement to retrieve data. I posted the error below. I'm not sure why I'm getting this error. So far I have this
<%@ page import ="java.sql.*" %>
<%
String url = "jdbc:mysql//sql.njit.edu:3306/user";
String user = "u";
String pass = "p";
String classPath = "com.mysql.jdbc.Driver";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try{
    Class.forName(classPath);
    conn = DriverManager.getConnection(url, user, pass);
} catch(Exception e){
    e.printStackTrace();
}

stmt = conn.createStatement();

String query = "SELECT * FROM Music";

try{
    rs = stmt.executeQuery(query);
    while(rs.next()){
        out.println(rs.getString("song"));
    }
}catch(SQLException e){
    e.printStackTrace();
}
finally {
    try {
        if (stmt != null)
            stmt.close();
        if (rs != null)
            rs.close();
        if (conn != null)
            conn.close();
    }catch (SQLException e) {
        e.printStackTrace();
    }
}
%>

I get the following error
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:451)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:321)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:257)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

root cause

java.lang.NullPointerException
org.apache.jsp.insert_jsp._jspService(insert_jsp.java:64)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:321)    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:257)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

A: Your JDBC URL format is wrong. It should be like
jdbc:mysql//sql.school.edu:3306/user


text:
Q: "fill in the blanks" I'm trying to make a simple "fill in the blanks" type of exam in django and would like to know what is the best way to design the database.
Example: "9 is the sum of 4 and 5, or 3 and 6."
During the exam, the above sentence would appear as "__ is the sum of __ and _, or _ and __."
Obviously there are unlimited number of answers to this question, but assume that the above numbers are the only answers. But the catch is that you can switch the places of 4 and 5, or the places of 3 and 6 and still get the right answer. Besides, the number of blanks is not known, so it can be 1 or more.

A: I would go with something like. First define a Question table:
Question
--------------------------
Id     Text
1      9 is the sum of 4 and 5, or 3 and 6
...

Then save the position of the hidden substrings, let's call them fields, in another table:
QuestionField
--------------------------
Id  QuestionId  StartsAt    EndsAt      Set
1   1           0           1           1
2   1           16          17          2
3   1           22          23          2  # NOTE: Is in the same set as QuestionField #2
...

This table lets you retrieve the actual value of the field by querying the Question table (e.g. entry one refers to the value '9' in the first question).
The "Set" column contains an identifier of the "set" in which this field is, where fields in the same set can be replaced by each other. When you populate it, you would have to ensure that all questions that can be replaced by each other are in the same set. The actual number of the set doesn't matter, as long as it's unique. But it makes sense to have it equal to the ID of one of the elements of the set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connect Python to Teradata in mac with pyodbc I successfully installed pyodbc module for python 2.7. However, when input the following code to connect to teradata,
import pyodbc
conn = pyodbc.connect('DRIVER={Teradata};DBCNAME=<tdwc>;UID=<UID>;PWD=<UID>;QUIETMODE=YES;')
I got the following error;
Traceback (most recent call last):
  File "", line 1, in
    pyodbc.connect('DRIVER={Teradata};DBCNAME=;UID=;PWD=;QUIETMODE=YES;')
Error: ('00000', '[00000] [iODBC][Driver Manager]dlopen(/Library/Application Support/teradata/client/ODBC/lib/tdata.dylib, 6): Library not loaded: libtdparse.dylib\n  Referenced from: /Library/Application Support/teradata/client/ODBC/lib/tdata.dylib\n  Reason: image not found (0) (SQLDriverConnect)')
What should I do to have this fixed? Any ideas?

A: Basically pyodbc is not straight forward and gives good enough debugging time for developers.
Follow the below steps,
You might have done them already, then just verify

*

*Install iodbc for mac http://www.iodbc.org/dataspace/iodbc/wiki/iODBC/Downloads

*Install Teradata ODBC Driver for Mac OS X, http://downloads.teradata.com/download/connectivity/teradata-odbc-driver-for-mac-os-x

*Also install unixodbc for mac, "brew install unixodbc"

*Download pyodbc source and change the setup.py file as below,

 elif sys.platform == 'darwin':
    # OS/X now ships with iODBC.
    settings['libraries'].append('iodbc')
    settings['libraries'].append('odbc')

you will be adding the last line of including "odbc" for build
Build and install pyodbc

*Setup the traditional LD_LIBRARY_PATH for mac as below ( I used TD version 15.00, you have to point to the one as you installed)

export DYLD_LIBRARY_PATH=/Library/Application\
  Support/teradata/client/ODBC/lib:/Library/Application\
  Support/teradata/client/15.00/lib/

*Export ODBCINI path

export ODBCINI=/Library/Application\
  Support/teradata/client/15.00/odbc/odbc.ini

Now pyodbc cursor happily will fetch record sets for you


text:
Q: How do I find the Kernal of a Linear Transformation Say I have a Linear Mapping from $R^3 \to R^2$ defined by $L(x) = (x + y, y + z)$. I know that to find the $\ker(L)$ you have to set $x + y = 0$ and $y + z = 0$. My question is, how did we get the vector (or answer) $(1,-1,1)$? I don't understand. Thank you.

A: If $x+y=0,~~y+z=0$ then you indeed have a line! The first equation is a plane and the other one is also. Solve these equations simultaniously as a system of linear eqations. If you  take $z=t$ then $y=-t$ and then $x=t$. So the set of all solutions are spaned with vector $V=(1,-1,1)$. This is a basis for that kernel.


text:
Q: Failed to verify bitcode in TNSMLKitCamera.framework/TNSMLKitCamera I am experiencing this issue that causes tns run ios to fail when building on a real device. Using the emulator works fine but whenever I try to run or build on a real device, the changes cannnot be applied and the error is error: exportArchive: Failed to verify bitcode in TNSMLKitCamera.framework/TNSMLKitCamera: error: Bundle only contains bitcode-marker /var/folders/5d/_v1mn0f16w7dt6k7dbvby_c00000gn/T/XcodeDistPipeline.neH/Root/Payload/mobile.app/Frameworks/TNSMLKitCamera.framework/TNSMLKitCamera (armv7)
Any help/guidance is appreciated. Thanks


text:
Q: Flash Builder debugger silently calls getters to update Variables View - is this a flaw? I've been using Flex/Flash Builder for a couple of years now, and have only discovered something today. I was looking at some complex code which worked fine, but I needed to know how it behaved, so I placed a breakpoint in it and low and behold it threw an exception. I took it out again and it ran through OK (even with trace statements). I thought this was odd.
To cut a long story short, after a lot of head scratching it turns out that if you have a getter in your code, and during the debug process your Variables View (or Expressions View) displays the var that the getter gets, then the Flash Builder debugger will run the getter (silently) in order to calculate the value displayed in the Variables View.
In other words, under certain circumstances, by debugging your code, it may run a completely different path to how it would run if you weren't debugging (and which path it follows depends upon whether you have the Variables View open and are displaying the var's value in it).
Is this a pretty serious flaw?
I always thought that if you run an application in debug mode it should run the exact same code path that it takes when not debugging, provided the inputs are identical (although I realise it can get pretty hard to replicate real time use when debugging around event handlers for losing/gaining focus etc).
The other scary thing is that the getter is called silently by the debugger - ie if you have a breakpoint in the getter it won't stop there when the debugger calls it to update the var's value in the Variables View. So you don't even realise its running the getter.
Shouldn't the var in the Variables View just display a value of null until its getter is eventually run under the normal course of code execution?
Edit (28/7/11): My original post stated that setters were run, which is wrong - it is the getters, as described above. As such this "flaw" exists only when code in the getters performs additional functionality above and beyond the mere getting of the var value - additional functionality like this in getters is a "code smell" to me, therefore the original flaw exists, but really only in tainted code


text:
Q: Solutions of $x^3 + (x+4)^2 = y^2$ I want to solve the above equation in integers. I'm pretty sure the only solutions are $(x,y) = (0, \pm 4)$ but I'm not sure how to prove it.

A: When $x=0$, $y^2 = 4^2$ and hence $y=\pm 4$. Thus $(x,y) = (0,\pm 4)$ are solutions. We will show there are no other solutions.
Suppose that $x \neq 0$. We have \begin{align}
 x^3 = y^2 - (x+4)^2 = (y+x+4)(y-x-4)
 \end{align} Let $d$ be the greatest common divisor of $y+x+4$ and $y-x-4$. We claim that $d$ is a power of 2. If $d$ has an odd prime factor $p > 1$, then clearly, $p$ divides $x^3$ and hence $x$. Also since $p$ divides both $y+x+4$ and $y-x-4$, it divides their sum, $2y$ and since $p$ is odd, $p$ divides $y$. But then $p$ must divide 4, a contradiction.
Thus $d = 2^k$ for some $k \geq 0$.Suppose that $k=0$. That is, $y+x+4$ and $y-x-4$ are coprime. Then, there exists integers $m,n$ such that $y+x+4 = m^3$ and $y-x-4=n^3$. We have $x=mn$ and $2x+8 = m^3-n^3$. Clearly, $m,n$ are both odd and hence $|m-n| \geq 2$.
Case 1 $x=mn > 0$, $m >  n$
    $$2mn+8 = m^3-n^3 = (m-n)((m-n)^2+3mn) \geq 6mn$$ and hence $mn \leq 2$. Since $m,n$ are both odd integers, it follows that $mn \geq 3$. Thus no solutions in this case.
Case 2 $x = mn >0$, $m < n$
We have $$2mn+8 = (m-n)^3 + 3(m-n)mn \leq -8-6mn $$
    This gives $mn \leq -2$, a contradiction to the assumption $mn > 0$.
Case 3 $x = mn <0$, $m > n$
We have $2mn + 8 = m^3 - n^3 > 0$ and hence $mn > -4$. Since $m,n$ are odd integers, the possibilities are $mn = -1, -3$. Thus $m = 1, n=-1$ or $m=3, n=-3$. Putting $m=1, n=-1$, we get $-1 + 27 = y^2$, and $y $ is not an integer. For $m=3, n=-1$, we have $-27+1 = y^2$ again an impossibility.
Case 4 $x = mn < 0$, $m < n$
Here, $m < 0$ and $n > 0$.
    $$2mn + 8 = m^3 - n^3 < -m^2 - n^2$$ giving $m^2+n^2+2mn = (m+n)^2 < -8$, an impossibility.
Suppose that $d = 2^k$ and $k >0$. Since $2^{2k}$ divides $x^3$, it follows that $k$ must be a multiple of $3$. We need to discuss two cases: $k > 3$ and $k=3$. Suppose that $k > 3$. Then, $2^6 | x$. But $2^6 | (y+x+4) - (y-x-4) = 2x+8$. This implies $2^6$ divides 8, a contradiction.
Suppose that $k=3$. Then $y+x+4 = 8a, y-x-4 = 8b$ where $a,b$ are coprime.
 We have $x^3 = 64ab$ and hence both $a,b$ must be cubes of integers. Let $a =m^3, b=n^3$. Note that both $m,n$ are odd integers. Also $x=4mn$ and $2x+8 = 8(m^3-n^3)$. Thus $mn+1 = m^3-n^3$ and since $m, n$ are both odd integers, $|m-n| \geq 2$. If $mn > 0$, then $m >n$ and $mn+1 = (m-n)((m-n)^2 + 3mn) \geq 6mn$ and we get $5mn \leq 1$, a contradiction. If $mn < 0$, two cases arise:
$m < 0, \, n > 0$: $2mn + 1 < mn+1 = m^3 - n^3 \leq  -m^2 - n^2$ giving $m^2+n^2+ 2mn \leq -1$, an impossibility.
$m > 0,\, n < 0$: $mn+1 = m^3 - n^3 > 0$ and $mn > -1$. Since $mn < 0$ and $m, n$ are integers, this is impossible.
Thus the only solutions of the given equation are $x=0, y=\pm 4$.

A: A subtle proof technique called proof by SageMath:
E = EllipticCurve([0,1,0,8,16])
E.integral_points(both_signs=True)

which gives:
[(0 : -4 : 1), (0 : 4 : 1)]

where the numbers in the constructor of the EllipticCurve are the Weierstrass coefficients of the curve. For reference, the Weirstrass coefficients are defined as a list $[a_1, a_2, a_3, a_4, a_6]$ where the curve is of the form $y^2 + a_1xy + a_3y = x^3 + a_2x^2 + a_4x + a_6$.
Try it here!
I don't want to give you a non-answer but in general I don't think there is a clean way to prove these things except by using the fact that we have terminating algorithms to find the solutions. I haven't looked at this specific case too closely (there may be a neat trick), but proof by SageMath is technically sufficient.
A few buzzwords for you to continue your search if you're interested: "weirstrass equation", "elliptic curve", "finite fields".
Here are also a few math overflow answers that are slightly more detailed:
Link 1
Link 2

Edit
The context that this is an olympiad question means there should be a neater way. I've had more time to look at this so:
We want to find all integer solutions to $x^3 + (x+4)^2 = y^2$. First notice we can write this as a difference of two squares:
$$
\begin{align}
x^3 + (x+4)^2 &= y^2 \\
x^3 &= y^2 - (x+4)^2 \\
x^3 &= (y+(x+4))(y-(x+4)) \\
x^3 &= (y+x+4)(y-x-4)
\end{align}
$$
Now, since $x$ and $y$ are integers, $(y+x+4)(y-x-4)$ must be an integer factorization of $x^3$. The ways to factor $x^3$ into two factors, if $x$ is prime, are:

*

*$x^3 \cdot 1$

*$1 \cdot x^3$

*$x \cdot x^2$

*$x^2 \cdot x$

We can simply enumerate through each of these for the factors on the RHS of our equation and see which gives integer solutions.
For ex. if we try the third factorization, we get $(y+x+4) = x$ and $(y-x-4) = x^2$. The first equation gives $y = -4$ and substituting into the second gives $x^2 + x + 8 = 0$ which has no integer solutions and thus this factorization won't work.
If you try all of these, you will notice no integer values for $x$ or $y$ satisfy any of those factorizations. This leaves one possibility: that $x^3 = 0$ and thus $x = 0$. Evaluating this on the RHS, we get $(y+0+4)(y-0-4) = 0$ and thus:
$$
(y+4)(y-4) = 0 \\
\implies y = \pm 4
$$
Thus the only solutions are $(x, y) = (0, \pm 4)$.
Correction:
Comment is correct, this only holds for prime $x$. Perhaps develop what could be done if $x$ is not prime or show this can't be so? This might be a good starting place.


text:
Q: Prevent scientific notation in ostream when using << with double I need to prevent my double to print in scientific notation in my file,
when I do this
outfile << X;

A: All the above answers were useful, but none directly answer the question.
outfile.setf(std::ios_base::fixed);
outfile << x;

I found the answer in @moogs link: https://en.cppreference.com/w/cpp/io/ios_base/fmtflags
Here's a demo program: http://ideone.com/FMxRp1

A: To set formatting of floating variables you can use a combination of setprecision(n), showpoint and fixed. In order to use parameterized stream manipulators like setprecision(n) you will have to include the iomanip library:
#include <iomanip>

setprecision(n): will constrain the floating-output to n places, and once you set it, it is set until you explicitly unset it for the remainder of the stream output.
fixed: will enforce that all floating-point numbers are output the same way. So if your precision is set to 4 places, 6.2, and 6.20 will both be output as:
6.2000
6.2000

showpoint: will force the decimal portions of a floating-point variable to be displayed, even if it is not explicitly set. For instance, 4 will be output as:
4.0

Using them all together:
outfile << fixed << showpoint;
outfile << setprecision(4);
outfile << x;

A: you can use format flags
http://en.cppreference.com/w/cpp/io/ios_base/fmtflags

A: Here's an example of usage
http://cplus.about.com/od/learning1/ss/clessontwo_4.htm
as per your question use
  std::cout << std::fixed << a << std::endl;


text:
Q: Avoid overlapping of lists in UL LI On the following code I do NOT want the 'level 2' list items be overlapped. How can I achieve that. Here is my sample code.

Level 0

Level 1

a Level 2

a Level 2

a Level 2

a Level 2

a Level 2

a Level 2

Level 1

Level 1

b Level 2

b Level 2

b Level 2

b Level 2

b Level 2

Level 1

Level 1

The idea is to show the boxes vertically without being overlapped.
Thanks in advance.


text:
Q: Reverse an ostringstream by line ostringstream ss;
ss << "(1,2)\n" << "(1,3)\n" << "(1,4)\n" ;
cout << ss.str();

should print the following:

(1,2)
(1,3)
(1,4)

How could i reverse the output by line so that it prints:

(1,4)
(1,3)
(1,2)

A: You could use a custom std::streambuf which internally keeps a stack of std::strings and puts them together upon using a str() member. For example:
#include <iostream>
#include <numeric>
#include <streambuf>
#include <string>
#include <vector>

class stackbuf
    : public std::streambuf
{
    std::vector<std::string> d_lines;
    int overflow(int c) {
        if (c != std::char_traits<char>::eof()) {
            this->d_lines.back().push_back(c);
            if (c == '\n') {
                this->d_lines.push_back(std::string());
            }
        }
        return std::char_traits<char>::not_eof(c);
    }
public:
    stackbuf(): d_lines(1) {}
    std::string str() const {
        return std::accumulate(this->d_lines.rbegin(),
                               this->d_lines.rend(),
                               std::string());
    }
};

int main()
{
    stackbuf sbuf;
    std::ostream out(&sbuf);
    out << "(1, 2)\n(1, 3)\n(1, 4)\n";
    std::cout << sbuf.str();
}

For a real-world application you should, obviously, set up a buffer in the stream buffer to improve the performance. You may also want to create a custom stream directly initializing the stream's stream buffer.

A: You can use reverse iterators:

std::ostringstream ss{ "(1,2)\n(1,3)\n(1,4)\n" };
std::string str = ss.str();

std::copy( str.rbegin(), str.rend(),
           std::ostream_iterator<std::string>{std::cout, "\n"} );

This code will require:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <sstream>

and basic C++11 support.

A: Using your original code with C++98:
  ostringstream ss;
  ss << "(1,2)\n" << "(1,3)\n" << "(1,4)\n" ;
  cout << ss.str();

  //assign a string to the contents of the ostringstream:
  string rawlines = ss.str();

  //now create an input stringstream with the value of the rawlines
  istringstream iss(rawlines);

  string temp;//just a temporary object used for storage
  vector<string> lines;//this is where your lines will be held

  //now iterate over the stream and store the contents into the vector `lines`:
  while(getline(iss, temp)) {
      lines.push_back(temp);
  }

  //now reverse the contents:
  reverse(lines.begin(), lines.end());

  //see what's inside:
  for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
    cout << *it << endl;
  }

This will print:
(1,4)
(1,3)
(1,2)

As desired
NOTE: This strips the newlines from the the original string.
And, this requires:
//for `getline`:
#include <cstdlib>
//for `reverse`:
#include <algorithm>
//for `string`:
#include <string>
//for `vector`:
#include <vector>

A: This would be the classic way, best leveraging the standard C++ library.
#include <iostream>
#include <sstream>
#include <stack>
#include <string>

using namespace std;

int main(int argv, char* arv[])
{
  ostringstream oss;
  oss << "(1,2)\n" << "(1,3)\n" << "(1,4)\n" ;
  cout << oss.str() << "----------\n";
  // Reverse lines
  // Fill an istringstream with buffer contents of the ostringstream
  istringstream iss(oss.str());
  stack<string> stk;
  while (iss) {
    string s;
    if (!getline(iss, s)) break; // Read a line
    s += '\n';                   // Put back newline stripped by readline
    stk.push(s);                 // Push line to stack
  }
  oss.clear();                   // Clear state of the ostringstream
  oss.str("");                   // Clear contents of the ostringstream for reuse
  while (!stk.empty()) {
    string s;
    s = stk.top();               // Get top of stack
    oss << s;                    // Output it to the ostringstream
    stk.pop();                   // Pop and throw away top of stack
  }
  cout << oss.str();
  return 0;
}


text:
Q: Overwrite file in Mobile Documents I have a file stored in the current location on my phone:
/private/var/mobile/Library/Mobile Documents/iCloud~is~workflow~my~workflows/Documents/File.JSON

Now, I have created a new JSON file that I want to replace it with, like this:
    let jsonObject: [String: Any] = [
        "ID": "819736471902",
        "TOKEN": "w5tw905y3475n30984um0f2ur0283urn27y4brt38t209"
    ]

    let valid = JSONSerialization.isValidJSONObject(jsonObject) // true

    print(valid)
    print("...")
    print(jsonObject)

    let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject)

I am going to use the same file name and the same location, so I just want to replace the old file with this new one.
I know I can now save this file using the UIDocumentPickerViewController, but is there any other way I can do this saving process in the background?

A: You can change to use FileManager to saving json in background
Code will be like this
func saveJson(fileName: String, json: [String: Any]) {
    // get documentary path to save image to
    guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    let fileName = fileName
    let fileURL = documentsDirectory.appendingPathComponent(fileName)

    let jsonData = try! JSONSerialization.data(withJSONObject: json)

    //Checks if file exists, removes it if so.
    if FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try FileManager.default.removeItem(atPath: fileURL.path)
            print("Removed old file")
        } catch let removeError {
            print("couldn't remove file at path", removeError)
        }
    }

    do {
        try jsonData.write(to: fileURL)
    } catch let error {
        print("error saving file with error", error)
    }
}

func loadJsonFromDiskWith(fileName: String) -> [String: Any] {
  let documentDirectory = FileManager.SearchPathDirectory.documentDirectory

    let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)

    if let dirPath = paths.first {
        let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: fileURL.path))
            let dict = try JSONSerialization.jsonObject(with: data)
            return dict as! [String : Any]
        } catch {
            return [:]
        }
    }
    return [:]
}

Usage
let jsonObject: [String: Any] = [
    "ID": "819736471902",
    "TOKEN": "w5tw905y3475n30984um0f2ur0283urn27y4brt38t209"
]

self.saveJson(fileName: "abc.json", json: jsonObject)
let finalDict = self.loadJsonFromDiskWith(fileName: "abc.json")
print(finalDict) // your json from store in Document


text:
Q: How to mock third party React Native NativeModules? A component is importing a library that includes a native module. Here is a contrived example:
import React from 'react';
import { View } from 'react-native';
import { Answers } from 'react-native-fabric';

export default function MyTouchComponent({ params }) {
  return <View onPress={() => { Answers.logContentView() }} />
}

And here is the relevant part of Answers from react-native-fabric:
var { NativeModules, Platform } = require('react-native');
var SMXAnswers = NativeModules.SMXAnswers;

When importing this component in a mocha test, this fails on account that SMXAnswers is undefined:
How do you mock SMXAnswers or react-native-fabric so that it doesn't break and allows you to test your components?
p.s.: you can see the full setup and the component I'm trying to test on GitHub.

A:
Use mockery to mock any native modules like so:
import mockery from 'mockery';

mockery.enable();
mockery.warnOnUnregistered(false);
mockery.registerMock('react-native-fabric', {
  Crashlytics: {
    crash: () => {},
  },
});

Here is a complete setup example:
import 'core-js/fn/object/values';
import 'react-native-mock/mock';

import mockery from 'mockery';
import fs from 'fs';
import path from 'path';
import register from 'babel-core/register';

mockery.enable();
mockery.warnOnUnregistered(false);
mockery.registerMock('react-native-fabric', {
  Crashlytics: {
    crash: () => {},
  },
});

const modulesToCompile = [
  'react-native',
].map((moduleName) => new RegExp(`/node_modules/${moduleName}`));

const rcPath = path.join(__dirname, '..', '.babelrc');
const source = fs.readFileSync(rcPath).toString();
const config = JSON.parse(source);

config.ignore = function(filename) {
  if (!(/\/node_modules\//).test(filename)) {
    return false;
  } else {
    const matches = modulesToCompile.filter((regex) => regex.test(filename));
    const shouldIgnore = matches.length === 0;
    return shouldIgnore;
  }
}

register(config);


text:
Q: Subquery using 3 Tables SQL I'm trying to display the last name of the lowest paid employees from each city. The city column falls under a table titled LOCATIONS while employee information(salary, last name) falls under EMPLOYEES. Both of these tables are related share no common table, so I have to rely on a third table, DEPARTMENTS to connect the two as DEPARTMENTS contains a department_id that it shares with EMPLOYEES as well as a LOCATION_ID that it shares with LOCATIONS. This is what I have so far, but I'm having trouble with this as I've mostly worked with only two tables in the past.
SELECT LAST_NAME
FROM EMPLOYEES
WHERE (DEPARTMENT_ID) IN
(SELECT DEPARTMENT_ID
FROM DEPARTMENTS
WHERE LOCATION_ID IN
(SELECT LOCATION_ID
FROM LOCATIONS
GROUP BY CITY
HAVING MIN(SALARY)));

A: This seems to be an assignment in an intro course in SQL. So let's assume you can't use analytic functions, match_recognize clause, etc. Just joins and aggregates.
In the subquery in the WHERE clause below, we compute the min salary for each city. We need to join all three tables for this. Then in the overall query we join the three tables again, and we use the subquery for an IN condition (a semi-join). The overall query looks like this:
select e.last_name
from   employees e join departments d
                     on e.department_id = d.department_id
                   join locations   l
                     on d.location_id   = l.location_id
where  ( e.salary, l.city ) in
       (
         select   min(salary), city
         from     employees e join departments d
                                on e.department_id = d.department_id
                              join locations   l
                                on d.location_id   = l.location_id
         group by city
       )
;

A: You should separate out the concept of table joins from WHERE clauses.
Use WHERE for filtering data, use JOIN for connecting data together.
I think this is what you are wanting. By the way, lose the ALL CAPS if you can.
SELECT
    LAST_NAME
FROM
    EMPLOYEES
    INNER JOIN (
        SELECT
            DEPARTMENTS.DEPARTMENT_ID,
            CITY,
            MIN(SALARY) AS LOWEST_SALARY
        FROM
            EMPLOYEES
            INNER JOIN DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
            INNER JOIN LOCATIONS ON DEPARTMENTS.LOCATION_ID = LOCATIONS.LOCATION_ID
        GROUP BY
            DEPARTMENTS.DEPARTMENT_ID,
            LOCATIONS.CITY
    ) AS MINIMUM_SALARIES
    ON EMPLOYEES.DEPARTMENT_ID = MINIMUM_SALARIES.DEPARTMENT_ID
       AND EMPLOYEES.SALARY = MINIMUM_SALARIES.LOWEST_SALARY

A: First of all join the tables, so you see city and employee in one row. If we group by city we get the minimum salary per city.
with city_employees as
(
  select l.city, e.*
  from locations l
  join departments d using (location_id)
  join employees e using (department_id)
)
select last_name
from city_employees
where (city, salary) in
(
  select city, min(salary)
  from city_employees
  group by l.city
);

It is easier to achieve the same, however, with window functions (min over or rank over here).
select last_name
from
(
  select
    e.last_name,
    e.salary,
    min(e.salary) over (partition by l.city) as min_salary
  from locations l
  join departments d using (location_id)
  join employees e using (department_id)
)
where salary = min_salary;


text:
Q: Intervention study design I am facing the following "problem": I want to evaluate the effects of an intervention on certain outcomes in a group of adolescents athletes. Obviously the best choice would be to conduct a randomized controlled trial. However, I won't get the coaches to perform the intervention with only half of their teams.
The next best choice imo would be to conduct a non-randomized trial, e.g. two teams with only one performing the intervention. However, I fear that the effect due to coach/team is greater than that of the intervention. Or said differently I fear that at baseline the teams are already "different" and thereby comparing them is not valid.
Therefore I came up with the following design. Athletes are measured three times. Between measurement 1 and 2 they perform their usual training without intervention. Between measurement 2 and 3 they do perform the additional intevention. Then I would compare the differences between 1&2 and 2&3. If the letter are greater the intervention has an effect.
First Question: Is there a name for such a design?
Second question: Can I make causal conclusion about the effect of the intervention based on this design?
I am quite unsure about this because there will also be changes due to the normal training and growth between measurement 1 and 2.


text:
Q: Batch Downloading files using NSURLSession with file integrity on iOS We have an application that downloads user contents. Our files could be big ones and usually our users download as batch. Our users having different troubles on download that described below. We want to refactor whole download process and possible use a library for that. We would like your opinion on problems and solutions.
Current Process:
We have list of items, which users can download, each item consists of a single file or multiple files (users don't aware of that).  User can initiate download of an item by pressing the "download button" on the list, and we support concurrent download of items. Remember each item can have multiple files or single file. We also need to show progress of download for items individually. We are using NSURLConnection to download files it was developed since iOS 4.
Problems:

*

*During download if there is a network glitch or some unknown reasons
download gets stuck.

*During download lost some data of the file

*Having trouble to download in the background (We have to keep screen
awake for example to make download continue etc. since it was
developed on iOS 4)

*There is no file integrity check when download is finished

*Resume Download

What we need:

*

*Download big files as batch, usually 10 to 50 files, size around 10
to 200 MB of each file

*Pause when there is a connection problem (lost, troubled/deadly
slow), auto resume when connection is back

*Download in the background (app suspended or closed)

*Resume download in background when app is crashed or terminated

*Pause, Cancel of Downloads by User

*Integrity check when download is complete

*Integrity check while download is in progress (on downloaded parts),
auto re-download bad parts before download completes

*Getting progress info (list of downloads, downloaded ones, percentage
of download, estimated time of complete, download speed etc.)

*Multiple threads to fast download

*Support from iOS 7 to Later

In which solution we can make sure each of our needs covered? How can we achieve this?

A: Ok it can be simply achieved by using NSUrlSession (NSURLSessionDataTask, NSURLSessionDownloadTask) - it will solve all your downloading problems(multiple threads to fast download(concurrent downloading ),resume, pause, cancel and etc.) including background downloads . Also it supports completion block which can be helpful for  file integrity check. To check for Internet connection in order to pause or resume downloads you can use Reachability library.
If you wish to use third-party library I stronglly recommend you to use AFNetWorking (everything from your requirements can be done by this library)-->https://github.com/AFNetworking/AFNetworking
Also, this tutorial can be helpfull for your needs - http://www.appcoda.com/background-transfer-service-ios7/


text:
Q: Xamarin.Forms controls disappear when navigate back to a page on Android I'm building an application with Xamarin.Forms and a Portable Class Library. The app can be used on Android, iOS and UWP.
I made a page that works correct on each platform:

After clicking an item in the ListView, a new page will be opened:

Navigation.PushAsync(new CourseInfoPage(ID));

When that page is opened and I press the "Back-button" and navigate back to the page shown above, it looks like this:

So some controls disappear when I'm navigating (away and then) back to this page.
This ONLY happens on Android. If I click somewhere in the white area, the controls still function but I don't get to see them.
What did I try:
protected override void OnAppearing()
{
    base.OnAppearing();
    Content = getContentPage();
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    this.Content = null;
}

But this doesn't solve the problem.
How do I fix this? What is the problem?

A: This is a weird issue, are you doing something with the view on the next Page? You can always double check the visibility of the view:
protected override void OnAppearing()
{
    base.OnAppearing();
    YourView.IsVisible = true;
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    YourView.IsVisible = true;
}

If that does not work, use BackgroundColor property to detect which of the views is doing this weird issue, maybe for some reason the color's are being changed.

A: If you want to go back to previous Page you can use
PopAsync()

or
PopModalAsync()

Grab some informations about Xamarin.Forms Navigation here :)
https://developer.xamarin.com/api/type/Xamarin.Forms.INavigation/

A: My issue was that I was generating views from code (which I have to), so for example in page1.xaml I would have a stacklayout with an x:name that I would then populate the children with views via code (generated from a singleton), then when I navigate to page2.xaml I would have another stacklayout that I would populate with views from the same singleton (sometimes with changes). To solve it was messy, I basically created two properties on the singleton that had the views, so when page1's stacklayout gets populated, it received singleton.Views and when I navigate to page2, it would get singleton.ViewsOther, page3 => singleton.Views, page3 => singleton.ViewsOther... and so on. Its messy, but I just needed it to work, you can get a better solution from experts, but just in case this helps someone else who needs a quick fix


text:
Q: Flutter Google Address Autofill I want an up to date example on how to add autofill addresses in flutter. I have looked at every resource I can and some people over complicate the heck out of it,or just copy and paste different messy code.
Atm I have a Google search that just shows a blue line as if Its waiting and gets no response.
TextFormField(
                controller: addressController,
                onTap: () async {
                  Prediction p = PlacesAutocomplete.show(
                          context: context,
                          apiKey: "MY_API_KEY_SECRET_SHHHHHH",
                          mode: Mode.fullscreen,
                          language: "En",
                          components: [new Component(Component.country, "NZ")])
                      as Prediction;
                  displayPrediction(p);
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return "Customer must have address! cannot be blank";
                  }
                },
                decoration: InputDecoration(
                  hintText: "Enter Customer Address",
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.map),
                ),
              ),

and I also have displayPrediction
Future<Null> displayPrediction(Prediction p) async {
  GoogleMapsPlaces _places = GoogleMapsPlaces(
    apiKey: "API_KEY",
    apiHeaders: await GoogleApiHeaders().getHeaders(),
  );
  PlacesDetailsResponse detail =
      await _places.getDetailsByPlaceId(p.placeId.toString());
  final lat = detail.result.geometry!.location.lat;
  final lng = detail.result.geometry!.location.lng;
}
Broken Search Example

A: So my problem was solved within the Prediction method. here is how I solved it with help from other resources.
Prediction? p = await PlacesAutocomplete.show(
        context: context,
        apiKey: kGoogleApiKey,
        radius: 10000000,
        types: [],
        strictbounds: false,
        mode: Mode.overlay,
        decoration: InputDecoration(
          hintText: 'Search',
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide(
              color: Colors.white,
            ),
          ),
        ),
        components: [Component(Component.country, "nz")],
      );


text:
Q: Unknown coordinate system need in Lat/Long degree format I received CAD data from PDs and the data they gave is already geocoded (which is great) and it reads well when I add it to my map on ARC map. However, the format is as follows (x = 632086.7, y = 1043211.35) I need them in the following format (x = 33.867022, y = -112.1409750) so that I can use it in R. My first question is what is the original coordinate system format? I've tried identifying it but I haven't found something that is helpful. Second question is, how can I transform the first coordinates into the second format?

A: I'm assuming you have points.
It sounds like you have already identified the native coordinate system of the CAD data as NAD 1983 HARN State Plane Arizona Central (international feet).
However, you want to get the latitude-longitude values for features instead.
I think you'll have to convert the CAD data into a feature class or shapefile. Once you do, you can use the Project Tool to create a copy in NAD 1983 HARN (geographic coordinate system) then use the Add XY Coordinates tool to populate two fields in the attribute table with the latitude-longitude values.
Note: latitude = y, longitude = x in ArcGIS
Another method is to leave the feature class in State Plane.

*

*Add the feature class to ArcMap.

*Change the data frame's coordinate system to NAD 1983 HARN (open data frame properties, coordinate system tab, select geographic coordinate systems, north america, NAD 1983 HARN).

*Open the attribute table.

*Add two new fields set to type double.

*Right-click a new field and select Calculate Geometry.

*Select X Coordinate or Y Coordinate.

*Select use coordinate system of the data frame.


text:
Q: pythonbrew with mod_wsgi pythonbrew isn't getting picked up by by mod_wsgi file, config follows:
import os
import sys
import site

site.addsitedir('/home/bharal/.pythonbrew/pythons/Python-2.7.2/lib/python2.7/site-packages')
sys.path.append ('/home/bharal/public_html/dumpstown')

os.environ['DJANGO_SETTINGS_MODULE'] = 'dumpstown.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

and the pythonbrew version of python i want to use is situated here:

/home/bharal/.pythonbrew/pythons/Python-2.7.2/lib/python2.7/site-packages

and my pythonbrew install is here:

/home/bharal/.pythonbrew/

How do i tell mod_wsgi to use this version (2.7.2) and not the  default python version that shipped with ubuntu (2.6)?
When i run my server, i get errors like so:
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1] mod_wsgi (pid=18694): Exception occurred processing WSGI script '/home/bharal/public_html/dumpstown/dumpstown/apache/dumpstown.wsgi'.
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1] Traceback (most recent call last):
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]   File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/wsgi.py", line 250, in __call__
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]     self.load_middleware()
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]   File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 39, in load_middleware
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]     for middleware_path in settings.MIDDLEWARE_CLASSES:
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]   File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]     self._setup()
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]   File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 42, in _setup
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]     self._wrapped = Settings(settings_module)
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]   File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 89, in __init__
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1]     raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
[Wed Jul 04 02:17:27 2012] [error] [client 127.0.0.1] ImportError: Could not import settings 'dumpstown.settings' (Is it on sys.path?): No module named gravatar.templatetags

as you can see from the logs, the server is still looking at python 2.6!! Why? I've kicked off pythonbrew so when i type in python i can see the version is 2.7.2, and all the settings and packages i need are importable!
UPDATE as indicated in the answer below, the mod_wsgi doesn't care which python i tell it to use - in fact, i cannot tell it to use any particular python. The only way to do so is to download an uncompiled wsgi file, compile with the particular python version i want, and use the  compiled wsgi.
See my other question Error: Command failed with rc=65536 python and mod_wsgi for some of the steps and links to tutes if you like. In the end i didn't compile against 2.7 (my 2.6 was fine and it was too hard to get the pythonbrew compile working)

A: That particular error has nothing to do with the version of Python used. Use:
sys.path.append ('/home/bharal/public_html')
  sys.path.append ('/home/bharal/public_html/dumpstown')
To get mod_wsgi to use a specific version, compile it from source code against that version or find a binary package for mod_wsgi compiled against the correct version.


text:
Q: is there any sample program using Kentor.AuthServices.MVC I am using mvc4 and I need SAML2.0 for the security. I tried some samples with Component Pro but we need to purchase it and it has good documentation also.
I came to know about Kentor.AuthServices.MVC which is an open source and may i know whether there is any learning site where I can implement with mvc4.

A: There is a working SampleMvcApplication included in the source on github.


text:
Q: Nuxt + Vuetify. How to apply theme colors I am using a Nuxt.js + Vuetify.js project
Looking at the file assets/style/app.styl we have
// Import and define Vuetify color theme
// https://vuetifyjs.com/en/style/colors
@require '~vuetify/src/stylus/settings/_colors'
$theme := {
  primary:     $blue.darken-2
  accent:      $blue.accent-2
  secondary:   $grey.lighten-1
  info:        $blue.lighten-1
  warning:     $amber.darken-2
  error:       $red.accent-4
  success:     $green.lighten-2
}

// Import Vuetify styling
@require '~vuetify/src/stylus/main'

.page
  @extend .fade-transition

The problem is, changing these theme colors does not result in any changes.
Any ideas how to solve this?

A: Docs not telling how to change color properly...
first of all you need to set your current theme and then config it.
I've waste 4 hours to figure this out. You need to change you config accordingly:
vuetify: {
        theme: {
            light: true,  //you don't actually need this line as it's for default
            themes: {
                light: {
                    primary: '#b71c1c',
                    ...
                }
            }
        }
    },

While working on this problem I figured out that you also can freely add your colors like this:
vuetify: {
        theme: {
            themes: {
                light: {
                    'custom-color-one': '#b71c1c',
                    'custom-color-two': '#3B8070',
                    ...
                }
            }
        }
    },

and then in your HTML:

  I'am div with custom background color!

  I'am div with custom text color!

A: Not sure, but try this maybe, depends how vuetify is included, but I presume if you used vuetify nuxt template then you need to include it in your nuxt.config.js file.
If you included vuetify like so:
modules: [
 '@nuxtjs/vuetify'

Then add theme like so:
module.exports = {
  modules: [
    '@nuxtjs/vuetify'
    // ...
  ]
  // Add the following:
  vuetify: {
    theme: {
      secondary: '#ff0000'
      // ...
    }
  },

A: NOTE: This solution isn't the best approach, and will not work in a production environment. It works for workflows where a static site is deployed (i.e. when you run yarn build and deploy that), since changes in node_modules aren't persistent across installs.
Two files govern this - nuxt.config.js and node_modules/vuetify/es5/colors.js.
You need to open nuxt.config.js, and head over to the vuetify property. The themes property under the vuetify: {...} section lets you map the class names to configured color variables.
Further, to change the values of the colour variables, modify the file node_modules/vuetify/es5/colors.js. Here, you define any colors you need to whatever hex color code you want.


text:
Q: Downloading files dynamically using PHP is slow I have a PHP script like this running on PHP-fpm 7.3:
<?php
$file = './French-Stories-Martine.zip';
if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: ".filesize($file));
        header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
        readfile($file);
        exit;
    }
}
?>

I've tried downloading this zip file statically (meaning without a PHP script - just using a plain old Apache + OpenLiteSpeed webserver), and the download speed is great. Nothing wrong with that.
The problem is when I'm trying to download the said zip file, with this PHP script. The download speed is 1/10th.
Now, I've concluded that the issue is with the PHP and not with the WebServer or the Server itself.
I can't figure out what the problem could be with my PHP?
I'm using the following configuration for PHP-fpm:
pm.max_children = 80
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30

This is the PHP log file when I'm trying to download from my script:
[08-Nov-2021 00:40:52] WARNING: [pool www] child 3267, script '/www/wwwroot/example.com/my-php-script-dl.php' (request: "GET /my-php-script-dl.php") executing too slow (31.192873 sec), logging
[08-Nov-2021 00:40:52] NOTICE: child 3267 stopped for tracing
[08-Nov-2021 00:40:52] NOTICE: about to trace 3267
[08-Nov-2021 00:40:52] NOTICE: finished trace of 3267
[08-Nov-2021 00:42:30] NOTICE: Reloading in progress ...
[08-Nov-2021 00:42:30] NOTICE: reloading: execvp("/www/server/php/73/sbin/php-fpm", {"/www/server/php/73/sbin/php-fpm", "--daemonize", "--fpm-config", "/www/server/php/73/etc/php-fpm.conf", "--pid", "/www/server/php/73/var/run/php-fpm.pid"})
[08-Nov-2021 00:42:30] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:42:30] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:42:30] NOTICE: fpm is running, pid 5317
[08-Nov-2021 00:42:30] NOTICE: ready to handle connections
[08-Nov-2021 00:42:44] NOTICE: Reloading in progress ...
[08-Nov-2021 00:42:44] NOTICE: reloading: execvp("/www/server/php/73/sbin/php-fpm", {"/www/server/php/73/sbin/php-fpm", "--daemonize", "--fpm-config", "/www/server/php/73/etc/php-fpm.conf", "--pid", "/www/server/php/73/var/run/php-fpm.pid"})
[08-Nov-2021 00:42:44] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:42:44] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:42:44] ERROR: Another FPM instance seems to already listen on /tmp/php-cgi-73.sock
[08-Nov-2021 00:42:44] NOTICE: fpm is running, pid 5539
[08-Nov-2021 00:42:44] ERROR: FPM initialization failed
[08-Nov-2021 00:42:44] NOTICE: ready to handle connections
[08-Nov-2021 00:45:18] NOTICE: Reloading in progress ...
[08-Nov-2021 00:45:18] NOTICE: reloading: execvp("/www/server/php/73/sbin/php-fpm", {"/www/server/php/73/sbin/php-fpm", "--daemonize", "--fpm-config", "/www/server/php/73/etc/php-fpm.conf", "--pid", "/www/server/php/73/var/run/php-fpm.pid"})
[08-Nov-2021 00:45:18] ERROR: Another FPM instance seems to already listen on /tmp/php-cgi-73.sock
[08-Nov-2021 00:45:18] ERROR: FPM initialization failed
[08-Nov-2021 00:45:18] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:45:18] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:45:18] NOTICE: fpm is running, pid 6200
[08-Nov-2021 00:45:18] NOTICE: ready to handle connections
[08-Nov-2021 00:45:44] NOTICE: Reloading in progress ...
[08-Nov-2021 00:45:44] NOTICE: reloading: execvp("/www/server/php/73/sbin/php-fpm", {"/www/server/php/73/sbin/php-fpm", "--daemonize", "--fpm-config", "/www/server/php/73/etc/php-fpm.conf", "--pid", "/www/server/php/73/var/run/php-fpm.pid"})
[08-Nov-2021 00:45:44] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:45:44] NOTICE: using inherited socket fd=8, "/tmp/php-cgi-73.sock"
[08-Nov-2021 00:45:44] ERROR: Another FPM instance seems to already listen on /tmp/php-cgi-73.sock
[08-Nov-2021 00:45:44] ERROR: FPM initialization failed
[08-Nov-2021 00:45:44] NOTICE: fpm is running, pid 6251
[08-Nov-2021 00:45:44] NOTICE: ready to handle connections
[08-Nov-2021 00:47:46] NOTICE: Finishing ...
[08-Nov-2021 00:47:46] NOTICE: exiting, bye-bye!
[08-Nov-2021 00:47:47] NOTICE: fpm is running, pid 6518
[08-Nov-2021 00:47:47] NOTICE: ready to handle connections


text:
Q: Scheme let* as nested unary lets As an exercise I am trying to rewrite strings representing source code for let* as nested unary lets.  Here is my best effort:
(define let*→nested-unary-lets
  (match-lambda
   (`(let* (()) ,<exprs>)
   `(let () ,<exprs>))
   (`(let* ((,<var> ,<val>)) ,<exprs>)
   `(let ((,<var> ,<val>)) (let () ,<exprs>)))
   (`(let* ((,<var> ,<val>) ,<clauses>) ,<exprs>)
   `(let ((,<var> ,<val>)) (let*→nested-unary-lets '(let* (,@<clauses>) ,<exprs>))))))

The problem I am experiencing at the moment is that the pattern:
`(let* ((,<var> ,<val>) ,<clauses>) ,<exprs>)

does not match a string like:
'(let* ((a b) (c d) (e f)) <expressions>)

The term clauses matches only the second clause (c d).  It seems to me that it should take all of the remaining (var val) clauses as a list ((c d) (e f)).  At any rate I need it to do so.
Any advice is appreciated.
What baffles me is that exprs will match a list of expressions so I can't think of any reason why clauses wouldn't also do so.

A: You will need . ,<clauses> since you want to match the rest of the list, not just a single element.  The ,<exprs> part will need to be . ,<exprs> for the same reason.  I believe there is other syntax specifically for matching lists, but using . is simple and matches how lists are implemented internally.


text:
Q: Decode utf8 to regular characters in python/R I have various strings such as e.g. xc3\x93\xc5\x81 those are encoded UTF-8 characters. The only file i have access to is with those encoded values. How can I decode this in either R or python to regular characters (not this UTF-8 slang)?

A: In R, we might use @Jeroen's function at https://stackoverflow.com/a/24958365/6197649 , with a minor modification to deal with \xnn rather than \unnnn
unescape_unicode <- function(x){
  #single string only
  stopifnot(is.character(x) && length(x) == 1)

  #find matches
  m <- gregexpr("(\\\\)+x[0-9a-z]{2}", x, ignore.case = TRUE)

  if(m[[1]][1] > -1){
    #parse matches
    p <- vapply(regmatches(x, m)[[1]], function(txt){
      gsub("\\", "\\\\", parse(text=paste0('"', txt, '"'))[[1]], fixed = TRUE, useBytes = TRUE)
    }, character(1), USE.NAMES = FALSE)

    #substitute parsed into original
    regmatches(x, m) <- list(p)
  }

  x
}

f <- tempfile()
cat("\\xc3\\x93\\xc5\\x81\n", file = f)
fpeek::peek_head(f)
#> \xc3\x93\xc5\x81

x <- readLines(f)
unlink(f)

unescape_unicode(x)
#> [1] "ÓŁ"

Interestingly, stringi::stri_escape_unicode gives a different result, seemingly misinterpreting \xc3\x93 as two separate characters (when it should be just one, "\xc3\x93" == "\u00d3", but I'm confused as to which convention determines that, I'd appreciate input from someone with more clarity on the subject in the comments)
stringi::stri_unescape_unicode(x)
#> [1] "Ã\u0093Å\u0081"

Created on 2019-04-15 by the reprex package (v0.2.1)


text:
Q: Side effects of allowing a container to listen on port 80 To simplify service port management between Docker containers I would like to allow the contained HTTP services to listen on HTTP's default TCP port 80 of their respective container's IP address.
Listening to port numbers below 1025 is classically restricted to users with special privileges, such as root. The reason for this, as far as I understand, is to prohibit non-privileged users on multi-user systems to act as the authoritative HTTP service for the whole machine.
In newer Linux versions it is also possible to allow this to specific executables by applying the Linux kernel capability CAP_NET_BIND_SERVICE. For this to work in Docker containers I also seem to need to apply this capability to the Docker container itself, either through the --add-cap flag on the Docker client or the Docker-Compose cap_add section.
Theoretically, the reason for this port number restriction is obsolete in this case, because the Linux kernel's network namespacing allows the processes within the container only to bind on their very own IP addresses which are exclusive to them.
My question now would be, if there are any serious caveats about doing this. Is this or could this become in any way a security problem in way unconsidered by me? Or are there any other issues about doing this?

A: I see zero issues in doing this.
While it is possible to use "cap add" and cause security holes to be exposed, allowing port 80 to be used is not an issue. It's just a TCP/IP port where your software listens, and from a security perspective it's no different than any other random port number.

A: For the moment I'd recommend to just bind to other ports. One an always forward them to another port when the container is created. Messing around with security and leaving unnecessary privileges in the container seems too much trouble to just internally bind to a specific port.


text:
Q: Не передается значение поля input с помощью Ajax Проблема состоит в том, что отсылается пустая строка, если в ручную в input не прописываю value.
Есть input и кнопка submit:
<input name='text_color' type='text' id ='hex'  class="hex_bodb"  >
<input name='submit_s' id = 'subm' type='submit' value='Информацию о краске' />

Результат выводиться в div:

Ждем ответа

Отбираю тестовое поле и заношу в переменную:
var hexx={
            hex: $('input[name=text_color]').val()
        }

Ajax:
$('#subm').click( function() {

        $.ajax({
          type: 'POST',
          url: 'response.php?action=sample2',
          data: hexx,
          success: function(data){
            $('.results').html(data);
          }
        });

    });

PHP файл, который получает данные:
echo 'Цвет  HEX= ' . $_POST['hex'];

A: У Вас перегружается страница из-за type="submit".
$('#subm').click( function() {

    var hexx = {
        hex: $('input[name=text_color]').val()
    };

    $.ajax({
        type: 'POST',
        url: 'response.php?action=sample2',
        data: hexx,
        success: function(data){
            $('.results').html(data);
        }
    });

    // !!!
    return false;
});

или
<input name='submit_s' id='subm' type='button' value='Информацию о краске' />


text:
Q: Java Class cast exception, Classloader error on using javax xml providers? I get the following error when I switched from OSGI Equinox to OSGI Karaf runtime.
Earlier the com.sun implementation was working fine, but now I need an apache implementation to run in one environment and com.sun in the older.
I know that OSGI has different class loading mechanism when compared to Java Class loading.
We are providing the javax packages as a part of the rt.jar which contains the Provider interface.
The implementation is coming from com.sun.xml
com.sun.xml.internal.ws.spi.ProviderImpl cannot be cast to javax.xml.ws.spi.Provider (loaded by org.apache.felix.framework.BundleWiringImpl$BundleClassLoader@0x0000000100162fd8) (found matching super class javax.xml.ws.spi.Provider loaded by , but needed loader org.apache.felix.framework.BundleWiringImpl$BundleClassLoader@0x0000000100162fd8)
            at javax.xml.ws.spi.Provider.provider(Provider.java:43)
            at javax.xml.ws.Service.<init>(Service.java:35)
            at javax.xml.ws.Service.create(Service.java:126)

When I look at the logs, both class loaders seem to have the same ID, then why get a class cast exception?
javax.xml.ws.spi.Provider (loaded by org.apache.felix.framework.BundleWiringImpl$BundleClassLoader@0x0000000100162fd8) (found matching super class javax.xml.ws.spi.Provider loaded by , but needed loader org.apache.felix.framework.BundleWiringImpl$BundleClassLoader@0x0000000100162fd8)
As of now, I am using a hack to get around this in two different environments
private static final String PROVIDER_CXF = "org.apache.cxf.jaxws.spi.ProviderImpl";
private static final String PROVIDER_DEFAULT = "com.sun.xml.internal.ws.spi.ProviderImpl";

private String setProvider() {
    log.debug("set default provider");
    System.setProperty(PROVIDER, PROVIDER_DEFAULT);
    try {
        Service.create(new QName(null, ""));
        return PROVIDER_DEFAULT;
    } catch (Exception e) {
        log.debug("setting cxf provider");
        System.setProperty(PROVIDER, PROVIDER_CXF);
        return PROVIDER_CXF;
    }
}

A: You may need to set -Dorg.osgi.framework.bootdelegation=com.sun.*. See https://osgi.org/specification/osgi.core/7.0.0/framework.module.html#framework.module.parentdelegation. It is possible Equinox provides a common, useful default for boot delegation while Karaf does not.


text:
Q: Force a break in a items control with wrap panel template I've got an interesting problem I've been trying to solve.  Basically I have an items control that uses a WrapPanel as it's ItemsPanel to simulate a paragraph built from several bound strings.  However there are times where I need to force a break, like when I start a new paragraph, however putting a break into the TextBlock DateTemplate does not actually put a break into the parent wrap panel.  Here is the code:
<ItemsControl ItemsSource="{Binding Fragments}" >
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock
                TextWrapping="Wrap"
                Text="{Binding}"/> <!--If this text has a break it won't
                                        propagate that break to the wrap panel,
                                        but instead just in this text block which
                                        causes the formatting to look wrong-->
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Here is a simple definition for fragments that will show what I am talking about:
Fragments = new ObservableCollection<string>();
Fragments.Add("This is");
Fragments.Add("the first line, ");
Fragments.Add("it is very long and will drift to the ");
Fragments.Add("second line naturally since it is controlled by a wrap panel");
Fragments.Add("\n\r This I want to force to the line below where the line above ends");
Fragments.Add("rapid \n\r new \n\r lines");

I would like this to flow as paragraphs that just continue to get concatenated, but honor the manual breaks when they are run into.  Like this:

This is the first line, it is very long and will drift to the second line
naturally since it is controlled by a wrap panel.
This I want to force to the line below where the line above ends.
rapid
new
lines

A: I would chuck the ItemsControl and use the Inlines collection of a textblock instead. Unfortunately you cannot bind your collection of strings directly, because TextBlock.Inlines is not a dependency property, but it's not hard to work around that with an attached dependency property:
I have also added support for propagation of the CollectionChanged event, so adding a string to ViewModel.Fragments will update the textblock. Removing will work too, although with the limitation that the first Fragment matching the string will be removed.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">

    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>

    <Grid>
        <TextBlock local:FlowSupport.Fragments="{Binding Fragments}" TextWrapping="WrapWithOverflow" Margin="10" Background="Beige" />
    </Grid>
</Window>

ViewModel:
public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<string> _fragments;
    public ObservableCollection<string> Fragments { get { return _fragments; } set { _fragments = value; OnPropertyChanged("Fragments"); } }

    public ViewModel()
    {
        Fragments = new ObservableCollection<string>();
        Fragments.Add("This is ");
        Fragments.Add("the first line, ");
        Fragments.Add("it is very long and will drift to the ");
        Fragments.Add("second line naturally since it is controlled by a wrap panel");
        Fragments.Add("\nThis I want to force to the line below where the line above ends\n");
        Fragments.Add("rapid \nnew \nlines");
    }
}

FlowSupport:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Collections.Specialized;

namespace WpfApplication1
{
    public static class FlowSupport
    {
        private static Dictionary<TextBlock, NotifyCollectionChangedEventHandler> _collChangedHandlers = new Dictionary<TextBlock,NotifyCollectionChangedEventHandler>();

        public static ObservableCollection<string> GetFragments(TextBlock tb) { return (ObservableCollection<string>)tb.GetValue(FragmentsProperty); }
        public static void SetFragments(TextBlock tb, ObservableCollection<string> value) { tb.SetValue(FragmentsProperty, value); }

        public static readonly DependencyProperty FragmentsProperty = DependencyProperty.RegisterAttached("Fragments", typeof(ObservableCollection<string>), typeof(FlowSupport), new PropertyMetadata(new ObservableCollection<string>(), OnFragmentsChanged));

        private static void OnFragmentsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var tb = d as TextBlock;
            if (tb != null)
            {
                CreateCollectionChangedHandler(tb); // create handler, once per textblock

                tb.Inlines.Clear();
                var oldInlines = e.OldValue as ObservableCollection<string>;
                if (oldInlines != null)
                {
                    oldInlines.CollectionChanged -= _collChangedHandlers[tb];
                }
                var inlines = e.NewValue as ObservableCollection<string>;
                if (inlines != null)
                {
                    inlines.CollectionChanged += _collChangedHandlers[tb];

                    foreach (string s in inlines)
                        tb.Inlines.Add(s);
                }
            }
        }

        private static void CreateCollectionChangedHandler(TextBlock tb)
        {
            if (!_collChangedHandlers.ContainsKey(tb))
            {
                _collChangedHandlers.Add(tb, (s1, e1) =>
                {
                    if (e1.NewItems != null)
                    {
                        foreach (string text in e1.NewItems)
                            tb.Inlines.Add(text);
                    }
                    if (e1.OldItems != null)
                    {
                        foreach (string text in e1.OldItems)
                        {
                            Inline inline = tb.Inlines.FirstOrDefault(i => ((Run)i).Text == text);
                            if (inline != null)
                                tb.Inlines.Remove(inline);
                        }
                    }
                });
            }
        }
    }
}


text:
Q: Line spacing between paragraphs For the following code, the output looks like as follows where there's no spacings between each paragraphs:
\documentclass{article}
\usepackage{lipsum}
\usepackage[margin=1in]{geometry}
\usepackage{setspace}
\begin{document}
    \lipsum[2-2]

    \lipsum[2-2]

    \lipsum[2-2]
\end{document}

However, for the blue text in my notes, there's clearly a spacing between the 2 paragraphs:

What has gone wrong in my following code to result in that spacing?
\subsubsection{Vertical Spacing}
\begin{itemize}
    \item Vertical spacing is the amount of vertical space between lines.
    \item It could be spacing between two paragraphs, or two text and image, or text and a table.
    \item By default, there is no spacing between 2 paragraphs, e.g. \textbackslash lipsum[1-2] gives:\\
        \textcolor{blue}{\lipsum[1-2]}

A: Inside an itemize, the spacing between paragraphs is set by \parsep which is a different value than used in regular text. In article, the default value at the top level of a list is 4pt plus2pt minus1pt¹ if your document is set in 10pt type. Given that multiple-paragraph items in a list are not indented by default, the extra spacing helps to identify the paragraph breaks.
This amount is generally set by the document class via a private macro called \@listi. Here is the definition² from size10.clo which is the common code for the default LaTeX classes:
\def\@listi{\leftmargin\leftmargini
            \parsep 4pt plus2pt minus1pt
            \topsep 8pt plus2pt minus4pt
            \itemsep4pt plus2pt minus1pt}

You could, if you wanted, redefine this to be
\def\@listi{\leftmargin\leftmargini
            \parsep\parskip
            \listparindent\parindent
            \topsep 8pt plus2pt minus4pt
            \itemsep4pt plus2pt minus1pt}

(surrounding it with \makeatletter…\makeatother so you can access the private macro name) to have the indentation of paragraphs and spacing between them be the same as in the main document.

*

*Certain dimensions in LaTeX, called glue in LaTeX parlance (or skips in TeX primitive-speak) can stretch or shrink. When you see a plus or minus in that context, it's indicating the amount the glue can stretch or shrink.

*This is not exactly the code you'd see in the file. I changed some abbreviations that are used because when LaTeX was originally written, the capacity of TeX was greatly limited and a lot of care was taken to reduce memory usage.


text:
Q: marching query does not exist in if statement well go to the question. I make this query:
Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)

This works perfect, but when i put this in a if statement, like this:
if(Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)):

I have a problem, when the query returns a object Puntuaciones i haven't any problems, but when there isn't a result it throws me:
Exception Value: Puntuaciones matching query does not exist.

So my question is, How i can do a if statement for a query if this query can be  unsuccessful.
I try with Q objects, with exists()(this just works for querysets... I dont know how make it work. Any suggestion? Thank you

A: get() is either returning an object or throws ObjectDoesNotExist exception, catch it with the help of try/except:
try:
    Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)
    # do something if object was found
except Puntuaciones.DoesNotExist:
    # do smth if nothing found

Another options is to use exists():
if Puntuaciones.objects.filter(bar__id=b, usuario=v.usuario2).exists():
   # do something if object was found

A: I would suggest a try: except: pair. That way, when the exception is triggered, you will be in the appropriate location to perform the code. Note that you really should use the correct exception type in the setup. Note that if you want to skip processing in the except, you need to put in an explicit pass (python noop) statement. Otherwise you will get an indentation error.
try:
  if(Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)):
    # put code in here
    pass # dummy statement to be replaced by actual code.
except:
  # Put exception code here.
  pass


text:
Q: How to avoid a particular line using fscanf()? I have a file contain assembly languages for sic machine.
eg:
   LDA ALPHA
   ADD BETA
   ;This is a comment line.
   ;just an example code.
   END

while reading using fscanf() how to avoid the comment line. note that length of the line is not fixed. Also the comment line can be appeared anywhere.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(int argc,char *argv[])
{
    if(argc<2){
        printf("No input file.\nExecution terminated.\n");
        exit(0);
    }
    FILE *infile,*outfile;
    int locctr,start=0,i,optablen=6;
    char opcode[25],label[25],operand[25];
    char optab[6][5]={"LDA","STA","LDCH","STCH","ADD","SUB"};
    infile=fopen(argv[1],"r");
    outfile=fopen("SYMTAB.txt","w");
    fscanf(infile,"%s%s%s",label,opcode,operand);
    if(strcmp(opcode,"START")==0)
    {
        start=atoi(operand);
        locctr=start;
    }
    else
        locctr=start;
    fscanf(infile,"%s%s",label,opcode);
    while(strcmp(opcode,"END")!=0)
    {
        fscanf(infile,"%s",operand);
        if(strcmp(label,"-")!=0)
            fprintf(outfile,"%s\t%d\n",label,locctr);
        for(i=0;i<optablen;i++){
            if(strcmp(opcode,optab[i])==0){
                locctr=locctr+3;
                break;
            }
        }
        if(strcmp(opcode,"WORD")==0)
            locctr=locctr+3;
        else if(strcmp(opcode,"RESW")==0)
                locctr=locctr+(3*(atoi(operand)));
            else if(strcmp(opcode,"BYTE")==0)
            {
                if(operand[0]=='X')
                    locctr=locctr+1;
                else
                    locctr=locctr+(strlen(operand)-2);
            }
            else if(strcmp(opcode,"RESB")==0)
                locctr=locctr+atoi(operand);
            fscanf(infile,"%s%s",label,opcode);
    }
    printf("Length of assembled program=%d\n",locctr-start);
    fclose(infile);
    fclose(outfile);
}

Here is my code how can i avoid comment line?


text: Q: Integrating react-hot-loader in Create-React-App without Ejecting I am working on a project using create-react-app and redux. The problem is that i can't seem to find a way how to integrate react hot loader without ejecting the app which is something i'm not allowed to do in my project. Is there any way to integrate RHL?


text:
Q: Dimension doesn't applied to Lookup window sum calculation I'm new to Tableau so please forgive me if I'm not asking this question the way it should. I hope you will understand me anyway.
I have he following table :
date(dd/mm/yy),country,postid
01/01/17, us, xxxx
01/01/17, fr, xxxx
02/01/17, fr, xxxx
02/01/17, us, xxxx
02/01/17, us, xxxx
03/01/17, fr, xxxx
etc...

so I have a calculated field like this one which is 'Nb of posts' :
if [Country]="us" THEN 1 else 0 END

Then I have the following formula 'Last 7 days' :
LOOKUP(WINDOW_sum(sum(iif([Last week],[nb of posts],null))),0)

When I'm dragging my 'Last 7 days' calculation in my Rows shelf with the Country dimension It give me the same number for each country...
Why is that ?
Thanks !

A: Setting it up like this should work:

*

*Drag country column to the rows 2. Create Boolean last week calculated field {  date]> now()-7  }. Drag the calculated field to the Filters and select True to only show the last week of dates 3. Create another calculated field { countd(postid)  } and drag to columns.


text:
Q: Checking html closing tags using java I want to check html file for closing tags in Java. If closing tags are not there then put closing tag.
Can anyone Please tell me how to achieve that.

A: I used TagSoup for that.

A SAX-compliant parser written in Java that, instead of parsing
  well-formed or valid XML, parses HTML...
TagSoup is free and Open Source software.


text:
Q: The relation is not parented to the table to which this DataView points <BusinessList>
  <Company>
    <CompanyName>StackOverflow</CompanyName>
    <Desc>FAQ Q & A Site</Desc>
    <Email>dummy@dummy.com</Email>
    <Mobile>123456</Mobile>
    <Phone>123456</Phone>
    <City>florida</City>
    <ZipCode>620020</ZipCode>
    <Country>USA</Country>
    <State>FL</State>
    <Image>a.png</Image>
  </Company>
  <Staff>
    <FirstName>A</FirstName>
    <Qualification>Bachelor in Engineering</Qualification>
    <Stories>Highly enthusiastic and energetic programmer will surely work with him again - Jane</Stories>
    <Designation>Chief Engineer</Designation>
    <Email>dummy@dummy.com</Email>
    <ContactNo>123456</ContactNo>
    <Fax>56565656</Fax>
    <Image>1.png</Image>
  </Staff>
  <Staff>
    <FirstName>B</FirstName>
    <Qualification>Bachelor in Engineering</Qualification>
    <Stories>Highly enthusiastic and energetic programmer will surely work with him again - Jane</Stories>
    <Designation>Team Leader</Designation>
    <Email>dummy@dummy.com</Email>
    <ContactNo>123456</ContactNo>
    <Fax>5757575</Fax>
    <Image>2.png</Image>
  </Staff>
  <Staff>
    <FirstName>C</FirstName>
    <Qualification>Bachelor in Engineering</Qualification>
    <Stories>Highly enthusiastic and energetic programmer will surely work with him again - Jane</Stories>
    <Designation>Programmer</Designation>
    <Email>dummy@dummy.com</Email>
    <ContactNo>123456</ContactNo>
    <Fax>565656</Fax>
    <Image>3.png</Image>
  </Staff>
  <Staff>
    <FirstName>D</FirstName>
    <Qualification>Bachelor in Engineering</Qualification>
    <Stories>Highly enthusiastic and energetic programmer will surely work with him again - Jane</Stories>
    <Designation>Developer</Designation>
    <Email>dummy@dummy.com</Email>
    <ContactNo>123456</ContactNo>
    <Fax>1231231234</Fax>
    <Image>4.png</Image>
  </Staff>
</BusinessList>

Above is my xml inout file for the Dataset, which i read with DataSet.ReadXml() method.However i get a error when i databind with nested repeater like below.
                        <asp:Repeater runat="server" id="rptrCompany">
                            <HeaderTemplate>
                                Staff in company
                            </HeaderTemplate>
                            <ItemTemplate>
                                Company Details:
                                <%# Eval("CompanyName") %>
                                .. blahblahblah Staff Details
                                <asp:Repeater runat="server" id="rptrStaff" datasource='<%# ((DataRowView)Container.DataItem).CreateChildView("BusinessList_Staff") %>'>
                                    <HeaderTemplate>
                                        Staff List
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <%# Eval("FirstName") %>
                                        ..blah blah blah
                                    </ItemTemplate>
                                </asp:Repeater>
                            </ItemTemplate>
                        </asp:Repeater>

blah blah blah part denoted extra fields that i databound. In the child repeater i get the error/exception The relation is not parented to the table to which this DataView points.
What am i doing wrong, the relation name "BusinessList_Staff" exists when i checked the dataset[ relation is automatically created by framework for me]. Also Container.Dataitem is a datarowview which also has 'CreateChildView' method used in markup. All i do is DataBind the parent repeater in backend pageLoad like below
rptrCompany.DataSource = dtTemp.Tables["Company"].DefaultView;
 rptrCompany.DataBind();

Please let me know what am i doing wrong

A: Could it be because the staff are not part of the Company? The only relation that could exist in your XML is an implicit relation to the Company by being after the company.
If you have control over the XML generation you should change the <Staff> elements to be contained within the <Company>.
Haven't databinding in this fashion in a long time, so sorry if this is not a complete solution.

A: I think the problem is because your dataset structure is flat. this structure of repeater needs to have a list of staffs in company entity. xml should look like :
<BusinessList>
  <Company>
    <!--Other Properties-->
    <Staffs>
      <!--Staff List-->
      <Staff>
      </Staff>
      <Staff>
      </Staff>
    </Staffs>
  </Company>
</BusinessList>


text:
Q: Need to use the internationalization for the column title I want to  use the internationalization for the column title, But i could not find the proper solution.
I am using angular datatable, i have initialized the columns in ngOnInIt() as shown in the code:
ngOnInit(){

this.model.columns = [{
  title: 'xyz',  // **Need to use the internationalization for the column title **
  data: 'XYZ',
  render: function (data, type, row, meta) {
        return data === null ? '-' : data
      }
}],

}


text:
Q: Unable to create multiple storage accounts with parameters value on arm template I am trying to create multiple storage accounts with arm templates, However i am unable to find syntax for creating with name as parameters. below is the my template.json file
Template.json:
     {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-
        01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
       "parameters": {
        "storageName": {
          "type": "array",
          "metadata": {
                 "description": "storageaccountname"
            }
        }

        },
    "functions": [],
    "variables": {},
    "resources": [{
        "name": "[concat('storage', uniqueString(resourceGroup().id),
  parameters('storageName')[copyIndex('copystorage')])]",
        "type": "Microsoft.Storage/storageAccounts",
        "apiVersion": "2021-04-01",
        "tags": {
            "displayName": "storageaccount1"
        },
        "location": "[resourceGroup().location]",
        "kind": "StorageV2",
        "sku": {
            "name": "Standard_LRS",
            "tier": "Standard"
        },
        "copy": {

            "name": "copystorage",
            "count": "[length(parameters('storageName'))]"

           }
         }],
       "outputs": {}
       }

Parameters.json
  {
   "$schema": "https://schema.management.azure.com/schemas/2019-04-
  01/deploymentParameters.json#",
   "contentVersion": "1.0.0.0",
   "parameters": {
      "storageName": {
        "value": [
          "storarm1",
          "storearm2",
          "storearm3"
        ]
    }
   }
 }

so what should be the "name" property inorder to create storage accounts with
storearm1,storearm2 and storearm3

A: after modifying from
"name": "[concat('storage', uniqueString(resourceGroup().id), parameters('storageName')[copyIndex('copystorage')])]",  to
"name": "[ parameters('storageName')[copyIndex('copystorage')]]",
i able to create with the names


text:
Q: Unity animation from foreach loop c# I have a UI text that I update in script off camera then uses an animation to have it slide across the screen. The script uses a foreach loop since the text change and number of times the animation runs are variable. It always skips the third animation (it will print the effect in console but will not play that animation), even when 4 or 5 effects are called.
private Animation Anim;
public Text NBtext;
public GameObject NBEffect, Tut, TouchInput;

public IEnumerator NiceBowlingEffects(List<string> Effects, bool FirstFrame)
{
    Anim = GetComponent<Animation>();
    NBEffect.SetActive(true);
    yield return new WaitForSeconds(.2f); //give frame ect a chance to load.
    foreach (var Effect in Effects)
    {
        NBtext.text = Effect;
        Print(Effect);
        Anim.Play();
        yield return new WaitForSeconds(Anim.clip.length);
    }
    NBEffect.SetActive(false);
    if (FirstFrame)
    {
        Tut.SetActive(true);
    }
    TouchInput.SetActive(true);
}

A: try changing "WaitForSeconds" to "WaitForSecondsRealtime" in the foreach loop, and tell me if it fixed it

A: Hopefully this helps someone but to finally get this to work for Nice Bowling I had to add a time delay between changing the text and playing the animation. Here's the code that's running on Nice Bowling right now.
public IEnumerator NiceBowlingEffects(List<string> Effects, bool FirstFrame)
{
    Anim = GetComponent<Animation>();
    NBEffect.SetActive(true);
    yield return new WaitForSecondsRealtime(.1f); //give frame ect a chance to load.
    foreach (var Effect in Effects)
    {
        NBtext.text = Effect;
        yield return new WaitForSecondsRealtime(.1f); //text time to change
        Anim.Play();
        yield return new WaitForSecondsRealtime(Anim.clip.length +.01f);
    }
    NBEffect.SetActive(false);
    if (FirstFrame)
    {
        Tut.SetActive(true);
        Tut.GetComponent<UISprite>().Trigger();
    }
    TouchInput.SetActive(true);
}


text:
Q: How can I make sublime looks like atom theme? I'm looking to get the atom's default theme to import it into sublime text 3, if that's possible. I'm looking especially for the color scheme, any tips or source code would be appreciated, ty!

A: Find a theme on Package Control.
There is a One Dark Material Theme which looks like Atom, but I haven't used it myself.
Boxy Theme is very good, I use it myself, the Monokai Boxy variation is good. You can make look similar to atom.

A: You can use Theme - One Dark (it works for both Sublime Text 2 and Sublime Text 3)
Installation Steps

*

*Press ⌘/Ctrl+Shift+P to open the Command Palette.

*Type Install Package and press Enter/Return.

*Search for Theme - One Dark and press Enter/Return.

Configuration Steps

*

*Open your preferences from Menu Preferences > Settings

*Add the following codes

Activation Codes
"color_scheme": "Packages/Theme - One Dark/One Dark.tmTheme",
"theme": "One Dark.sublime-theme",
"one_dark_sublime_text_2": true, // Only for Sublime Text 2

Recommended settings
"animation_enabled": false,
"caret_extra_bottom": 1,
"caret_extra_top": 2,
"caret_extra_width": 1,
"caret_style": "blink",
"draw_white_space": "none",
"ensure_newline_at_eof_on_save": true,
"highlight_line": true,
"line_padding_bottom": 1,
"line_padding_top": 2,
"margin": 0,
"match_selection": false,
"tree_animation_enabled": false,
"scroll_past_end": false,
"show_definitions": false,
"show_tab_close_buttons": true, // mandatory to see unsaved files in tab

Optional settings
"one_dark_native_title_bar": true,          // only for Mac & Sublime Text 3 >= build 3127
"one_dark_show_scroll_tabs": true,          // only for Sublime Text 3
"one_dark_show_tabs_dropdown": true,        // only for Sublime Text 3
"one_dark_bigger_sidebar": true,            // uses font-size 14 for the sidebar
"one_dark_sidebar_font_fira_light": true,   // uses Fira Light for the sidebar

To get latest version of codes browse package homepage

A: Simple steps for those on windows. It may work on other OS but haven't tested it.
Firstly go here and download the Source Code (zip) file.
Then go to your Sublime packages directory, which should look like this

C:\Users\User1\AppData\Roaming\Sublime Text 2\Packages

You can find yours by clicking on the Preference and then Browse Packages..
Unzip the file downloaded file and paste it into your to your packages directory.
Once done simply go to 'Preferences' -> 'Colour Scheme' and find the folder there and select the theme you like, as illustrated below.

A: I made an adaptive One theme with Dark and Light One color schemes, it works for ST3 and ST4. https://packagecontrol.io/packages/Theme%20-%20One.


text:
Q: Cloudfront serving png/jpg vs webp based on request headers I have Cloudfront in front of S3 serving images (png and jpg).
I have all png and jpg images in webp format in the same directory with .webp extension. For example:

*

*png: /path/to/file.png

*webp: /path/to/file.png.webp

I'd like to serve the webp file dynamically without changing the markup.
Since browsers flag webp support via Accept header, what i need to do is: if the user has support for webp (via Accept header) Cloudfront would pull the webp version (filename.png.webp), if not it should serve the original file (filename.png)
Is this possible to achieve?

A: Making Cloudfront serve different resources is easy (when you have done it a couple of times), but my concern is whether the entity making the request (i.e. browser) and possible caching elements between (proxies etc) expects to have different media types on the same request URI. But that is a bit beyond your question. I believe the usual way to handle this problem is with a  element where the browser is free to choose an image from different media types like this:
<picture>
  <source type="image/svg+xml" srcset="pyramid.svg" />
  <source type="image/webp" srcset="pyramid.webp" />
  <img
    src="pyramid.png"
    alt="regular pyramid built from four equilateral triangles" />
</picture>

But if you still want to serve different content from Cloufront for the same URL this is how you do it:
Cloudfront has 4 different points where you can inject a lamdba function for request manipulation (Lambda@Edge).

For your use case we need to create a Lambda@Edge function at the Origin Request location then associate this function with your Cloudfront Distribution.
Below is an example from AWS docs that looks on device type and does URL manipulation. For your use case, something similar can be done by looking at the "Accept" header.
'use strict';

/* This is an origin request function */
exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    /*
     * Serve different versions of an object based on the device type.
     * NOTE: 1. You must configure your distribution to cache based on the
     *          CloudFront-Is-*-Viewer headers. For more information, see
     *          the following documentation:
     *          https://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers
     *          https://docs.aws.amazon.com/console/cloudfront/cache-on-device-type
     *       2. CloudFront adds the CloudFront-Is-*-Viewer headers after the viewer
     *          request event. To use this example, you must create a trigger for the
     *          origin request event.
     */

    const desktopPath = '/desktop';
    const mobilePath = '/mobile';
    const tabletPath = '/tablet';
    const smarttvPath = '/smarttv';

    if (headers['cloudfront-is-desktop-viewer']
        && headers['cloudfront-is-desktop-viewer'][0].value === 'true') {
        request.uri = desktopPath + request.uri;
    } else if (headers['cloudfront-is-mobile-viewer']
               && headers['cloudfront-is-mobile-viewer'][0].value === 'true') {
        request.uri = mobilePath + request.uri;
    } else if (headers['cloudfront-is-tablet-viewer']
               && headers['cloudfront-is-tablet-viewer'][0].value === 'true') {
        request.uri = tabletPath + request.uri;
    } else if (headers['cloudfront-is-smarttv-viewer']
               && headers['cloudfront-is-smarttv-viewer'][0].value === 'true') {
        request.uri = smarttvPath + request.uri;
    }
    console.log(`Request uri set to "${request.uri}"`);

    callback(null, request);
};

Next you need to tell Cloudfront that you want to use the Accept header as a part of your cache key (otherwise Cloudfront would only execute your Origin Request lambda once and also not expose this header to your function).
You do this nowadays with cache and origin request policies. Or with legacy settings (Edit Behaviour under your Cloudfront distribution settings) such as:

Worth to note here is that, if you get low cache hit ratio due to different variants of the Accept header you need to pre-process / clean it. The way I would do it is with a Viewer Request Lamdba that gets executed for each request. This new Lambda would then check if the Accept header supports Webp and then add a single NEW header to the request that it passes on to the Origin Request above. That way the Origin Request can cache on this new header (which only has two different possible values)
There's more config/setup needed such as IAM policies to get Lamdba to run etc, but there's lots of great material out there that walks you through the steps. Maybe start here?


text:
Q: Why is an ($\boldsymbol{\sigma}$-)algebra called a ($\boldsymbol{\sigma}$-)field in probability? This is not strictly a math problem, but more of a question on nomenclature and history; so, if it's not appropriate for this site, let me know, and I'll ask someplace else.
Probability theory is known for its distinct nomenclature pattern that sets it apart from measure theory proper. Most of these names reflect the subject's informal beginnings and strong subsequent connections with mathematical statistics and other applications. I am listing as many of these differences as I can think off the top of my head:
measurable space --- sample space
measurable set --- event
almost everywhere --- almost surely (less commonly, almost certainly)
measurable function --- random variable
(Lebesgue) integral --- expected value
$\mathscr{L}_2$-norm --- standard deviation (not exactly, but similar)
$\mathscr{L}_2$-inner product --- covariance (again, not exactly)
weak-$\ast$ convergence --- convergence in distribution/law
($\sigma$-)algebra --- ($\sigma$-)field
Most of these probabilistic alternatives are more intuitive, except for the last one! I can't think of any empirical/pragmatic/intuitive/statistical reason to call a collection of 'events' either an 'algebra' or a 'field'. The name 'algebra', though, makes sense from a strictly mathematical point of view (the same way 'rings' are rings). So, why then do probabilists insist on 'field'?
Of course, tradition may be an answer, but I am more interested in knowing what/who started this tradition. Were 'algebra' and 'field' synonyms in the early days of Lebesgue theory, and over time, only one name survived in each of the two literatures? Do the two terms have to do with different mathematical schools, say, Moscow versus Paris, or something like that?


text:
Q: Is modifying Laravel base config files a bad idea? Laravel comes with some basic config files available in config directory.
which each file is basically an associated array.
now, I want to change the structure of config/mail.php from
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
],

to
'from' => [
    'noreply' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ]
],

so I can have several emails with differnt name.
My question is generic here.
What are(if any) disadvantages of modifying structure of the config files?
Is it possible to be troublesome between LTS upgrades?

A: You shouldn't modify email.form data because Laravel uses the data:

You may specify a global from address in your config/mail.php configuration file. This address will be used if no other from address is specified within the mailable class


text:
Q: How do I get non-ascii characters from child_process.stdout? I have a node task that spawns a child process and forwards that process' output to stdout:
var child = require( 'child_process' ).spawn( 'some_cmd' );
child.stdout.on( 'data', process.stdout.write.bind( process.stdout ) );

This works fine except that any non-ascii characters, specifically control characters for text color, don't come through.  So all my text from the child_process is white.
Does anyone have any idea how to fix this?  Alternatively, does anyone know how to just show child_process output directly without bridging the streams?

A: Answering my own question (though if anyone has an answer as to how to actually read character control data, I'd still be interested):
Calling child_process.spawn with stdio: 'inherit' passes stdout and stderr to the child process, so this issue goes away.
require( 'child_process' ).spawn( 'cmd', { stdio: 'inherit' } );