text:
Q: Solving an algebraic exercise using only one variable $x$ This exercise is supposed to be solved using only one  though I don't see how would that be possible.
Could someone tell how to solve using only one unknown variable $x$?
Thank you.
Exercise.
The sum of two numbers is $108$ and the double of the greater exceeds the triple of the minor in $156$. Find the numbers.
I solved using two variables $x$ and $y$ and specifying that $x>y$.

A: So let's piece this together:
"The sum of two numbers is $108$" - this gives us $x+y = 108$
"the double of the greater exceeds the triple of the minor in 156"- Without loss of generality, we can assume $x>y$, and thus see $2x - 3y = 156$.
Thus, we have a system of equations, which we seek to find $x$ and $y$:
$$x+y = 108$$
$$2x - 3y = 156$$
You could solve this by whatever method you prefer to do so. Since you seek to use only one variable, notice that the first equation implies $y = 108-x$, yielding
$$x+(108-x)= 108$$
$$2x - 3(108-x) = 156$$
This is a technique known as solving by substitution: solving for one of the variables and then substituting the resulting expression into the other equations.
Notice, too, if you used the second of the equations from our original system, you could have found
$$y = \frac{156-2x}{-3}$$
You also could solve for $x$ instead and use that as your substitution! Using the first equation,
$$x = 108-y$$
or perhaps using our second equation
$$x = \frac{156+3y}{2}$$
Any of these four substitutions is completely valid. These substitutions turn one of the equations into a true statement (notice how our original substitution turned the first equation, after simplifying, into $108=108$?). The other equation then becomes an equation of just one variable (after simplifying, the second equation in our original substitution becomes $-x-324=156$).
This also is a valid method if you have $n$ equations in $n$ variables, too, but it can become more complicated since you have to solve for all but one of the variables and substitute them into an equation. It can get messy pretty fast.

A: If one of the numbers is $x$ and the sum of the two is 108, the other number is $108 - x$.  If $x \ge 108 - x$, we write
$2x = 3(108 - x) + 156; \tag 1$
$2x = 324 - 3x + 156 = 480 - 3x; \tag 2$
$5x = 480; \tag 3$
$x = 96; \tag 4$
$108 - x = 12. \tag 5$
OR, if $108 - x \ge x$,
$2(108 - x) = 3x + 156; \tag 6$
$216 - 2x = 3x + 156; \tag 7$
$5x = 60; \tag 8$
$x = 12; \tag 9$
$108 - x = 96. \tag{10}$


text:
Q: Using a Query instead of a for loop Is there a way to do the following in a single line with a django query?
providers_with_no_contacts = []
for provider in Provider.objects.all():
    if not provider.userprofile_set.all():
        provider_with_no_contacts.append(provider)

Or a better way than this?
providers_with_no_contacts = [provider for provider in Provider.objects.all()
                               if not provider.userprofile_set.all()]

A: Provider.objects.filter(userprofile__isnull=True)

A: providers_with_no_contacts = Provider.objects.filter(userprofile_set=None)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Align 2 TextViews one under other but centered to their relative parent I'm trying to center a TextView under another one (it's centering), but I'm getting this

