text:
Q: How to add autocompletetext in textinputlayout programatically in android I created a layout in main activity and now I am trying to call this method where I need to add this view in my main layout. Its not behaving the same way as TextInputLayout Behaves.
Please check my code and let me know what should I change.
public static View getTypeAHeadView(Context context) {

    RelativeLayout layout = new RelativeLayout(context);
    try {
        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layout.setLayoutParams(lp1);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 5, 0, 0);
        TextInputLayout textInputLayout = new TextInputLayout(context);
        AutoCompleteTextView autoCompleteTextView = new AutoCompleteTextView(context);
        autoCompleteTextView.setHeight(R.dimen.dim_40);
        autoCompleteTextView.setWidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT);
        autoCompleteTextView.setTextSize(R.dimen.dim_20_sp);
        autoCompleteTextView.setLines(1);
        autoCompleteTextView.setDropDownHeight(R.dimen.dim_200);
        autoCompleteTextView.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,"));
        autoCompleteTextView.setPadding(10, 0, 0, 0);
        autoCompleteTextView.setSingleLine(true);
        autoCompleteTextView.setLayoutParams(lp);

        textInputLayout.addView(autoCompleteTextView);

        layout.addView(textInputLayout);
    } catch (Exception e) {
        e.printStackTrace();
    }
  /*parent.addView(text);
    parent.addView(editText);*/
    return layout;
}

A: I'm not entirely certain but perhaps try defining layout parameters for the TextInputLayout you are adding programmatically.


text:
Q: this.setState does not seem to be called on react native iOS I am currently using setState in my react-native app to render a screen.
Below is the code, for some reason the code runs everything normally except
setting the state.
showCard(event) {

  const { loadCard } = this.state;
  this.setState({ loadCard: true });

  console.log(loadCard)
  // get value of marker ID
  const markerID = parseInt(event.nativeEvent.id);
  console.log(markerID)
  if (markerID <= this.state.markers.length && markerID != null) {

    setTimeout(() => {
      //USE THIS FORMAT
      this.scrollView.getNode().scrollTo({
         x: markerID * (CARD_WIDTH),
         animated: true
      });

    }, 0.01);

    console.log(this.scrollView)

  }

}

Advice on this matter will be greatly appreciated, as it works on android for me

A: It does work but setting state is asynchronous so you can't just log the result after, observe with the following change:
this.setState({ loadCard: true }, () => console.log(this.state.loadCard));

The second argument is a callback fired after state is set, but you very rarely need that in reality.
Also setTimeout delay is an integer representing milliseconds not a floating point. If you want it as soon as possible use 0.

A: You need to bind your functions in the constructor while settling the state
constructor(props){
  super(props);
  this.state = {
    loadCard : false;
  }
   this.changeCard =  this.changeCard.bind(this);
}

changeCard = (userId) => {
   this.setState({ loadCard: true});
}

render(){
   return(
       console('working state'+ this.state.loadCard);
  );
}

A: I have somehow solved the issue. The main cause apparently as I was working with react-native maps dependency, it could not register the input directly from the marker component and required the method to be called in the main map.
But thank you for all the input guys!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show first li after last li with jQuery I want to remove first li and add that after last li using jQuery. Here is my html code.

1

2

3

4

5

6

7

Is it possible to do with jQuery hide() and show() methods? Any help highly appriciate.

A: Use insertAfter() along with :first and :last. You can use the id attributes to select the elements if you want, but that will make your code more brittle.

$('li:first').insertAfter('li:last');

1

2

3

4

5

6

7

A: You can also achieve this, with the following approach.

var firstLI = $("#client_list li").first();
$("#client_list").append(firstLI);

1

2

3

4

5

6

7

A: You can use eq() in jquery also. But @Rory has suggested a much simple approach. But eq() can find any position in you list.

eq() method providing 0-based position.

$('#client_list').find('li').eq(0).insertAfter('#client_list>li:last');

1

2

3

4

5

6

7


text:
Q: Show that the cardinalities of $(0,1)$ and $(1,2)\cup (3,4)$ are the same I am asked to show that $|(0,1)|=|(1,2)\cup(3,4)|$. I tried to define the function $f:(0,1)\to(1,2)\cup(3,4)$ by
$f(x)=\begin{cases}2x+1 & x\in(0,\frac{1}{2})
\\ 2x+2 & x\in[\frac{1}{2},1)
\end{cases}$. Problem is, $\frac{1}{2}$ gets mapped to $3$ which is not in the codomain. Any ideas of how to deal with that?

A: Hint Define a new function $g$ via
$$g(\frac{1}{2})=f(\frac{1}{3}) \\
g(\frac{1}{3})=f(\frac{1}{4}) \\
...\\\
g(\frac{1}{n})=f(\frac{1}{n+1})$$
and
$g(x)=f(x)$ otherwise.
Show that this $g$ works.


text:
Q: How to use ClipBoard on windows phone 8? I want to copy a phonenumber from PeopleHub, and then paste it to my app, is there have a ClipBoard API to support do that? Thank you!

A: You can only set text to clipboard in windows phone and can not read:
System.Windows.Clipboard.SetText( TextBox.Text );

msdn


text:
Q: Chain rule confusion(multivariable functions) I am confused bz the chain rule of multivariable function. I know, that sometimes it is impossible to dot it.
For example i have the following functions:
$f(x_1,x_2) = \begin{bmatrix} x_1x_2^2 + x_1^3x_2\\x_1^2x_2 + x_1 + x_2^3\\\end{bmatrix}$
$g(u) = \begin{bmatrix} e^u \\ u^2 + u\\\end{bmatrix}$
Is it possible to take a derivative of $f(g)$ or $g(f)$. If not - why?
And in general, when can we take a derivative of such functions(multivariable) and when not?

A: $f:\Bbb R^2 \to \Bbb R^2$ and $g: \Bbb R \to \Bbb R^2$.
Both functions are of class $C^{\infty}$ on their domains, so we only need to know how composing the two functions makes sense. We can't compose $g$ with $f$, but we can compose $f$ with $g$ and $f \circ g: \Bbb R \to \Bbb R^2$: it is a vector function, and $(f\circ g)'(u) = J_f(g(u)) g'(u)$, where $J_f$ is the Jacobian matrix of $f$.


text:
Q: jQuery UI Autocomplete in ASP.NET MVC 4 does not work I'm deploying autocomplete jQueryUI in ASP.NET MVC 4 but it wasn't working perfectly. When I typed a name of Bike, it displays an error like this parsererror. Here's my simply code:
public JsonResult GetAutoComplete(string modelname)
    {
        var result = db.Products;
        var search = result.Where(p => p.Name.ToLower().Contains(modelname.ToLower())).ToList();
        return this.Json(result, JsonRequestBehavior.AllowGet);
    }

Index.cshtml:
<script type="text/javascript">
    //Javascript function to provide AutoComplete and Intellisense feature for finding Users.
$(document).ready(function () {
    $("#Name").autocomplete({
        source: '@Url.Action("", "StoreManager")'
    });
});
 </script>
<p>
    Search the Name of Bikes @Html.TextBox("Name")
    <input type="submit" value="Submit" id="GetName" />
</p>

Does anyone can tell me where I'm doing something wrong ? I just updated my code.

A: try this it may helpful to you.
<script src="../../Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function () {
      $('#Name').autocomplete({
          source: '@Url.Action("GetAutoComplete")',
          minLength: 3,
          select: function (evt, ui) {
            }
      });
  });
 </script>


text:
Q: C++: pointers to data members or traits? I'm practicing with some binary tree algorithms in C++ and trying to write as generic code as possible. In particular, I would like my functions (algorithms) be able to operate on any (to some extend, of course) tree-like data structures.
A tree node structure might be defined in different ways, like this, for instance:
struct binary_tree_node
{
    int data;
    struct binary_tree_node *left;
    struct binary_tree_node *right;
};

Or like this:
struct binary_tree_node2
{
    long key;
    struct binary_tree_node2 *first_child;
    struct binary_tree_node2 *second_child;
};

Or anyhow else, but pretty similar to that pattern.
So I would like my functions/algorithms be able to work with any of these or similar data structures.
For example, here is how I define one simple function:
template <typename TreeNode, typename DataType = typename TreeNode::data_type>
TreeNode*
binary_tree_new_node(DataType value = DataType(),
                     DataType  TreeNode::* data  = &TreeNode::data,
                     TreeNode* TreeNode::* left  = &TreeNode::left,
                     TreeNode* TreeNode::* right = &TreeNode::right)
{
    TreeNode *newnode = new TreeNode();
    newnode->*data  = value;
    newnode->*left  = nullptr;
    newnode->*right = nullptr;
    return newnode;
}

Thus, it is possible to use the function with any suitable tree-node type of your choice. If the data members have different names (not data, left and right), then one can call the function and pass the pointers to the corresponding data members. This way, the function does not depend on (or at least can adjust itself to) how the data members of the input type are named.
It worked pretty well so far, but as I implement more and more functions, I'm getting tired of these pointer-to-data-member parameters which I have to list as optional parameters of the functions. So is there any better way to handle this? Maybe some sort of traits? Or somehow else?
I would like to keep the requirements on the input type as few as possible. For example, the client program should not be forced to define anything more than just the tree-node type. It shall not also be forced to use/derive-from any provided types or templates. Of course, the client program might re-use some of the provided templates, like the one below, which I also define, but should not really be forced to.
template<typename T>
struct binary_tree_node
{
    using data_type = T;
    data_type data;
    struct binary_tree_node *left;
    struct binary_tree_node *right;
};

What are the available options here?
Does it make any sense at all? :)
Thanks in advance

A: The way the STL collection libraries work is that the author of the tree library would supply the node class so that all the user of the template needs to do is supply the data.  The other option which you seem to be going for are intrusive data structures(that would be a good term to google for ideas). With those you have a couple of choices, the first is require the data members to be left, right, and data. Second require access functions with a specific name so the template can find them.  Third require functors to be passed in as template parameters so you can use them to find the data you need.  Personally I find the STL way the least messy, followed by the functors approach.

A: To make your algorithm as generic as possible I recommend using functors. Your binary_tree_new_node would look like
template<typename G, typename L, typename R, typename AT, typename AD, typename D>
auto binary_tree_new_node(
    G generator,
    L left,
    R right,
    AT assign_tree,
    AD assign_data,
    D data) ->decltype( generator() )
{
    auto  tree = generator();
    auto& l    = left(tree);
    auto& r    = right(tree);
    assign_data(tree, data);
    assign_tree(l, nullptr);
    assign_tree(r, nullptr);
    return tree;
}

For your binary_tree_node, the functors would look like:
// WARNING!!! Very dangerous code!!!

binary_tree_node* generator()
{
    return new binary_tree_node;
}

binary_tree_node*& left(binary_tree_node* tree)
{
    return tree->left;
}

binary_tree_node*& right(binary_tree_node* tree)
{
    return tree->right;
}

void assign_data(binary_tree_node* node, int data)
{
    node->data = data;
}

void assign_tree(binary_tree_node*& node, binary_tree_node* data)
{
    node = data;
}


text:
Q: IndexError: list index out of range - python I have the following error:
currency = row[0]
IndexError: list index out of range

