text:
Q: ArgumentOutOfRangeException parameter name: Index I keep getting this 'ArgumentOutOfRange exception non-negative number required, Parameter name: index', whenever I try to open the page and I can't seem to figure out where/how exactly the negative number is appearing.  Thank you all in advance!!
var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
var upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));

I'm getting the exception when the code reads the 'upcomingMonths' variable.
stack trace:
[ArgumentOutOfRangeException: Non-negative number required. Parameter name: index]
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) +72
System.Collections.Generic.List`1.GetRange(Int32 index, Int32 count) +4951591
InitializeChartBC()
Page_Load(Object sender, EventArgs e)
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811

A: According to Documentation header of the List
// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     index is less than 0.-or-count is less than 0.

So I think months doesn't contain Current Month.
Before you call the months.GetRange check whether it contains current month and then call the GetRange.
var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
 //Anyone corrent me as the list is converted to **.ToList** it wont throw null error I feel
List<T> upcomingMonths = null;  //Where T is the type of the list
if(months.IndexOf(DateTime.Today.Month)>=0)
      upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));


text:
Q: console-kit-daemon : GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed When I run Linuxmint 18.1, I get this error. Which error can be associated with this message? And how I can solve this?
I searched for answers and I found this, but I don't understand it very well. Can any one explain the problem a bit better, please?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Moment.js startOf is returning end of day I am passing in the following date through query string: 2020-09-23
I am trying to figure out why the below code with the doesn't work comment above it is not working.
// If figure here I should only have to convert to a moment once
const momentDate = moment.utc(req.query.dateTime);

// Doesn't work
const startOfDay = momentDate.startOf('day');
const endOfDay = momentDate.endOf('day');

This is what I am getting:
console.log(startOfDay) = Moment<2020-09-23T23:59:59Z>
console.log(endOfDay) = Moment<2020-09-23T23:59:59Z>
// Works (when I directly pass in the query string param)
const startOfDay = moment.utc(req.query.dateTime).startOf('day');
const endOfDay = moment.utc(req.query.dateTime).endOf('day');

console.log(startOfDay) = Moment<2020-09-23T00:00:00Z>
console.log(endOfDay) = Moment<2020-09-23T23:59:59Z>

A: You are doing on the same object momentDate, so same reference, so the safer way is to work on the copy of that object by cloning that momentDate with clone() method
const momentDate = moment.utc(new Date())

const startOfDay = momentDate.clone().startOf("day")
const endOfDay = momentDate.clone().endOf("day")

console.log(startOfDay)
console.log(endOfDay)

A: If you have a timezone problem, try this approach.
let myDate = new Date();

const timezoneOffset = moment(myDate).utcOffset();

moment(myDate).utc().add(timezoneOffset, 'minutes').startOf('day').format();
moment(myDate).utc().add(timezoneOffset, 'minutes').endOf('day').format();


text:
Q: XmlDocument.Loadxml() transforming "<" into "&lt" when loading XSLT I faced a strange problem working with XSLT and XML. I am creating an MVC application that reads an XSLT file containing templates and variables and process their contents. After the processing I saw that many changes were made to some nodes that would not have to be touched. At some point in the XSLT file, I have a variable which content is
 <xsl:choose>
      <xsl:when test="@resCurrPage = 1">1</xsl:when>
      <xsl:when test="@resCurrPage > 4">3</xsl:when>
      <xsl:otherwise>2</xsl:otherwise>
 </xsl:choose>

but when the processing is finished the sedond <xsl:when> is transformed into<xsl:when test="@resCurrPage > 4">3</xsl:when>.  I figured it out that the transformation from > into > seems to be happened when the
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(templateFile);
XmlNodeList nodeList = xDoc["xsl:stylesheet"].ChildNodes;

is called. (templateFile is a string containing the XSLT file)
My question is why is this transformation happening? and how could I avoid it?

A: Based on your question title: XML specification says that < character must always be encoded unless it's marking the beginning of a tag.
Based on your question: the > character doesn't need to be encoded in attribute values etc, but it may be. When it is used in ]]> combination, it must be encoded.
Unfortunately there is no way to tell XmlDocument not to encode the value, and it is completely legal for it to do so. It could encode everything if it wanted. This makes comparing XML documents non-trivial, because you have to actually take the structure into account. But since XML is structural, this is needed anyway. So a simple diff type of comparison will never work without problems, since there can be different types of whitespace for indentation, newlines etc, which are not important for XML structure or contents, but will be noticed with a simple textual diff tool.

A: XML has some set of unescape characters. Such as: ', ", & <, and >
Cause when you write a node as
<xsl:when test="@resCurrPage > 4">3</xsl:when>

now this <xsl:when test="@resCurrPage > part becomes a node and obviously  4">3 becomes data which again contains >. So it is needed to be transformed into escape character.
The XML escape character list is:
' is replaced with '
" is replaced with "
& is replaced with &
< is replaced with <
> is replaced with >


text:
Q: Find the right selector css to crawl a webpage on scrapy I'm trying to crawl this webpage "https://www.woolworths.com.au/shop/browse/drinks/cordials-juices-iced-teas/iced-teas" to extract the products name but I can't find the right selector, even for the price, h1 or the title! I tried :
response.css(".shelfProductTile-descriptionLink") #for the name product
response.css(".price-cents") # for the price
response.css(".tileList-title") # for the title

How can I proceed?

A: Content is dynamically loaded from a POST xhr returning json you can find in network tab of browser.
Request goes to:
https://www.woolworths.com.au/apis/ui/browse/category

Payload:
{"categoryId":"1_9573995","pageNumber":1,"pageSize":24,"sortType":"TraderRelevance","url":"/shop/browse/drinks/cordials-juices-iced-teas/iced-teas","location":"/shop/browse/drinks/cordials-juices-iced-teas/iced-teas","formatObject":"{\"name\":\"Iced Teas\"}","isSpecial":False,"isBundle":False,"isMobile":False,"filters":"null"}

with response in scrapy use:
json.loads(response.body_as_unicode())


text:
Q: How to Populate a JSP table using JSP, Java Beans and Servlets I have a JSP application and I am trying to use a JSP to populate a table of customer's  wedding cake orders that has one order for each row. The way I have approached it so far has been to set each order in the MySQL table to an Order object and then add all of the order objects to a HashMap to be referenced in the JSP.
Here's my question. So far, the Order objects are being created with the data in the database and placed in the HashMap. My only problem is I am confused about how I'm supposed to access the data in the JSP. I am using a c:forEach loop over the hashmap and am unsure how to access the attributes of the Order objects in the HashMap (such as the firstName or dueDate fields). I might have chosen a totally faulty approach as I'm relatively new to JSP. Here's my code.
The class that sets the HashMap with populated Order objects:
public HashMap getOrders() {
    dbm = new DatabaseManager();
    Statement stmt = null;
    String sql = "SELECT * FROM orders";
    HashMap<Integer, Order> orderMap = new HashMap<Integer, Order>();

    dbm.setUrl("jdbc:mysql://localhost:3306/pattycakes");
    dbm.connect();
    try {
        stmt = dbm.getConn().createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        rs.beforeFirst();
        int i = 0;
        while (rs.next()) {
            orderMap.put(i + 1,
                    new Order(rs.getString("first_name"), rs.getString("last_name"), rs.getString("phone"),
                            rs.getString("email"), rs.getString("due_date"), rs.getString("product_type"),
                            rs.getString("comments"), rs.getInt("id")));
            i++;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        dbm.disconnect(stmt, dbm.getConn());
    }
    return orderMap;
}

The Servlet that sets it as an attribute:
FormManager fm = new FormManager();
HashMap hm = fm.getOrders();
request.setAttribute("orders", hm);

The JSP attempting to populate the table:
        <c:forEach var="orders" items="${ orders }">

              <%-- How to get the data from the order objects???? --%>

                    ${ }

                ${ }
                ${ }
                ${ }

        </c:forEach>

Any help is really appreciated. If I have approached this incorrectly, suggestions on the best way to do this would be great.

A: We can iterate the hashmap in jsp as below <c:forEach var="country" items="${capitalList}"> Country: ${country.key} - Capital: ${country.value} </c:forEach>


text:
Q: Proving that overspecifying a linear model increases variance Suppose that a random variable Y is defined as $Y=\beta_0 + \beta_1x + \epsilon$, where $var(\epsilon)=\sigma^2$, the error has zero mean, and is independent across observations.
Suppose that we fit $\hat{Y}=\hat{\beta_0}+\hat{\beta_1}x+\hat{\beta_2}x^2+\hat{\beta_3}x^3$. I would like to show that $var(\hat{\beta_0}+\hat{\beta_1}x) \geq var(\tilde{\beta_0}+\tilde{\beta_1}x)$, where $(\tilde{\beta_0},\tilde{\beta_1})$ are the estimates obtained by fitting the model correctly. One of my homework assignments asked me to show this for a specific dataset, but I think it should be true generally.
It's easy to show that $var(\hat{\beta_1}) \geq var(\tilde{\beta_1})$ and so on, as this question seems to ask. But I'm finding it difficult to extend this result to $var(\hat{\beta_0}+\hat{\beta_1}x) \geq var(\tilde{\beta_0}+\tilde{\beta_1}x)$. We can break the terms apart into $var(\hat{\beta_0}+\hat{\beta_1}x)=var(\hat{\beta_0})+x^2var(\hat{\beta_1})+2cov(\hat{\beta_0},\hat{\beta_1}x)$, but how can I simplify the covariance term?
I attempted to use the law of total covariance. Covariance is bilinear, and the estimated $\beta_0$'s are equivalent, so $cov(\hat{\beta_0},\hat{\beta_1}x) \geq cov(\tilde{\beta_0},\tilde{\beta_1}x)$ is equivalent to $cov(\hat{\beta_0},(\hat{\beta_1}-\tilde{\beta_1})) \geq 0$. By the law of total covariance,
        \begin{align*}
        Cov(\hat{\beta_0},(\hat{\beta_1}-\tilde{\beta_1})x) &= E(cov(\hat{\beta_0},(\hat{\beta_1}-\tilde{\beta_1})x|Y)) + cov(E(\hat{\beta_0}|Y),E(\hat{\beta_1}-\tilde{\beta_1}x|Y)) \\
        &= E(cov(\bar{Y},(\hat{\beta_1}-\tilde{\beta_1})x|Y)) + cov(E(\bar{Y}|Y),E((\hat{\beta_1}-\tilde{\beta_1})x|Y)) \\
    \end{align*}
        $\bar{Y}|Y$ is a constant, so its covariance with any other variable is zero. The first term equals zero. The second term, though, doesn't seem like it has to be positive or negative in general. Does anyone know if there's a way to complete the proof? My approaches have focused on reducing the covariance term to a separable function of the individual beta variances. Maybe there's another method?

A: Not sure if you are familiar with matrices, but I am writing the general results. Suppose the true model is $Y=X_1\beta_1 +\epsilon$, but you fit the misspecified model $Y=X_1\beta_1 +X_2\beta_2+\epsilon =X\beta +\epsilon$, where $Y$ is $n \times 1$ vector, $X_1$ is $n \times p_1$ matrix, $X_2$ is $n \times p_2$, and $X=(X_1,X_2), \beta=(\beta_1^T,\beta_2^T)^T$, which are $n \times p, p \times 1$, respectively. The variance of $\hat{\beta_1}$ under the true model is $\sigma^2 (X_1^TX_1)^{-1}$, thus the variance of prediction $$var(X_1\hat{\beta_1}) =\sigma^2 X_1(X_1^TX_1)^{-1}X_1^T =\sigma^2 P_1,$$
 $P_1$ is the hat matrix. Under the misspecified model, the variance of $\tilde{\beta_1}$ is the $p_1 \times p_1$ submatrix of $\sigma^2 (X^TX)^{-1}$, which can be shown to be $$(X_1^TX_1-X_1^TP_2X_1)^{-1}$$ using the results from matrix inverse of block form , where $P_2$ is the hat matrix corresponds to $X_2$. Thus
,$$var(X_1\tilde{\beta_1})\ = \sigma^2 (X_1(X_1^TX_1-X_1^TP_2X_1)^{-1}X_1^T) \ge \sigma^2 P_1$$.


text:
Q: Using crash reporting in an open source application I would like to use crash reporting in an open source application. The code will be published and would include the implementation of the crash reporter API. In particular, the code displays the crash report account number in plain text. I am concerned that someone can take the account info from the code and troll/flood/pollute the crash report account.
Your thoughts? Maybe I can put the crash report account info in a dll so at least it is not publicly displayed in the source code.
I checked github and it seems very rare that an open source app will use a crash reporter service.


text:
Q: Why does Firefox say it "can't establish a connection to the server at ws://localhost:3000/" after successful return upgrade request? I wrote a program in c++ to upgrade an HTTP session to a WebSocket. The server correctly receives the upgrade request, and responds with 101 switching protocols. Firefox receives the 101 response, but in the console claims it couldn't connect. Here's the full output in Firefox.

The interesting thing is, in the network tab you can see the 101 response come in so it did establish an HTTP connection, the server got it, accepted it, tried to upgrade, and sent an upgrade response, but it's at that point that firefox doesn't upgrade to a WebSocket and prints the error.
I tried in Google Chrome as well. Similar error, but a bit more detail. WebSocket connection to 'ws://localhost:3000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
My code c++ hangs on the while loop, no errors thrown, which I think means it thinks the connection is still working?
I did notice it's sending Sec-Websocket-Protocol, even though I only asked for ws, not wss. Do chrome and firefox disallow non secure websockets? Or am I missing something in my code?
C++:
#define PORT (unsigned short) 3000
#define MAX_BUF 2048

int main()
{
    Poco::Net::ServerSocket x(PORT);
    Poco::Timespan timeout(25000000);
    if (x.poll(timeout, 1)) {
        Poco::Net::StreamSocket ss = x.acceptConnection();
        Poco::AutoPtr<Poco::Net::HTTPServerParams> params = new Poco::Net::HTTPServerParams();
        Poco::Net::HTTPServerSession sess(ss,params);
        Poco::Net::HTTPServerResponseImpl res(sess);
        Poco::Net::HTTPServerRequestImpl req(res, sess, params);
        if (req.getMethod()=="GET" && req.get("Upgrade")=="websocket") {
            Poco::Net::WebSocket webSock(req,res);
            while (!webSock.available());
            char buf[MAX_BUF];
            memset(buf,0,MAX_BUF);
            int flags = 0;
            webSock.sendFrame("Hello, World!\n",15);
            webSock.receiveFrame(buf,MAX_BUF,flags);
            printf("received %s\n",buf);
        }
    }
    else {
        printf("Timeout!\n");
    }
    return 0;
}

Javascript:
$(document).ready(function() {
    webSoc = new WebSocket("ws://localhost:3000");
    webSoc.onopen = function (event) {
        $("#c").click(function () {
            console.log("Sending 'Hello, World!'");
            webSoc.send("Hello, World!\n");
        });
    }
});

I've tried new WebSocket("ws://localhost:3000") with and without the echo-protocol parameter, because I read it in an answer to a question I didn't understand, which I can't find now.


text:
Q: What would the prototype declaration of a C function look like that returns an n-dimensional array? What would the prototype declaration of a C function look like that returns an n-dimensional array?
Here, n>=2.
Please explain it with dynamic-array/pointers.
My idea is not to pass any-dimensional array.
Please give me 3 examples with 2, 3 and 4 dimensions.
That will be enough for me to grab the idea.

A: I would suggest this:
array foo();

where array is an struct defined as:
struct array
{
    int *data;
    unsigned int ndim;  //number of dimensions
    unsigned int *size; //size of each dimension is size[i].
};

Of course, data is just a pointer to int, but the other two fields in the struct can be used in such a way that the data can be interpreted like an n dimensional array, and size of each dimension can be stored in size which is yet another pointer.
For example, take 4-dimensional array (dimension size are 10, 20, 30 and 40), then you can create and initialize 4D array as:
unsigned int size[] = {10,20,30,40};
array arr = create(4, size);

where create function is defined as:
array create(unsigned int n, unsigned int *size)
{
    array arr;
    arr.ndim = n;
    arr.size = (unsigned int*) malloc(n * sizeof(unsigned int));
    int i;
    unsigned int totalElements =  1;
    for( i = 0 ; i < n ; ++i)
    {
          arr.size[i] = size[i];
          totalElements *= size[i];
    }
    arr.data = (unsigned int*) malloc(totalElements * sizeof(int));
    return arr;
}

Of course, you've to work a lot with the fields of the struct, to make it look like n-dimensional array. You don't need to follow me exactly the way I explained, but this is just a basic idea. You can modify it, to suit your specific need.
I would suggest you to write few functions, to manipulate the array, and to access the array elements. I've written create function, likewise here is destroy function:
void destroy(array arr)
{
    if (arr.size != NULL && arr.data != NULL)
    {
       free(arr.size);
       free(arr.data);
       arr.size = arr.data = NULL;
    }
}

A: You can return a simple pointer and inside the function allocate memory for an n-dimensional array:
int* foo( int nSize )
{
   int*** x;
   x = (int***)malloc( sizeof(int**) * nSize );
   for ( int i = 0 ; i < nSize ; i++ )
   {
      x[i] = (int**)malloc( sizeof(int*) * nSize );
      for ( int j = 0 ; j < nSize ; j++ )
      {
     x[i][j] = ( int* ) malloc(sizeof(int) * nSize );
     for ( int k = 0 ; k < nSize ; k++ )
     {
        x[i][j][k] = i + j+ k;
     }
      }
   }

   return (int*)x;
}

Outside the function, since you already know the sizes, you can assume your pointer is of correct size - in this case, a 3-dimensional array:
int main(int argc, _TCHAR* argv[])
{
   int*** x =(int***) foo(4);
   for ( int i = 0 ; i < 4 ; i++ )
      for ( int j = 0 ; j < 4 ; j++ )
     for ( int k = 0 ; k < 4 ; k++ )
        cout << x[i][j][k] << endl;

   return 0;
}

Yes, the casts aren't nice, but it works :)

A: Your question is missing some detail (like the array's type, whether or not n is passed in as a parameter, whether or not the array is created in the function), so I will try and guess what you mean.
Arrays are referenced by a pointer and an offset. i.e.
double a[10];
a[1] = 1.0f;
double *b = &(a[0]);
double c = b[1];

Lets assume you want the function to create an array of n elements of type double.
double * createArray(int n);

There is your function prototype. Your function may look like
double * createArray(int n)
{
    double * newarray = new double[n];
    return &(newarray[0]);
}

You could use createArray like so
double * arrayoftendoubles = createArray(10);
double fifthelement = arrayoftendoubles[4];

It is irrelevant what the size of n is.


text: Q: Загрузка файлов Yii Для загрузки изображений на сайте пользовался этим http://yiiframework.ru/doc/cookbook/ru/form.file.upload . Но удается поменять расширение, например script.php на script.png и успешно загрузить файл на сервер. Что можно сделать для предотвращения подобного.


text:
Q: Passing a BIT value to a sql server stored procedure I have a stored procedure:
CREATE PROCEDURE myproc(@a nvarchar(50), @b nvarchar(100), @c bit)
AS ...

   SELECT @retVal;

I have the following aspx code:
SqlCommand cmd = new SqlCommand("myproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@a", a);
cmd.Parameters.AddWithValue("@b", b);
cmd.Parameters.Add("@c", SqlDbType.Bit).Value = false;

SqlParameter returnValue = new SqlParameter("@retVal", SqlDbType.NVarChar, 9999999);
returnValue.Direction = ParameterDirection.Output;
cmd.Parameters.Add(returnValue);
conn.Open();
cmd.ExecuteNonQuery();
retVal = (string)cmd.Parameters["@retVal"].Value;
conn.Close();

This gives me the error:
Procedure or function myproc has too many arguments specified.

If I remove the line:
cmd.Parameters.Add("@c", SqlDbType.Bit).Value = false;

I get this error:
Procedure or function 'myproc' expects parameter '@c', which was not supplied

I have tried these alternatives for this line:
cmd.Parameters.AddWithValue("@c", 0);
cmd.Parameters.AddWithValue("@c", false);

How do I pass that BIT parameter?

A: I present the 3 ways we can get data out of a procedure:
Here is an sp that returns a value
CREATE PROCEDURE x AS
BEGIN
  return 1
END

You have to get that 1 in your c# by adding a parameter with direction ReturnValue and type int (it can only be an int), and reading the parameter .Value after you ExecuteNonQuery
Typically we use returnvalue to indicate the state of the operation, NOT some data in the table. Eg an AddUser proc that returns 0 for success, 1 for fail because user exists, 2 for fail because password is too weak etc, we wouldn't use returnvalue to return the userid of the newly added user

Here is an sp that has an output parameter
CREATE PROCEDURE x
    @y INT OUTPUT
AS BEGIN
  SET @y = 1
END

You have to get that 1 in c# by adding a parameter with name @y and direction Output and read the parameter value after you ExecuteNonQuery. If you use the parameter for input as well, declare the direction as InputOutput

Here is an sp that returns a resultset
CREATE PROCEDURE x
AS BEGIN
  SELECT 1 AS y
END

You have to get that 1 by doing ExecuteScalar or ExecuteReader
ExecuteScalar returns the top left cell of a resultset; fine for this example. If you plan on returning more rows and columns than just a single value, use ExecuteReader

It sounds like you're mixing things up; decide how your sp will return its values and code the c# accordingly.
You can mix and match these and have a sproc that has an output parameter, a return value and selects a resultset but you should be clear on which bits of the c# collect what data from which bits of the sproc

A: Your stored procedure doesn't define an output parameter. @c isn't your problem, the problem is @retVal.
You need something like this:
CREATE PROCEDURE myproc(@a nvarchar(50), @b nvarchar(100), @c bit, @retVal NVARCHAR([LEN]) OUTPUT)
AS...

...where [LEN] is whatever you need, I doubt it's 9,999,999, but you can do MAX if you want.
Then store [YOUR RESULT] in your shiny new output parameter:
SELECT @retVal = [YOUR RESULT]

...at this point I believe your C# code will behave correctly.

A: Try to change this:
    returnValue.Direction = ParameterDirection.Output;

to this:
    returnValue.Direction = ParameterDirection.ReturnValue;

OK, if the @retVal is not integer, then you can't use ParameterDirection.ReturnValue. Stay with SELECT @retVal, but change cmd.ExecuteNonQuery() to var result = Convert.ToString(cmd.ExecuteScalar()); and also don't define @retVal parameter at C#.


text:
Q: How can I get j_username on my index.jsp after successful authentication with j_security_check? I'm using j_security_check on a login.jsp. The server is GlassFish Server 3. It all works, when the user is authenticated it then opens index.jsp. My problem is I need to get j_username in my index.jsp, but I couldn't find a way of doing it. All solutions I found are in Java and I need something that works with my jsp.
Any ideas? Thank you very much in advance!

A: The involved request  is in JSP EL available by PageContext#getRequest(). The logged-in user is available by HttpServletRequest#getUserPrincipal(). The username is in turn available by Principal#getName().
So,

Welcome, <c:out value="${pageContext.request.userPrincipal.name}" />

should do.
Using <c:out> is by the way not necessary, but useful for the case that the username could contain special HTML characters which could malform the HTML output like <, >, " and so on (which is a source for XSS attacks). The <c:out> just escapes them so that they get displayed literally instead of being interpreted as part of HTML markup.


text:
Q: Web connection through Arduino with WiFi I'd like to be able to make an HTTP request on the web to a specific server from my Arduino. I already have a Wireless SD Shield, and I am wondering if what I want to do is possible / what I would need to buy to make it work. From what I understand, I can plug an "add-on" shield to that with an antenna, like an XBee Wireless Transmitter. However, all examples I find on the web of such things use two Arduinos, one as a receiver and one as a transmitter. What I want is to use a single Arduino to connect wirelessly to the web and make an HTTP request.
It doesn't matter if HTTP itself is not supported, I can always create a basic client using TCP. But at the very least I need to be able to create a TCP connection and send data to the web through Wifi. Basically exactly like an Ethernet shield, but through Wifi.

A: Effectively what you have discovered (your wireless SD shield) is a method of sending serial data wirelessly, from one Arduino to another, via using xBee shield, wireless shields, etc. What you need to do is to connect to the internet. As you have ruled out ethernet and specified wifi, lets talk wifi shields.
There are a number of wifi shields available for the Arduino that you can use, though they are generally much more pricey than ethernet shields.
Here is one from sparkfun,
And another here.
Take a look at the documentation on the http://arduino.cc website for ways to write code for server connection.
Cheers.

A: I would recommend that you check out a Rugged Circuits Yellowjacket. It has a Wifi on board and can serve simple web pages and control inputs/outputs. Also, look at their code samples.


text:
Q: Character Encoding Mismatch My scripts are definitely saved in UTF-8. I'm instantiating PDO with "{$this->engine}:host={$this->host};dbname={$this->name};charset=UTF-8". My tables use InnoDB and are collated using utf8_general_ci. My pages are sent either with the Content-Type: text/html; charset=UTF-8 header or the <meta> equivalent.
When using PDO to store a € character originating either from HTTP input or a string literal in the source code, I'm left with c3 a2 e2 80 9a c2 ac according to MySQL Workbench 5.2. Retrieving this from the database and displaying it on the page works fine. Yet in phpMyAdmin and Workbench, I see €.
When using these two tools to store a €, I'm left with e2 82 ac, which is apparently the correct UTF-8 representation, but if I try to retrieve and then output this with PHP, � is displayed.
My question is, from where does this discrepancy arise and is it possible to have my web pages and database tools both work flawlessly?

A: The charset directive in the DSN actually applies to MSSQL. I simply needed to execute SET NAMES. Sorry about that.
I achieved that thus:
parent::__construct("{$this->engine}:host={$this->host};dbname={$this->name}",
                    $this->user, $this->password,
                    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));

A: simply, convert € to an html entity € for the superfix (but you may get the issue with other special chars)
the other side of the problem (and more specifically) is check the mysql character_set_server and the most common cause character_set_client - seeAlso: connection charsets
also, it's important to note that the meta equiv makes no difference, you need to always set the header('Content-Type: ...)

A: Since your HTML page is correct, it seems that you're storing the correct data in the database.
€ is the UTF-8 encoding of the Euro sign misinterpreted as windows-1252.  It appears that your Windows tools use "ANSI" encoding instead of the database encoding.


text:
Q: Why SQL binary convert function results a non-0101... value? Why when I use the command in SQL Server 2005
select convert(varbinary(16),N'123')

results 0x310032003300 and not 1111011?

A: Basically each letter of '123' gets converted to it's UCS-2(basically the ASCII value padded to make it a double byte) value in the three double bytes of 0x3100, 0x3200, 0x3300, and concatenated together in a varbinar.
Hopefully that answers why you see this behavior.  If you convert to an int first you may see what you were perhaps hoping for instead:
select convert(varbinary(16),cast(N'123' as int))

produces hex value 0x0000007B which in binary is 1111011
See http://www.asciitable.com/ the entry for numeric 3, the hex representation is 0x33 which corresponds to the same entry in unicode: http://www.ssec.wisc.edu/~tomw/java/unicode.html (this pattern does not necessarily hold true for all ASCII/unicode characters, but does for the 10 integers).


text:
Q: How do I use the Supply monad to create a function that generates globally unique names? Background:
I'm doing a code translation project that requires me to generate variable names. None of the names I generate should be duplicates of each other.
I'm really frustrated since this would be stupidly simple and elegant with a Python generator function.
What I've tried:
The way I was doing it before was to pass a counter variable down through recursive calls to my translate code, and pass the (possibly incremented) counter back up in the return value of basically every function.
This was really messy: it added an extra parameter to keep track of to each of these functions; and worse still it forced me to work with messy tuple return values where I would otherwise have a simple unary return value.
I've never really gotten proficient with monads in my short time with Haskell, but I had an inkling that I could use a wrapper on the State monad to simulate a global counter variable. After 3 days of messing around trying to grok monads and make one of my own, then trying to alter someone else's monads to generate the values I needed, I've finally resigned myself to straight-up using someone else's high-level monad (perhaps with a few alterations.)
My problem now:
I've identified the MonadSupply and MonadUnique modules as a couple which likely provide the simple kind of interface I need. Unfortunately I can't figure out how to use them.
In particular the MonadSupply module documentation provides this nice example use case:
runSupplyVars x = runSupply x vars
    where vars = [replicate k ['a'..'z'] | k <- [1..]] >>= sequence

Looks like what I want! Once I got the module to compile I checked the type of this function in the interpreter:
> :t runSupplyVars
runSupplyVars :: Supply [Char] a -> Identity (a, [[Char]])

I've tried passing lots (hours worth) of different things to this function, with no success. I also tried passing the function to some various other functions to see if they would provide the parameters I needed implicitly. No luck so far.
The Questions:
Could someone please provide an example use case of this runSupplyVars function?
Would it be possible to do what I'm thinking with it? I want to have a function I can call from anywhere in the program, which will provide me with a different variable name or integer on each call.

A: To actually use the Supply monad you should structure your code with do notation and call the supply function when you actually need a name.
For example, this will produce a new variable name prefixed with var_, just to show how you might get something from the supply and use it:
newVar :: Supply [Char] [Char]
newVar = do
    name <- supply
    return ("var"_++name)

You'll need to structure your whole program around the Supply monad and then only call runSupplyVars once at the top-level, otherwise different parts of the program will have independent supplies and so might reuse the same variable name.
Finally, you'll need runIdentity from Control.Monad.Identity to unpack the result of runSupplyVars into the underlying tuple of type (a, [[Char]]), and then throw away the second value which is just the (infinite) list of unused names. You might be better off redefining runSupplyVars to do this for you:
import Control.Monad.Identity

[...]

runSupplyVars :: Supply [Char] a -> a
runSupplyVars x = fst (runIdentity (runSupply x vars))
    where vars = [replicate k ['a'..'z'] | k <- [1..]] >>= sequence

Here's a more complete example putting it all together. Note the different monads with which do notation is used - IO for the main function, and Supply [Char] for realProgram and probably most of the rest of the code in a bigger version:
import MonadSupply
import Control.Monad.Identity

main :: IO ()
main = do
    let result = runSupplyVars realProgram
    print result

realProgram :: Supply [Char] Int
realProgram = do
    x <- newVar
    return 0

newVar :: Supply [Char] [Char]
newVar = do
    name <- supply
    return ("var_"++name)

runSupplyVars :: Supply [Char] a -> a
runSupplyVars x = fst (runIdentity (runSupply x vars))
    where vars = [replicate k ['a'..'z'] | k <- [1..]] >>= sequence


text:
Q: When should I assert the actions of the SUT? Consider the following unit test:
[Test]
public void Success()
{
  var userID = 5;
  var user = new User();
  var dataAccess = new Mock<IDataAccess>();
  dataAccess.Setup(x => x.GetUser(userID)).Returns(user).Verifiable();
  var sut = new UserController(dataAccess.Object);

  var returnedUser = sut.GetUser(userID);

  Assert.AreSame(user, returnedUser);
  dataAccess.Verify(x => x.GetUser(userID), Times.Once());
}

Recent reading has suggested that I should only use the mock to provide the user and there should be a single assert (the AreSame one). Apparently the ideal unit test shouldn't worry about verifying the sut's behaviour.
More like this:
[Test]
public void Success()
{
  var userID = 5;
  var user = new User();
  var dataAccess = new Mock<IDataAccess>();
  dataAccess.Setup(x => x.GetUser(userID)).Returns(user);
  var sut = new UserController(dataAccess.Object);

  var returnedUser = sut.GetUser(userID);

  Assert.AreSame(user, returnedUser);
}

Is this simplified test better? Should Unit Tests assert the behaviour of methods they call or just the results?

A: One basic idea is to have only one Assert in test. So maybe you should consider two tests here. The first value-based test is important. The second interaction test is probably not suitable in this case. According to Roy Osherove: 'You use interaction testing when calling another object is the end result of specific unit of work.'.
Example:
namespace Tests
{
    [TestClass]
    public class UserControllerTest
    {
        [TestMethod]
        public void GetUser_WhenCalled_ReturnsUserSameAsDataAccess()
        {
            // Arrange
            const int userID = 5;
            User expectedUser = new User();

            Mock<IDataAccess> dataAccessStub = new Mock<IDataAccess>();
            dataAccessStub.Setup(x => x.GetUser(userID)).Returns(expectedUser);
            UserController controller = new UserController(dataAccessStub.Object);

            // Act
            User actualUser = controller.GetUser(userID);

            // Assert
            Assert.AreSame(expectedUser, actualUser);
        }

        [TestMethod]
        public void GetUser_WhenCalled_GetUserOnDataAccessIsCalledOnce()
        {
            // Arrange
            const int userID = 5;
            const int getUserCallsCountExpected = 1;
            int getUserCallsCount = 0;

            Mock<IDataAccess> dataAccessMock = new Mock<IDataAccess>();
            dataAccessMock.Setup(x => x.GetUser(userID)).Callback(() => getUserCallsCount++);
            UserController controller = new UserController(dataAccessMock.Object);

            // Act
            controller.GetUser(userID);

            // Assert
            Assert.AreEqual(getUserCallsCountExpected, getUserCallsCount);
        }
    }
}


text:
Q: Dpac File - Errors I have a problem with unresolved referenced in synonyms with a VS2013 Database project I have created for Team Foundation Server, which cause the project to not build. The synonyms reference another Database on the same server. I have seen online there are 3 main ways people handle this. I am going for this approach 1.

*

*Create a DPAC file and add as a Database reference in Visual Studio Database Project.

*Bring in the other database project in the current team Foundation Server project ?

*Set the build action to None for the failing scripts that have the unreferenced synomns.

So when I go to extract the DPAC file from the Database it fails with an error.
Validation of the schema model for data package failed.
Error SQL71564: Error validating element [UAT_*********]: The element [UAT_*****] has been orphaned from its login and cannot be deployed.
( There is about 9 similar messages with other logons as well)
Is there anyway to bypass this and generate a valid DPAC file from sql server ?

A: If you need a .DACPAC file as a reference to your database projects, there is no need for referencing object to have any real code - As long as the signature met the requirements that the reference from Database Project was looking for, it will be just fine (syntactically valid).
You do not have to create a .DACPAC directly from SQL Sever, you can create a new empty Database Project, create/import all objects needed as references and then "Snapshot Project". This will generate valid .DACPAC and keep the size to minimum, which then you can put under source control.
If you wanted to create a .DACPAC from SQL Server, then I am afraid you would have to delete those objects, because it is unable to find logins in master database that are associated with them.
Great article to read about your approach 1 :
A complex database project
Hope this helps.


text:
Q: Update data property / object in vue.js is there a way I can programmatically update the data object / property in vue.js? For example, when my component loads, my data object is:
data: function () {
    return {
        cars: true,
    }
}

And after an event is triggered, I want the data object to look like:
data: function () {
    return {
        cars: true,
        planes: true
    }
}

I tried:
<script>

module.exports = {

    data: function () {
        return {
            cars: true
        }
    },

    methods: {
        click_me: function () {
            this.set(this.planes, true);
        }
    },

    props: []

}

</script>

But this gives me the error this.set is not a function. Can someone help?
Thanks in advance!

A: Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it's possible to add reactive properties to a nested object, So you may create an object and add a new property like that:
data: function () {
    return {
        someObject:{
            cars: true,
    }
}

and add the property with the vm.$set method:
methods: {
        click_me: function () {
            this.$set(this.someObject, 'planes', true)
        }
    }

for vue 1.x use Vue.set(this.someObject, 'planes', true)
reactivity


text:
Q: nginx Subdomain Redirect to URL I have a server running nginx + php5-fpm with a wordpress installation.  My website is served on example.com and I would like to configure admin.example.com to point my site contributors to example.com/wp-admin. How do I configure my server{} block to do this?

A: I believe something like this should work:
server {
    server_name  admin.example.com;
    rewrite ^(.*) http://example.com/wp-admin permanent;
}

A: Try this:
    location / {
        root   /home/kiputih0/public_html;
        index  index.php;
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

In my permalinks I've custom rules:
/%year%/%monthnum%/%day%/%postname%.html
And when I browse to some article it will be:
/2010/11/15/beta.html
Cheers...


text:
Q: Maximum likelihood estimation using R I have a multiple linear regression, that I want to estimate using a MLE approach. I would like to make the fit using a Beta distribution, with parameters u and v. How can I do this using R?

A: Beta regression is implemented in betareg CRAN package, see [1], and also CRAN webpage.
[1] https://cran.r-project.org/web/packages/betareg/vignettes/betareg.pdf


text:
Q: Why does Kotlin with Spring MVC JSON return an empty object? I've been playing with server side Kotlin, Spring MVC and Jackson.
I built a simple application using http://start.spring.io/, but I might have made a mistake in the JsonView annotation.
This:
@RestController

class MyRestController {
    @RequestMapping("/user")
    @JsonView(User::class)
    fun getUser() : User = User("Fred",50)
}

data class User(val name: String, val age: Int)

...when called with curl
ph@sleek ~ $ curl -X GET http://localhost:8080/user; echo
{}
ph@sleek ~ $

...the result is {} when I expected {"name":"Fred","age":50}. Is there something I did wrong?

A: Much simpler than I thought. After finding that Jackson was able to serialise the object just fine, I started making adjustments, and found the default was better than configuration:
class MyRestController {
    @RequestMapping("/user")
    fun getUser() : User = User("Fred",50)
}

Perfect:
ph@sleek ~ $ curl -X GET http://localhost:8080/user; echo
{"name":"Fred","age":50}

A: if you do want to use @JsonView (which is necessary in many scenarios), I was running into the same empty object problem until I added the jackson-module-kotlin dependency to my project.
compile 'com.fasterxml.jackson.module:jackson-module-kotlin'

See here: https://stackoverflow.com/a/48019143/5258628


text:
Q: Entreprise library caching configuration without configuration file I am using Enterprise Library Caching block without configuration  file. Cache settings are initialized from my code. I initialize the cache with the following code:
static class LocalCache
    {
        private static readonly CacheManager CacheManager;

        static LocalCache()
        {
            try
            {
                string localCacheName = "MyCache";

                DictionaryConfigurationSource configSource = new DictionaryConfigurationSource();
                CacheManagerSettings cacheSettings = new CacheManagerSettings();

                configSource.Add(CacheManagerSettings.SectionName, cacheSettings);
                CacheStorageData storageConfig = new CacheStorageData("NoStorage", typeof(NullBackingStore));
                cacheSettings.BackingStores.Add(storageConfig);

                var expirationPollFrequencyInSeconds = 2;
                CacheManagerData cacheManagerData = new CacheManagerData(
                    localCacheName,
                    expirationPollFrequencyInSeconds,
                    100,
                    20,
                    storageConfig.Name
                    );
                cacheSettings.CacheManagers.Add(cacheManagerData);
                cacheSettings.DefaultCacheManager = cacheManagerData.Name;

                CacheManagerFactory cacheFactory = new CacheManagerFactory(configSource);
                CacheManager = cacheFactory.CreateDefault();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        public static T GetData<T>(string cacheKey)
        {
            var value = CacheManager.GetData(cacheKey);
            return (T)value;
        }

        public static void AddData(string cacheKey, object value)
        {
            CacheManager.Add(cacheKey, value);
        }
    }

The issue is that the expirationPollFrequencyInSeconds (here 2 seconds) is not taken into account when retrieving a cache item that is supposed to be expired. The item reside in cache longer than 2 seconds.
Any idea ?
See test example below:
private static void Main(string[] args)
    {
        try
        {
            LocalCache.AddData("One", 1);
            Thread.Sleep(5000);
            LocalCache.AddData("Two", 2);

            object data = LocalCache.GetData<object>("One");

            if (data == null) Console.WriteLine("Data not in cache");
            else Console.WriteLine("-----> Data in cache whereas it should not !!!");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

Output:
-----> Data in cache whereas it should not !!!

A: Based on the online documentation for CacheManagerData class, the constructor doesn't take in a cache experts duration period. Instead the second argument is the time period after which the manager will check if the cached items are to be removed if there are too many items.
So, 2 seconds is not the cache expiry.
Whether there are too many items is dependant on the third argument.
https://msdn.microsoft.com/en-us/library/ee779632.aspx
If you wish to add an expiry period, then have a look at the following:
http://www.codeproject.com/Articles/51409/Exploring-Caching-Using-Caching-Application-Enterp#heading0016


text:
Q: Phases/Plugins and Maven Project Builder When i save changes in my java source code with Eclipse i notice in the Progress tab

As i am using Maven which phase or plugin (goal) is being invoked here ?
What happens behind the scene ?

A: simply it updates maven dependencies based on your pom.xml or resolves Maven dependencies from the Eclipse workspace without installing to the local Maven repository.
visit this site to know about that in detail https://maven.apache.org/ref/3.0.1/maven-core/apidocs/org/apache/maven/project/ProjectBuilder.html

A: Any change to the source code or pom file of the project signal eclipse to rebuild (if build automatically is enabled). However, maven builds, would check for the required artefacts from the remote repository and download them to local repository (under .maven dir) before running compile phase. Maven plugin can be configured to run offline in which when remote repository will not be queried - making the build execute faster.


text:
Q: Could not change profile image of my Android app while automating with Appium
I could not select an image from the gallery app. I am automating my Android app using Appium.

A: how are you implementing it? You can use UIAutomator to find out the xPATH or IDs to reach to the image. you can also use "tap" to select a particular image. post your existing code,

A: *

*I have launch Android photo gallery using following code from a activity.
Intent intent =  new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivity(intent);

*Test code can have following implementation.
WebDriverWait wait = new WebDriverWait(driver, 30);wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("com.android.gallery:id/grid")));
 driver.context("NATIVE_APP");
 HashMap<String, Double> map = new HashMap<String, Double>();
 map.put("x", 0.3);
 map.put("y", 0.3);
 (driver).executeScript("mobile: tap", map);


text:
Q: Sort Properties of Object Powershell All
i'm using this code to get data from SharePoint List and export it to txt file
as you see i'm using New-Object PSObject to get this
my question is how can i sort the the properties by the name i gave or how to export this items sorted by those name
Thanks in advance
$MyWeb = Get-SPWeb "http://ilike-eg.suz.itcgr.net/SM"
$MyList = $MyWeb.Lists["SCGC"]
$exportlist = @()
$Mylist.Items |  foreach {
$obj =   New-Object PSObject -property @{
        "A"="   "+$_["AACCOUNT_ID"]
        "B"="   "+$_["BTRANSACTION_ID"]
        "C"="          "+$_["CDATE"]
        "D"="      "+$_["DCUSTOMER_ID"]
        "E"="     "+$_["ECUSTOMER_NAME"]
        "F"=" "+$_["FAMOUNT"]
        "G"=$_["GCLASS"]
}
$exportlist += $obj | Sort-Object -descending
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
$NameOnly = "CDP"
$exportlist | Export-Csv -Delimiter "`t"-path "$NameOnly.txt"
}
$a, ${d:CDP.txt} = Get-Content .\CDP.txt
$a, ${d:CDP.txt} = Get-Content .\CDP.txt
(Get-Content D:\CDP.txt) |
Foreach-Object {$_ -replace $([char]34), ""} |
Set-Content D:\CDP.txt
(Get-Content D:\CDP.txt) |
Foreach-Object {$_ -replace "/", "-"} |
Set-Content D:\CDP.txt
(Get-Content D:\CDP.txt) |
Foreach-Object {$_ -replace "`t", ""} |
Set-Content D:\CDP.txt