The 2 items are not aligned correctly (as I'd want)
I'm looking for something like this:

You can see both items centered, not just the bigger one
my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/r1"
android:clickable="true"
android:background="?android:selectableItemBackground"
android:layout_height="?android:attr/listPreferredItemHeight"
>
   <ImageButton
        android:id="@+id/status"
        android:layout_width="wrap_content"
    android:background="@null"
        android:paddingRight="6dp"
        android:layout_height="fill_parent"
        android:src="@drawable/download"
        android:layout_centerVertical="true" />
    <TextView
        android:id="@+id/descricao"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:text="Texto de baixo"
        android:singleLine="true"
        android:typeface="serif"
        android:textSize="10sp"
        android:layout_centerVertical="true"
        android:layout_below="@+id/titulo"
        android:layout_toRightOf="@+id/status" />
    <TextView
        android:id="@+id/titulo"
        android:textStyle="bold"
        android:text="Text Title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textSize="16sp"
        android:layout_toRightOf="@+id/status" />
</RelativeLayout>

EDIT
Thanks Der Golem, your answer made the trick, but I got another problem, the text when it gets more than one line, is there a way not to hide it behind the below text, and align it again?

A: You are nearly there: Observe the drawing.
Be the red line a generic View (let's give it an id of vwDummy), aligned to the center of the row (android:layout_centerInParent="true").
Let its dimensions be 0dp and 0dp.
Then Just put the title above it (android:layout_above="@id/vwDummy").
And put the lower text below it (android:layout_below="@id/vwDummy").

A: Just change the layout_height of the parent layout to wrap_content from "?android:attr/listPreferredItemHeight"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/r1"
android:clickable="true"
android:background="?android:selectableItemBackground"
android:layout_height="wrap_content"
>
<ImageButton

        android:id="@+id/status"
        android:layout_width="wrap_content"
    android:background="@null"
        android:paddingRight="6dp"
        android:layout_height="fill_parent"
        android:src="@drawable/download"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/descricao"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:text="Texto de baixo"
        android:singleLine="true"
        android:typeface="serif"
        android:textSize="10sp"
        android:layout_centerVertical="true"
        android:layout_below="@+id/titulo"
        android:layout_toRightOf="@+id/status" />

    <TextView
        android:id="@+id/titulo"
        android:textStyle="bold"
        android:text="Text Title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textSize="16sp"
        android:layout_toRightOf="@+id/status" />

</RelativeLayout>


text:
Q: Unable to execute binary file. Exec format error I recently heard about Breach, a Node.js based browser. I was following the instructions from here to install it but got the following error :
breach-v0.3.22-alpha.6-linux-x64/__AUTO_UPDATE_BUNDLE__/exo_browser/exo_browser: cannot execute binary file: Exec format error
After some googling, I found that it is because I am trying to install the 64 bit package on the 32 bit Ubuntu installation. I tried to find 32 bit package of the same but ended up with no luck. The browser is only available in 64 bit packet(as far as i know).
So, My question is :
Is it possible to somehow install it on the 32 bit OS or if any program available which can run 64 bit applications on the 32 bit OS.
I have been googling around and found no help. Can anyone help me?
I am using Ubuntu 14.04 (32 Bit).

A: If you have a 32-bit OS, then you need to have 32-bit applications.  The only way to get 64-bit applications to run is to run them under a 64-bit OS.  BTW, it is possible to run 32-bit applications under a 64-bit OS.
So the suggestion here:

*

*Find and use the 32-bit package

*Find the source, do a full recompilation for a 32-bit system, install and use that.

*Upgrade your system to a 64-bit Ubuntu.

A: You can't run 64-bit executables on a 32-bit kernel:
Can I run 64-bit executables on a 32-bit Linux?
A poster on that thread suggested using an emulator (i.e. emulating a 32-bit architecture).
This may sound a bit unhelpful, but it's usually best to go with a 64-bit install unless you have a specific need for 32 (i.e. hardware-related) as it's easier to run 32-bit software on a 64-bit kernel.


text:
Q: Examples of non-trivial fexpr usage I'm looking for (real world) uses of fexprs, where they are used in a way different to what can be accomplished with lazy evaluation.
Most examples that I could find use fexprs only to implement conditional evaluation, like for a short circuit "and" operative (Evaluate first argument, if false, don't evaluate second and directly return false).
I'm looking for "useful" uses, that is where using fexpr leads to code that is "better" (cleaner) than what could be done without fexprs.

A: There are two main reasons you would want to use fexprs.
The first one is because they allow you to evaluate the arguments an arbitrary number of times. This makes it possible to implement operators that evaluate their arguments lazily like you suggested. Constructs built this way are also capable of evaluating their arguments more than once. This makes it possible to implement loops through fexprs!
The other case is for transformation. Transforming code is basically a way of writing a compiler on top of your existing Lisp. Although it uses macros and not fexprs, cl-who is a great example of the kind of transformations that can be made.

A: Fexpr are somewhat orthogonal to lazy/eager evaluation.
The usual function approach is to eval the arguments to a function then call it on the result. Lazy eval still behaves like this, it just delays the evaluation until immediately before the parameter is used.
The usual macro approach is to pass the unevaluated arguments into a template which evaluates anything that isn't quoted. The resulting piece of AST is injected into the call site where it is usually evaluated again. This works much the same with lazy eval.
The historically insane fexpr approach is to pass unevaluated arguments to the function, which does as it pleases with them. The result is injected directly into the call site and usually not evaluated automatically.
The fexpr is pretty close to an arbitrary transform. So you can implement macros and lambdas with them. You can also implement whatever hybrid of eager/lazy evaluation you wish. Likewise you could implement fexpr given default lazy eval and explicit calls to eval() in various places to force eager behaviour.
I don't think I would characterise fexpr as an easy solution to implementing lazy eval though, in a cure is worse than the disease sense.


text:
Q: Casting from int* to char* in c++
*

*line 1 prints 'X'

*line 2 prints 'c'

*line 3 prints 11

*line 4 prints 5.

I   understand these lines but why does

*

*line 5 print 20

?
Should it not print   11 instead of 20 since line 1 and 2 print 'X' and 'c'.
Your help is much appreciated.
#include "iostream"
using namespace std;
int main()
{
int arr[] = {88, 20, 30, 40, 50, 99};
int *ptr1 = arr;
int *ptr2 = arr + 5;
cout<<(char*)ptr1<<endl;//line 1
cout<<(char*)ptr2<<endl;//line2
cout<<('c'-'X')<<endl;//line3
cout<<ptr2-ptr1<<endl;//line4
cout<<(char*)ptr2-(char*)ptr1<<endl;//line5

return 0;
}

A: In the environment where the program was compiled sizeof( int ) is equal to 4. That is each object of type int occupies 4 bytes (characters). Between ptr2 and ptr1 there are 5 integers. The difference of two pointers that point to elements of the same array is the number of elements between them.
It is so-called pointer arithmetic. Thus ptr2 - ptr1 gives 5. But if you will cast these pointers to type char * then between these pointers there are 5 * sizeof( int ) characters that is equal to 20.

A: Because of (char*)ptr2-(char*)ptr1 is the difference of addresses. Then 5*sizeof(int) = 20 in your (I guess) 32 bits platform.

A: TO get the output what you are expecting use:
(char)*ptr2-(char)*ptr1

A: The answer is absolutely correct let me explain your anwer step by step according to code:
cout<<(char*)ptr1<<endl;//line1

Since ptr1 = arr, therefore first char is 88 and thus printed X
cout<<(char*)ptr2<<endl;//line2

Since ptr1 = arr +5, therefore fifth char is 99 and thus printed c
cout<<('c'-'X')<<endl;//line3

Since the value of 'c' =99 and 'X' = 88 thus answer is 11
cout<<ptr2-ptr1<<endl;//line4

Since the arr is an array and distance between 5th and 0th element 5-0 = 5
cout<<(char*)ptr2-(char*)ptr1<<endl;//line5

What here happens there you are subtracting two address and answer is provided as differance of two addresss, for instance
 (char *)ptr1 --- Address = 10
 (char *)ptr2 --- Address = 30

and if we subtract both then 30-10=20. Why it is 20 as it depends on the sizeof void *
32 bit sizeof void* = 4
64 bit sizeof void* = 8

Thus on 32 bit system answer would be 4*5=20 and on 64 bit system it would be 8*5=40

A: The first ptr1 points to these bytes in memory: 88,0,0,0 - which is the first index in array.
The ptr2 points to these bytes in memory: 99,0,0,0.
So the first two lines are outputting two null terminated strings: X and c.
The third line is outputting the difference between chars c and X, which is int value.
The fourth value is difference between two pointers in respect to on what these pointers are pointing to (relative position in array). This is an int number.
The last is cast to char*, where char is 1 byte, which makes it 4 times smaller then int (int is 4 bytes big). So the difference is (array position difference) * (size of int) = 5 * 4 = 20. This value is int so that is why you see number 20.
Try to change all those ints in to char and see the difference:
char arr[] = { 88, 20, 30, 40, 50, 99 };
char *ptr1 = arr;
char *ptr2 = arr + 5;

Suddenly these first two lines are no longer one chars, because there is no longer the 0 terminator for (char*) strings.
X¶▲(2c╠╠╠╠╠╠╬H@▼ñ¸4
c╠╠╠╠╠╠╬H@▼ñ¸4
11
5
5
This will vary between debug and release.


text:
Q: How to run C++ code in a sandboxed environment using docker client in Golang I am trying to build a code evaluation service for online judge.

*

*It will get C++ code along with some problemId.

*Then we fetch test cases, judging code, time and memory limits against the give problemId.

*Finally we run the code, the run the judge against the received output to evaluate the verdict - TLE,MLE, etc.

To do this currently I am thinking to spin up docker container with fixed CPU time and memory limit and then run the code inside of it. But there are some problems:

*

*How to read the test case and answer inside the container?

*How to create image with preinstalled compiler to run c++ code?

*How to determine the maximum number of docker container that should be running concurrently?

*Should the evaluation code run in the same container as the original code ran.

*Finally is there a better approach than docker for this objective?
I am just going through docker client documentation. https://pkg.go.dev/github.com/docker/docker/client


text:
Q: ZSH Equivalent to Bash `_command` completion Given an example wrapper shell function:
app() {
    setsid "$@"
}

In Bash, you can do complete -F _command app to automatically give app completions for all commands (not just binaries on the path but also the arguments afterwards).
How can you do this in ZSH? I have some leads with _normal and -command-line- but I've been unable to figure out the correct command to put in a .zshrc.
Update:
Just wanted to document something interesting, this produces a SIGSEGV:
autoload -U compinit && compinit
compdef _normal app

# Attempt tab completion of app:
# _normal:1: maximum nested function level reached; increase FUNCNEST?

FUNCNEST=999

# Attempt tab completion of app again
# !!! ZSH crashes (see coredumpctl) !!!

A: Figured it out:
# Set up autocomplete
_app() {
    shift words
    (( CURRENT-- ))
    _normal
}
autoload -U compinit && compinit
compdef _app app

This was somewhat of a duplicate of this question: How do I dynamically select a completion function in zsh?
If someone knows a shorter solution like what Bash has then please answer as that would be nice.


text:
Q: How to load csv files from the internet into an Access database? I have the following array that contains ticker symbols: Public Shared tickerArray() As String = {"GOOG", "AAPL", "V", "MSFT"}. I need to use this loop: For Each tickerValue In Form1.tickerArray to load the csv file for each ticker symbol into one large table in Microsoft Access.  The csv files are located at "http://ichart.yahoo.com/table.csv?s=" & tickerValue.  I also need the respective ticker symbol to be loaded into each line of the table that is imported from the csv file in order to make each line unique.  So the columns in the database should be: "Ticker, Date, Open, High, Low, Close, Volumne & Adj Close".
I've found information about loading a local csv file into Access but I can't seem to figure out how to load csv files from the internet into Access through vb.net.
Also, I will need to update this table frequently so I need to only insert new unique lines from the csv file.  No duplicates.
Any suggestions?  Thanks!
UPDATE:
Here is the code I have so far.
Imports System.Data
Imports System.Data.OleDb
Imports System.Net
Imports System.IO

Public Class Form1

Public Shared tickerArray() As String = {"GOOG", "AAPL", "V", "MSFT"}

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
    Dim myConnection As OleDbConnection
    Dim DBpath As String =
    Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
    myConnection = New OleDbConnection(sConnectionString)
    myConnection.Open()

    Dim strURL As String
    Dim strBuffer As String
    For Each tickerValue In Form1.tickerArray
        'Creates the request URL for Yahoo.
        strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
        strBuffer = RequestWebData(strURL)
        'Create array.
        Dim sReader As New StringReader(strBuffer)
        Dim List As New List(Of String)
        Do While sReader.Peek >= 0
            List.Add(sReader.ReadLine)
        Loop
        Dim lines As String() = List.ToArray
        sReader.Close()
        For Each Line In lines.Skip(1)
            MsgBox(Line)
            Dim myInsert As String = TextToInsert(Line, tickerValue)
            Dim cmd As New OleDbCommand(myInsert, myConnection)
            cmd.ExecuteNonQuery()
        Next
    Next
End Sub

Function TextToInsert(ByVal inputString As String, ByVal ticker As String)
    Dim Dt As String = inputString.Split(",")(0).Trim
    Dim Open As String = inputString.Split(",")(1).Trim
    Dim High As String = inputString.Split(",")(1).Trim
    Dim Low As String = inputString.Split(",")(1).Trim
    Dim Close As String = inputString.Split(",")(1).Trim
    Dim Volume As String = inputString.Split(",")(1).Trim
    Dim Adj_Close As String = inputString.Split(",")(1).Trim
    Dim SQLstr As String
    SQLstr = "INSERT INTO Historical (Ticker, Date, Open, High, Low, Close, Volume, Adj Close) " & "VALUES (" & "'" & ticker & "','" & Dt & "','" & Open & "','" & High & "'," & "'" & Low & "','" & Close & "','" & Volume & "','" & Adj_Close & "'" & ")"
    Return SQLstr
End Function

Private Function RequestWebData(ByVal pstrURL As String) As String
    Dim objWReq As WebRequest
    Dim objWResp As WebResponse
    Dim strBuffer As String
    'Contact the website
    objWReq = HttpWebRequest.Create(pstrURL)
    objWResp = objWReq.GetResponse()
    'Read the answer from the Web site and store it into a stream
    Dim objSR As StreamReader
    objSR = New StreamReader(objWResp.GetResponseStream)
    strBuffer = objSR.ReadToEnd
    objSR.Close()

    objWResp.Close()

    Return strBuffer
End Function

End Class

I get error code "OleDBException was unhandled.  Syntax error in INSERT INTO statement." at line cmd.ExecuteNonQuery() Please help!

A: you may use the System.Data.OleDb Namespace to define function to make insert into the db.
Something like (in a very rough way):
Dim myConnection As OleDbConnection

Dim sConnectionString  As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"

myConnection = New OleDbConnection(sConnectionString)

myConnection.Open()

Then make a cycle on each line in the csv
Dim myInsert as String= functionTextToInsert(inputString)

Dim cmd As New OleDbCommand(myInsert, myConnection)

cmd.ExecuteNonQuery()

The functionTextToInsert(ByVal inputString as string) is a function that converts a line from the csv in a insert string: "max;min;vol" -> "Insert into MYTABLE (Column_01,Column_02,Column_03) VALUES (max,min,vol);"

A: Try this:
Writing large number of records (bulk insert) to Access in .NET/C#
I've never worked with DAO, so I can't be much help here, but...
if this MSSQL syntax works on MS ACCESS, use a command object and pass it a parameter containing your csv as a varchar(max), or similar access data type, which will the content of the CSV from your app:
BULK
INSERT mytable
FROM @myCSVstring
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

Two things, the SO post states that DAO is a lot faster, and your terminators may be different, but I'd start with these.

A: I think the previous answers are unnecessarily complicated. All you need to do it send an XMLHTTP request. That fetches the CSV data as a string, which can then be parsed into a table.
Below is a VBA subroutine that does that. Documentation of where I found the techniques is in the code comments. I've run this in Access 2019, and it works.
The modifications of the data indicated in the question can be performed before or after inserting the data into the table.
Sub pImportOnlineCsvAsTable(sURL As String, sTableName As String, Optional sKey As String)

' Download a CSV file from the Internet and parse it into an Access table (all strings).

' Adapted from "www.stackoverflow.com/questions/52142757/vba-download-csv-from-a-link/#52175815"
'   This shows how to download an online CSV file into an ADO stream, then save it as a local file.
' and "www.stackoverflow.com/questions/33860833/convert-adodb-binary-stream-to-string-vba/#33883789"
'   This shows I don't need the stream, but can use the CSV data as a string and parse it into a table.

' Documentation on "XMLHTTP" object:
'   "https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms760305(v=vs.85)"

Dim oWinHttpReq As Object
Dim oDB As Database
Dim sSQL As String, sCSVdata As String, _
    asCSVrows As Variant, asCSVfields As Variant, _
    nCSVrows As Long, nCSVfields As Integer, _
    nCountRows As Long, nCountFields As Integer

Set oDB = CurrentDb()
Set oWinHttpReq = CreateObject("Microsoft.XMLHTTP")
oWinHttpReq.Open "get", sURL, False
oWinHttpReq.send
If oWinHttpReq.status = 200 Then
    sCSVdata = oWinHttpReq.ResponseText
    asCSVrows = Split(sCSVdata, Chr(10))
    nCSVrows = UBound(asCSVrows) + 1
    asCSVfields = Split(asCSVrows(0), ",")
    nCSVfields = UBound(asCSVfields) + 1
    sSQL = ""
    For nCountFields = 0 To (nCSVfields - 1)
        sSQL = sSQL & "[" & asCSVfields(nCountFields) & "] varchar(255)" & _
                    IIf(nCountFields = nCSVfields - 1, "", ", ")
      Next
    sSQL = "create table [" & sTableName & "] (" & sSQL & ");"
    oDB.Execute (sSQL)
    For nCountRows = 1 To (nCSVrows - 1)
        asCSVfields = Split(asCSVrows(nCountRows), ",")
        sSQL = ""
        For nCountFields = 0 To (nCSVfields - 1)
            sSQL = sSQL & """" & asCSVfields(nCountFields) & """" & _
                        IIf(nCountFields = nCSVfields - 1, "", ", ")
          Next
        sSQL = "insert into [" & sTableName & "] values (" & sSQL & ");"
        oDB.Execute (sSQL)
      Next
    If sKey <> "" Then _
        oDB.Execute "alter table [" & sTableName & "] add primary key ([" & sKey & "]);"
  End If

Set oWinHttpReq = Nothing
Set oDB = Nothing

End Sub     ' pImportOnlineCsvAsTable()


text:
Q: Pass variables in url path to fetch GET request I have this fetch request below, and variables data_type and data_subtype. I want to pass the value of data_type and data_subtype in the place of :type and :subtype respectively, without actually writing the variable values in there.
fetch('http://localhost:3000/feature/type/:type/subtype/:subtype,{
    method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => response.text())
.then(data => {
        console.log(data);
})
.catch(err => {
          console.log(err);
});

A: You can replace with the variable values in the URL.
eg.
const data_type = 'data Type'
const data_subtype = 'data subtype
fetch(`http://localhost:3000/feature/type/${data_type}/subtype/${data_subtype}`,{
    method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => response.text())
.then(data => {
        console.log(data);
})
.catch(err => {
          console.log(err);
});

A: as expanding the @junkie answer, you should put your url request in string literal so where you can use variables which will conditionaly replace the values without actually writing values in there, so just define and replace them.


text:
Q: What are the benefits of writing "functional" Javascript as opposed to OO? I often come across Javascript code snippets that consist of many anonymous functions that are called where they are created, such as here:
var prealloc = (function() {
    // some definitions here

    return function prealloc_win(file, size, perms, sparseOk) {
        // function body
    };
})();
// can be called like this:
prealloc(...);

So this calls an anonymous function which returns another function prealloc_win. To me this seems equivalent to instantiating a class where the resulting object exposes the function prealloc_win:
function preallocObj() {
    // some definitions here
    this.prealloc_win = function(file, size, perms, sparseOk) {
        // function body
    };
}
prealloc = new preallocObj();
// can be called like this:
prealloc.prealloc_win(...);

Is this assumption correct? What are the benefits of using anonymous functions that are called directly? And why is this idiom so often seen in Javascript, but not often in other languages which could be written in the same way (C, C++, Python)?

A: You pretty much have the right idea. The benefits of this module pattern/function builder are that the resultant function can enclose its own internal definitions or state.
It's basically just a way to create a function with private variables or constants. Consider the less efficient alternative:
var prealloc = function() {
  // some definitions here
  // function body
}

Every time this function is called it would reassign/instantiate its variables, adding unnecessary performance overhead and overwriting any state data that resulted from previous calls.
This method is useful when there are some variables that are important to the workings of a function that you want only private access to or that you need to persist between invocations without contaminating the outer scope.

A: The deal is that the preallocObj class says that this is something that could be
instantiated multiple times. I could just create more instances of it even though it wasn't really designed for that. You could do some hacks to prevent that but it's easier just to use the immediately invoked anonymous function for this.
With the immediately created and invoked anonymous function, a "class" is created, instantly "instantiated" and assigned to prealloc and
there is no way to reference the original anonymous function that created the prealloc object after this. It was created, invoked and lost.

A: Javascript is fundamentally very different to C++, JAVA and Python and should be written in differnt ways.  At the risk of repetition, Javascript is not an OOP language it is a prototype language.  Douglas Crockford (inventor of JSON) at Yahoo has some wonderful articles and particuarily Videos entitled 'Javascript - the good parts' you should watch them all.


text:
Q: Why does my $http put not actually send any data? I am using the following code block:
app.putConfigs = function () {
    $http({
        data: app.config,
        headers: app.user.getHeaders(),
        url: '/api/Config/Put',
        method: "PUT"
    });
}

As far as I can see this is the same as in the angular documentation. app.config is an object.
When I check with fiddler no JSON data is being sent to the server.
Is there something wrong with the way I am using $http ?

A: I would start with something simple to help diagnose your problem.  See if this works:
$http.put('/api/config', { key: 'test' }).then(function(resp) {
  console.log(resp);
});

Docs ref: https://docs.angularjs.org/api/ng/service/$http#put


text:
Q: C++ Pointer Assignment in custom class constructor So I have a custom class 'Book' that has a bunch of member variables, amongst which are a vector of another custom class called 'Review' and a pointer to point at that vector as I need to pass that around through function calls in a driver program. The driver program reads the details of the each book (such as title, author, publish date etc.) from a text file and inserts into a temporary 'Book' object which it then adds onto a vector of Books maintained by the driver program. Here is the code for reading from the file:
ifstream file("books.txt");
string line;
if(file.is_open())
{
    while(!file.eof())
    {
        Book buffBook;
        getline(file, line);
        buffBook.setTitle(line);
        getline(file, line);
        buffBook.setAuthor(line);
        getline(file, line);
        buffBook.setPubDate(line);
        getline(file, line);
        buffBook.setIsbn(line);
        getline(file, line);
        buffBook.setCategory(line);
        getline(file, line);
        buffBook.setFormat(line);
        getline(file, line);
        buffBook.setSynopsis(line);
        vectBooks.push_back(buffBook);
    }
}

else
    cout<<"File not found(1)!"<<endl;

file.close();

This is running inside a int main() function.
One of the functions of the driver program is to add a review, which takes in data from the user and inserts it into a temporary 'Review' object. That object is then passed onto to be inserted in to the vector of reviews for the corresponding book. Here is the code for the addReview() function:
void addReview()
{
    string name = "";
    string title;
    Book rTemp;
    cin.ignore();
    cout<<"Which book would you like to rate (Title)?: ";
    getline(cin, name);
    name = toLow(name);
    Review r;
    string re, user;
    int ra;
    cout<<"Username (Full Name): ";
    getline(cin, user);
    string fname = user.substr(0, user.find_first_of(' '));
    string lname = user.substr( user.find_first_of(' ') + 1, user.size());
    r.setUsrFName(fname);
    r.setUsrLName(lname);
    cout<<"Enter rating (1-5):";
    cin>>ra;
    r.setRating(ra);
    cout<<"Enter a short textual review: ";
    cin.ignore();
    getline(cin, re);
    r.setReview(re);
    for(unsigned int i = 0; i < vectBooks.size(); i++)
    {
         title = toLow(vectBooks[i].getTitle());
         if(title.find(name) != string::npos)
         {
             vectBooks[i].getReviews()->push_back(r);
         }
    }
}

Now the problem is if i add a review, it adds it for all the books. In other words, when I fetch the book info for any book, the review shows on all the books. I assume this is a problem with the pointer as it seems like all the reviews are getting stored in the same vector. I am not sure where I am messing up but I have a feeling it's with the pointer some where. Any help is appreciated.
Thank You
UPDATE
The point to the title of this problem is that I am doing the assignment of the pointer to the vector of Reviews in the constructor of the Book class, of which those 2 are member variables. Code as follows for constructor:
Book::Book()
{
    pointRev = &vectReviews;
}

UPDATE 2
Here is the code for the Book Class and supporting classes:
book.h
#ifndef BOOK_H_
#define BOOK_H_

#include <string>
#include <iostream>
#include <vector>
#include "review.h"

using namespace std;

class Book
{
private:
    string title;
    string author;
    string pubDate;
    string isbn;
    string category;
    string format;
    string synopsis;
    vector<Review> vectReviews;
    vector<Review>* pointRev;
public:
    Book::Book() : pointRev(&vectReviews) {};
    string getAuthor() const;
    string getCategory() const;
    string getFormat() const;
    string getIsbn() const;
    string getPubDate() const;
    string getSynopsis() const;
    string getTitle() const;
    vector<Review>* getReviews();
    void setAuthor(string author);
    void setCategory(string category);
    void setFormat(string format);
    void setIsbn(string isbn);
    void setPubDate(string pubDate);
    void setSynopsis(string synopsis);
    void setTitle(string title);

    friend ostream& operator <<(ostream& out, Book& book);
    vector<Review> *getPointRev() const;
    vector<Review> getVectReviews() const;
    void setPointRev(vector<Review> *pointRev);
    void setVectReviews(vector<Review> vectReviews);

};

#endif /* BOOK_H_ */

book. cpp
#include "book.h"
string Book::getAuthor() const
{
    return author;
}

string Book::getCategory() const
{
    return category;
}

string Book::getFormat() const
{
    return format;
}

string Book::getIsbn() const
{
    return isbn;
}

string Book::getPubDate() const
{
    return pubDate;
}

string Book::getSynopsis() const
{
    return synopsis;
}

string Book::getTitle() const
{
    return title;
}

void Book::setAuthor(string author)
{
    this->author = author;
}

void Book::setCategory(string category)
{
    this->category = category;
}

void Book::setFormat(string format)
{
    this->format = format;
}

void Book::setIsbn(string isbn)
{
    this->isbn = isbn;
}

void Book::setPubDate(string pubDate)
{
    this->pubDate = pubDate;
}

void Book::setSynopsis(string synopsis)
{
    this->synopsis = synopsis;
}

void Book::setTitle(string title)
{
    this->title = title;
}

vector<Review> *Book::getPointRev() const
{
    return pointRev;
}

vector<Review> Book::getVectReviews() const
{
    return vectReviews;
}

void Book::setPointRev(vector<Review> *pointRev)
{
    this->pointRev = pointRev;
}

void Book::setVectReviews(vector<Review> vectReviews)
{
    this->vectReviews = vectReviews;
}

vector<Review>* Book::getReviews()
{
    return pointRev;
}

ostream& operator <<(ostream& out, Book& book)
{
    out<<"\nTitle: "<<book.getTitle()<<endl;
    out<<"Author: "<<book.getAuthor()<<endl;
    out<<"Publish Date: "<<book.getPubDate()<<endl;
    out<<"ISBN: "<<book.getIsbn()<<endl;
    out<<"Category: "<<book.getCategory()<<endl;
    out<<"Format: "<<book.getFormat()<<endl;
    out<<"Synopsis: "<<book.getSynopsis()<<endl;
    cout<<"\n--- Reviews ---"<<endl;
//  vector<Review>* revs = book.getReviews();
    for(unsigned int h = 0; h < book.getReviews()->size(); h++)
    {
        cout<<"Review by: "<<book.getReviews()->at(h).getUsrFName()<<" "<<book.getReviews()->at(h).getUsrLName()<<endl;
        cout<<"Rating: "<<book.getReviews()->at(h).getRating()<<endl;
        cout<<"Review: "<<book.getReviews()->at(h).getReview()<<endl;
    }

    return out;
}

review.h
#ifndef REVIEW_H_
#define REVIEW_H_

#include <string>

using namespace std;

class Review
{
private:
    int rating;
    string review;
    string usrFName;
    string usrLName;
public:
    int getRating() const;
    string getReview() const;
    void setRating(int rating);
    void setReview(string review);
    string getUsrFName() const;
    string getUsrLName() const;
    void setUsrFName(string usrFName);
    void setUsrLName(string usrLName);
};

#endif /* REVIEW_H_ */

review.cpp
#include "review.h"

int Review::getRating() const
{
    return rating;
}

string Review::getReview() const
{
    return review;
}

void Review::setRating(int rating)
{
    this->rating = rating;
}

string Review::getUsrFName() const
{
    return usrFName;
}

string Review::getUsrLName() const
{
    return usrLName;
}

void Review::setUsrFName(string usrFName)
{
    this->usrFName = usrFName;
}

void Review::setUsrLName(string usrLName)
{
    this->usrLName = usrLName;
}

void Review::setReview(string review)
{
    this->review = review;
}

A: From the behavior you describe, a copy-constructor is running and making two objects that point to the same vector.  push_back does indeed use a copy-constructor.
But your first code snippet doesn't make a bunch of copies of the same Book, but a new Book is created on each loop iteration (and then copied into vectBooks.
If Book doesn't have a correct user-defined copy-constructor then you aren't managing pointRev correctly.  From the observed behavior, I believe that you have a destructor which frees pointRev, and then the copy inside vectBooks is left with a dangling pointer.  Everything after this falls into the category of undefined behavior according to the standard, meaning "anything can happen"  Then the next Book happens to reuse the same memory area, so all the instances of Book end up with the same value in the wild pointer.  And then updating any one changes the vector (which isn't even alive anymore) seen by all Book instances.
Why are you using a pointer to a std::vector anyway?  Much better to just put the vector into the class as a direct data member, which lets the compiler construct, copy, and destruct it automatically with no additional help from you.

Of course, it's entirely possible that you've made vectReviews a global variable, and then every single book points to the same instance.  That would a review show up in all books simultaneously, because they share the vector you're adding it to.


text:
Q: Laravel 5.3 get last insert id after registration Using laravel5.3
php 5.6.3
I want the last inserted id in users table for the redirected page after registration
So I want the last inserted id to userprofileadd.blade.php
I have also tried  ->with('id', $user->id) from register function
I don't want automatic login after registration , so I removed the login part , and after registration the user will be redirected to another form  , and i want the latest user id (who ever registered) from users table
Register controller:
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\role;
use App\Userdetails;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/userprofileadd';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'hr']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [

            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'role'=>'required'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([

            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'role_id'=>$data['role'],
        ]);
    }

    public function showregistrationform()
    {
        $roles = role::all(); // get all teams
    return view('auth.register', [ 'roles' => $roles]);
    }
}

register function (i have commented out login after registration)
 public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

       // $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
            // ->with('id', $user->id)
    }

A: if you are using model then
$user = new User();
$user->name = "JOHN";
$user->save();
$user->id; // contain the inserted id

if you are using db class
$id = DB::table('users')->insertGetId(
   ['email' => 'john@example.com', 'votes' => 0]
);

A: To get the last created user
$user = User::create([

    'email' => $data['email'],
    'password' => bcrypt($data['password']),
    'role_id'=>$data['role'],
]);

$this->lastCreatedUserId = $user->id;

To pass the userId to custom redirection page
You may use the Laravel Auth  redirectTo method. Doc.
protected function redirectTo()
{
    return route('customroutename', ['id' => $this->lastCreatedUserId]);
}

Example:
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\role;
use App\Userdetails;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    public $lastCreatedUser;

    use RegistersUsers;

    protected $redirectTo = '/userprofileadd';

    //The redirectTo method will take precedence over the redirectTo attribute.
    protected function redirectTo()
    {
        //assuming your route name is 'userprofileadd' if not, use your route name of the route('/userprofileadd')
        return route('userprofileadd', ['id' => $this->lastCreatedUser]);
    }

    public function __construct()
    {
        $this->middleware(['auth', 'hr']);
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [

            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'role'=>'required'
        ]);
    }

    protected function create(array $data)
    {
        $user = User::create([

            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'role_id'=>$data['role'],
        ]);

        $this->lastCreatedUser = $user->id;
        return $user;
    }

    public function showregistrationform()
    {
        $roles = role::all(); // get all teams
    return view('auth.register', [ 'roles' => $roles]);
    }
}

You can access the last created user in your UserprofileController's index method like,
public function index($id)
{
    $lastCreatedUser = $id;
    //you may pass this variable to the view
}

Hope it helps.. Let me know the results..

A: I'm not sure if this is what you're looking for or not, but you can do this to retrieve the latest record in the users table:
$latestUser = App\User::latest()->first();

Hopefully this helps.


text:
Q: Magento 2: How to add css class to body tag programmatically I am trying to figure out how to add css class to body tag programmatically using Magento 2 framework

A: You can add a class to the body from a block by overriding the _prepareLayout method:
public function _prepareLayout(){
    $this->pageConfig->addBodyClass('my-class');
    return parent::_prepareLayout();
}

A: I've created an observer to layout_load_before as follows:
...
public function __construct(
    \Magento\Framework\View\Page\Config $pageConfig
) {
    $this->_pageConfig = $pageConfig;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
     $this->_pageConfig->addBodyClass('my-new-body-class');
}

A: Use the following code in layout to add css class or id to the body tag programmatically
   <body>
    <attribute name="class" value="custom-body-class" />
    <attribute name="id value="custom-html-id"/>

For example - open the file customer_account.xml in layout folder
    MagentoDir > vendor > magento > module-customer > view > frontend >layout
after open the customer_account.xml file you can see to add css class
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Customer My Account (All Pages)" design_abstraction="custom">
    <body>
        <attribute name="class" value="account"/>

A: See the following example that I created, this plugin adds the store code to the body class: https://github.com/samgranger/StoreCodeBodyClass
Place the plugin in app/code/SamGranger and run the usual scripts to enable it (bin/magento module:enable SamGranger_StoreCodeBodyClass + bin/magento setup:di:compile).


text:
Q: How to print multiple instance of crystal report using single Crystal Report Viewer in c#
I am trying to print multiple crystal report using single Crystal Report Viewer.
I have 'n' number of items in a database and I need to print 'n' crystal reports. As it is dynamic in nature so I cannot fix number of Report Viewer, so I thought to use single Report Viewer and load crystal report using 'For loop'.
I created a new datatable in dataset and I was trying to put value from another datatable it didnt worked out so created parameter fields and is putting values in through

For Loop

Here my code(I have 3 parameter fields for ease of viewing showing only one):
private void CRVtakeout_Load(object sender, EventArgs e)
    {
      try
           {
            string sqlqry = "Select KOTNo,Time,TableNo,WaiterName,ItemCode,ItemName,Quantity,Amount,Foodtype From tblOrder Where KOTNo=@kotno";
            SqlCommand cmd = new SqlCommand(sqlqry, connectionclass.con);
            cmd.Parameters.AddWithValue("@kotno", NewOrderBL.KOTNo);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet1 ds = new DataSet1();

            adapter.Fill(ds, "Takeout");
            //adapter.Fill(ds, "Takeout");
            string tableno = ds.Tables["Takeout"].Rows[i][2].ToString();
            tableno = tableno.Substring(6, 1);
            if (ds.Tables["Takeout"].Rows.Count == 0)

            {
                MessageBox.Show("No Data Found", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (tableno == "T")
            {
                for (int i = 0; i < ds.Tables["Takeout"].Rows.Count; i++)
                {
                    crystalReportViewer1.RefreshReport();
                ParameterFields paramFields = new ParameterFields();
                ParameterField paramField = new ParameterField();
                ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
                paramField.Name = "Billno";
                paramDiscreteValue.Value = ds.Tables["Takeout"].Rows[0][0].ToString();
                paramField.CurrentValues.Add(paramDiscreteValue);
                paramFields.Add(paramField);
printtakeout printtakeout = new printtakeout();
                printtakeout.SetDataSource(ds);
                crystalReportViewer1.ReportSource = printtakeout;
                System.Drawing.Printing.PrintDocument printdocument = new System.Drawing.Printing.PrintDocument();
                printtakeout.PrintOptions.PrinterName = printdocument.PrinterSettings.PrinterName;
                printtakeout.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
                printtakeout.PrintToPrinter(1, false, 0, 0);

                   }
  }
 }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally { connectionclass.disconnect(); }**strong text**
}

Each time I do it gives error :

activex control 8856f961-340a-11d0-a96b-00c04fd705a2 cannot be instantiated because the current thread is not a single-thread apartment

If I dont use parameter field theirs no error.
If any clarification needed please do tell.
Thanks .

A: There is an example to do queries
using (SqlConnection connection = new SqlConnection("connectionString"))
            {
                connection.Open();
                SqlCommand command = new SqlCommand();
                command.CommandText = "SELECT * FROM Customers";
                command.CommandType = CommandType.Text;

                using (SqlDataReader objDataReader = command.ExecuteReader())
                {
                    if (objDataReader != null)
                    {
                        while (objDataReader.Read())
                        {
                          // To get results...
                          // objDataReader["NameResultParam"];
                        }
                    }
                }
          }


text:
Q: How to lane against AP Mid LeBlanc My play-style is a ranged counter-attack, and my Mid Lane Champs matches my play-style. However, I find it hard to lane against mid-lane assassins, specifically LeBlanc.
How do I effectively lane against LeBlanc using each and one of these champs?
Here are my usual Mid-Lane Champs:

*

*Morgana

*Veigar

*Zilean

*Zyra

For those who are thinking if I use support as a primary role, the answer is yes. However I find it hard to shift from support to AP mid, some good tips would be greatly appreciated.

A: Well for starters you havent picked the strongest midlaners. But ill try to give some tacs etc for your picked champions and some other suggestions

*

*Morgana: Go cry. This lane is a mess. The massive CD on your shield vs her low CD spells is practically useless. You can block one burst but if you don't kill her afterwards you are dead. Your binding & soil will practically never hit unless you predict the dash. She is very mobile. Especially after lvl 6. Same for your ult. She can just dash out of its range.

*Veigar: You actually stand quite a chance as Veigar. Once you get lvl 6 your kill potential is higher then hers I think. Lane safely. Use Q to poke her instead of stacking Q. And when she dashes. Place the "Event Horizon" on the dash marker and launch the meteor. With this tactic you can shut her down pretty easy if she plays a little reckless.

*Zilean: Your bomb range is higher the her spells and she has no real counter to them as well. I've played this lane last week. You can negate her burst completely with your ult. The main thing in lane is keep up with cs and exp. Also build mana sustain early. So that you can keep spamming rewind for extremely low cd on chrososhift.

*Zyra: Zyra is actually pretty tricky. Although some similarities with Morgana, your bind goes through minions. But she can still dash out of both your bind & ult with little effort. So if you want kills. Roam.
Like all mid lanes. If you feel unsafe. Play secure. And don't die. After lvl 6 start roaming and make sure you always know where the other mid laner is. Leblanc is a great roamer so be careful
Good Counters to Leblanc:

*

*Syndra: Her long range poke and stun are amazing and have a fast travelling time. Although the stun can be tricky to aim. At lvl 6, place as many balls as possible, stun & ult & ignite will kill her

*Annie: My little pyromaniac <3 although pre-6 it's hard to play vs Leblanc you can easily farm under turret with your Q. Annie her spells are all point and click and there is little room for her to dodge your stun charged "Tibbers". For firstblood. Get stun, flash in, R > W> Q + ignite and she is dead. Annie her burst is amazing at lvl 6.
If you need anymore help & tips just comment.

A: To be able to counter champions efficiently, you need a way bigger pool of champions you can play to pick from, 4 is just not enough. That's good at first if you just started to learn midlane, but it won't be enough in the long run. Moreover as you only have one playstyle, being versatile is even more difficult.
If you want to counter a champion your pick is the priority (considering you can actually play it ^^, never pick a champ just because it's a counter, you need to know him for it to work). Champions like Galio (non burstable) or Fizz (can stick to her at all times) are the best for this match-up. But if you really want a "ranged counter-attack" champion, Syndra is the one to take. She is a really strong pick against Leblanc for several reasons :

*

*You have a lot of a quick harass to keep-up with her

*As soon as you are 6, it's a burst race but your full combo outdamages her (stun(Q+E) + slow(W) + ult(R) + ignite)

*A lot of champions have a hard time finishing her because of her strong decoy/invisibility passive, but with Syndra just make sure to ult + ignite right before it triggers and it will kill her anyways.

A: What's lacking in the answers IMO is HOW to play against a Leblanc not as a specific champion, but in general.
Leblanc has a very high damage output, but is probably one of the squishiest champ in the game. After the removal of the silence on her Q-proc laning against Leblanc has become much easier - You can now efficiently trade back once she has used her combo. But not only that, after her Q+W (in lane) you typically have a 15 second window to exploit the hell out of her cooldown (W CD: 18/16/14/12/10).
The important thing to do against a Leblanc is to push when she has CDs! Even if she just took you down to 50% with one Q+W, don't be scared - Retaliate! The one thing you have to be obs for is a Q+E as her Q has a low cd. She also has terrible waveclear unless she is going to be using W on minions (which doesn't even clear the wave early and would put her at great disadvantage when it comes to trading). Therefore when you have the upper hand you can and should push her to the turret and make her focus on lasthitting as you poke her.
Additional Notes:
Jungler:
If you can easily communicate with the jungler, be it that you're a fast typer or using voice-chat, you should inform him/her whether or not the Leblanc is being aggressive with her W. The jungler should stand in a bush and wait for her to use Distortion (W) and then go in towards the pop-back for the gank. If you are duoQing with a jungler, you might consider choosing a champion with hard cc mid as to organize your ganks.
Champions:
I've seen a lot of players going Galio recently as you can negate her combo pretty well with your shield (W) and stacking MR is a natural thing on him.
Syndra counters Leblanc for various reasons, most mentioned above. But IMO the most important being that she can actually stop her midair with her E (when she W), like Galio, completey negating and often with a follow up stun to burst her down.
Zed and Yasuo can both dodge Q+W by using their own dashes if you're good at predicting them. Zed can also negate a lot of damage with his ulti.
Zed (Faker) vs. Leblanc:

Runes:
Could be an idea to have your own runepage where you replace yellows with hp instead of armor and flat mr blues instead of scaling.

A: Most leblancs take flask + 2 pots now adays against any match up to increase her sustain since her wave clear is almost absolute trash . But she does have damage . She can set a huge amount of chunk with a q + w combo . Know this , Her cooldown for her distorition (W) is so high . You can abuse that , the best way to not get combo'd is to poke her first . But it also depends on the match up , You can't play those type of mids against her , but they are not even in the meta. Veigar can however always always outscale her but you should know , right after you see the animation of leblac throwing a q on you , as veigar , throw your e on yourself and her w is canceld . The animation is stunned and you take no damage from w + q proc. She can't take damage back . That's why shes very easy to trade against her if you play it smart .
1. PLay agrresive , She will abuse the w and her passive to get through escapes .
2. Out cs her . Lb wave clear is bad because if she is forced to use w or w+r to wave clear , you have 10 seconds to kill her , poke her and or make her use her passive.
3. Ganks. Bait her poke the q+w and you can easily gank her if shes not 6.
Kill the lane doesn't mean you have to kill the champ , just outsmart her . If you know what she's ganna do , Why not stop it ?

A: When a LeBlanc sees an opening, they will immediately Q W E or Q R E W for hard poke and all ins, respectively. (Hope!) Her other spells might be on cooldown, so when you take her Q, stand far behind your minons and use your ranged spells to take CS. For example, when I AP Ezreal mid and a LeBlanc Q's me, I immediately blink right when she dashes and unleash full combo hell. But if you picked an immobile caster, you're dead. End of story.
Moral? PICK AP EZ VS LEBLANC


text:
Q: How to exclude some options from React Select options I have around 50 options to be shown in the react select options. But I want to exclude some of the options with logic to already posted values.
The purpose is, that we have a form where we add values from the drop-down list. if one item is been added then that should not have to be shown in the dropdown list.
refactored code:
export default function App() {
  const choices = [
    {
      value: 0,
      label: "Container empty to shipper"
    },
    {
      value: 1,
      label: "Container pickup at shipper"
    },
    {
      value: 2,
      label: "Container arrival at first POL (Gate in)"
    },
    {
      value: 3,
      label: "Container loaded at first POL"
    }
  ];

  const postedList = [
    "Container empty to shipper",
    "Container pickup at shipper"
  ];
  return (

Select Box

      <Select
        isClearable={false}
        // here the choices should be 2 eliminating the other 2 whose labels are matching to postedlist
        options={choices}
        defaultValue={choices[0]}
        onChange={(choice) => console.log(choice.value)}
      />

  );
}

Currently, it's rendering all 4 choices available but I want to return only 2 of them whose labels are not matching to postedlist
I also have created Codesandbox. If you want to see it there.

A: You can use Array.prototype.filter() and Array.prototype.includes() to filter out already posted items. Then use the filteredList as input to the Select component as below.
  const filteredList = choices.filter(({ label }) =>
    !postedList.includes(label)
  );

  return (

Select Box

      <Select
        isClearable={false}
        options={filteredList}
        defaultValue={filteredList[0]}
        onChange={(choice) => console.log(choice.value)}
      />

  );

A: You can dynamically filter items and exclude them with the includes method.
    <Select
    options = {choices.filter((choice) => !postedList.includes(choice.label))}
    ...
    />


text:
Q: Proof involving binomial sums I'm reading about Cover's Function Counting Theorem and I want to prove that when $p/N = 2$ it is true that
$$\frac{C(p,N)}{2^p}=\frac12$$
as is shown in the plot in that same link.
In Hertz, Krogh & Palmer's Introduction to the Theory of Neural Computation it is stated that

It is actually easy to show from the symmetry ${{2n}\choose{n-m}}={{2n}\choose{n+m}}$ of binomial coefficients that $$C(2N,N)=2^{p-1}$$

That's exactly the result I want, as is just another way of writing the equality I wrote at the beginning. In sum, what I want to prove is that
$$2\sum\limits_{i=0}^{N-1}{{2N-1}\choose{i}}\stackrel{?}{=}2^{2N-1}$$
I don't know how to start, because the superior limit of the summation doesn't match the upper index of the binomial coefficient. According to the book I quoted, it appears that at some point the symmetry of binomial coefficients should be used, but I can't come up with any ideas.

A: So we would like to prove $$2\sum\limits_{i=0}^{N-1}{{2N-1}\choose{i}}\stackrel{}{=}2^{2N-1}$$
First we know:
$$1.1.\sum\limits_{i=0}^{2N-1}{{2N-1}\choose{i}}=(1+1)^{2N-1}=2^{2N-1}$$
Secondly we know the rule of symmetry of the binomial coefficients
$${{K}\choose{i}}={{K}\choose{K-i}}\implies{{2N-1}\choose{i}}={{2N-1}\choose{2N-1-i}}$$
The above sum can be written:$$\sum\limits_{i=0}^{2N-1}{{2N-1}\choose{i}}=\sum\limits_{i=0}^{N-1}{{2N-1}\choose{i}}+{{2N-1}\choose{2N-1-i}}=2\sum\limits_{i=0}^{N-1}{{2N-1}\choose{i}}$$
The last equality by the symmetry, and from 1.1 our equality holds.
Q.E.D


text:
Q: Magento 2 New Order Event: get Customer's telephone I have an observer for every order status change, and another for every new order. In both observers I need to retrieve the customer's phone number. In order-status-change this happens as follows:
$phone = $order->getBillingAddress()->getTelephone();

However in new-order, none of the below succeed. They all return null. Why does this happen? What could I do?
$order->getCustomerPhone();
$order->getBillingAddress();
$order->getShippingAddress();
$order->getPrimaryBillingAddress();

A: You can use the event <event name="sales_order_address_save_after"> in which order id already stored (if you need it). Just check is it billing or shipping address:
$event = $observer->getEvent();
/** @see \Magento\Framework\Model\AbstractModel::_getEventData() */
/** @var \Magento\Sales\Model\Order\Address $address */
$address = $event->getDataObject();
/** @var int $orderId */
$orderId = $address->getParentId();
$addressType = $address->getAddressType();

switch ($addressType) {
    case Address::TYPE_BILLING:
        // Do something with billing address
        break;
    case Address::TYPE_SHIPPING:
        // Do something with shipping address
        break;
    default:
        /**
         * This is a not usual case, when address type is not in one of this types: billing or shipping
         */
        break;
}

this event is triggered each time order address was saved. So you should add an additional check: is your info (telephone) was already stored recently or not?

A: I found a trick that worked. (The event remained unchanged: sales_order_save_after)
private function getPhoneFromObserver(Observer $observer)
{
    $data = $observer->getEvent()->getOrder();
    foreach( $data['addresses'] as $addr ) {
        if( $addr['telephone'] !== null ) {
            return $addr['telephone'];
        }
    }
    return null;
}


text:
Q: React: this is not defined in async callback function I have been on this for long now please I need assistance.
Am trying to make a call to an API link and I have an array of data to make the call as parameters to the call.
And After the call has been made I want to set the component state to the result gotten.
let animals = ['cats','goats'] ;
async.each(animals, function(item, cb){
  axios.get(`http://api.com?keyword=${item}`)
    .then(res=> {
        apiData.push(res.data)
        this.setState({
          stateData: apiData
        });
     });
   })

A: async.each only makes sense if you want to execute one request after another, and then you have to call cb() so that the chain continues:
 async.each(array, (item, cb) => { // <- arrow func!
   axios.get(`/http://api.com?keyword=${item}`)
   .then(res => {
     apiData.push(res.data);
     this.setState({ stateData: apiData });
     cb(); // <---
   });
});

Or to execute all in parallel (which is probably much faster):
 const promises = array.map(item => axios.get(`/http://api.com?keyword=${item}`).then(res => res.data));

 Promise.all(promises).then(stateData => {
   this.setState({ stateData });
 });

PS: You should always handle errors in a promise, so just attach a .catch(/*..*/) to the chain ...,

A: Use arrow function for both forEach and api request callback, that will prevent javascript re-assigning the value of this during your callback chain.
More info about arrow functions in ES6 read: https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc


text:
Q: Make UArray a Functor I want to treat UArray as instance of Functor. I want to write a numeric code, and I need to use something more efficient than Array to represent the state (says the profiler). I understand that I could write my code without using functors, but I think functors are a very valuable abstraction that I'd like to have.
As-is this doesn't work, because UArray is only an instance of IArray for certain basic types such as Int or Double. I am contemplating two approaches to make it work nonetheless:

*

*Return an error (either implicitly or explicitly) if the result of fmap is not an instance of IArray

*Define a "composite" type that is either based on UArray (if possible) or on Array (if not), akin to a C++ template specialization

I've tried various approaches based on various GHC extensions (existential types, functional dependencies, generalized algebraic data types, multi-parameter type classes, undecidable instances), but I just can't make things work. I always arrive at a point where I need to promise the compiler that "yes, the result will be representable via UArray", but there's just no syntax for it.
I've read various papers, tutorials, and documentation for the GHC extensions above in the hope to find an example that tells me how to do that. The closest I could find is https://wiki.haskell.org/GADTs_for_dummies, which defines a class IsSimple that is very close to what I probably need.
Can you give me a pointer for how to get started?

A: Data.Vector.Unboxed provides an implementation of what I am looking for. It is already an instance of Functor, and automatically chooses an efficient representation if possible.


text:
Q: i am not able to follow the following code snippet from the node beginners book app.js , server.js and router.js are the 3 files
app.js
var server = require('./server');
var router = require('./router'); //here we are requiring the module
server.start(router.route);

server.js
var http = require("http");
var url = require("url");
function  start(route){
    function onRequest(request, response) {
        var pathname = url.parse(request.url);
        console.log("request for " + pathname + " recieved");

                            //in this line we are using route function
        route(pathname);    //which is in router.js
                            //why are we not requiring the module ie     require('./router')

        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write("Hello World");
        response.end();
    }
    http.createServer(onRequest).listen(8080);
    console.log("Server has started.");
}
exports.start = start;

router.js
function route(pathname){
    console.log("About to route a request for "+pathname);
}
exports.route = route;

why are we not requiring router.js in the server.js file (require('./router');)

A: As you may see, the server.js does not require the routes.js file since it is being pass as an argument of the function start on server.js.
Being that said, I see an error in your code, the start function on server.js should have a "route" parameter.
Then when you instantiate your app.js, you require both but then when you call start and send that argument, afterwards you don't need to import routes.js again since it is already there as a reference.
Let me know if that answer your question.
Best,
Dario

A:
why are we not requiring router.js in the server.js file

Because there's no need to. server.js doesn't need the router module for anything.
The code in app.js calls server's start passing in the route information as an argument. But start doesn't accept any parameters, so it doesn't use that argument for anything. Perhaps later in the tutorial they'll start using the routing information.
But the point is that server.js doesn't need to require it, because it receives it (or will receive it at some point when the code is updated) as a parameter to start.


text:
Q: I keep getting 401 [No Body response] using RestTemplateBuilder I have two RestTemplate Beans, however sometimes when authRestTemplate is used get a 401 error (org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]) I'm not sure why this is happening since it does not happen consistently.
This is how I have configured my RestTemplate.
@Configuration
@RequiredArgsConstructor
public class AppConfig {

    private final FooConfig fooConfig;

    @Bean
    @LoadBalanced
    public RestTemplate authRestTemplate(final RestTemplateBuilder restTemplateBuilder){
        return restTemplateBuilder
                .basicAuthentication(fooConfig.getUsername(), fooConfig.getPassword())
                .build();
    }

    @Bean
    @LoadBalanced
    public RestTemplate basicRestTemplate(final RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder
                .build();
    }

}

If I am using the authRestTemplate it would look something like this
@Service
@RequiredArgsConstructor
public class authSubmissionServiceImpl implements CompletedApplicationService {
    private final RestTemplate authRestTemplate;
    private final FooConfig fooConfig;

    @Override
    public void doSomething() {
        try {

             Objects.requireNonNull(
                 authRestTemplate.getForObject(
                     String.format(somePath, fooConfig.getBaseUrl()),
                     String.class)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I use constructor injection and use the same variable name as the RestTemplkete bean to differentiate between the two. Because of this, I don't need to use @Qualifier(). However, I know the authentication is being sent because 99% of the time the request goes through fine but there are spontaneous times where I get 401 [No Body] and I'm stumped. Any help would be greatly appreciated


text:
Q: Is threading the best way to handle 40 Clients at a time in UDP Server? I am working on a UDP server/client application.
I want my server to be able to handle 40 clients at a time. I have thought of creating 40 threads at server side, each thread handling one client. Clients are distinguished on the basis of IP addresses and there is one thread for each unique IP address.
Whenever a client sends some data to a server, the main thread extracts the IP address of the client and decides which thread will process this specific client. Is there a better way to achieve this functionality?

A: There are different approaches for scale able server application, one thread per client seems good if no of clients are not many, another most efficient approach to accomplish this task is to use thread pool. These threads are work as task base when ever you have any new task assign this task to free worker thread.

A: Take a look at this project, I think it is very helpful to start with: http://www.codeproject.com/Articles/16935/A-Chat-Application-Using-Asynchronous-UDP-sockets

With IPAddress.Any, we specify that the server should accept client
  requests coming on any interface. To use any particular interface, we
  can use IPAddress.Parse ("192.168.1.1") instead of IPAddress.Any. The
  Bind function then bounds the serverSocket to this IP address. The
  epSender identifies the clients from where the data is coming.
With BeginReceiveFrom, we start receiving the data that will be sent
  by the client. Note that we pass epSender as the last parameter of
  BeginReceiveFrom, the AsyncCallback OnReceive gets this object via the
  AsyncState property of IAsyncResult, and it then processes the client
  requests (login, logout, and send message to the users). Please see
  the code attached to understand the implementation of OnReceive.

A: A better way would be to use the Proactor pattern (take a look at Boost.Asio library), instead of creating thread per client. With such an approach your application would have much better scalability and performace (especially on platforms that have native async i/o)
Besides, with this technique the threading would be de-coupled from the concurrency, meaning that you don't necessarily have to mess with multi-threading with all its complications.


text:
Q: Extracting Multiple Dataframes from a folder and using them in multiple functions I am new to R and I need help sorting a scenario in R programming.
For the First Part of the problem:
I have a folder with multiple SAS files in a specific location and whose path would be coming in an excel file. I have managed to extract the files from the path provided in excel file as below:
Spec <- read_excel("file", sheet = "first")

Then to extract the dataframes from the folder with the below code (There are 3 dataframes in the folder namely "aa.sas7bdat", "bb.sas7bdat", "cc.sas7bdat" or it can be any number depending on the folder, but for this one we are taking 3 dataframes)
Path <- Spec$`Source Data Path`[1:1]   (#it is in the first row in first column of excel file)
Files <- list.files(path = Path, pattern="*.sas7bdat", full.names=FALSE)

then putting a loop for sorting the dataframes as required for further process (as explained later)
Final_List <- NULL

for (y in Files){
        List <- unlist(strsplit(y, split = ".sas7bdat", fixed = TRUE))
      Final_List <- c(Final_List, List)
      Final_List <- toupper(Final_List)
      read_files[[List]] <- read_sas(y)
}

print(Final_List)

The above loops output is 3 dataframes namely "AA", "BB", "CC" stored in variable "Final_List" and now we need to access these dataframes from here on to another function.
Now for the second part
Now there is a requirement to filter all the dataframes based on one value of a column of single dataframe Dynamically
Let's say the input by user is a value of "Male" from column name "Gender" from dataframe "AA" (It can be any value from any column of any dataframe as this needs to be DYNAMIC)
Column_Name_Value <- "MALE" (#from the column "Gender" selecting only male values)
Dataframe_Name <- "AA"

I have created 3 functions to help in filtering
1st Function to filter the unique values of "Gender" (or any column name) from dataframe "AA"
Unique_Value_Fun <- function (dataframe, value) {

  Unique_Value1 <- dataframe %>% distinct({{value}}) %>% filter({{value}} != "")
  Unique_Value <- unlist(Unique_Value1)
  return(Unique_Value)
}

Unique_Value <- Unique_Value_Fun({{Dataframe_Name}}, UQ(sym(Column_Name_Value)))

Now we have the dataframe AA with only "Male" values. Now there is a common column of ID's in all the dataframes, if the first dataframe is filtered with the "Unique Value" it will have only those "ID's" present. Now we need to filter all other dataset present in the folder with the same "ID's". The CATCH is all other dataframes will not have the same column name and the same values. BUT they have a common column "ID" for every dataframe so we need to use this common ID for filtering the rest of the dataframes.
Below code have the rest 2 functions
for (z in Unique_Value) {
  print(z)
  First_dataframe_Fun <- function (dataframe, value) {
    dataframe %>% filter({{value}} == {{z}})
  }
  First_dataframe <- First_dataframe_Fun({{Dataframe_Name}}, UQ(sym(Column_Name_Value)))

Now if I take the dataframes values and put it against the functions, it works well (i.e, it's hardcoded but not Dynamic)
AA <-  First_dataframe

  BB <- BB %>% filter(ID %in% First_dataset$ID) (# filtering as per ID of first dataset to match the ID's)
  CC <- CC %>% filter(ID %in% First_dataset$ID)

Based on the "First Dataframe ID's" we need to filter the rest of the dataframes dynamically. Now to make it dynamic I tried with if condition inside a for loop but it didn't work out.
Please suggest a logic or a similar code where I can make this Dynamic. If I provide any value of a dataframe it should filter the rest of datasets with the ID's (as there can be n number of  dataframes but in our case we have taken only 3 dataframes for example).


text:
Q: useEffect blocking render in React18 I was trying to demonstrate the difference between useEffect and useLayoutEffect, and I stumble upon something strange. Since React 18, effects seem to be blocking render when taking a long time, while in React 17 render was done (and screen painted) before the effect was triggered.
For example, if you have this in a component :
function MyComponent() {
  React.useEffect(() => {
    sleep(1000)
    console.log('effect done!')
  })

  return ...
}

// Sleep is a small util like this:
function sleep(time = 0) {
  const wakeUpTime = Date.now() + time;
  while (Date.now() < wakeUpTime) {}
}

In React 17, it would render the component and only then it would get "stuck" in this long useEffect. In React 18, it's actually blocking the render. Why ? Aren't effects supposed to be triggered asynchronously after render ?
I don't see the point of useLayoutEffect if the screen doesn't get painted before useEffect runs
I made two sandboxes to show the difference :

*

*With React 17 (working as expected) => https://codesandbox.io/s/useeffect-with-react-17-l8p0vd?file=/src/App.tsx:0-1249

*With React 18 (blocking render) => https://codesandbox.io/s/useeffect-with-react-18-o2qhtb?file=/src/App.tsx:87-192


text:
Q: MapStruct mapper based on type Consider the following simplified structure (that has both a DO and a DTO for each):
Component {
   UUID id;
   String name;
}

MotherboardComponent extends Component {
    String type;
    List<Component> components;
}

For both I have a mapper that does the mapping between the DO and DTO, However, I am facing a problem and don't really know how to handle it. If for the MotherboardComponent in the list I have another MotherboardComponent, the resulting mapped object is to ComponentDO and not to MotherboardComponentDO.
How can I tell MapStruct to use the MotherboardComponentMapper inside the MotherboardComponentMapper, if the object is actually an extended one, not a base?
Thanks

A: MapStruct does not do anything on runtime. It once knows about the types during compilation time.
In order to solve this problem you will have to help it a bit:
e.g.
@Mapper
public abstract class MotherboardComponentMapper {

    public abstract MotherboardComponentDO map(MotherboardComponent component);

    public ComponentDO map(Component component) {
        if (component instanceof MotherboardComponent) {
            return map((MotherboardComponent) component);
        }

        return mapAsComponentDO(component);
    }

    @Named("asComponentDO")
    protected abstract ComponentDO mapAsComponentDO(Component component);

}

Since we have marked the mapAsComponentDO with @Named MapStruct will not treat it is a possible method for mapping from Component to ComponentDO and it will use the map(Component) method instead.
There is an open issue for supporting such down cast mapping in the MapStruct issue tracker.


text:
Q: page.ClientScript.RegisterClientScriptBlock has to be called from code-behind? Do I have to call this from within page load?  OR can I do something like this in my .aspx page:
<%=SomeClass.RegisterMyScript(this, (int)Code.Home, UserId, "Home", 0, "", 0, 0, "" ) %>

I've got this at the bottom of my .aspx page.
The method RegisterMyScript has the following inside it:
    if (!page.ClientScript.IsClientScriptBlockRegistered("cartScript"))
        page.ClientScript.RegisterClientScriptBlock(typeof(Page), "cartScript", finalScript);

I do'nt know if by the time the page has already rendered if this will still work.  My guess is that I'm required to do it in page init or load but thought maybe I can still do it outside those initial load functions.

A: That should work within your page, but not 100% sure why you would need to do it that way.
If you are having problems, we would need to see the full method.


text:
Q: Babylon.js error "export not found" when adding fire library I got this error:

export 'FireProceduralTexture' (imported as 'BABYLON') was not found in '@babylonjs/core'

I added these :
<script src="https://cdn.babylonjs.com/proceduralTexturesLibrary/babylon.fireProceduralTexture.js"></script>

<script src="https://babylonjs.azurewebsites.net/lib/babylon.fireMaterial.min.js"></script>

<script src="https://babylonjs.azurewebsites.net/lib/babylon.fireProceduralTexture.min.js"></script>

Still says the same error.


text:
Q: Can't activate rack (~> 1.4.0, runtime) already activated rack-1.5.0 I've been looking for an answer to this for over a day now, and searched StackOverflow thoroughly.
I understand the conflict that's happening, and I should just uninstall the version of Rack I don't need, but here's the thing. I'm developing on Koding (http://koding.com) and I don't have access to system level gems.
Rails was working before, I installed the mongo gem, removed it, and installed mysql2 gem.
bash4.1$ rails
/usr/lib/ruby/site_ruby/1.8/rubygems.rb:233:in `activate': can't activate rack (~> 1.4.0, runtime) for ["actionpack-3.2.11", "railties-3.2.11"
], already activated rack-1.5.0 for ["rack-ssl-1.3.2", "railties-3.2.11"] (Gem::LoadError)
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:249:in `activate'
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:248:in `each'
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:248:in `activate'
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:249:in `activate'
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:248:in `each'
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:248:in `activate'
from /usr/lib/ruby/site_ruby/1.8/rubygems.rb:1082:in `
from /usr/bin/rails:18

I've wiped my directory clean, tried using RVM, and still nothing. Any ideas?
Thanks!

A: Use Bundler to resolve the Rack dependency according to the app Gemfile.
$ bundle exec rails

Otherwise, delete Rack 1.5.0 and retry.
$ gem uninstall rack
# select the proper version to delete


text:
Q: images broken on meteor I'm doing this Meteor course where an old version of Meteor is used and unsure of where to put files and folders. I have images in a public folder which is in my main folder and the following main.html client code

  <title>image_share</title>

Welcome to Coursera!

  {{>images}}

<template name="images">
    {{#each images}}

    {{/each}}
</template>

and the following client code main.js
if (Meteor.isClient) {
    console.log("I am the client");

var img_data = [
    {
        img_src:"image1.jpg",
        img_alt:"dental surgery"
    },

    {
        img_src:"image2.jpg",
        img_alt:"carribean night"
    },

    {
        img_src:"image3.jpg",
        img_alt:"full moon palm tree"
    },

];

Template.images.helpers({images:img_data});
}

My problem is only image1.jpg is appearing in the browser window.

A: Your helpers should be functions:
Template.images.helpers({
    images:function() {
        return img_data;
    },
});

And in your template its good to explicitly reference to the data in the loop in context of "this":
{{#each images}}

{{/each}}

"This" refers here to the current object in the array, you iterate.


text:
Q: Differential of the Rabinowitz Action Functional On an exact Hamiltonian system $(M,d\alpha,H)$ define the Rabinowitz action functional
$$\mathcal{A}^H \colon C^\infty(\mathbb{S}^1,M) \times (0,+\infty) \to \mathbb{R}$$
by
$$\mathcal{A}^H(\gamma,\tau) := \int_{\mathbb{S}^1}\gamma^*\alpha - \int_{\mathbb{S}^1}H(\gamma(t))dt.$$
Following the book The Restricted Three-Body Problem and Holomorphic Curves by Frauenfelder/Koert, p. 97 it is claimed that
$$d\mathcal{A}^H_{(\gamma,\tau)}(X,\widehat{\tau}) = \int_{\mathbb{S}^1}\gamma^*\mathcal{L}_X\alpha - \tau \int_{\mathbb{S}^1}dH(X) - \widehat{\tau}\int_{\mathbb{S}^1}H \circ \gamma$$
for any pair
$$(X,\widehat{\tau}) \in T_\gamma C^\infty(\mathbb{S}^1,M) \times \mathbb{R} = \Gamma(\gamma^*TM) \times \mathbb{R}.$$
I do not understand this computation. I mean, it is clear to me that to compute the differential (or merely define it in that infinite-dimensional setting), we pick a variation of $(\gamma,\tau)$, for example
$$\Gamma(\varepsilon,t) := (\exp_{\gamma(t)}^\nabla(\varepsilon X_t), \tau + \varepsilon \widehat{\tau}).$$
Then
$$d\mathcal{A}^H_{(\gamma,\tau)}(X,\widehat{\tau}) = \frac{d}{d\varepsilon}\bigg\vert_{\varepsilon = 0}\mathcal{A}^H(\Gamma(\varepsilon,\cdot)).$$ So in the first term we end up with
$$\int_{\mathbb{S}^1}\frac{d}{d\varepsilon}\bigg\vert_{\varepsilon = 0}\gamma_\varepsilon^*\alpha,$$ where $\gamma_\varepsilon := \exp_\gamma^\nabla(\varepsilon X)$. What I do not understand is, why that
$$\int_{\mathbb{S}^1}\frac{d}{d\varepsilon}\bigg\vert_{\varepsilon = 0}\gamma_\varepsilon^*\alpha = \int_{\mathbb{S}^1}\gamma^*\mathcal{L}_X\alpha.$$ I mean, since $X$ is only a vector field along $\gamma$, for me, the expression $\mathcal{
L}_X\alpha$ does not even make sense.


text:
Q: Opening a featureclass not being the owner of the data in SDE How can you open a featureclass if you are not the schema owner but have been given privs to select or view the data?
So given a name of a featureclass, say "STREETS" - how can I open this if I am using an SDE connection with username "VIEWER" (given privs to see "EDITOR" owned data) but the owner of "STREETS" is "EDITOR"? - using the following code:
IFeatureWorkspace.OpenFeatureClass(string name)

This will work if you are the owner, you just put:
IFeatureWorkspace.OpenFeatureClass("STREETS")

But if you are not the owner then you have to fully qualify it, a la:
IFeatureWorkspace.OpenFeatureClass("EDITOR.STREETS")

Is there anyway round this? Bearing in mind my users will not have access to an sde connection for the data owner.

A: Relational database software generally permits multiple tables with the same name if they are:

*

*Owned by different users, or

*Placed in different databases (for RDBMSes which support multiple containers within an instance)

The usual way to distinguish which table is being referenced is by prefixing it with the owner name (and a period separator).  The default behavior is to assume that a table without an owner prefix is owned by the current user, which is why you need to specify the owner of an other-owned table.  Of course, security rules may prevent you from accessing tables owned by other users, so a "table does not exist" error may really be saying, "the table may exist, but if it does, you don't have SELECT access on it, so I'm not going to tell you about it."
Some databases (Oracle is one) support "public synonyms," which override the default naming by checking the list of synonyms before prepending the connected username.  However, ArcGIS does not support synonyms, so this will not be part of an
ArcObjects solution.
It's best practice to always specify a table owner when scripting. ArcObjects provides helper functions to parse and qualify table and field references in an RDBMS-independent fashion.  It's also advisable to avoid use of a data owner connection when testing, partially to detect incomplete table and field references, and partially to prevent data corruption during testing (a self-inflicted denial of service attack).
Recommended use of the SQL security model involves creating logins for each individual
who will connect to the database, "data owner" users to manage spatial datasets (the password(s) for which is closely held by the geodatabase administrator(s)), and database roles for each type of access to be granted to the users.  If there is any unauthenticated access (as in a web application), then there should also be a user created for this as well (with a bare minimum of permissions). Then the necessary access to data tables can be granted to roles, and the roles granted to users (in a geodatabase, the GRANTs should be performed with ArcGIS tools, so ancillary tables all get the correct permissions). In this way, you can prevent situations where the "Bill" user owns core business data even though Bill moved on to a different job three years earlier.  It takes a bit more work up front, but it makes for much less difficulty in maintenance later.


text:
Q: d3 js topojson colors don't show My question is about making a choropleth of US counties using d3 js. I've merged a dataset (providing a value for each US county) with topojson data for the US. When I console.log the topojson data, the required value appears and I can pick out a value for any given index.
I've also provided a range of colors in a scaleQuantile scale and set the domain to be the extent of values. Again, I can console.log colorScale(value) and get back a color, and invertExtent the color to see the range of colors, so that appears to be working.
My problem is with setting the fill attribute. The data value I want is stored in data.objects.counties.geometries, but when I set that in the topojson.feature function, the map doesn't show at all. So I tried instead adding the geometries to the fill function itself, but get a map of all-black US counties, even when I set the default color to blue. Here is the relevant code, this is my first choropleth attempt (and first stackoverflow question) and I'd be grateful for any help. Thank you
 svg.selectAll("path")
.data(topojson.feature(data, data.objects.counties).features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function (d){
   var value = geometries.d.value;
   if (value) {
     return colorScale(value);
   } else {
     return "blue";
   }
 });


text:
Q: Loading data into a designated row in EXCEL I'm new to C# and with some help on web I have been able to load data from a SQL Server into EXCEL with individual sheets with corresponding data.
I should add that I am trying to accomplish this using a SSIS package "Script Task".  C# script.
Now I would like to insert the data in row A7 and not A1.  I've tried "insert [9442$A7:A7] (col...) VALUES ... but I get a syntax error.  Probably easy solution but I can seem to figure it out.

ERROR: System.Data.OleDb.OleDbException: The Microsoft Access database
  engine could not find the object '9442A7:A7'. Make sure the object
  exists and that you spell its name and the path name correctly. If
  '9442 A7:A7' is not a local object, check your network connection or
  contact the server administrator.

Here is my code relevant to creating and loading data into EXCEL.
Thanks in advance.
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table [" + ColumnValue + "] (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();

//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
    String sqlCommandInsert = "";
    String sqlCommandValue = "";
    foreach (DataColumn dataColumn in table.Columns)
    {
        sqlCommandValue += dataColumn + "],[";
    }

    sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
    sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
    //sqlCommandValue = sqlCommandValue.Replace(",", " ");
    sqlCommandInsert = "INSERT into [" + ColumnValue + "A7:A7" + "] (" + sqlCommandValue + ") VALUES(";

    int columnCount = table.Columns.Count;
    foreach (DataRow row in table.Rows)
    {
        string columnvalues = "";
        for (int i = 0; i < columnCount; i++)
        {
            int index = table.Rows.IndexOf(row);
            columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";

        }
        columnvalues = columnvalues.TrimEnd(',');
        var command = sqlCommandInsert + columnvalues + ")";
        //MessageBox.Show(command);
        Excel_OLE_Cmd.CommandText = command;
        Excel_OLE_Cmd.ExecuteNonQuery();
    }

}
Excel_OLE_Con.Close();

A: Use a Data Flow task for this, not a Script Task. Use a SQL Server data flow component to select your data, and map that result set into an Excel File Output data flow component.
If you want your data to start on A7 (which I assume to mean "the first column but on the seventh row"), I am 99% sure that you can set a property on the Excel File Output component to use 6 rows as "header rows" - this will start your data on the 7th row.


text:
Q: Assembly 8086; Floating Point Numbers, Add, Subtract I need some resources to get to know more about numbers with floating point, I need to code add and subtract operations for that kind of numbers in emu8086 environment ....
Any help is much appreciated

A: You can implement the addition and subtractions for floating point numbers if you store each number in an array of size 2.
The first block of the array can be the base number and the second being the decimal number (implemented as a regular integer of course).
This may not be the most efficient way, but it is surely possible.  Your algorithm will have to take into consideration the way the numbers are stored then perform the ADD and SUB instructions.
You said you didn't want code so I won't post an example, but hopefully this gives you an idea how you can do this on a processor that has no floating point unit.

A: As far as I can tell, emu8086 does not emulate a machine with an 8087 FPU.
Any floating-point you do has to be pure software, not using fld / fadd / fstp or any of the usual legacy1 x87 instructions.
If you want to use FP instructions in real mode, your best bet is an emulator like DOSBox or BOCHS that emulate a more recent x86 + x87, not emu8086.  This also has the advantage of letting you use more convenient instructions like imul ax, 1234 instead of having to use 1-operand mul.
If you are stuck with emu8086 (or a real 8086 microcontroller), most problems can be solved with fixed-point, not actually floating point:  treat a fixed number of bits as the fractional part.  This is easier to do in software with integer instructions.  But it still lets you represent numbers like 1.25.

Footnote 1:  In modern x86, the x87 FPU is obsolete; we use SSE and SSE2 now for scalar and SIMD FP math, unless 80-bit precision is actually needed.  emu8086 of course doesn't have this either.  Modern x86 CPUs of course still support x87 instructions; being backwards compatible with existing binaries is x86's primary reason for still existing.

A: The 8086 processor doesn't have a floating point unit. There was a floating point coprocessor called the 8087, which was meant to be used with the 8086.
You can see the instruction set for the original 8087 here: http://en.wikipedia.org/wiki/X86_instruction_listings#x87_floating-point_instructions


text:
Q: How call / write the following method using GCD dispatch_async in objective c For some reasons to fix some crashes i need write / call the following method in GCD, But as it is having return type NSArray here dispatch blocks do not allow to write this method in dispatch blocks.
Actual crash is  Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSCFSet: 0x6080002531a0> was mutated while being enumerated.'
Can someone please help me on this
-(NSArray*)getManagedObjectsArrayForEntity:(NSString*)entityName
                               sortByFields:(NSArray*)sortByFields
                                  predicate:(NSPredicate*)predicate
                                  ascending:(BOOL)ascending {

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];
    [fetchRequest setFetchLimit:-1];

    // Set the sort descriptor
    if (sortByFields) {
        NSMutableArray *sortDescriptors = [NSMutableArray array];
        for (NSString *sortByField in sortByFields) {
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortByField ascending:ascending];
            [sortDescriptors addObject:sortDescriptor];
            [sortDescriptor release];
        }
        [fetchRequest setSortDescriptors:sortDescriptors];
    }

    if (predicate) {
        [fetchRequest setPredicate:predicate];
        //DDLogVerbose(@"Predicate: %@", [predicate description]);
    }

NSLog(@"HAS CHANGES %d",self.managedObjectContext.hasChanges);

    NSError *error;
    //===
    return [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

}

A: dispatch_async(dispatch_get_main_queue(), ^{
    //write your method body here
});

A: try
-(void)getManagedObjectsArrayForEntity:(NSString*)entityName
                               sortByFields:(NSArray*)sortByFields
                                  predicate:(NSPredicate*)predicate
                                  ascending:(BOOL)ascending {

//your code here

//at last [nsnotification center code here]

}