Here is the code:
 crntAmnt = int(input("Please enter the amount of money to convert: "))
    print(currencies)
    exRtFile = open ('exchangeRate.csv','r')
    exchReader = csv.reader(exRtFile)
    crntCurrency = input("Please enter the current currency: ")
    validateloop=0
    while validateloop == 0:
        for row in exchReader:
                currency = row[0]
                if currency == crntCurrency:
                    crntRt = row[1]
                    validateloop=+1

Heres the CSV file:
Japanese Yen,169.948
US Dollar,1.67
Pound Sterling,1
Euro,5.5
Here's an input/Output example:
Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: Pound Sterling

A: You probably have a blank row in your csv file, causing it to produce an empty list
There are a couple solutions

 1. Check if there are elements, only proceed if there are:

for row in exchReader:
    if len(row):  # can also just do   if row:
        currency = row[0]
        if currency == crntCurrency:

 2. Short-circuit an and operator to make currency an empty list, which won't match crntCurrency:

for row in exchReader:
    currency = row and row[0]
    if currency == crntCurrency:

A: Try printing out the row. The convention for variable names in python are like_this and not likeThis. You might find the break keyword useful:
for row in exch_reader:
    currency = row[0]
    if currency == crnt_currency:
        crnt_rt = row[1]
        break

To only index the row when the row actually contains something:
currency = row and row[0]

Here row[0] is only executed if row evaluates to True, which would be when it has at least one element.


text:
Q: All 3 digit numbers the sum of whose digits is not greater than 16 My working: Let the digits of the numbers be $x,y,z$ where
\begin{align}1\leq x&\leq 9\\0\leq y,z&\leq 9\\x+y+z &\leq 16 \end{align}
I tried to solve it by making different cases here and using counting but it got really complicated and i couldnt get very far.
So how do i solve such questions?

A: Let $h$ denote the hundreds digit, $t$ denote the tens digit, and $u$ denote the units digit.  Since the digit sum is at most $16$,
$$h + t + u \leq 16 \tag{1}$$
where $1 \leq h \leq 9$, $0 \leq t \leq 9$, and $0 \leq u \leq 9$.
Let $h' = h - 1$.  Then $h'$ is a non-negative integer satisfying the inequalities $0 \leq h' \leq 8$.  Substituting $h' + 1$ for $h$ in inequality 1 yields
\begin{align*}
h' + 1 + t + u \leq 16\\
h' + t + u \leq 15 \tag{2}
\end{align*}
Inequality 2 is an inequality in the non-negative integers.
If we let $s = 15 - (h' + t + u)$, then we obtain the equation
$$h' + t + u + s = 15 \tag{3}$$
which is an equation in the non-negative integers.  If we ignore, for the moment, the restrictions on $h'$, $t$, and $u$, a particular solution of equation 3 corresponds to the placement of three addition signs in a row of fifteen ones.  For instance,
$$1 1 1 1 + 1 1 1 1 1 + 1 1 1 1 1 1 +$$
corresponds to the solution $h' = 4$, $t = 5$, $u = 6$, and $s = 0$, while
$$1 1 1 + 1 1 1 1 + 1 1 + 1 1 1 1 1 1$$
corresponds to the solution $h' = 3$, $t = 4$, $u = 2$, and $s = 6$.  Hence, the number of solutions of equation 3 in the non-negative integers is
$$\binom{15 + 3}{3} = \binom{18}{3}$$
since we must select which three of the eighteen symbols (fifteen ones and three addition signs) will be addition signs.
However, we have counted solutions in which $h' > 8$, $t > 9$, or $u > 9$.  We must exclude those solutions.
Suppose $h' > 8$.  Then $h' \geq 9$.  Let $h'' = h' - 9$.  Then $h''$ is a non-negative integer.  Substituting $h'' + 9$ for $h'$ in equation 3 yields
\begin{align*}
h'' + 9 + t + u + s & = 15\\
h'' + t + u + s & = 6 \tag{4}
\end{align*}
Equation 4 is an equation in the non-negative integers with
$$\binom{6 + 3}{3} = \binom{9}{3}$$
solutions.
Suppose $t > 9$.  Then $t \geq 10$.  Let $t' = t - 10$.  Then $t'$ is a non-negative integer.  Substituting $t' + 10$ for $t$ in equation 3 yields
\begin{align*}
h' + t' + 10 + u + s & = 15\\
h' + t' + u + s & = 5 \tag{5}
\end{align*}
Equation 5 is an equation in the non-negative integers with
$$\binom{5 + 3}{3} = \binom{8}{3}$$
solutions.
By symmetry, there are also $\binom{8}{3}$ solutions in which $u > 9$.
Notice that since $9 + 10 = 19 > 15$, at most one of the conditions $h' \leq 8$, $t \leq 9$, and $u \leq 9$ can be violated simultaneously in equation 3.  Hence, the number of solutions of equation 3 subject to those restrictions is
$$\binom{18}{3} - \binom{9}{3} - 2\binom{8}{3}$$

A: I think of these sorts of problems geometrically. Here, you can imagine $x$, $y$, and $z$ as describing the physical position of points on a cubic lattice. (It's not quite a cube, since the $x$ dimension is shorter than the other two.)
The constraint $x+y+z\le16$ describes a plane that cuts this cube into two parts: the acceptable part and the unacceptable part.
We can't immediately convert 'volume' to 'number of points in the cube', but this still guides the intuition of how to step through the problem and count correctly. For example, one might go slice by slice (in the $x$ direction, since that's the one that's distinct). For the slice $x=1$, the acceptable region is $0\le y\le9$ and $0\le z\le \mathrm{min}(9,15-y)$. That's a rectangle of size 10 by 7 (all $y$, $z$ from 0 to 6), a rectangle of size 7 by 3 ($z$ from 7 to 9, $y$ from 0 to 6), and then three points left over. So that's 94 for the $x=1$ slice, and now we can repeat the process for all possibilities of $x$.
We might have seen this more easily by realizing that there are 100 points in the slice and 6 points were excluded, and that's what I recommend you do going forward, as it's easier to calculate the new exclusion region (triangular numbers) than it is to calculate the new inclusion region. This longer method should make the explanation more clear, though.

A: Let $k\in\{1,2,...,16\}$ a fixed number. If you count the number of triplets $(x,y,z)$ such that $x+y+z=k$, say $S_k$, then you are searching for $S_0+S_1+...+S_{16}$,
Now, by generating functions method, we use the polinomyal $p(x)=(x+x^2+...+x^9)(1+x+x^2+...+x^9)^2$ and we want to find the coefficient of $x^k$.
But
$\begin{eqnarray}
p(x)&=&(x+x^2+...+x^9)(1+x+x^2+...+x^9)^2\\
&=&x\left(\frac{1-x^{9}}{1-x}\right)\left(\frac{1-x^{10}}{1-x}\right)^2\\
&=&x(1-x^9)(1-x^{10})^2(1-x)^{-3}\\
&=&x(1-x^{9})(1-2x^{10}+x^{20})\sum_{r=0}^\infty\binom{2+r}{2}x^r
\end{eqnarray}$
Now, it is easy to see that for $k=1,...,9$, the coefficient of $x^k$ is $\binom{2+k-1}{2}=\binom{k+1}{2}$.
For $k=10$, the coefficient is $\binom{2+9}{2}-\binom{2+0}{2}=\binom{11}{2}-1$
For $k=11,...,16$, the coefficient is $\binom{2+k-1}{2}-2\binom{2+k-11}{2}-\binom{2+k-10}{2}=\binom{k+1}{2}-2\binom{k-9}{2}-\binom{k-8}{2}$.
So, the answer is
$\begin{eqnarray}
S_0+...+S_{16}&=&\sum_{k=1}^{16}\binom{k+1}{2}-1-2\sum_{k=11}^{16}\binom{k-9}{2}-\sum_{k=11}^{16}\binom{k-8}{2}\\
&=&816-1-2*56-83\\
&=&620
\end{eqnarray}$


text:
Q: Trying to select a row of data with MYSQL by using a foreach loop Im trying to make a simple friend system with PHP & MYSQL and I don't know if it's even possible to get use data from another table with just their id. I am very new by the way so I don't know the language very well :) Any help would be very much valued
<?php if(count($friend_request) > 0): ?>
    <?php foreach ($friend_request as $friend_request): ?>
        <?php
            try{
                $statement = $db->query("SELECT * FROM users WHERE id = '$friend_request['id']' ");
                $user_info = $statement->fetchAll(PDO::FETCH_ASSOC);

            }catch (PDOException $ex){
                $user_info = flashMessage("An error occurred: " .$ex->getMessage());
            }

        ?>
        <?=$friend_request['id'] ?>
        <?=$friend_request['user_requested'] ?>
        <?=$friend_request['user_to'] ?>
        <?=$friend_request['request_date'] ?>
    <?php endforeach; ?>
<?php else: ?>

        <input id="emailInput" type="text" name="requestEmail" placeholder="someonesemail@bruh.com">

<?php endif; ?>

A: You need to use curly syntax if you want to put a quoted string in the index of a variable inside a string.
$statement = $db->query("SELECT * FROM users WHERE id = '{$friend_request['id']}' ");

You can also leave the quotes out of the index, but that's not my preference.
But it would be better to use a prepared statement.
<?php
if(count($friend_request) > 0):
    $statement = $db->prepare("SELECT * FROM users WHERE id = :id ");
    foreach ($friend_request as $friend_request):
        try{
            $statement->execute([':id' => $friend_request['id']]);
            $user_info = $statement->fetchAll(PDO::FETCH_ASSOC);
        }catch (PDOException $ex){
            $user_info = flashMessage("An error occurred: " .$ex->getMessage());
        }
        ?>
        <?=$friend_request['id'] ?>
        <?=$friend_request['user_requested'] ?>
        <?=$friend_request['user_to'] ?>
        <?=$friend_request['request_date'] ?>
    <?php endforeach; ?>
<?php else: ?>

        <input id="emailInput" type="text" name="requestEmail" placeholder="someonesemail@bruh.com">

<?php endif; ?>

A: I assume your id is numeric, pass the value to a new var like $id = friend_request['id']; then your query can be
"SELECT * FROM users WHERE id = $id LIMIT 1"
without the " ' ", the "limit 1" is for performance, and the fetch you need to use just fetch more info here to retrieve just the row
$statement->fetch(PDO::FETCH_ASSOC);
later you can print or use the array $user_info for whatever you need it directly.


text:
Q: Excel Regression with Multiple Data Sets I have a dataset of job titles, salaries, and experience levels. I want to regress salary on experience BY job title. (I.E. several different regression analyses, one for each job title). Any way to do this without separating or sorting the data? I think an array formula plus INTERCEPT and SLOPE might do it?

A: You are correct. For single-term models, SLOPE, INTERCEPT, and RSQ as array formulas will do it:
=SLOPE(IF(Table1[Job Title]=E2,Table1[Salary]),IF(Table1[Job Title]=E2,Table1[Experience]))

Just change SLOPE to INTERCEPT or RSQ to get those values.

A: You could also use the data analysis toolpak, built-in regression tool.


text:
Q: Jboss error New missing/unsatisfied dependencies jboss.naming.context.java.jboss.datasources I have the following datasource, we are using oracle jdbc driver, ojdbc6.jar :
<?xml version="1.0" encoding="UTF-8"?>
<datasources xmlns="http://www.jboss.org/ironjacamar/schema">
  <datasource jndi-name="java:jboss/datasources/hubAdminDS" enabled="true"
   use-java-context="true" pool-name="hubAdmin" jta="false">
    <connection-url>jdbc:oracle:thin:@10.0.153.177:1521:XE</connection-url>
    <driver>ojdbc6.jar</driver>
    <pool>
      <min-pool-size>5</min-pool-size>
      <max-pool-size>10</max-pool-size>
      <prefill>true</prefill>
    </pool>
    <security>
      <user-name>HUBDBLOCAL</user-name>
      <password>HUBDBLOCAL</password>
    </security>
  </datasource>

  <datasource jndi-name="java:jboss/datasources/TASK_DB" enabled="true"
   use-java-context="true" pool-name="TASK_DB" spy="true" use-ccm="true">
    <connection-url>jdbc:oracle:thin:@10.0.153.177:1521:XE</connection-url>
    <driver>ojdbc6.jar</driver>
    <pool>
      <min-pool-size>10</min-pool-size>
      <max-pool-size>20</max-pool-size>
      <prefill>true</prefill>
    </pool>
    <security>
      <user-name>HUBDBLOCAL</user-name>
      <password>HUBDBLOCAL</password>
    </security>
  </datasource>

 <datasource jndi-name="java:jboss/datasources/SAFE" enabled="true"
  use-java-context="true" pool-name="SAFE" jta="false">
   <connection-url>jdbc:oracle:thin:@10.0.153.177:1521:XE</connection-url>
   <driver>ojdbc6.jar</driver>
   <pool>
     <min-pool-size>3</min-pool-size>
     <max-pool-size>4</max-pool-size>
     <prefill>true</prefill>
   </pool>
   <security>
     <user-name>HUBDBLOCAL</user-name>
     <password>HUBDBLOCAL</password>
   </security>
 </datasource>

 <datasource jndi-name="java:jboss/datasources/JDBC_DB" enabled="true"
  use-java-context="false" pool-name="JDBC_DB" jta="false">
   <connection-url>jdbc:oracle:thin:@10.0.153.177:1521:XE</connection-url>
   <driver>ojdbc6.jar</driver>
   <pool>
      <min-pool-size>5</min-pool-size>
      <max-pool-size>10</max-pool-size>
      <prefill>true</prefill>
    </pool>
    <security>
      <user-name>HUBDBLOCAL</user-name>
      <password>HUBDBLOCAL</password>
    </security>
  </datasource>

  <datasource jndi-name="java:jboss/datasources/MAIL_SENDER_DB"
   enabled="true" use-java-context="true" pool-name="MAIL_SENDER_DB"
   jta="false">
    <connection-url>jdbc:oracle:thin:@10.0.153.177:1521:XE</connection-url>
    <driver>ojdbc6.jar</driver>
    <pool>
      <min-pool-size>3</min-pool-size>
      <max-pool-size>4</max-pool-size>
      <prefill>true</prefill>
    </pool>
    <security>
      <user-name>HUBDBLOCAL</user-name>
      <password>HUBDBLOCAL</password>
    </security>
  </datasource>

   <datasource jndi-name="java:jboss/datasources/HELPDESK" enabled="true"
    use-java-context="true" pool-name="HELPDESK" jta="false">
     <connection-url>jdbc:oracle:thin:@10.0.153.177:1521:XE</connection-url>
     <driver>ojdbc6.jar</driver>
     <pool>
       <min-pool-size>10</min-pool-size>
       <max-pool-size>20</max-pool-size>
       <prefill>true</prefill>
     </pool>
     <security>
       <user-name>HUBDBLOCAL</user-name>
       <password>HUBDBLOCAL</password>
     </security>
   </datasource>
</datasources>

when I deploy the application, I got the following error :
15:44:40,915 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 2)
JBAS014774: Service status report
JBAS014775:    New missing/unsatisfied dependencies:
  service jboss.naming.context.java.jboss.datasources.JDBC_DB (missing) dependents: [service jboss.naming.context.java.module.bpm.bpm.env."com.hds.hub.api.processes.impl.UserServicesEJB".dataSource, service jboss.naming.context.java.module.bpm.bpm.env."com.hds.hub.iArchive.impl.FileArchiveServiceEJB".dataSource]
  service jboss.naming.context.java.jboss.datasources.MAIL_SENDER_DB (missing) dependents: [service jboss.naming.context.java.module.bpm.bpm.env.jdbc.MAIL_SENDER_DB]
  service jboss.naming.context.java.jboss.datasources.TASK_DB (missing) dependents: [service jboss.naming.context.java.module.bpm.bpm.env.jdbc.TASK_DB, service jboss.persistenceunit."bpm.war#org.jbpm.persistence.jpa"]
  service jboss.naming.context.java.jboss.datasources.hubAdminDS (missing) dependents: [service jboss.naming.context.java.module.bpm.bpm.env.jdbc.HUB_ADMIN_DB]

15:44:40,921 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014771: Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.bpm.bpm.env.\"com.hds.hub.iArchive.impl.FileArchiveServiceEJB\".dataSourcejboss.naming.context.java.jboss.datasources.JDBC_DBMissing[jboss.naming.context.java.module.bpm.bpm.env.\"com.hds.hub.iArchive.impl.FileArchiveServiceEJB\".dataSourcejboss.naming.context.java.jboss.datasources.JDBC_DB]","jboss.naming.context.java.module.bpm.bpm.env.jdbc.HUB_ADMIN_DBjboss.naming.context.java.jboss.datasources.hubAdminDSMissing[jboss.naming.context.java.module.bpm.bpm.env.jdbc.HUB_ADMIN_DBjboss.naming.context.java.jboss.datasources.hubAdminDS]","jboss.naming.context.java.module.bpm.bpm.env.jdbc.TASK_DBjboss.naming.context.java.jboss.datasources.TASK_DBMissing[jboss.naming.context.java.module.bpm.bpm.env.jdbc.TASK_DBjboss.naming.context.java.jboss.datasources.TASK_DB]","jboss.naming.context.java.module.bpm.bpm.env.\"com.hds.hub.api.processes.impl.UserServicesEJB\".dataSourcejboss.naming.context.java.jboss.datasources.JDBC_DBMissing[jboss.naming.context.java.module.bpm.bpm.env.\"com.hds.hub.api.processes.impl.UserServicesEJB\".dataSourcejboss.naming.context.java.jboss.datasources.JDBC_DB]","jboss.naming.context.java.module.bpm.bpm.env.jdbc.MAIL_SENDER_DBjboss.naming.context.java.jboss.datasources.MAIL_SENDER_DBMissing[jboss.naming.context.java.module.bpm.bpm.env.jdbc.MAIL_SENDER_DBjboss.naming.context.java.jboss.datasources.MAIL_SENDER_DB]","jboss.persistenceunit.\"bpm.war#org.jbpm.persistence.jpa\"jboss.naming.context.java.jboss.datasources.TASK_DBMissing[jboss.persistenceunit.\"bpm.war#org.jbpm.persistence.jpa\"jboss.naming.context.java.jboss.datasources.TASK_DB]"]}}}