A: If you know the propertynames, then use the following:
$exportlist |
Select-Object A,B,C,D,E,F,G |
Export-Csv -Delimiter "`t"-path "$NameOnly.txt"

If you don't know the name of the properties, try:
$properties = $exportlist |
Foreach-Object { $_.psobject.Properties | Select-Object -ExpandProperty Name } |
Sort-Object -Unique

$exportlist |
Select-Object $properties |
Export-Csv -Delimiter "`t"-path "$NameOnly.txt"

I made a few other modifications to your script to make it more efficient and easier to read:
$MyWeb = Get-SPWeb "http://ilike-eg.suz.itcgr.net/SM"
$MyList = $MyWeb.Lists["SCGC"]
$exportlist = @()

$Mylist.Items |  ForEach-Object {
    $obj =   New-Object PSObject -property @{
            "A"="   "+$_["AACCOUNT_ID"]
            "B"="   "+$_["BTRANSACTION_ID"]
            "C"="          "+$_["CDATE"]
            "D"="      "+$_["DCUSTOMER_ID"]
            "E"="     "+$_["ECUSTOMER_NAME"]
            "F"=" "+$_["FAMOUNT"]
            "G"=$_["GCLASS"]
    }

    #Remove unnecessary sort
    $exportlist += $obj
    $DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
    $NameOnly = "CDP"

    #Exporting with sorted properties
    $exportlist |
    Select-Object A,B,C,D,E,F,G |
    Export-Csv -Delimiter "`t"-path "$NameOnly.txt"
}