JDBC_DB, MAIL_SENDER, TASK_DB and hubAdminDS are defined in the datasource
When I connect to the remote server there is no error but when I connect to the local server I have the above errors.
Anyone can explain, why I have thoses errors ? How I can correct it ?

A: It looks like your datasource ("java:jboss/datasources/JDBC_DB") is not properly deployed inside JBoss  server, Follow the below steps to get this done:
Install a JDBC driver as a core module:

1.Create a directory under $JBOSS_HOME/modules. In this example: "$JBOSS_HOME/modules/com/oracle/jdbc/main".
2.Put the the JDBC driver jar (ojdbc6.jar) in this directory
3.Create a module configuration file module.xml:

<module xmlns="urn:jboss:module:1.1" name="com.oracle.jdbc">
  <resources>
    <resource-root path="ojdbc6.jar"/>
  </resources>
  <dependencies>
    <module name="javax.api"/>
    <module name="javax.transaction.api"/>
  </dependencies>
</module>

Note that the jdbc driver jar must contain a META-INF/services/java.sql.Driver text file that specifies the jdbc Driver, otherwise the Java service provider mechanism used to load the driver will not work. From the main/common vendors only Informix does not have this out of the box.

4.Configure a datasource setting in standalone.xml or domain.xml.

You can now edit your standalone(-).xml or domain(-).xml to configure a datasource that references this module:
<subsystem ...>
    <datasources>
      <datasource jndi-name="java:jboss/datasources/OracleDS" pool-name="OracleDS" enabled="true" use-java-context="true">
        <connection-url>jdbc:oracle:thin:@myhostname:1521:oracle</connection-url>
        <driver>oracle</driver>
        <pool>
          <min-pool-size>10</min-pool-size>
          <max-pool-size>20</max-pool-size>
          <prefill>true</prefill>
        </pool>
        <security>
          <user-name>myuser</user-name>
          <password>mypass</password>
        </security>
        <validation>
          <validate-on-match>true</validate-on-match>
          <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker"></valid-connection-checker>
          <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker"></stale-connection-checker>
          <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter"></exception-sorter>
        </validation>
      </datasource>
      <drivers>
        <driver name="oracle" module="com.oracle.jdbc">
          <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
        </driver>
      </drivers>
    </datasources>
  </subsystem>

or for an xa-datasource:
<subsystem ...>
      <datasources>
          <xa-datasource jndi-name="java:/XAOracleDS" pool-name="XAOracleDS">
              <driver>oracle</driver>
              <xa-datasource-property name="URL">jdbc:oracle:thin:@myhostname:1521:oracle</xa-datasource-property>
              <security>
                  <user-name>admin</user-name>
                  <password>admin</password>
              </security>
              <xa-pool>
                   <is-same-rm-override>false</is-same-rm-override>
                   <no-tx-separate-pools />
              </xa-pool>
              <validation>
                   <validate-on-match>true</validate-on-match>
                  <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker"></valid-connection-checker>
                  <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker"></stale-connection-checker>
                  <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter"></exception-sorter>
              </validation>
          </xa-datasource>
          <drivers>
               <driver name="oracle" module="com.oracle">
                   <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
               </driver>
          </drivers>
      </datasources>
  </subsystem>

Once DB-Driver is set up as a module and  server log says below:
12:10:47,381 INFO  [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-2) JBAS010400: Bound data source [java:jboss/datasources/OracleDS]
....

A: I needed to allow multiple connection to my database which was limited by the following command :
sqlplus / as sysdba

ALTER SYSTEM SET PROCESSES= 300 SCOPE=SPFILE;
SHUT IMMEDIATE;
STARTUP;


text:
Q: Displaying warning to IE6-8 users once per session I've looked around and I couldn't find an exact solution, but if one does exist, I apologise.
Now, the problem I'm having is displaying a div once per session to users of the older versions of Internet Explorer i.e. < IE9.
Here is the code I quickly put together but it doesn't seem to be working, could someone please tell me what's wrong with it? Am I doing it all wrong?
<!--[if lt IE 9]>
<script>
    /* Set initial cookie after entire page has loaded */
    document.cookie="messageseen=true";

    /***********
       This cookie won't exist initially, but when the if statement below checks
       for the message seen cookie, the clear message cookie will also be set,
       this is so on subsequent page-loads, it won't take 5 seconds for the the
       message to disappear.
    ***********/
    if (document.cookie == "clearmessage") {
       $('.ie-message').hide(); // hide message without delate
    }

    /***********
       After 5 seconds, check for the messageseen cookie, if it exists, set the
       clearmessage cookie and hide .ie-message. On all subsequent page-loads,
       the message will be hidden immediately without the delay.
    ***********/
    setTimeout(function (){
       if (document.cookie == "messageseen") {
          document.cookie="clearmessage=true";
          $('.ie-message').hide(); // hide message if cookie is set
       }
    }, 5000); // delay the hiding of the message for 5 seconds