#Removed duplicate get-content line
$a, ${d:CDP.txt} = Get-Content .\CDP.txt

#Combined replace statements to avoid multiple read/writes
(Get-Content D:\CDP.txt) |
Foreach-Object {$_ -replace $([char]34) -replace "`t" -replace '/', ''} |
Set-Content D:\CDP.txt


text:
Q: ImageView not showing on emulator I've some ImageViews in my application. They show up fine on my phone but there's no way to show them on an emulator. I've already tried different version and screen size. In another questions people where able to solve the problem using android:hardwareAccelerated="false" or using src instead of srcCompat, but nothing of this seems to help.
The ConstraintLayout where imageViews are:
<android.support.constraint.ConstraintLayout
    android:id="@+id/login_header"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <ImageView
        android:id="@+id/title_background_log"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:background="@color/colorPrimary"
        android:elevation="10dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/colorPrimary" />

    <ImageView
        android:id="@+id/company_logo"
        android:layout_width="331dp"
        android:layout_height="90dp"
        android:layout_marginEnd="39dp"
        android:layout_marginLeft="39dp"
        android:layout_marginRight="39dp"
        android:layout_marginStart="39dp"
        android:elevation="15dp"
        android:scaleType="fitXY"
        android:src="@drawable/zeeromed_text"
        android:visibility="visible"
        app:layout_constraintHorizontal_bias="0.489"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="ContentDescription"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