</script>
<![endif]-->

A: Using
https://github.com/carhartl/jquery-cookie
<!--[if lt IE 9]>
<script>
    /* Set initial cookie after entire page has loaded */
    $.cookie("messageseen",true);

    /***********
       This cookie won't exist initially, but when the if statement below checks
       for the message seen cookie, the clear message cookie will also be set,
       this is so on subsequent page-loads, it won't take 5 seconds for the the
       message to disappear.
    ***********/
    $('.ie-message').toggle(!$.cookie("clearmessage")); // hide message without delate

    /***********
       After 5 seconds, check for the messageseen cookie, if it exists, set the
       clearmessage cookie and hide .ie-message. On all subsequent page-loads,
       the message will be hidden immediately without the delay.
    ***********/
    setTimeout(function (){
       if ($.cookie("messageseen")) {
          $.cookie("clearmessage",true);
          $('.ie-message').toggle(0); // hide message if cookie is set
       }
    }, 5000); // delay the hiding of the message for 5 seconds
</script>
<![endif]-->

A: If you only going to have that one cookie you can do something like that:
(note that i'm hiding the div inline to prevent blinking on slow page load)
<!--[if lt IE 9]>
<div class"ie-message" style="display:none;">IE MESSAGE</div>
<script>
(function($){
  if ( document.cookie == "" ) {
  // show message
  $('.ie-message').show();
  // add cookie;
  document.cookie = "seen=true";
}
</script>
<![endif]-->


text:
Q: Checkbox not setChecked not smoothly I have a CheckBox that I set OnCheckedChangeListener for it and in the onCheckedChange method I have heavy code. When I want to set Checkbox.checked it gets checked with a little delay. I want it to set checked smooth with no delay I used post and runnable in onCheckedChange method but it wasn't changed.

A: Try to use threads , I think it'll help
new Thread(new Runnable() {
        public void run(){
            // Your heavy code
        }
    }).start();

A: You can use setOnClickListener, in onClick method write your code..
To get the status of checkbox, you can use isChecked() method which returns boolean value.
c.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean checked = ((CheckBox) v).isChecked();
            switch (v.getId()) {

                case R.id.checkboxid:

                    if (checked) {
                        //true case
                    } else {
                        //false case
                    }
                    break;
            }
        }
    });

A: Thread and post on View didn't help,but postDelayed helped me
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   final int id = buttonView.getId();

    buttonView.postDelayed(new Runnable() {
        @Override
        public void run() {

           //hard code

            }

        }
    },400);

}


text:
Q: ActiveRecord::RecordNotFound in AlbumsController#show In my web app I'm trying to make a show action in which the current_users photos are showed for a particular album when that album is clicked. However, every time I click on the link to the show action I get an error saying 'Couldn't find Album with 'id'=:id [WHERE "albums"."user_id" = ?]'. The show action looks like this:
def show
    @album = current_user.albums.find(params[:id])
    @photos = @album.photos
end

view:

    <% @albums.each do |x| %>

<%= link_to x.name, "/albums/:id", :style => "text-decoration:none;" %>

    <% end %>

        <%= link_to 'New Album', "/albums/new", :style => "text-decoration:none;" %>

            <%= link_to '+', "/albums/new", :style => "text-decoration:none; color:black; font-size:80px; color:#85adad;" %>

routes:
      get '/albums' => 'albums#index', as: :albums
  get '/albums/new' => 'albums#new'
  post '/albums/new' => 'albums#create'
  get '/albums/:id' => 'albums#show'
  get '/albums/:id/destroy' => 'albums#destroy'

A: Your issue is the link_to URL you're displaying
link_to x.name, "/albums/:id"

That's assigning :id as the argument passed to the URL. Instead you want to do something like "/albums/#{x.id}" so that it uses the album ID as the ID parameter on the URL path.


text:
Q: onchange event not working for notifications permission in SW for firefox I recently added a notification part for our web application and it's working fine on chrome and opera, but for firefox, initially, I got an error with this message:

The Notification permission may only be requested from inside a short running user-generated event handler.

So, I added a button for granting the notifications permission and now I find out there is a bigger bug; the 'onchange' event of navigator.permissions not working to activate notifications after getting permission from the user. here is my code:
self.addEventListener('activate', async () => {
   if ('permissions' in navigator) { // inside of this if not executing on firefox
       navigator.permissions.query({ name: 'notifications' }).then(function (permissionStatus) {
           permissionStatus.onchange = function () {
            // do thing in here...
           };
      });
   }
   //...
});

Although I know 'window' is the default variable in js files, I also tried 'window.navigator' instead of 'navigator' and nothing changed.

A: Finally, I found out since we are triggering ask permission by hand and by clicking on a button, the firefox mechanism is different and we should do our onchange action as a result of the permission request promise just like below:
      Notification.requestPermission()
     .then(async result => {
        if (result === 'granted') {
           // subscribe and do stuff in here...
        }
     })
     .catch(err => {
        console.log('Error: ', err);
     });

You can still use the explained onchange method for other browsers like chrome.


text:
Q: Using iTextSharp to stamp form field with bold text I have a field in a form that I want to fill with both bold and regular text, rather than creating two separate fields.  I know I can do this:
var normalfont = FontFactory.GetFont(FontFactory.HELVETICA);
            var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD);
            var phrase = new Phrase();
            phrase.Add(new Chunk("Name: ", boldfont));
            phrase.Add(new Chunk(line.LastName + ", " + line.FirstName, normalfont));
 form.SetField("name", phrase);

But then how do I set the field in the form to the phrase I just created?
Is there a better way to do this or should I just break up my fields?


text:
Q: Application Defined or Object defined error when setting data validation dynamically for a range Im trying to add data validation to a column dynamically in which the values for each cell dropdown are from another sheet.
Here is the code
Dim fRange As Range
Dim lRow As Integer
lRow = Sheets("Service_master").Cells(Sheets("Service_master").Rows.count, 1).End(xlUp).Row
Set fRange = Sheets("Service_master").Range("A2:A" & lRow)
Dim dRange As Range
lRow = Sheets("resource_master").Cells(Sheets("resource_master").Rows.count, 1).End(xlUp).Row
Set dRange = Sheets("resource_master").Range("G2:G" & lRow)
With dRange.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="=Service_master!" & fRange.Address
End With

But in .Add line where we are specifying the formular its triggering an error Application defined or object-defined error
The formula is "=Service_master!$A$2:$A$6" at that line.
At that sheet there is data in that range which I wants to be there for the dropdown or resource_master


text:
Q: postgres, how to put all the content of a table in a hash? I would like to put all the results from a select to a hash, that will have the name of the table as the key and the value is an array that will have the rows, here is what I did so far :
def table_content_to_hash(table)
 hash = {}
 rs = @pg_conn.exec "SELECT * FROM #{table}";
 rs.each do |child|
  # want to put table name as key and value is an array that has the rows
  hash['#{table}'] = child  # THIS ONE IS WRONG
 end
 puts hash
end

Update, my code works after using Spickermann solution, here is the result :
{"company"=>[{"id"=>"1", "name"=>"Paul", "age"=>"32", "address"=>"California                                        ", "salary"=>"20000"}, {"id"=>"2", "name"=>"Allen", "age"=>"25", "address"=>"Texas                                             ", "salary"=>"15000"}, {"id"=>"3", "name"=>"Teddy", "age"=>"23", "address"=>"Norway
                                    ", "salary"=>"20000"}, {"id"=>"4", "name"=>"Mark", "age"=>"25", "address"=>"Rich-Mond
", "salary"=>"65000"}, {"id"=>"5", "name"=>"David", "age"=>"27",
"address"=>"Texas                                             ",
 "salary"=>"85000"}, {"id"=>"6", "name"=>"Kim", "age"=>"22",
 "address"=>"South-Hall                                        ",
 "salary"=>"45000"}, {"id"=>"7", "name"=>"James", "age"=>"24",
  "address"=>"Houston                                           ",
"salary"=>"10000"}]}

I don't know ho to remove that space the value of the address.
Thanks,

A: Just initialize your hash with the table name and an empty array right away:
def table_content_to_hash(table)
  hash = { table => [] }

  rows = @pg_conn.exec "SELECT * FROM #{table}";
  rows.each do |row|
    hash[table] << child
  end

  puts hash
end


text:
Q: How do you reference other project's dll on vscode I installed asp.net mvc with yo generator and using vs code in Ubuntu linux. It is working great with angular single page App.  But how will I build Business, Data Access dll project, test project with visual studio code and reference from Web Project?

A: In your project.json file there is the dependencies section. Put your other projects in this section.
In your web project's project.json
...
"dependencies": {
  "Business": 1.0.0-*"
}
...

In your Business project's project.json
...
"dependencies": {
  "DataAccess": 1.0.0-*"
}
...

I also have a global.json file in the root folder to specify the src and test projects. Example layout of global.json:
{
  "projects": [
    "src",
    "tests"
  ]
}

This works for me with the following folder structure:
project/
  global.json
  .vscode/
  src/
    web/
    business/
    dataaccess/
  tests/
    ...


text:
Q: Android camera - taken picture inconsistent with preview I'm having an issue with the camera on Android, basically when I take a photo with the Camera class, the taken output picture actually shows more than the preview. The best way to put it would be the preview is cropped. How would I fix this?
I've run the app on Samsung Galaxy S4, Samsung Galaxy S3, HTC One M8 and Nexus One and all exhibit this same issue. (All running Android 4.0 ICS)
The camera preview is full screen in an Activity with no Action Bar and the status bar hidden.
The camera i'm trying to create is portrait so I've set displayOrientation to 90.
The code I use for determining preview size and output photo size is as follows (I believe the problem is most likely here somewhere):
public static Camera.Size getBestAspectPreviewSize(int displayOrientation,
                                                 int width,
                                                 int height,
                                                 Camera.Parameters parameters,
                                                 double closeEnough) {
double targetRatio=(double)width / height;
Camera.Size optimalSize=null;
double minDiff=Double.MAX_VALUE;

if (displayOrientation == 90 || displayOrientation == 270) {
  targetRatio=(double)height / width;
}

List<Size> sizes=parameters.getSupportedPreviewSizes();

Collections.sort(sizes,
                 Collections.reverseOrder(new SizeComparator()));

for (Size size : sizes) {
  double ratio=(double)size.width / size.height;

  if (Math.abs(ratio - targetRatio) < minDiff) {
    optimalSize=size;
    minDiff=Math.abs(ratio - targetRatio);
  }

  if (minDiff < closeEnough) {
    break;
  }
}

return(optimalSize);
}

 public static Camera.Size getLargestPictureSize(CameraHost host,
                                              Camera.Parameters parameters,
                                              boolean enforceProfile) {
Camera.Size result=null;

for (Camera.Size size : parameters.getSupportedPictureSizes()) {

  // android.util.Log.d("CWAC-Camera",
  // String.format("%d x %d", size.width, size.height));

  if (!enforceProfile
      || (size.height <= host.getDeviceProfile()
                             .getMaxPictureHeight() && size.height >= host.getDeviceProfile()
                                                                          .getMinPictureHeight())) {
    if (result == null) {
      result=size;
    }
    else {
      int resultArea=result.width * result.height;
      int newArea=size.width * size.height;

      if (newArea > resultArea) {
        result=size;
      }
    }
  }
}

if (result == null && enforceProfile) {
  result=getLargestPictureSize(host, parameters, false);
}

return(result);
 }

Size comparator class:
private static class SizeComparator implements
  Comparator<Camera.Size> {
@Override
public int compare(Size lhs, Size rhs) {
  int left=lhs.width * lhs.height;
  int right=rhs.width * rhs.height;

  if (left < right) {
    return(-1);
  }
  else if (left > right) {
    return(1);
  }

  return(0);
}
}

This is using cwac-camera and using SimpleCameraHost with no changes.
Any help is appreciated!

A:
How would I fix this?

If you are using the full-bleed preview, the preview will be cropped in most cases, as the aspect ratio of the CameraView is unlikely to match the aspect ratio of the preview frames.
Quoting the documentation:

The original default behavior of CameraFragment and CameraView was to show the entire
  preview, as supplied by the underlying Camera API. Since the aspect ratio of
  the preview frames may be different than the aspect ratio of the CameraView,
  this results in a "letterbox" effect, where the background will show through on
  one axis on the sides.
The new default behavior is to completely fill the CameraView, at the cost of
  cropping off some of the actual preview frame, what is known as "full-bleed preview"
  (stealing some terminology from the world of print media).
To control this behavior:

*

*Have your CameraHost
  return true or false from useFullBleedPreview()

*Or, call useFullBleedPreview()
  on your SimpleCameraHost.Builder, passing in a boolean value to use by default.
Note that the pictures and videos taken by this library are unaffected by
  useFullBleedPreview(). Hence, if useFullBleedPreview() returns true, the
  picture or video may contain additional content on the edges that was not
  visible in the preview.


text:
Q: How to verify this identity? From Weinstock, "Calculus of Variations", p.24:

We have the readily verifiable identity
\begin{align}\frac{d}{dx}\left(y'\frac{\partial f}{\partial y'}-f\right) = y'\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right) - \frac{\partial f}{\partial x} - \frac{\partial f}{\partial y}y'=-y'\left[\frac{\partial f}{\partial y}-\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right)\right]-\frac{\partial f}{\partial x}\end{align}

Where $f$ is $f(x,y,y')$ and $y$ is a function of $x$.
For some reason I can't seem to verify this identity. Applying the product rule didn't, to the extent of my (admittedly limited) knowledge, seem to help. What am I doing wrong?

A: You can't prove it- it simply isn't true!
For example, if we take $y'(x)= x^3$ and $f(y')= y'^2$ so that $f(x)= (x^3)^2= x^6$  then $y'\frac{\partial f}{\partial y'}- f= y'(2y')- y'^2= y^2$ so $\frac{d}{dx}\left(y'\frac{\partial f}{\partial y'}- f\right)= \frac{dy^2}{dx}= \frac{dx^6}{dx}= 6x^5$.
But $y'\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right)-\frac{\partial f}{\partial x}- \frac{\partial f}{\partial y'}y'$ is $(x^3)\frac{d}{dx}(2x^3)- 6x^5- (2x^3)x^3= 6x^5- 6x^5- 2x^6= 2x^6$

A: Thanks to achille hui (and stated in p.5 of the quoted book), I see it now:
If $f$ is $f(x, y, y')$ and $y=y(x)$ then
$$\frac{df}{dx}=\frac{\partial f}{\partial x}+y'\frac{\partial f}{\partial y}+y''\frac{\partial f}{\partial y'}$$
This way,
$$\require{cancel}\begin{align}\frac{d}{dx}\left(y'\frac{\partial f}{\partial y'}-f\right)=y'\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right)+\cancel{y''\frac{\partial f}{\partial y'}}-\frac{\partial f}{\partial x}-y'\frac{\partial f}{\partial y}-\cancel{y''\frac{\partial f}{\partial y'}}
=y'\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right)-y'\frac{\partial f}{\partial y}-\frac{\partial f}{\partial x}\end{align}$$
Thereby proving the identity.


text:
Q: Disable rounded avatar I hate these rounded avatars in Gitlab.  They look ridiculous and cause more problems than they are worth when trying to set logo images and such.  How do I turn that thing off and go back to good old fashioned square avatars?
BTW, I would want to disable them across the board.  Everywhere they are used, I want them gone and back to square.


text:
Q: Angular.js beginner what version should I use? I am starting to integrate Angular.js into my web project.
I see on the Angular.js download page they have version 2.0.0-snapshot although I don't think version 2 has been formally released.
From the looks of the download page I think the last stable version was 1.4.7. Is that the last stable version?
And also what is recommended? Should start with version 2 or version 1.4.7 (keeping in mind a I am complete beginner).

A: Angular 2 is currently in Developer Preview. Angular 1.X is recommended for production applications.
That said. It's pretty important to remember that Angular 2 is basically a completely different framework with little-to-no backwards compatibility. When we all do switch (and we will someday), we'll have to start with a fresh plugin community, or wait until developers choose to update their modules to include an Angular 2 version.

Our goal with Angular 2 is to make the best possible set of tools for building web apps not constrained by maintaining backwards compatibility with existing APIs. - Angular Blog

I think the time to migrate will be around 6 months after a production release of Angular 2. That will give the developer community time to catch up and give the framework time to mature in the real world.


text:
Q: Is it possible to share header file only with a cc_test target? Say I have a package with a single cc_library target and an inner package for tests with a single cc_test target as follows:
mylib/
     BUILD
     mylib.h
     mylib.c
     mylib-private.h
     tests/
         BUILD
         test.c

In order to perform some unit-tests I need access to "private" methods, so I created mylib-private.h which I want to include only in the test code.
Obviously this header should not be part of the library API and should not be shipped with it.
If I add mylib-private to the hdrs of mylib - It'll be visible to all.
If I add mylib-private to srcs of mylib - only mylib can use it...
Is there a way to control the visibility of a single header file?

A: Not sure what is the official recommended pattern here, but I ended up inclduing both mylib and mylib-tests in the same package, and then they could both add mylib-private to their srcs attribute:
BUILD:
cc_library(
    name="mylib",
    hdrs=["mylib.h",],
    srcs=[
        "mylib.c",
        "mylib-private.h"
    ]
)

cc_test(
    name="mylib-tests",
    srcs=glob([
        "tests/*.c",
        "mylib-private.h"
    ]),
    deps=[
        "//:mylib"
    ]
)

And the structure:
mylib/
     BUILD
     mylib.h
     mylib.c
     mylib-private.h
     tests/
         test.c


text:
Q: Coldfusion Cross site authentication Ok, so on the coldfusion site I'm working on I just installed a third party (open source) CF forum known as "Galleon".
I asked a similar question a bit ago but now we have progressed a bit.
The issue at hand is that it will not recognize -any- variables (sessions, etc) that exist of the parent site proper. The forum itself is stored inside of a sub folder within the site directory.. But when we try to output session variables, which we know have not expired or whatnot, it spits out an error and doesn't recognize them.
I scanned for anything that clears variables (like structclear(session), etc) and didn't turn up much.. Is there some kind of setting in application.cfm I should be aware of?
In general how do you get cross application authentication going on CF?
What we want to do is populate a new session variable based off of the existing session.userid variable that is created when the user logs onto the main site. We want this so we can bypass having to ask them to login in AGAIN into the Galleon forum (and all the complications this causes).

A: It's very possible that in the forum's Application.cfc, you'll need to extend the root Application.cfc. Then you'll update the forum's onApplicationStart() to call super.onApplicationStart() before anything else. The same may be true for each Application.cfc function, depending on what's going on in the parent Application.cfc.
Galleon's Application.cfc would no longer need the application name and other variables setup in the parent Application.cfc (like @Ben noted).

A: Make sure your Application name is the same in both application.cfms/application.cfc between the two applications otherwise they won't share the same session/application data.
And do a quick scan for possible variable conflicts between the applications like "session.user" etc.


text:
Q: Python how to rotate log file when file is busy? Using Python's RotatingFileHandler, if the log file happens to be open in another application (e.g. Notepad) when the logger tries to rotate, it fails with this error.  Is there some way to force it to "take over" the file and rename it anyway?
--- Logging error ---
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\logging\handlers.py", line 74, in emit
    self.doRollover()
  File "C:\Program Files\Python310\lib\logging\handlers.py", line 179, in doRollover
    self.rotate(self.baseFilename, dfn)
  File "C:\Program Files\Python310\lib\logging\handlers.py", line 115, in rotate
    os.rename(source, dest)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\admin\\Documents\\rpi_miniconfig\\hi5_monitoring.log' -> 'C:\\Users\\admin\\Documents\\rpi_miniconfig\\hi5_monitoring.log.1'
Call stack:
  File "C:\Users\admin\Documents\rpi_miniconfig\hi5_monitoring.py", line 46, in <module>
    main()
  File "C:\Users\admin\Documents\rpi_miniconfig\hi5_monitoring.py", line 16, in main
    logger.info(datetime.now().strftime('%x %X'))
Message: '07/15/22 16:50:42'
Arguments: ()


text:
Q: How to calculate total memory used by one table? I have innodb_buffer_pool_size=100GB;
show table status where name='test_tb'\G

gives
    Data_length: 4686086144
Max_data_length: 0
   Index_length: 5107564544

seems index uses 5GB memory.
ANALYZE table test_tb;
SELECT
sum(stat_value) pages,
  index_name,
  sum(stat_value) * @@innodb_page_size /1024/1024 "size(MB)"
  FROM
  mysql.innodb_index_stats
  WHERE
  table_name = 'test_tb'
  AND database_name = 'test_dbs'
  AND stat_description = 'Number of pages in the index'
  GROUP BY
  index_name;

+--------+-------------------+---------------+
| pages  | index_name        | size(MB)      |
+--------+-------------------+---------------+
| 286016 | PRIMARY           | 4469.00000000 |
| 150014 | test_key1         | 2343.96875000 |
| 161727 | test_key2         | 2526.98437500 |
+--------+-------------------+---------------+

its 8GB.
So which one is accurate?