</android.support.constraint.ConstraintLayout>

The complete Activity Layout:
<android.support.constraint.ConstraintLayout
    android:id="@+id/login_header"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <ImageView
        android:id="@+id/title_background_log"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:background="@color/colorPrimary"
        android:elevation="10dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/colorPrimary" />

    <ImageView
        android:id="@+id/company_logo"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginEnd="39dp"
        android:layout_marginLeft="39dp"
        android:layout_marginRight="39dp"
        android:layout_marginStart="39dp"
        android:elevation="15dp"
        android:scaleType="center"
        android:visibility="visible"
        app:layout_constraintHorizontal_bias="0.489"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="ContentDescription"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:id="@+id/login_body"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:layout_marginTop="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/login_header">

    <EditText
        android:id="@+id/email_editText"
        style="@android:style/Widget.EditText"
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_marginEnd="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginTop="136dp"
        android:background="@drawable/rounded_transparent_button_focusable"
        android:ems="10"
        android:hint="@string/email_hint"
        android:inputType="textEmailAddress"
        android:paddingLeft="10dp"
        android:selectAllOnFocus="false"
        android:textAlignment="viewStart"
        android:textColor="@color/colorPrimary_text"
        android:textColorHint="@color/colorSecondary_text"
        android:textSize="18sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="37dp"
        android:text="oppure"
        android:textAlignment="center"
        android:textColor="@color/colorPrimary_text"
        android:textSize="14sp"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/send_button"
        tools:ignore="HardcodedText,RtlHardcoded" />

    <ImageView
        android:id="@+id/imageView7"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:background="@color/colorAccent"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <br.com.simplepass.loading_button_lib.customViews.CircularProgressButton
        android:id="@+id/send_button"
        style="@android:style/Widget.Material.Button"
        android:layout_width="300dp"
        android:layout_height="48dp"
        android:layout_marginBottom="81dp"
        android:layout_marginEnd="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginStart="32dp"
        android:background="@color/colorPrimary"
        android:elevation="10dp"
        android:text="accedi"
        android:textColor="@color/white"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/sing_in"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:spinning_bar_color="#FFFFFF"
        app:spinning_bar_width="4dp"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

    <Button
        android:id="@+id/security_button"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="65dp"
        android:layout_height="60dp"
        android:layout_marginBottom="29dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="15dp"
        android:background="@drawable/hexagon_lock"
        android:backgroundTint="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.055"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:ignore="RtlHardcoded" />

    <Button
        android:id="@+id/login_intro_button"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="197dp"
        android:layout_height="48dp"
        android:layout_marginBottom="89dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text="Ripeti introduzione"
        android:textColor="@color/colorPrimary_text"
        android:textSize="12sp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:ignore="HardcodedText" />

    <Button
        android:id="@+id/sing_in"
        style="@android:style/Widget.DeviceDefault.Button.Borderless"
        android:layout_width="300dp"
        android:layout_height="48dp"
        android:layout_marginBottom="122dp"
        android:layout_marginEnd="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginStart="15dp"
        android:text="@string/registration_link"
        android:textAppearance="@android:style/TextAppearance.Material.Body2"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

    <TextView
        android:id="@+id/security_text"
        android:layout_width="65dp"
        android:layout_height="15dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text="Sicurezza"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.432"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/innovation_text"
        tools:ignore="HardcodedText,RtlHardcoded" />

    <TextView
        android:id="@+id/innovation_text"
        android:layout_width="65dp"
        android:layout_height="15dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:text="Innovazione"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.487"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:ignore="HardcodedText,RtlHardcoded"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/innovation_button"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="65dp"
        android:layout_height="60dp"
        android:layout_marginBottom="29dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="15dp"
        android:background="@drawable/hexagon_cloud"
        android:backgroundTint="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.488"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:ignore="RtlHardcoded" />

    <EditText
        android:id="@+id/password_editText"
        style="@android:style/Widget.EditText"
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_marginBottom="302dp"
        android:layout_marginEnd="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/rounded_transparent_button_focusable"
        android:ems="10"
        android:hint="@string/password_hint"
        android:inputType="textPassword"
        android:paddingLeft="10dp"
        android:selectAllOnFocus="false"
        android:textAlignment="viewStart"
        android:textColor="@color/colorPrimary_text"
        android:textColorHint="@color/colorSecondary_text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/email_editText"
        app:layout_constraintVertical_bias="0.414"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />
</android.support.constraint.ConstraintLayout>

I don't think that my layout structure is the problem, but maybe you could prove me wrong.
Images show on phone with API 24 Nougat 7.0.
I tried emulators from API 21 to 23 because my minimum API is 21.

A: I really don't know why scr isn't working but you could try:
android:background="@drawable/zeeromed_text"
instead of :
android:src="@drawable/zeeromed_text" or scrCompact
don't do multiple like you did mixing background and src on the first ImageView

A: Change like this
 android:id="@+id/login_header"
 android:layout_width="wrap_content"

Reference
Hope this may help you


text:
Q: SQL determine column name next to a particular column Here is the scenario...
I have an SQL table with columns:
Power | Quality1 | Energy | Quality2 | Voltage | Quality3... Current | Quality165 | Temp | Quality166

I want to extract the data contained in for example the column labelled as 'Quality3', which tells me what the quality of the data is regarding the voltage data, with column 'Voltage' containing the actual value. However, I have hundreds of columns and I am not always sure which 'Quality#' table to select in order to obtain the quality of the recorded data for a particular table entry.
So to be clear, I don't know that 'Quality166' informs me of the 'Temp' column's data validity, but I do know that the column proceeding the 'Temp' column contains the quality information that I desire.
I have thought of maybe getting the column number where for example the column is labelled as 'Voltage'. Now, as mentioned, I don't know that column 'Quality3' is associated with the 'Voltage' column's entry, but if I could perhaps obtain the actual number of the 'Voltage' column entry (5 in this case) then if i wanted to get the 'Quality3' value I could simply search for it in column 6, which contains this desired data.
Any suggestions ?
This is what I've tried, but I am way off...
query = "SELECT count() FROM information_schema.tables WHERE table_schema = 'Plant_Data_raw' AND table_name = 'Voltage'"

Looking forward to your replies !


text:
Q: NGINX Serve static files inside a nested location I have a nested location directive, I want to serve the app at the /api and the static files in the /api/static/
For serving static files I'm using try_files $uri /dev/null =404 inside a nested location.
location /api/ {

        location /api/static/ {
            try_files $uri /dev/null =404;
            root /shared_volumes/staticfiles/;
        }

        proxy_set_header        Host                    $host;
        proxy_set_header        X-Real-IP               $remote_addr;
        proxy_set_header        X-Forwarded-For         $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto       $scheme;
        proxy_pass              http://app:8000/api/;
    }

but that doesn't work, nginx returns not found when accesing http://app/api/static/afile.css although the file exists in /shared_volumes/static/afile.css
In the NGINX docs $uri is

current URI in request, normalized The value of $uri may change during
  request processing, e.g. when doing internal redirects, or when using
  index files.

How does nginx $uri behave in nested location?
Does nginx search file api/static/afile.css in /shared_volumes/staticfiles/ instead of afile.css?

A: I changed the /api/static/ location directive as sugested by @Richard and @Alexey in the comment above
    location /api/static/ {
        alias /shared_volumes/staticfiles/;
    }

and it now works, thanks!


text:
Q: I have written some code and i am trying to use "else" and i keep getting errors ive written some code and it works fine (from what i can see anyway) until I get to the "else" part, really i just want to set up a simple loop but I dont know how. the error is "Statement expected, found Py:ELSE_KEYWORD Statement expected, found Py:COLON"
name = input("Hello, what is your name? ")

restart =  input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
while restart == "y":

 print("Hello " + name)

feeling = input("How are you today? ")

print("I'm feeling good!")

else:
print("Sorry, the restart")
else: print("goodbye")

I am just trying to set up my loop then I will finish my code.

A: Three things:

*

*Python is unique in that whitespace matters - code within the same block should have the same indentation

*Else-statements can only be used following an if-statement. Since you don't have any if-statements in your code, you can't have any else-statements. We can just remove them.

*You need to ask the user if they want to keep going at the end of your loop.

Here's a cleaned-up version of your code:
name = input("Hello, what is your name? ")

restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
while restart == "y":
    print("Hello " + name)
    feeling = input("How are you today?")
    print("I'm feeling " + feeling)
    restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")

print("Goodbye")

A: The loop structure needs to be changed. We need to run an infinite loop and only when user types 'n' we should come out of that loop


text:
Q: Rails 2 - How to Use a Different Layout for an entire sub-site but still be able to use existing Controllers and Models I am using Rails version 2.3.14 and I am trying to figure out the best way to use a different layout for an entirely new section of my site but I can't think of the most efficient way to do it.
e.g. I have a CRM and everything is localhost/controller/method as normal but what I want to do is create a sub-section of my site named portal.
I considered creating a new app but I don't really want to do that since this sub section will be using existing controllers so I don't want to end up in the situation of having to remember to update both controllers to make sure their contents are identical as that will end up getting messy.
I read this answer rails 3, how add a view that does not use same layout as rest of app? and it makes sense but I can't think how to apply that to my situation.
e.g. http://localhost/ would show my existing login page and something like localhost/portal would show the login page for the new section but with a completely different layout but using the same models and controllers.
I'm new to rails so I might be over-thinking it or I might be barking up the wrong tree.
If it's possible I think the easiest way would be to somehow check the url for portal and set the layout based on the outcome of that check.

A: I read the answer you posted, it makes sense, I just try to give you some real codes in your case.
You have a sub site, it means that your path of all pages in sub site will start with '/portal', right?
In your app/views/layout , you can add a layout named "portal_subsite.html.erb".
In your application_controller.rb
class ApplicationController < ActionController::Base
  layout :get_layout

  private

  def get_layout
    if  request.path.start_with?('/portal')
      'portal_subsite'
    else
      'application'
    end
  end
end

I have not a environment of Rails 2  now, but I think it should work, if you have any questions, please comment below.


text:
Q: Data is disappearing from UITableView I am building an iOS app with a custom tab bar at the top. When i click on the home icon, I want it to show a tableview directly below the tab bar. Currently my code does just that, however the data doesnt show correctly. If I limit my Cells to 4 or less (in the numberFoRowsInSection), the data will show, if i have like say 15 cells, the data shows for a split second and then it disappears. I have been looking at tutorials all over the place and everything seems to be correct, the data will show correctly in a stand alone view(like i created a similar to a singleview application in the story board and made that the initial view). I dont know where i am wrong. Below is my code in implementation file of the tableviewContoller class:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