A: Both are correct; both say the same values.  (Don't divide by 1024*1024; it will be a little more obvious.)
In InnoDB, the PRIMARY KEY is "clustered" with the data.  That is, they are both in the same BTree structure.  The PK provides the order; the data provides the content.
In your table, the data is ~4GB, including the PK and BTree overhead; the two indexes are in two separate BTrees, adding up to about 5GB.


text:
Q: Difference between Adjusted R Squared and Predicted R Squared As we all know, depending solely on R squared to determine goodness of fit is faulty because the R squared value will always increase when more predictors are added, regardless of their physical correlation. With this in mind, many people recommend using the adjusted R squared value, especially if the equation will be used to estimate future values.
However, I recently stumbled upon something called the predicted R squared value, which relies on the predicted residual error sum of squares (PRESS) statistic. In this method,

*

*A data point from your dataset is removed

*A refitted linear regression model is generated

*The removed data point is plugged into the refitted linear model, generating a predicted value

*The removed data point is placed back into your dataset. Repeat from step 1 for the next data point until all data points have had a chance to be removed.

Afterward, you get a vector of predicted values which you subtract from their analogous true values to get a predicted residual value, which can be squared to convert it into a PRESS value. When calculating the predicted R Squared, the PRESS effectively replaces the sum of squares residuals value in the R Squared formula.
My question is which method is better at taking into account overmodeling, adjusted R Squared or predicted R Squared? The adjusted R Squared formula relies on the R squared value and the dataset size and predictor number, but the predicted R Squared completely re-calculates the sum of squares residual.
A part of a project I'm working on requires creating a multilinear regression model to correlate predictors (fictional example) such as grass length, intensity of green grass color, quantity of grass per square area, etc. (x variables) to cow happiness (y variable). The adjusted R squared and predicted R squared values react completely differently when I go from 3 to 4 to 5 predictors. The adjusted R squared value stays pretty much constant around 91% from 3 to 5 predictors. However, the predicted R squared value decreases from 87% to 71% to 60%. Which R Squared value applies more here?
Any help is appreciated. Thanks!

A: I won't attempt to give you a highly technical answer here.
I am inclined to trust the PRESS statistic more than I would trust adjusted R squared. The adjusted R squared is still an "in-sample" measure, while the PRESS is an "out-of-sample" measure. I would consider the out-of-sample measure to be more powerful generally.
Additionally, the adjusted R squared might not be very different from R squared if you have a small number of predictors compared to the number of observations you are fitting. So it might not be as informative as the PRESS statistic.
However, If what you are describing is correct, and the PRESS statistic is calculated correctly, then it is clear that the predictive performance of your model is suffering when you add predictors. But it is also not clear why your PRESS statistic is suffering so much compared to the adjusted R squared. It doesn't feel like that should be the case.
I would recommend checking that you are calculating the PRESS statistic correctly (if this is not something that is provided by the tool you are using to fit the model).
It is quite difficult to diagnose what is happening without having more detail of the issue at hand.

A: I will give a shot at a technical answer.
Let us assume that all regression assumptions are met and that the predictors have a multivariate normal distribution. In notation, we can summarize this as
$Y=\beta^{\top}X+\epsilon, \text{with} \quad  X \sim N(\mu_X, \Sigma_X),\quad \epsilon \sim N(0,\sigma_\epsilon^2)$
with $Y$ representing the dependent variable and $X$ the independent variables/predictors, $\epsilon$ the error.
When using adjusted-R-squared, what we actually want to estimate is $$\rho^2=1-\frac{\sigma_\epsilon^2}{Var(Y)}.$$
In words: this is the amount of variance of the dependent variable that the best linear function f (as represented by the true regression weights $\beta$) explains. On a side note, I wrote a paper [1] that shows that often there are better ways to do this than standard adjusted R-squared.
For predicted R-squared, we almost use the same formula, only a different error term. Instead of estimating the irreducible error $\sigma_\epsilon^2$, we are interested in
$$E_{X,Y}([\hat{f}(X)-Y]^2)$$
where $\hat{f}$ is an estimate of the best function $f$ that we got from applying linear regression on a training set $D$.
Thus, the population value of predicted R-squared is
$$\rho_c^2=1-\frac{E_{X,Y}([\hat{f}(X)-Y]^2)}{Var(Y)}$$
This is thus the amount of variance that the particular function $\hat{f}$ explains in the population.
We can decompose (this is the start of the well-known bias-variance decomposition from machine learning)
$$E([\hat{f}(X)-Y]^2)=E_{X,Y}([\hat{f}(X)-f(X)]^2)+E_{X,Y}([\hat{f}(X)-Y]^2)=E_{X,Y}([\hat{f}(X)-f(X)]^2)+\sigma_\epsilon^2.$$
Note that thus $E_{X,Y}((\hat{f}(X)-Y)^2) \geq\sigma_\epsilon^2$ and equality holds if  $\hat{f}=f$, which is generally not the case.
In words: The error that the estimated function $\hat{f}$ makes consists of the difference between the estimated function $\hat{f}$ and the true function $f$ and the difference between the true function $f$ and the true value $Y$. Or, in other words, $\rho^2_c$ is an upper bound for $\rho^2$, and no function can predict better than $\sigma_\epsilon^2$.
So which measure is better at model selection? It depends. If you want to select the set of predictors that will lead to the most accurate predictions based on the current sample, then the predicted R-squared is better. If you want to select the set of predictors that will lead to the most accurate predictions if you had the whole population available (which is arguably often the question we would like to ask when we do explanatory modeling), then adjusted R-squared is better.
One word of warning. Predictive R-squared estimation via cross-validation works with rather minimal assumptions (only independence is needed). In contrast, adjusted R-squared estimation generally relies on all regression assumptions and the assumption that the predictors are multivariate normal.
References
$[1]$: Karch J (2020): Improving on adjusted R-squared. Collabra: Psychology (2020) 6 (1): 45. (link)


text:
Q: Installing Ruby 2.0 and Rails 4.0.0beta on AWS EC2 Installing Ruby 2.0.0 and Rails 4.0.0beta1 on the default Amazon EC2 Linux install (Amazon Linux AMI 2012.09.1) goes smoothly.
But openssl gets in the way (eg http://railsapps.github.com/openssl-certificate-verify-failed.html) and weird either prevent openssl from getting installed or causing the RubyGem package manager from installing rails.
How can I work around these problems?

A: Log into your brand new instance:
[19:59:22] paul:~ $ ssh -i ~/.ssh/server.pem ec2-user@your.ip

   __|  __|_  )
   _|  (     /   Amazon Linux AMI
  ___|\___|___|

  https://aws.amazon.com/amazon-linux-ami/2012.09-release-notes/

and impersonate the root:
$ sudo su -

You are logged in as root from here. Apply the server updates:
[root@ip-xx ~]# yum update
...
Complete!
[root@ip-xx ~]# yum groupinstall "Development Tools"
...
Install      72 Package(s)
...
Complete!

Now, this is where it differs from the standard solution. Install RVM but without a distribution of ruby:
[root@ip-xx ~]# \curl -L https://get.rvm.io | bash -s stable

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   184  100   184    0     0    135      0  0:00:01  0:00:01 --:--:--   183
100 11861  100 11861    0     0   7180      0  0:00:01  0:00:01 --:--:-- 64113
Downloading RVM from wayneeseguin branch stable
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   124  100   124    0     0    161      0 --:--:-- --:--:-- --:--:--   185
100 1615k  100 1615k    0     0   258k      0  0:00:06  0:00:06 --:--:--  401k

Installing RVM to /usr/local/rvm/
    Creating group 'rvm'

# RVM:  Shell scripts enabling management of multiple ruby environments.
# RTFM: https://rvm.io/
# HELP: http://webchat.freenode.net/?channels=rvm (#rvm on irc.freenode.net)
# Cheatsheet: http://cheat.errtheblog.com/s/rvm/
# Screencast: http://screencasts.org/episodes/how-to-use-rvm

# In case of any issues read output of 'rvm requirements' and/or 'rvm notes'

Installation of RVM in /usr/local/rvm/ is almost complete:

  * First you need to add all users that will be using rvm to 'rvm' group,
    and logout - login again, anyone using rvm will be operating with `umask u=rwx,g=rwx,o=rx`.

  * To start using RVM you need to run `source /etc/profile.d/rvm.sh`
    in all your open shell windows, in rare cases you need to reopen all shell windows.

# root,
#
#   Thank you for using RVM!
#   I sincerely hope that RVM helps to make your life easier and
#   more enjoyable!!!
#
# ~Wayne

Let's check that no ruby version is installed:
[root@ip-xx ~]# rvm list

rvm rubies

# No rvm rubies installed yet. Try 'rvm help install'.

Now, openssl is already installed on the system but is incompatible with setup:
[root@ip-xx ~]# openssl version
OpenSSL 1.0.0k-fips 5 Feb 2013

[root@ip-xx ~]# openssl version -d
OPENSSLDIR: "/etc/pki/tls"

Attempting to install ruby2 with this version will result in the following error:
[root@ip-xx ~]# rvm install 2.0.0 -- --with-openssl-dir=/etc/pki/tls
Fetching yaml-0.1.4.tar.gz to /usr/local/rvm/archives
######################################################################## 100.0%
Extracting yaml to /usr/local/rvm/src/yaml-0.1.4
Prepare yaml in /usr/local/rvm/src/yaml-0.1.4.
Configuring yaml in /usr/local/rvm/src/yaml-0.1.4.
Compiling yaml in /usr/local/rvm/src/yaml-0.1.4.
Installing yaml to /usr/local/rvm/usr
Installing Ruby from source to: /usr/local/rvm/rubies/ruby-2.0.0-p0, this may take a while depending on your cpu(s)...
ruby-2.0.0-p0 - #downloading ruby-2.0.0-p0, this may take a while depending on your connection...
######################################################################## 100.0%
ruby-2.0.0-p0 - #extracting ruby-2.0.0-p0 to /usr/local/rvm/src/ruby-2.0.0-p0
ruby-2.0.0-p0 - #extracted to /usr/local/rvm/src/ruby-2.0.0-p0
ruby-2.0.0-p0 - #configuring
ruby-2.0.0-p0 - #compiling
ruby-2.0.0-p0 - #installing
Retrieving rubygems-2.0.3
######################################################################## 100.0%
Extracting rubygems-2.0.3 ...
Removing old Rubygems files...
Installing rubygems-2.0.3 for ruby-2.0.0-p0 ...
Error running 'env GEM_PATH=/usr/local/rvm/gems/ruby-2.0.0-p0:/usr/local/rvm/gems/ruby-2.0.0-p0@global:/usr/local/rvm/gems/ruby-2.0.0-p0:/usr/local/rvm/gems/ruby-2.0.0-p0@global GEM_HOME=/usr/local/rvm/gems/ruby-2.0.0-p0 /usr/local/rvm/rubies/ruby-2.0.0-p0/bin/ruby /usr/local/rvm/src/rubygems-2.0.3/setup.rb', please read /usr/local/rvm/log/ruby-2.0.0-p0/rubygems.install.log
Installation of rubygems did not complete successfully.
Saving wrappers to '/usr/local/rvm/bin'.
ruby-2.0.0-p0 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/gem'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/irb'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/erb'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/ri'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/rdoc'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/testrb'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/rake'? y
ruby-2.0.0-p0 - #importing default gemsets, this may take time ...
Install of ruby-2.0.0-p0 - #complete

Although you'll get ruby2, the "Installation of rubygems did not complete successfully" - notice the warning: "Error running 'env GEM_PATH=..."
Instead, we'll get RVM install a copy of openssl for us (see https://rvm.io/packages/openssl/). The zlib-devel package is required:
[root@ip-xx ~]# yum install zlib-devel
...
Installed:
  zlib-devel.x86_64 0:1.2.5-7.11.amzn1

Complete!
[root@ip-xx ~]# rvm pkg install openssl
Fetching openssl-1.0.1c.tar.gz to /usr/local/rvm/archives
Extracting openssl to /usr/local/rvm/src/openssl-1.0.1c
Configuring openssl in /usr/local/rvm/src/openssl-1.0.1c.
Compiling openssl in /usr/local/rvm/src/openssl-1.0.1c.
Installing openssl to /usr/local/rvm/usr

Please note that it's required to reinstall all rubies:

    rvm reinstall all --force

Updating openssl certificates

We can now install ruby2:
[root@ip-xx ~]# rvm reinstall 2.0.0 --with-openssl-dir=/usr/local/rvm/usr
Removing /usr/local/rvm/src/ruby-2.0.0-p0...
Removing /usr/local/rvm/rubies/ruby-2.0.0-p0...
Installing Ruby from source to: /usr/local/rvm/rubies/ruby-2.0.0-p0, this may take a while depending on your cpu(s)...
ruby-2.0.0-p0 - #downloading ruby-2.0.0-p0, this may take a while depending on your connection...
ruby-2.0.0-p0 - #extracting ruby-2.0.0-p0 to /usr/local/rvm/src/ruby-2.0.0-p0
ruby-2.0.0-p0 - #extracted to /usr/local/rvm/src/ruby-2.0.0-p0
ruby-2.0.0-p0 - #configuring
ruby-2.0.0-p0 - #compiling
ruby-2.0.0-p0 - #installing
Removing old Rubygems files...
Installing rubygems-2.0.3 for ruby-2.0.0-p0 ...
Installation of rubygems completed successfully.
Saving wrappers to '/usr/local/rvm/bin'.
ruby-2.0.0-p0 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/gem'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/irb'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/erb'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/ri'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/rdoc'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/testrb'? y
cp: overwrite `/usr/local/rvm/rubies/ruby-2.0.0-p0/bin/rake'? y
ruby-2.0.0-p0 - #importing default gemsets, this may take time ...
Install of ruby-2.0.0-p0 - #complete
Making gemset ruby-2.0.0-p0 pristine.
Making gemset ruby-2.0.0-p0@global pristine.

[root@ip-xx ~]# ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-linux]

And rails4:
[root@ip-xx ~]# gem install rails -v 4.0.0beta1
...
28 gems installed
[root@ip-xx ~]# gem list

*** LOCAL GEMS ***

actionmailer (4.0.0.beta1)
actionpack (4.0.0.beta1)
activemodel (4.0.0.beta1)
activerecord (4.0.0.beta1)
activerecord-deprecated_finders (0.0.3)
activesupport (4.0.0.beta1)
arel (4.0.0.beta2)
atomic (1.0.1)
bigdecimal (1.2.0)
builder (3.1.4)
bundler (1.3.4)
erubis (2.7.0)
hike (1.2.1)
i18n (0.6.4)
io-console (0.4.2)
json (1.7.7)
mail (2.5.3)
mime-types (1.21)
minitest (4.3.2)
multi_json (1.7.1)
polyglot (0.3.3)
psych (2.0.0)
rack (1.5.2)
rack-test (0.6.2)
rails (4.0.0.beta1)
railties (4.0.0.beta1)
rake (10.0.3, 0.9.6)
rdoc (4.0.0, 3.12.2)
rubygems-bundler (1.1.1)
rvm (1.11.3.6)
sprockets (2.9.0)
sprockets-rails (2.0.0.rc3)
test-unit (2.0.0.0)
thor (0.17.0)
thread_safe (0.1.0)
tilt (1.3.6)
treetop (1.4.12)
tzinfo (0.3.37)

That's all folks!

A: Here is a variant with rbenv.
SSH into your brand new instance:
   __|  __|_  )
   _|  (     /   Amazon Linux AMI
  ___|\___|___|

https://aws.amazon.com/amazon-linux-ami/2012.09-release-notes/
There are 16 security update(s) out of 57 total update(s) available
Run "sudo yum update" to apply all updates.
Amazon Linux version 2013.03 is available.
[jimjh ~]$ ruby --version
ruby 1.9.3p286 (2012-10-12 revision 37165) [x86_64-linux]

Impersonate the root and apply server updates:
$> sudo su -
$> yum update

Install couple of packages:
$> yum install git pcre pcre-devel

Clone rbenv:
$> git clone git://github.com/sstephenson/rbenv.git /usr/local/rbenv

Create the following file:
# /etc/profile.d/rbenv.sh
export RBENV_ROOT=/usr/local/rbenv
export PATH="${RBENV_ROOT}/bin:$PATH"
eval "$(rbenv init -)"

Install ruby-build:
$> . /etc/profile
$> git clone https://github.com/sstephenson/ruby-build.git /usr/local/rbenv/plugins/ruby-build

Install ruby:
$> rbenv install 2.0.0-p195  # wait ...
$> rbenv global 2.0.0-p195
$> rbenv rehash

Update rubygems and install passenger:
$> gem update --system
$> gem install bundler
$> gem install passenger

Install nginx through passenger:
$> passenger start

At the time of writing, the latest version of passenger is 4.0.0, which works with ruby 2.0.0.
Elastic Beanstalk
If you are using Elastic Beanstalk, stop passenger
$> sudo service passenger stop

Initialize rbenv by adding the following to /opt/elasticbeanstalk/support/envvars.d/appenv
. /etc/profile.d/rbenv.sh

Start passenger
$> sudo service passenger start


text:
Q: IIS Recycle Global.asax Is it possible to catch an recycle event in the global.asax?
I know Application_End will be triggered but is there a way to know that it was triggered by a recycle of the application pool?
thx, Lieven Cardoen aka Johlero

A: I found this article on Scott Guthries's blog:
Logging ASP.NET Application Shutdown Events

Someone on a listserv recently asked
  whether there was a way to figure out
  why and when ASP.NET restarts
  application domains.  Specifically, he
  was looking for the exact cause of
  what was triggering them on his
  application in a production shared
  hosted environment (was it a
  web.config file change, a global.asax
  change, an app_code directory change,
  a directory delete change,
  max-num-compilations reached quota,
  \bin directory change, etc).
Thomas on my team has a cool
  code-snippet that he wrote that uses
  some nifty private reflection tricks
  to capture and log this information.
  It is pretty easy to re-use and add
  into any application, and can be used
  to log the information anywhere you
  want (the below code use the NT Event
  Log to save it – but you could just as
  easily send it to a database or via an
  email to an admin).  The code works
  with both ASP.NET V1.1 and ASP.NET
  V2.0.
Simply add the System.Reflection and
  System.Diagnostics namespaces to your
  Global.asax class/file, and then add
  the Application_End event with this
  code:

public void Application_End() {

    HttpRuntime runtime =
       (HttpRuntime) typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime",
          BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField,
          null, null, null);

    if (runtime == null)
        return;

    string shutDownMessage =
       (string) runtime.GetType().InvokeMember("_shutDownMessage",
           BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
           null, runtime, null);

    string shutDownStack =
       (string) runtime.GetType().InvokeMember("_shutDownStack",
           BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
           null, runtime, null);

    if (!EventLog.SourceExists(".NET Runtime")) {
        EventLog.CreateEventSource(".NET Runtime", "Application");
    }

    EventLog log = new EventLog();
    log.Source = ".NET Runtime";

    log.WriteEntry(String.Format(
          "\r\n\r\n_shutDownMessage={0}\r\n\r\n_shutDownStack={1}",
          shutDownMessage, shutDownStack),
       EventLogEntryType.Error);
}

A: So, here is an idea how this could work.
Based on my previous answer (attach to AppDomain.CurrentDomain.ProcessExit) and stephbu's comment:

This will trap most structured process
  teardowns e.g. - but I'm not sure that
  it will trap all tear downs. e.g.
  http://blogs.msdn.com/jmstall/archive/2006/11/26/process-exit-event.aspx
  Process recycle will kill the process
  if it seems to be hung - your handler
  wouldn't get called.

I suggest following strategy:
In the (regular) ProcessExit handler (which we suppose will not be called on a application pool recycling), write some file to disk like "app_domain_end_ok.tmp".
Then in the Application_Start of your global.asax check for this file. If it doesn't exist it is a sign that the application was not terminated in a clean way (or that it is the first time ever it started). Don't forget to delete this file from disk after the check.
I didn't try that myself, but it could be worth a try.

A: I've never tried this myself, but you could try to attach an event handler to the ProcessExit event of the AppDomain.
...
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnExit);
...

void OnExit(object sender, EventArgs e) {
    // do something
}

I hope this helps!

A: I was much more successful with attaching to DomainUnload event, it is triggered on AppPool recycle and stoppage of the AppPool itself.
AppDomain.CurrentDomain.DomainUnload += this.CurrentDomainOnProcessExit;


text:
Q: NoSuchMethodException: org.apache.spark.ml.classification.GBTClassificationModel in Pyspark model load I have trained a model in pyspark
##Model
gbt = GBTClassifier(maxIter=10)
gbtModel = gbt.fit(train)
predictions = gbtModel.transform(test)

Here I am saving pipeline and model
#Save pipeline
pipelineModel.write().overwrite().save("s3://data-production/pipelineModel_v1")

#Save Model
gbtModel.save("s3://data-production/first_trade.model_v0")

Now in production /future datasets, I am loading pipeline and model
pipelineModel = PipelineModel.load("s3://data-production/pipelineModel_v1")

new_test= pipelineModel.transform(new_df1)

model = GBTClassifier.load("s3://data-production/first_trade.model_v0")

I am getting this error after model load
Py4JJavaError: An error occurred while calling o4701.load.
: java.lang.NoSuchMethodException: org.apache.spark.ml.classification.GBTClassificationModel.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.apache.spark.ml.util.DefaultParamsReader.load(ReadWrite.scala:496)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)

(<class 'py4j.protocol.Py4JJavaError'>, Py4JJavaError('An error occurred while calling o4701.load.\n', JavaObject id=o4702), <traceback object at 0x7f247a3eb9c8>)

A: The saved model is essentially a serialized version of your trained GBTClassifier. To deserialize the model you would need the original classes in the production code as well. Add this line to the set of import statements.
from pyspark.ml.classification import GBTClassifier, GBTClassificationModel


text:
Q: Embed vs reference my dependencies: Best practices for .NET/NuGet package? I'm providing a C#/.NET class library to clients within my company as a NuGet package. My library depends upon some other 3rd-party libraries (e.g. Newtonsoft's excellent Json.NET).
I'm assuming that the standard way NuGet works is that my package would only include references to other NuGet packages I depend upon. The client's Developer Studio will automatically download them when they install my NuGet package in their project.
Question #1:

Can I be certain that Developer Studio will download the versions of
  those NuGet packages that I was building against and not the 'latest'
  versions?

Question #2:

Will it cause problems if their project also uses a 3rd-party library
  that I'm using (like Json.NET), especially if they are using a different version? Does this 'just work', or do I need to do something about this?

Apologies if this is spelled out somewhere, but I've not been able to find specific answers to these questions.

A: That's clearly laid out in the Nuspec Reference
Specifically:

Specifying Dependencies
Starting from version 2.0, package dependencies can be specified to vary according to the framework profile of the target project. The  element contains a set of  elements. Each group contains zero or more  element and a target framework attribute. All dependencies inside a group are installed together if the target framework is compatible with the project's framework profile.
  <dependencies>
   <group>
      <dependency id="RouteMagic" version="1.1.0" />
   </group>
   <group targetFramework="net40">
      <dependency id="jQuery" />
      <dependency id="WebActivator" />
   </group>
   <group targetFramework="sl30">
   </group>
</dependencies>

Where version is:

The range of versions acceptable as a dependency. Typically this is
  just a version number which represents a minimum version. However a
  more explicit version range syntax is supported.

(update: updated references to more recent version of nuget)


text:
Q: loader constraint violation: when resolving method 'void javax.xml.crypto.dsig.dom.DOMSignContext.(java.security.Key, org.w3c.dom.Node)' - jdk17 While working on OCI function (Functions is to Oracle OCI as Lambda is to AWS), we are using Java as runtime and wrote a program that creates XML document and signs it. Oracle Functions uses Fn Project Function Development Kits (FDKs) to support Java and we are using below environment setup:
build_image: fnproject/fn-java-fdk-build:jdk17-1.0.149
run_image: fnproject/fn-java-fdk:jre17-1.0.149
The error that we are facing is as below:

An error occurred in function: loader constraint violation: when resolving method 'void javax.xml.crypto.dsig.dom.DOMSignContext.(java.security.Key, org.w3c.dom.Node)' the class loader com.fnproject.fn.testing.FnTestingClassLoader @55040f2f of the current class, com/example/fn/HelloFunction, and the class loader 'platform' for the method's defining class, javax/xml/crypto/dsig/dom/DOMSignContext, have different Class objects for the type org/w3c/dom/Node used in the signature (com.example.fn.HelloFunction is in unnamed module of loader com.fnproject.fn.testing.FnTestingClassLoader @55040f2f, parent loader 'app'; javax.xml.crypto.dsig.dom.DOMSignContext is in module java.xml.crypto of loader 'platform')
Caused by: java.lang.LinkageError: loader constraint violation: when resolving method 'void javax.xml.crypto.dsig.dom.DOMSignContext.(java.security.Key, org.w3c.dom.Node)' the class loader com.fnproject.fn.testing.FnTestingClassLoader @55040f2f of the current class, com/example/fn/HelloFunction, and the class loader 'platform' for the method's defining class, javax/xml/crypto/dsig/dom/DOMSignContext, have different Class objects for the type org/w3c/dom/Node used in the signature (com.example.fn.HelloFunction is in unnamed module of loader com.fnproject.fn.testing.FnTestingClassLoader @55040f2f, parent loader 'app'; javax.xml.crypto.dsig.dom.DOMSignContext is in module java.xml.crypto of loader 'platform')
at com.example.fn.HelloFunction.calculateLAU(HelloFunction.java:192)
at com.example.fn.HelloFunction.handleRequest(HelloFunction.java:39)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)

:::: pom.xml ::::
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
     http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <fdk.version>1.0.149</fdk.version>
</properties>
<groupId>com.example.fn</groupId>
<artifactId>hello</artifactId>
<version>1.0.0</version>

 <dependencies>
    <dependency>
        <groupId>com.fnproject.fn</groupId>
        <artifactId>api</artifactId>
        <version>${fdk.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fnproject.fn</groupId>
        <artifactId>testing-core</artifactId>
        <version>${fdk.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.fnproject.fn</groupId>
        <artifactId>testing-junit4</artifactId>
        <version>${fdk.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>17</source>
                <target>17</target>
            </configuration>
        </plugin>
        <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-surefire-plugin</artifactId>
             <version>2.22.1</version>
             <configuration>
                <argLine>--add-opens java.xml/jdk.xml.internal=ALL-UNNAMED</argLine>
                <useSystemClassLoader>false</useSystemClassLoader>
             </configuration>
        </plugin>
    </plugins>
</build>

:::: Code ::::
SecretKeySpec secret_key =
    new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");

Element LAUElement =
    document.createElementNS("urn:swift:saa:xsd:saa.2.0",
             "Saa:LAU");

Element rootElement = document.getDocumentElement();

//At this point it is failing
DOMSignContext domSignContext =
    new DOMSignContext(secret_key, LAUElement);
domSignContext.setDefaultNamespacePrefix("dsig");

Checked all the SO answers related to generic "loader constraint violation" and the answers point to removing "xml-apis" or "xerces" dependency from the project and that it is related to "org.w3c.dom.Node" being already packaged in java.xml by default post jdk8. However, neither the present pom.xml file has any additional dependencies nor I am getting any reference to these conflicting jars.
Thanks in advance.


text:
Q: Which data model for storing a month and year? I need to create a model which has a production month and year.
I can see 2 possibilities here:

*

*Use a DateField, with the day set to 1, and only use the month and date

*Use 2 IntegerFields, one for the month and the other for the year.

What are the advantages of each solution? Which do you recommend and why? Are there any other better way to achieve this?

A: Date field with a day set to 1 would be a better option. If you don't need a day it's not critical, it's just a date formatting problem when displaying end result to a user, like displaying a month as May instead of 05. You can use dates with day 01 in all sql queries as you normally would (filtering, grouping, sorting, etc).
To make the choice more obvious let me ask in return what would be the best way to store time if I didn't care about seconds - as a time field with seconds set to 0, or as hours and minutes in two separated integers.
Storing it as a date comes with free benefits: date validation, date functions, date ordering, date formatting.


text:
Q: Should I use Table View or one long chunk of HTML for iPhone? I'm making an application for the iPhone. Essentially it'll be a guide of sorts, and all the generated information will be in one long window. Each block of information can have a 'link' in it to generate another block of connected information (for example a block about Wallace could link to a block about Gromit) that would appear at the top.
For example, at the start 1 block of data:
Wallace: Owner of Gromit
would become 2 blocks (on clicking Gromit):
Gromit: Wallace's Dog
Wallace:Owner of Gromit
Each block would also have the ability to be added to favorites list by clicking an icon. The text would need to be laid out with HTML and each block may be of a different length. A search on a different could also add a block to the top.
I'm OK with objects in 'easy' languages like PHP, but am basically new to iPhone and Cocoa, and I want to start off with the right approach here. A Table and cells looks like the correct approach, but is there any advantage of doing it as a long list (like I might do on a web version) or are there any restrictions in the way cells can hold/layout information that will cause me trouble down the line.
I believe this approach is popular for dictionaries.
I'm committed to doing it the way with a single scroll for a couple of reasons. The main one is that I want the user to be able to scroll instantly back to entries they've looked at before. i.e. the single view essentially represents a history of the data they've looked at. (if it's a lot stuff can drop off the end). Each entry will be very short but there will be a lot in total. So if the user has looked at

*

*Wallace

*Gromit

*The Wrong Trousers

*Cheese

*Penguin

And they are not looking at Wallace, a quick half second scroll takes them back to 'penguin'.

A: Hierarchy is the way to go on the iPhone.
Remember that the iPhone has a small screen and that users can only see a very small amount of information at anyone time. (One interface expert compared it to driving while peering down a two inch pipe with one eye.) Users can easily get lost scrolling up and down a very long list even if it has index. (That's assuming your information can be easily indexed in a form that users will instantly recognize.) It's usually easier for users to click through several views with the data in each view getting more and more specific with each level. In addition, so many apps use this hierarchal system that your users will be used to it and expect it.
System wise, its easier for the iPhone to display just one level of hierarchy at a time so your app feels more responsive. The hardware doesn't to maintain all the data in memory but just the data it needs to immediately display.
If I understand you data model correctly, you would be best off with a hierarchy of two tables and a detail view. The first table would have an list of letters A-Z. The second table would be list of all records starting with that letter. The third would be a detail view showing links to that record. So, to see the example in the OP, a user would select W-->Wallace-->(Detail) Gromit.

Edit01:
I think you should do a test scroll of either a very long web page or UIScrollView and see how it affects performance and usability. I would caution you that layouts that seem perfectly usable and fast on laptop or desktop hardware become unusable and slow on mobiles with their weaker processors and much smaller screens. It's much more difficult to do " a quick half second scroll" back to a specific point on a long page on a mobile than on a larger screen.
You do have the option of creating a outline-like table view that inserts new indented cells as needed. I still think hierarchy is the quickest and most usable layout on a mobile.


text:
Q: Finding the delta of two unmatched dataframes in pandas Having 2 Data Frames with  readings at 2 different times as:
DF1
       Sensor ID    Reference Pressure     Sensor Pressure
0         013677                100.15               93.18
1         013688                101.10               95.23
2         013699                100.87               93.77
...          ...                  ...                  ...

And
DF2
       Sensor ID    Reference Pressure     Sensor Pressure
0         013688                120.01              119.43
1         013677                118.93              118.88
2         013699                120.05              118.85
...          ...                  ...                  ...

What would be the optimal way of creating a third Dataframe, that contains the difference between those readings, given that the "Sensor ID" values order does not match between the two dataframes?

A: Pandas has this beautiful feature where it automatically aligns on indices. So we can use that to solve your problem:
df1.set_index("Sensor ID").sub(df2.set_index("Sensor ID"))

           Reference Pressure  Sensor Pressure
Sensor ID
13677                  -18.78           -25.70
13688                  -18.91           -24.20
13699                  -19.18           -25.08


text:
Q: Cannot check answer. Perhaps output format is wrong. Returning 0 in IDE def max_pairwise_product(numbers):
    index1 = 0
    n = len(numbers)

    #loop through the list and store the highest item in index1

    for i in range(1, n):
        if numbers[i] > numbers[index1]:
            index1 = i

    #swap index1 and the last item in the list

    temp1 = numbers[index]
    numbers[index] = numbers[n-1]
    numbers[n-1] = temp1

    index2 = 0

    #loop through the list except for the last item

    for i in range(1, n-1):
        if numbers[i] > numbers[index2]:
            index2 = i

    #swap index2 and second to the last item

    temp2 = numbers[index2]
    numbers[index2] = numbers[n-2]
    numbers[n-2] = temp

    return numbers[n-2] * numbers[n-1]

if __name__ == '__main__':
    input_n = int(input())
    input_numbers = [int(x) for x in input().split()]
    print(max_pairwise_product(input_numbers))

It is a maximum pairwise question and I am using Python.
I use Pycharm to run it and it returns 15129 if I test a list of 3 items [1,2,3]. When I submit it to the grader, it says "Cannot check answer. Perhaps output format is wrong."
Any feedback will be greatly appreciated


text:
Q: need to match a string and then print next string matches and continue till next string I am having troubles with manipulating a big text file,
My sample f1.txt have several 3000 plus lines, with below format
I need to match a string , and then match lines after that string with another string (here in this case "needed") and print those matching lines along with original string.
This should continue till all the strings are over.
Example requirement is below, can you help ?
======f1.txt====
String      :  a

--
==

==

needed line ------------ 100

needed line -------------200

-

String      :  b

--
==

==

needed line ------------ 500

needed line -------------600

needed line ------------ 700

needed line -------------800

-

String      :  c

--

==

needed line ------------ 900

===
===

OUTPUT NEEDED
a needed line ------------ 100

a needed line -------------200

b needed line ------------ 500

b needed line -------------600

b needed line ------------ 700

b needed line -------------800

c needed line -------------900

A: In awk,
awk -F" : " '/^String/ {string = $2}; /^needed/ {print string, $0}' f1.txt

You can do a similar thing in sed, although it's not quite so compact - basically it uses sed's hold space as the equivalent of the string variable. Unfortunately AFAIK there's no simple way to prepend the hold space to the pattern space in sed, so we have to append and then swap the order after:
sed -rn -e '/^String : / {s///;h;}' -e '/^needed/ {G;s/(.*)\n(.*)/\2 \1/;p;}'  f1.txt

NOTE: a full solution should probably check that a String has been found and assigned before trying to print it (in case the file contains needed lines before any String).

A: Here's an example script that does this: http://paste.ubuntu.com/8186522/
I have made a few assumptions:

*

*Your assignment is going to use : as the separator. I have taken advantage of this in setting the IFS for read.

*You don't mind going over the file multiple times. This can be done in one pass, in fact might be easier that way, depending on the implementation.