// Return the number of rows in the section.
return 4;//this works... but change to 15 it doesnt work
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{
  PrayerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
if (cell == nil) {
    NSLog(@"cell is Nil"); //never hits this
    cell = [[PrayerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CustomCell"];
}

//the data showing is the correct data that i want to see
cell.dName.text = [[news objectAtIndex:indexPath.row] objectForKey:@"displayname"];
cell.priority.text = [[news objectAtIndex:indexPath.row]objectForKey:@"priority"];
cell.dateTime.text = [[news objectAtIndex:indexPath.row] objectForKey:@"datetime"];
cell.numPraying.text = @"2 praying";
cell.requestPreview.text = [[news objectAtIndex:indexPath.row] objectForKey:@"request"];

NSLog(@"created cell") //verify cell was made

return cell;
}

Here is my PrayerCell.H file
@interface PrayerCell : UITableViewCell

@property (weak, nonatomic)IBOutlet UILabel *requestPreview;
@property (weak, nonatomic)IBOutlet UILabel *dName;
@property (weak, nonatomic)IBOutlet UILabel *dateTime;
@property (weak, nonatomic)IBOutlet UILabel *numPraying;
@property (weak, nonatomic)IBOutlet UILabel *priority;

@end

I made no Changes to the prayerCell.M file
if you need me to post any other code blocks/screenshots please let me know.

A: The cell should not be an ivar, it should be a local variable. You also need to dequeue the cell in your tableView:cellForRowAtIndexPath: method:
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];


text:
Q: Allow apostrophe in multiple email id field I have a email field in my form. User can enter more than one email id on same time like the below format
test1@test.com,test2@test.com
test1@test.com, test2@test.com
test1@test.com;test2@test.com
test1@test.com; test2@test.com

I did this.
Now I want to allow aj''joy@css.com, ab''coy@css.com, these kind of mail id also. I tried but i am not able to  find how to allow apostrophe in email validation. Anyone can help me?
fiddle link : http://jsfiddle.net/WwRVy/8/

A: Since my comment answered your question...
That's because those characters aren't apostrophes, they're weird floating comma things. Nobody is going to enter those. Use actual apostrophes and your current regex is fine:
aj''joy@css.com, ab''coy@css.com

A: The updated jsfilddle link is http://jsfiddle.net/WwRVy/9/
I added apostrophe in
var email_reg = "[A-Za-z0-9\._%-']+@[A-Za-z0-9\.-]+\.[A-Za-z]{2,4}";

Now working fine

A: How about you string replace the apostrophe's first and then validate? That way you can keep using standard validators.
Just out of curiosity - why would you want to do this? Kindof defeats the purpose of 'validating' the e-mail address. Since an e-mail address with an apostrophe is not valid...

A: Not fully tested, but you could try
^([a-zA-Z0-9\'_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

As a starting point.
See this c# answer adding apostrophe while checking email address for reference. Should work fine in JavaScript.
If you paste this into http://scriptular.com/ it matches emails with apostrophe's


text:
Q: VBA CDO Runtime Error 429 Having issue getting this vba remote email send script to work.
Run-time error 429
ActiveX component can't create object.
I've downloaded Microsoft CDO 1.21 Library, registered cdo.dll cmd prompt as Administrator, and referenced it.
.dll Location: C:\Program Files\ExchangeMapi\cdo.dll
OS: Windows 7 Professional, 32 bit, Service Pack 1.
Application with VBA: Iconics ScriptWorx32
Code:
Public Sub SendEmail(nFrom As String, nSubject As String, nOutGoingServer As String, _
                     nMessage As String, nPassword As String, nUserName As String, _
                     nServerPort As Long, nTo As String, Optional nIntProxyPort As Long)

  Dim Msg As Object
  Dim Confg As Object
  Dim Flds As Variant

  Set Msg = CreateObject("CDO.Message")
  Set Confg = CreateObject("CDO.Configuration")

  Confg.Load -1
  Set Flds = Confg.Fields
  With Flds
      .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
      .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
      .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = nUserName
      .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = nPassword
      .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = nOutGoingServer
      .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
      .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = nServerPort
      ' If using internet proxy
      .Item("http://schemas.microsoft.com/cdo/configuration/urlproxyserver") = nIntProxyPort
     .Update
  End With

  nMessage = nMessage & vbNewLine & vbNewLine & _
  "THIS IS AN AUTOMATED REPSONSE FROM ADMIN"

  With Msg
      Set .Configuration = Confg
          .To = nTo
          .From = nFrom
          .Subject = nSubject
          .TextBody = nMessage
          .Send
  End With

End sub

I'm wondering if this software built in some sort of cdo.dll class instantiating block so you have buy their software GUI version. Any help would be great. Thanks.

A: I solved this issue by using a different library: cdosys.dll instead of cdo.dll, reference: Microsoft CDO For Windows 2000 Library.


text:
Q: Jenkins pipeline how to change to another folder and run npm tests Currently, I am using Jenkins pipeline script.
For running my tests, I need to access my code which is sitting on the desktop.
I tried this:
pipeline {
  agent any

  tools {nodejs "node"}

  stages {
    stage('Tests') {
      steps {
        sh 'cd users/tests/'
        sh 'npm run shopfloor.shopfloor'
      }
    }
  }
}

How I can change to my test folder and then run "npm run test"
I tried the answer below however i am getting this error now:
Running in users/tests/
[Pipeline] {
[Pipeline] sh
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
+ npm run shopfloor.shopfloor
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted
Error: EPERM: operation not permitted, uv_cwd
    at process.wrappedCwd (internal/bootstrap/switches/does_own_process_state.js:129:28)
    at process.cwd (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:10:19)
    at Conf.loadPrefix (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/lib/config/load-prefix.js:46:24)
    at load_ (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/lib/config/core.js:109:8)
    at Conf.<anonymous> (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/lib/config/core.js:96:5)
    at Conf.emit (events.js:315:20)
    at ConfigChain._resolve (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/node_modules/config-chain/index.js:281:34)
    at ConfigChain.add (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/node_modules/config-chain/index.js:259:10)
    at Conf.add (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/lib/config/core.js:338:27)
    at Conf.<anonymous> (/Users/.jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/node/lib/node_modules/npm/lib/config/core.js:314:25)
internal/bootstrap/switches/does_own_process_state.js:129
    cachedCwd = rawMethods.cwd();

A: Use the dir step to switch the directory and execute the commands in that context:
pipeline {
  agent any

  tools {nodejs "node"}

  stages {
    stage('Tests') {
      steps {
        dir('users/tests/') { // <<------------
          sh 'npm run shopfloor.shopfloor'
        }
      }
    }
  }
}

A: Please try once using double quotes.
dir("folder")

in groovy Single quotes are a standard Java String while Double quotes are a templatable String.


text:
Q: c# - Invoke button_click event handler in a method I have a Start and a Done button on a windows form, and I have vehicles stored in a list.
 private void btnStart_Click(object sender, EventArgs e) {
        Start();
    }

 private void Start() {
  for (int i = 0; i < vehicles.Count; i++) {
                txtLicensePlate.Text = vehicles[i].LicensePlate;
  }

So by clicking on the start button makes the txtLicensePlate textbox show the car's license plate number one by one.
But before moving on from a license plate number, I would like the for loop to wait for a button click.
        private void btnDone_Click(object sender, EventArgs e) {
        Add();
    }

I tried to invoke the event handler like this:
 private void Start() {
  for (int i = 0; i < vehicles.Count; i++) {
                txtLicensePlate.Text = vehicles[i].LicensePlate;
  btnDone_Click(sender, e);
  }

But I got an error message saying, that "sender and e does not exist in the current context".
And on the other hand it seems I want the loop to trigger the button click on it's own (which is not my intention), and this leads to my question:
How can make the for loop to wait for a button click by the user?
Edit: Seems like I caused a little confusion, so I'd like to clarify:
The Start button would start the loop showing the first license plate number. Then the user can "tell" if the current vehicle will go for a run, and if it will how many kilometres it will run. When the user clicks the Done button, the amount of kilometres will added to the vehicle, and the next license plate number should be shown.

A: You should call the PerformClick method of the Button.
That said, why not just call the Add method at the end of the Start method?  That's what you really want to achieve and clicking the btnDone is simply a means to that end so why not just go straight to the end instead of trying to artificially invokes the means?

A: I am going to take a guess at answering what I think you are trying to do.
Edit Based on your update to the question, this is probably how I would solve the issue.  One thing to note, you probably want to disable the start button once you begin looping through the vehicles.  You could do that within the btnStart_Click event handler.  Depending on your goals, you may want to have a way to re-enable it with either a reset button or when you have reached the end of your list.  I don't know what you want to happen when you reach that point, so I updated the done handler code to check for the end of the list, but you would need to determine what to do when the end of the list is reached.
Instead of having a loop in your Start button code, have the Start method just place the initial string into the TextBox.  You will then just need to store the current position in the list and you can update the next license plate from your Done button.
private int _currentVehicleIndex;

private void btnStart_Click(object sender, EventArgs e) {
    txtLicensePlate.Text = vehicles[0].LicensePlate;
    _currentVehicleIndex = 1;
}

private void btnDone_Click(object sender, EventArgs e) {
    Add();
    if (_currentVehicleIndex < vehicles.Count)
    {
        txtLicensePlate.Text = vehicles[_currentVehicleIndex].LicensePlate;
        _currentVehicleIndex++;
    }
    else
    {
        // Handle the case where we have reached the end of the list
        // clear the license plate text, reset form, etc...
    }
}


text:
Q: compare two datetime fields in apex Comparing two date time fields and if they are equal, greater, lesser than then i am doing some logic
 DateTime currentDate  = DateTime.Now();
 DateTime previousDate = currentDate.addDays(+0);
 // Set date times to dates
 currentDate = Datetime.Now();
 previousDate = previousDate.Date();
 System.debug('Current Date: ' + currentDate);
 System.debug('Previous Date: ' + previousDate);
 System.debug(previousDate  == currentDate);

how ever in the debug i am getting false...
how to overcome this??

A: If you want to compare Date-Times as Dates, just use prevStartDat.Date() and currStartDate.Date() to convert them to Date values. See the date-time class for more.


text:
Q: How to position a ListView in Android? I want to put a ListView at the top of my activity, and something else on the bottom without the ListView "swallowing" the widgets on the bottom? I tried this (with the "something else" being a RelativeLayout with a single button in it), but it doesn't work.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom" >

    </ListView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="bottom" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="Button" />

    </RelativeLayout>

</LinearLayout>

I looked for some hints here, which is very useful, but doesn't say anything about ListViews. I can place widgets above a ListView without problem, but not below.

A: Use a RelativeLayout as the root layout then position the ListView with layout_above and the Button with layout_alignParentBottom:
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/button" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Button" />

</RelativeLayout>

A: I'm sure this is already answered several times on SO...
Change your layout like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_gravity="bottom" >

    </ListView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="Button" />

    </RelativeLayout>

</LinearLayout>


text:
Q: $regexMatch alternative for MongoDB < 4.2 I have MongoDB 4.0 and was wondering if the functionality of $regexMatch operator can be achieved in versions earlier than 4.2 similar to below that returns a boolean.
'$regexMatch': {
    'input': '$field1',
    'regex': '$field2'
}

A: I don't think any alternate option available for $regexMatch operator below MongoDB 4.2.

You can try the below option, it will match words, we can not say this is an exact regex match,

*

*$split to split field1 string by space

*$map to iterate loop of above split string's array and match $in condition if word available in field2 split string's array

*$allElementsTrue to check all elements in available in field2 then return true otherwise false

db.collection.aggregate([
  {
    $addFields: {
      matchResult: {
        $allElementsTrue: {
          $map: {
            input: { $split: ["$field1", " "] },
            in: {
              $in: ["$$this", { $split: ["$field2", " "] }]
            }
          }
        }
      }
    }
  }
])

Playground


text:
Q: Django form not saving if I use action attribute For context, here is the view.py
from .forms import SignIn

...

def sign_in_view(request, *args, **kwargs):
    form = SignIn(request.POST or None)
    if form.is_valid():
        form.save()
        form = SignIn(request.POST or None)

    context = {
        'form': form
    }
    return render(request, "accounts/sign_in.html", context)

here is the HTML file for accounts/sign_in.html
{% extends "accounts/base.html" %}

{% block title %}
<title>Log-in</title>
{% endblock %}

{% block content %}

Sign in

<form method="POST" action="http://127.0.0.1:8000/home/">  # currently in localhost
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Sign in">
</form>
{% endblock content %}

Without the attribute action="http://127.0.0.1:8000/home/" in my form tag in accounts/sign_in.html, I manage to successfully add a user to the database by typing in the required parameters on the browser.
However, with the attribute action="http://127.0.0.1:8000/home/", I was redirected to the URL, but when I checked the database in /admin/, I was unable to see the user there.
I don't know if the form isn't saved, or I had just done some stupid mistake.
Thanks.

A: This is a better way for the user to register.
view.py
 def sign_in_view(request):
 form = SignIn(request.POST or None)

 if form.is_valid():
     user = form.save()
     username = form.cleaned_data.get('username')
     password = form.cleaned_data.get('password')

     user = authenticate(request, username=username, password=password)

     if user is not None:
         login(request, user)
     return redirect('/')

  context = {
    'form': form
}

 return render(request, "accounts/sign_in.html", context)

and than in you template you can do this
{% extends "accounts/base.html" %}

 {% block title %}
 <title>Log-in</title>
 {% endblock %}

  {% block content %}

Sign in

  <form method="POST" action="">  # currently in localhost
    {% csrf_token %}
    {{ form.as_p }}
   <input type="submit" value="Sign in">
 </form>
 {% endblock content %}

A: Action attribute is not for redirection after sending the form. It should be the url attached to the view that is responsible for handling a form. What is the url of your sign_in_view? If it is for example /sign-in/ that should be value of action attribute. If you want to redirect user after signing in, do it in your   sign_in_view:
 if form.is_valid():
     ...
     return redirect('/home/')

Here is a link for Django docs that includes all the useful information about forms:
https://docs.djangoproject.com/en/3.0/topics/forms/


text:
Q: How to scrape using simple html dom when no hierarchy in HTML

Screen: 3

    1:00
    11:00
    13:00
    15:00

Screen: 4

    12:05
    14:05
    16:05
    18:05
    20:05

Screen: 3 (3D)

Above is the HTML i'm ing.
I want to take the data in  for screen 3 and Screen 4 separately.
This is my code below but it takes data from all the s
foreach($cinema->find("td.cinetime span") as $times) {
    echo $times->plaintext;
}

A: You need to go over all elements inside td.cintime and check if  text is what you need (like Screen: 3) and then check if other element is span, then put it in some array till you get another div. It means one screen block is over. Repeat till you get everything you need.
Pseudo code:
$screensData = array();
$start = false;
foreach($cinema->find("td.cintime *") as $times) {
   if($times->tag == 'div') {
      $start = false;
      if($times->plaintext == 'Screen: 3') {
         $screensData[3] = array();
         $start = 3;
      }
   }

   if($start && $times->tag == 'span') {
      $screensData[$start][] = $times->plaintext;
   }
}

A: Something like this:
$dom = new simple_html_dom();
$dom->load($source);

$cinetime = $dom->find('.cinetime',0);

$screens = array();
$screenName = '';

foreach($cinetime->children() as $elem){
    if($elem->tag == 'div'){
        $screenName = $elem->innertext;
    } else
    if($elem->tag == 'span'){
        $screens[$screenName][] = $elem->innertext;
    }
}
print_r($screens);

That produces this:
Array
(
[Screen: 3] => Array
    (
        [0] => 1:00
        [1] => 11:00
        [2] => 13:00
        [3] => 15:00
    )

[Screen: 4] => Array
    (
        [0] => 12:05
        [1] => 14:05
        [2] => 16:05
        [3] => 18:05
        [4] => 20:05
    )

)

?


text:
Q: Filter files globally in the Documents and Media portlet in Liferay I have my Liferay organizations set up like this:
North America
      |
   |     |
 Dept1  Dept2

What I would like to do is allow Dept1 and Dept2 to view any documents posted in North America (as read only), but prevent Dept1 from viewing Dept2's documents and vice versa.
For example, a vacation request form will be posted in North America that both Dept1 and Dept2 should be able to read but not modify. However, if Dept1 posts a sign up sheet for the Dept1 golf tournament, Dept2 should not be able to view this.
I've successfully managed to set up something similar to this by creating multiple sites, but I'd to be able to view all these files in the same portlet rather than the user having to switch between their Dept site and the North American site.

A: Okay, I've implemented something similar myself (this is the only way I could figure out how to do this).
1) Create two Regular Roles, one for each department

2) Assign the appropriate new roles to each user

3) Within Documents and Media create your documents/media/folders (e.g. Dept. 1 Files / Dept. 2 Files folders)

4) Define their permissions - see above image for where to click - (e.g. for Dept. 1 Files folder uncheck everything for the Department 2 role, also make sure guest can't do stuff)

5) For the global folder (North America), just set the permissions so both roles can have full permissions
Hope I've understood you correctly and this helps.


text:
Q: Getting an error when trying to create a tarball of my Redhat VM I'd appreciate some assistance as to where I'm going wrong please.
Ultimately my objective is to have Redhat available via Windows Subsystem for Linux.
Reading the instructions on the following website ....
https://learn.microsoft.com/en-us/windows/wsl/use-custom-distro
Apparently you can import a tarball of any OS that you create, so with that in mind I created a Redhat 9.1 VM via HyperV and intended to tar the contents up.
I initially tried this command "tar -cvf /rh9.tar *" (I know if this command had worked I may have ended up with a recursion type error where it tried to add itself to the archive) but it didn't work and I ended up getting an error similar to this one:
tar: /mnt/rh9.tar: Wrote only 6144 of 10240 bytes
tar: Error is not recoverable: exiting now

I then created a virtual disk of 500Gb and mounted it under /mnt and tried again - and received the error I showed above, however this time I used the following command:
tar -cvf /mnt/rh9.tar -exclude /mnt /

Looking at the file in /mnt it is basically nearly 500Gb large, but I can't understand how this can be as when I do a "df -h" I see the following:
Filesystem             Size  Used Avail Use% Mounted on
devtmpfs               4.0M     0  4.0M   0% /dev
tmpfs                  1.8G     0  1.8G   0% /dev/shm
tmpfs                  731M  8.9M  722M   2% /run
/dev/mapper/rhel-root   70G  4.4G   66G   7% /
/dev/sdb2             1014M  277M  738M  28% /boot
/dev/sdb1              599M  7.0M  592M   2% /boot/efi
/dev/mapper/rhel-home   52G  413M   52G   1% /home
tmpfs                  366M   36K  366M   1% /run/user/1000

Adding up all the disk space in use results in a number well less than the 500Gb - can anyone give some pointers as to what I'm doing wrong please?

A: This method is advised in the post
How would I use tar for full backup and restore with system on SSD and home on HDD?
sudo su
cd /
tar -cvpzf backup.tar.gz --exclude=/backup.tar.gz --one-file-system /
tar -cvpzf backuphome.tar.gz --one-file-system /home/

The second command is to be used if home is on a different partition
than root.
Note that the backup file is excluded, in order to avoid looping.


text:
Q: Migrating Windows scheduled tasks or windows services to Azure Web Jobs We have couple of scheduled tasks associated with web application which we plan to move to Azure. Some are console apps and using Windows task scheduler to run them in time intervals.
Some are in form on windows services and we have pragmatically scheduled the tasks in threads. These tasks may connect to SQL database, cleanup storage or even send bulk emails to users.
What are the recommendations for moving those to Azure. Webjobs is the prime candidate so far we found. Basically our requirement is scheduling and monitoring. Any suggestions, samples or links to resources are welcome.

A: Another option to shchedule tasks is "Azure Function", it's based on the webjob SDK and it offers "Webjobs as a Service", no deployment is necessary.
Morover you can use a "dynamic service plan" with Azure Functions, with this service plan you pay only when the function is running.
Here is a post which compare Azure Functions and Webjobs.


text:
Q: android resources not found after moving I am creating an Android keyboard with Eclipse. I want to implement popup keyboards which show up when you long press a key.
Therefore I assigned the
android:popupKeyboard="@xml/a_popup"

property to the key-tag and created a popup keyboard under "res/xml/a_popup.xml"
That works fine, but since I want a lot of different popup keyboards and I don't want them all to be directly in "res/xml/", so I moved the "a_popup.xml" file to "res/xml/popup_keyboards/"
But now I can't make a reference to the xml-file any more from my popupKeyboard-property by saying
android:popupKeyboard="@xml/popup_keyboards/a_popup"

If I do so, I get the message, that there is no resource which matches the given name. There is also no entry in the R.java file, although I cleaned the project.
I also tried to reference the popup keyboard by an ID but then I get a ResourcesNotFound Exception everytime I longpress the button.
Has anybody an idea why this happens?

A: You can't use nested lists in resources in Android. "res/xml/popup_keyboards/" - it's wrong, you can't create directories under xml dir, only files.