text:
Q: How to compute ranks in mysql? I have a table 'student_marks' with two columns 'student_id' and  'mark':
student_id | marks
-------------------
    1      |  5
    2      |  2
    3      |  5
    4      |  1
    5      |  2

I need to compute the rank corresponding to the marks. The expected output for the above table is:
student_id | marks  | rank
-------------------------
    1      |  5     | 1
    2      |  2     | 3
    3      |  5     | 1
    4      |  1     | 5
    5      |  2     | 3

Since the two students with students_id 1 and 3 has highest mark 5, they are placed in rank 1. For students with marks 2, the rank is 3 as there are two students who has more marks then these guys.
How do we write queries to compute the ranks as shown above?

A: This should work although it's heavy on variables.
SELECT student_id, mark, rank FROM (
    SELECT t.*,
           @rownum := @rownum + 1 AS realRank,
           @oldRank := IF(mark = @previous,@oldRank,@rownum) AS rank,
           @previous := mark
    FROM student_marks t,
         (SELECT @rownum := 0) r,
         (SELECT @previous := 100) g,
         (SELECT @oldRank := 0) h
    ORDER BY mark DESC
 ) as t
 ORDER BY student_id;

Look at this fiddle: http://sqlfiddle.com/#!2/2c7e5/32/0


text:
Q: Obtain different combinations from sets I have distinct sets identified by some names against which there are values. I use construct like Dictionary<string, List<string>> to store such entities.
As my output I need all possible combinations of values that can be generated from this input syntax. In my attempt, I have devised an index based approach such that if the indices are correctly manipulated, I'd get required output of the form similar to the example. I understand that it might use recursion but I'm not sure how to go about it. Is this a recognized problem? Please find code below:
using System;
using System.Collections.Generic;

namespace Rextester
{
    public class Program
    {
        private static Dictionary<string, string> dataAtIndex(Dictionary<string, List<string>> iArgs, Dictionary<string, int> iArgIndex)
        {
            Dictionary<string, string> oConditionKeys = new Dictionary<string, string>();

            foreach (var vArgName in iArgs.Keys)
            {
                int index = iArgIndex[vArgName];
                string argValue = iArgs[vArgName][index];
                oConditionKeys.Add(vArgName, argValue);
            }

            return oConditionKeys;
        }

        private static void testFunc(Dictionary<string, List<string>> iArgs, ref List<Dictionary<string, string>> oListSelectKeys)
        {
            Dictionary<string, int> argIndex = new Dictionary<string, int>();
            foreach (var vArgName in iArgs.Keys)
            {
                argIndex.Add(vArgName, 0);
            }

            oListSelectKeys.Add(dataAtIndex(iArgs, argIndex));
        }

        public static void Main(string[] mainargs)
        {
            Dictionary<string, List<string>> args = new Dictionary<string, List<string>>();

            List<string> listArgData1 = new List<string>();
            listArgData1.Add("1=>Arg0");
            listArgData1.Add("1=>Arg1");
            listArgData1.Add("1=>Arg2");

            List<string> listArgData2 = new List<string>();
            listArgData2.Add("2=>Arg0");
            listArgData2.Add("2=>Arg1");

            List<string> listArgData3 = new List<string>();
            listArgData3.Add("3=>Arg0");
            listArgData3.Add("3=>Arg1");
            listArgData3.Add("3=>Arg2");
            listArgData3.Add("3=>Arg3");

            args.Add("Param1", listArgData1);
            args.Add("Param2", listArgData2);
            args.Add("Param3", listArgData3);

            Console.WriteLine("Input Data : ");
            foreach(var vKey in args.Keys) {
                Console.Write(vKey + " : ");
                foreach(var vData in args[vKey]) {
                    Console.Write(vData + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

            List<Dictionary<string, string>> listSelectKeys = new List<Dictionary<string, string>>();
            testFunc(args, ref listSelectKeys);

            int count = 0;
            Console.WriteLine("Output Data : ");
            foreach(var vElem in listSelectKeys) {
                Console.Write(count++ + " : ");
                foreach(var vKey in vElem.Keys) {
                    Console.Write("(" + vKey + ", " + vElem[vKey] + ") ");
                }
                Console.WriteLine();
            }
        }
    }
}

Output should be like:
0 : (Param1, 1=>Arg0) (Param2, 2=>Arg0) (Param3, 3=>Arg0)
1 : (Param1, 1=>Arg0) (Param2, 2=>Arg0) (Param3, 3=>Arg1)
2 : (Param1, 1=>Arg0) (Param2, 2=>Arg0) (Param3, 3=>Arg2)
...
n : (Param1, 1=>Arg2) (Param2, 2=>Arg1) (Param3, 3=>Arg3)

Thanks!

A: Finally got it to work...:)
I used some looped recursion.:)
Here you go:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Rextester
{
    public class Program
    {
        private static Dictionary<string, string> dataAtIndex(Dictionary<string, List<string>> iArgs, Dictionary<string, int> iArgIndex)
        {
            Dictionary<string, string> oConditionKeys = new Dictionary<string, string>();

            foreach (var vArgName in iArgs.Keys)
            {
                int index = iArgIndex[vArgName];
                string argValue = iArgs[vArgName][index];
                oConditionKeys.Add(vArgName, argValue);
            }

            return oConditionKeys;
        }

        private static void generateArgIndexList(Dictionary<string, List<string>> iArgs, Dictionary<string, int> iArgIndex, ref List<Dictionary<string, int>> oListArgIndices)
        {
            if(iArgs.Count > 0)
            {
                string firstArgName = iArgs.First().Key;

                Dictionary<string, List<string>> newArgs = new Dictionary<string, List<string>>(iArgs);
                Dictionary<string, int> tmpArgInd = iArgIndex;
                while (tmpArgInd[firstArgName] < iArgs[firstArgName].Count)
                {
                    string lastArgName = newArgs.Last().Key;
                    if (tmpArgInd[lastArgName] < iArgs[lastArgName].Count)
                    {
                        oListArgIndices.Add(new Dictionary<string, int>(tmpArgInd));
                        ++tmpArgInd[lastArgName];
                    }
                    else
                    {
                        tmpArgInd[lastArgName] = 0;
                        newArgs.Remove(lastArgName);
                        lastArgName = newArgs.Last().Key;
                        if (tmpArgInd[lastArgName] < iArgs[lastArgName].Count)
                        {
                            ++tmpArgInd[lastArgName];
                            if (tmpArgInd[lastArgName] < iArgs[lastArgName].Count)
                                generateArgIndexList(iArgs, tmpArgInd, ref oListArgIndices);
                        }
                    }
                }
            }
        }

        private static void testFunc(Dictionary<string, List<string>> iArgs, ref List<Dictionary<string, string>> oListConditionKeys)
        {
            Dictionary<string, int> argIndex = new Dictionary<string, int>();
            foreach (var vArgName in iArgs.Keys)
            {
                argIndex.Add(vArgName, 0);
            }

            List<Dictionary<string, int>> listArgIndices = new List<Dictionary<string, int>>();
            generateArgIndexList(iArgs, argIndex, ref listArgIndices);
            foreach(var vArgIndex in listArgIndices)
            {
                oListConditionKeys.Add(dataAtIndex(iArgs, vArgIndex));
            }
        }

        public static void Main(string[] mainargs)
        {
            Dictionary<string, List<string>> args = new Dictionary<string, List<string>>();

            List<string> listArgData1 = new List<string>();
            listArgData1.Add("1=>Arg0");
            listArgData1.Add("1=>Arg1");
            listArgData1.Add("1=>Arg2");

            List<string> listArgData2 = new List<string>();
            listArgData2.Add("2=>Arg0");
            listArgData2.Add("2=>Arg1");

            List<string> listArgData3 = new List<string>();
            listArgData3.Add("3=>Arg0");
            listArgData3.Add("3=>Arg1");
            listArgData3.Add("3=>Arg2");
            listArgData3.Add("3=>Arg3");

            args.Add("Param1", listArgData1);
            args.Add("Param2", listArgData2);
            args.Add("Param3", listArgData3);

            Console.WriteLine("Input Data : ");
            foreach(var vKey in args.Keys) {
                Console.Write(vKey + " : ");
                foreach(var vData in args[vKey]) {
                    Console.Write(vData + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

            List<Dictionary<string, string>> listSelectKeys = new List<Dictionary<string, string>>();
            testFunc(args, ref listSelectKeys);

            int count = 0;
            Console.WriteLine("Output Data : ");
            foreach(var vElem in listSelectKeys) {
                Console.Write(count++ + " : ");
                foreach(var vKey in vElem.Keys) {
                    Console.Write("(" + vKey + ", " + vElem[vKey] + ") ");
                }
                Console.WriteLine();
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: General dimension hairy ball theorem and division algebras Question: Can someone please give a clear explanation, or point to a clear visual, that explains how the existence (or non-existence) of a non-vanishing continuous $n$-vector field on an $n$-sphere relates to division algebras over the Reals in $n+1$ dimensions?

As different sources use slightly different definitions of the term "division algebra" (for example some assuming an identity element, or some assuming associativity unless explicitly stating as a "non-associative" algebra, etc.), let me define a division algebra according to this review article (which does not assume an identity element or associativity):

Let $k$ be a field. A $k$-algebra is understood to be a vector space $A$ over $k$, endowed with a bilinear multiplication mapping $A \times A \to A$, $(x,y) \mapsto xy$. The algebra $A$ is said to be a division algebra if $A \ne \{0\}$ and the linear endomorphisms $L_a : A \to A$, $x \mapsto ax$ and $R_a : A \to A$, $x \mapsto xa$ are bijective for all $a \in A \setminus \{0\}$. In case $A$ is finite-dimensional, this is equivalent to saying that $A$ has no zero divisors, i.e. $xy=0$ only if $x=0$ or $y=0$.

The usual "hairy ball theorem" proves there is no non-vanishing continuous tangent vector field on the $2$-sphere. I have heard there is a more general version which concludes that the only dimensions which allow a non-vanishing continuous $n$-vector field on the $n$-sphere are: $n=1, 3, 7$ (and maybe $n=0$ as a trivial case depending on definitions). The review paper gives two references: Bott and Milnor, and Kervaire in 1958. I do not currently understand these proofs, but am willing to take it as a given.
What I am interested in is the connection between the existence (or non-existence) of such a $n$-vector field on an $n$-sphere, and the existence of an $(n+1)$-dimesional division algebra over the reals. This connection is even mentioned briefly in the wikipedia article on division algebras. But currently I do not see the connection.
First, is the ultra basics: is this just a necessary requirement, i.e. it shows an $n+1$ dimensional real division algebra is possible, but alone does not mean that one does exist.  Or is the relationship strong enough that given such a vector field on an $n$-sphere, I could "extract" the division algebra that corresponds to this.
Second, I am having trouble seeing the connection because the dimension of the vector field is one less than the division algebra.
It is easy to visualize "combing the n-hair" on a circle, and seeing that it doesn't work on a sphere.  But I do not understand how to relate this to a division algebra. Such a tangent field would only give a map on some patch from $\mathbb{R}^n \to \mathbb{R}^n$, where as some $L_a$ for the division algebra would give me $\mathbb{R}^{n+1} \to \mathbb{R}^{n+1}$. Where did the other dimension go? I can see that if I knew $L_a$ on just the sphere, I could use bilinearity to get the rest, but that would still require input information that looks more like $\mathbb{R}^n \to \mathbb{R}^{n+1}$. And I don't see why non-vanishing on $\mathbb{R}^{n+1}$ leads to non-vanishing when truncating (projecting?) to $\mathbb{R}^{n}$.

A: Let $A$ be an $n$-dimensional division $\mathbb{R}$-algebra in the sense that you describe.  If I'm understanding the article linked to in this MSE answer, every $A$ is isotopic to a unital algebra.  In particular, if there is an $n$-dimensional division $\mathbb{R}$-algebra, then there is a unital one.  So, I will assume $A$ is unital.
So, let $1\in A$ be the unit.  We identify $\mathbb{R}\subseteq A$ as the $\mathbb{R}$-multiples of $1$.
Proposition  The elements in $\mathbb{R}$ associate and commute with everything in $A$.  That is, if $r\in \mathbb{R}$ and $x,y\in A$, then $rx = xr$ and $r(xy) = (rx)y$.
Proof:  First, $1x = x1$ because both are just $x$.  Then bilinearity of multiplication gives $r(1x) = (r1)x = x(r1)$, so $rx = xr$.
Bilinearity also gives $r(xy) = (rx)y$.  $\square$
Now, fix a basis $\{e_1, e_2, ..., e_n\}$ of $A$ with $e_1 = 1$.  Note that for any real numbers $\lambda_i$ and any $v\in A$, we have $$\left(\sum_{i=1}^n \lambda_i e_i\right) v = \sum_{i=1}^n (\lambda_i e_i) v = \sum_{i=1}^n \lambda_i(e_i v)$$ where the first equality is the distributive property and the second is from the fact that real numbers associate.
Proposition:  If $v\in A$ with $v\neq 0$, then the elements $e_i v$ are linearly independent.
Proof.  Assume $\sum_{i=1}^n \lambda_i (e_i v) = 0$.  As mentioned above, this is the same as $(\sum_{i=1}^n \lambda_i e_i)v=0$.  Now, setting $a = \sum_{i=1}^n \lambda_i e_i$, we have $L_a(v) = L_a(0) = 0$.  Thus, since we're in a division algebra, $a = 0$.  That is, $\sum_{i=1}^n \lambda_i e_i = 0$.  Since the $e_i$ are a basis, we conclude all $\lambda_i = 0$, so the $e_i v$ are linearly independent.  $\square$
Now, put an arbitrary inner product on $A$.  (What I mean by arbitrary is that I'm not making any assumptions about how the inner product interacts with the multiplication on $A$)  Having an inner product, we define $S^{n-1} = \{v\in A: \langle v,v\rangle = 1\}$.  Since all inner products on a finite dimensional space are equivalent, $S^{n-1}$ is diffeomorphic to the usual $S^{n-1}$.
Proposition  The space $S^{n-1}$ has a family of $n-1$ continuous vector fields which are linearly independent at every point.
Proof:  Let $p \in S^{n-1}$.  For any $i = 2,.., n$, define the vector field $V_i(p)$ as the projection of $e_i p$ onto the codimension one hyperplane $p^\bot\subseteq A$.
Bilinearity means the multiplication is given by some degree $2$ of polynomial in the coordinates, so multiplication is continuous.  Projection is also continuous, so the $V_i(p)$ are continuous.
Now, assume $\sum_{i=2}^{n} \lambda_i V_i(p) = 0$.  This means that $\sum_{i=2}^n \lambda_i(e_i p)$ is parallel to $p$, i.e., $sum_{i=2}^n \lambda_i(e_i p) = \lambda p$ for some real number $\lambda$.
But $\lambda p = \lambda (e_1 p)$, so this is equivalent to $\sum_{i=2}^n \lambda_i(e_i p) - \lambda (e_1 p) = 0$.  Since $p\in S^{n-1}$ implies $p\neq 0$, the previous proposition now shows that for any $i$, $\lambda_i = \lambda = 0$.  Thus, the $V_i(p)$ are linearly independent.  $\square$
Now we use a topological result (that I would have attributed to Adams, though perhaps Kevaire, Milnor, and Bott were the first to tease it out of what Adams proved?)
Theorem:  If $S^{n-1}$ has $n-1$ linearly independent vector fields, then $n-1 = 0,1,3,7$.
Thus, if there is an $n$-dimensional division $\mathbb{R}$-algebra, $n = 1,2,4,8$.


text:
Q: How to debug: "HEADER ALREADY SENT" and GD2? I have an annoying HEADER ALREADY SENT error in system.log.
It is not easy to debug it, what I could do was to improve the logging to isolate the source of the issue (has described here):
Cannot send headers; headers already sent in lib/Varien/Image/Adapter/Gd2.php, line 133

Line 133 of Gd2.php:
call_user_func($this->_getCallback('output'), $this->_imageHandler);

And it is part of the method display:
public function display()
    {
        header("Content-type: ".$this->getMimeType());
        call_user_func($this->_getCallback('output'), $this->_imageHandler);
    }

How to go on ?

A: This is a tough one. I had an errant whitespace character at the beginning of a core class definition which screwing with me for a couple months till I realized what was going on.
Someone will write an extension one day to fix this, but till they do, one way to troubleshoot in Magento would be to start output buffering manually in index.php, then try to catch the output culprit in Varien_Autoload:
index.php:
ob_start();

lib/Varien/Autoload.php: (see note below)
public function autoload($class)
{
    if (max(array_column(ob_get_status(true),'buffer_used'))) {
        header('Content-Type: text/plain');
        ob_end_clean();
        debug_print_backtrace(2);
        die;
    }
    //... rest of method as normal ...
}

If you for example place a space at the beginning of Mage/Page/Block/Html/Footer.php then you would see the following:
#0  Varien_Autoload->autoload()
#1  spl_autoload_call() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Page/Block/Html/Footer.php:43]
#2  Mage_Page_Block_Html_Footer->_construct() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/lib/Varien/Object.php:112]
#3  Varien_Object->__construct() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/Layout.php:491]
#4  Mage_Core_Model_Layout->_getBlockInstance() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/Layout.php:437]
#5  Mage_Core_Model_Layout->createBlock() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/Layout.php:472]
#6  Mage_Core_Model_Layout->addBlock() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/Layout.php:239]
#7  Mage_Core_Model_Layout->_generateBlock() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/Layout.php:205]
#8  Mage_Core_Model_Layout->generateBlocks() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/Layout.php:206]
#9  Mage_Core_Model_Layout->generateBlocks() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Controller/Varien/Action.php:344]
#10 Mage_Core_Controller_Varien_Action->generateLayoutBlocks() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Cms/Helper/Page.php:113]
#11 Mage_Cms_Helper_Page->_renderPage() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Cms/Helper/Page.php:52]
#12 Mage_Cms_Helper_Page->renderPage() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Cms/controllers/IndexController.php:45]
#13 Mage_Cms_IndexController->indexAction() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Controller/Varien/Action.php:419]
#14 Mage_Core_Controller_Varien_Action->dispatch() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php:250]
#15 Mage_Core_Controller_Varien_Router_Standard->match() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Controller/Varien/Front.php:176]
#16 Mage_Core_Controller_Varien_Front->dispatch() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/code/core/Mage/Core/Model/App.php:354]
#17 Mage_Core_Model_App->run() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/app/Mage.php:683]
#18 Mage::run() called at [/Volumes/dev-cs/sites-enabled/optimizely/optimizely.dev/index.php:87]

This won't catch everything, so the offending file won't always be line #1, but it can get you very close to the offending context.
Note: I'm using array_column() here, a GREAT new function from Ben Ramsey in php 5.5. Without php 5.5 you can define it using his code, which is available on Github.

A: Apologies, I know this is not an answer but for some reason we can only comment if we have a reputation of 50. I could post another question the same but doubtless it will be closed as a duplicate! I want to comment on this question with some additional information that has not been mentioned here and that might lead to an answer.
I've also been investigating this issue thinking it might have something to do with admin users being logged out unexpectedly when working on pages and static blocks (another question). As part of this investigation I found that this exact log is generated whenever images are displayed in CMS pages or static blocks. It doesn't have to be on the page/block itself, simply open the Insert/Edit Image dialog and then browse for uploaded images - there will be one such a log for each image displayed. Same for images in pages/static blocks. Turn on/off the WYSIWYG editor and you'll get a log for each image on the page.
So to me this looks like a core Magento bug (I'm using 1.7.0.2). It's not surprising really given that displaying an image attempts to change the header (see code in the question).
Does anyone have a solution to this?
As it's only when editing pages or static blogs that admin gets logged out I'm guessing the two are somehow related. [This logout is not a session lifetime config issue - that works fine everywhere else on the dashboard - it's only pages/blocks that this happens and it can happen after just a few minutes when you go to save the changes you've been actively working on.]

A: Most likely that error is caused by an existing image that GD is trying to parse via imagepng/imagejpg/etc functions. If you use rsync/etc you may have corrupted image headers within wysiwyg directory.
Don't waste your time tracking down the headers.
Simply go in media/wysiwyg/ directory and check if you have existing content (run ls -alh to see hidden files). If you do, back it up and recreate it with proper server permissions.


text:
Q: CkEditor: is there a method to output the input content How can I get the user's input, is here a method to output or encode?
Now what I can do is
var content = $('#cke_ckeditor1 iframe').contents().find('.cke_show_borders').clone();

A: There's a method that returns editor's content - editor.getData() - see documentation.
You can find editor instance in CKEDITOR.instances object.

A: I used reference of itextsharp to use ckeditor.
Declare a hidden text field in html
<%= Html.Hidden("EditECurrentComplainText")%>

Here inside a div i used a textArea and converted it to ckeditor and then placed value of that ckeditor into a hidden field.
<div id="EditECurrentComplain_ckEditor">
                                    <%= Html.TextAreaFor(model => model.Current_Complain, new { rows = "10", id = "EditCurrent_ComplainCK" })%>
                                    <%= Html.ValidationMessageFor(model => model.Current_Complain)%>
                                        <% if (Model.Current_Complain != "")
                                    { %>
                                        <script type="text/javascript">
                                            jQuery(document).ready(function () {
                                                CKEDITOR.replace('EditCurrent_ComplainCK');
                                            });
                                        </script>
                                <%} %>
                                 </div>

get content of ckeditor into hidden textfield using the following statement
$("#EditECurrentComplainText").val(CKEDITOR.instances["EditCurrent_ComplainCK"].getData());

and finally used this hiddentext field content as my desired output/input.
Thanks.


text:
Q: Scrollview inside scrollview with recyclerview is not scrolling I have used one parent scrollview and in that I have used child scrollview with two recyclerviews. I have used lots of solutions to apply scrolling to child scrollview but not able to do that.
main layout is given below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bid_root_rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background_color">

    <include
        android:id="@+id/appbar"
        layout="@layout/toolbar" />

    <TextView
        android:id="@+id/txt_msg"
        style="@style/error_textview_style"
        android:layout_below="@+id/appbar" />

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/llLast"
        android:layout_below="@+id/txt_msg"
        android:fillViewport="true"
        android:fitsSystemWindows="true"
        android:scrollbarThumbVertical="@drawable/scrollbar_thumb_color">

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

            <LinearLayout
                android:id="@+id/ll1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="1">

                <RelativeLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="0.5"
                    android:background="@color/color_wallet_background"
                    android:padding="@dimen/dimen_10dp">

                    <TextView
                        android:id="@+id/tvBTCWalletBalance"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="@dimen/dimen_2dp"
                        android:layout_marginStart="@dimen/dimen_2dp"
                        android:layout_toEndOf="@id/ic_deposit"
                        android:layout_toRightOf="@id/ic_deposit"
                        android:text="09999"
                        android:textColor="@color/white"
                        android:textSize="@dimen/textSizeInvoiceBuy"
                        android:textStyle="bold" />

                    <com.ebitcoinics.ebitcoinicsapp.customview_virtual_currency.CustomVirtualCurrencyImageViewWhiteColor
                        android:id="@+id/localImageView"
                        android:layout_width="@dimen/imageSizeTooSmallBTCLogoForMin"
                        android:layout_height="@dimen/imageSizeTooSmallBTCLogoForMin"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="@dimen/dimen_2dp"
                        android:layout_marginStart="@dimen/dimen_2dp"
                        android:layout_toEndOf="@id/tvBTCWalletBalance"
                        android:layout_toRightOf="@id/tvBTCWalletBalance" />

                    <ImageView
                        android:id="@+id/ic_deposit"
                        android:layout_width="@dimen/imageSizeTooSmallBTCLogoForMin"
                        android:layout_height="@dimen/imageSizeTooSmallBTCLogoForMin"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="@dimen/dimen_2dp"
                        android:layout_marginStart="@dimen/dimen_2dp"
                        android:src="@drawable/ic_deposit" />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="@dimen/dimen_2dp"
                        android:layout_marginStart="@dimen/dimen_2dp"
                        android:layout_toEndOf="@+id/localImageView"
                        android:layout_toRightOf="@+id/localImageView"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:text="("
                            android:textColor="@color/white"
                            android:textSize="@dimen/bid_ask_current_trades_size"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/tvPriceAsPerBuy"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="@dimen/dimen_2dp"
                            android:layout_marginStart="@dimen/dimen_2dp"
                            android:textColor="@color/white"
                            android:textSize="@dimen/bid_ask_current_trades_size"
                            android:textStyle="bold" />

                        <com.ebitcoinics.ebitcoinicsapp.customview_local_currency.CustomLocalCurrencyImageViewWhiteColor
                            android:id="@+id/imgLocalCurrencyAsPerWallet"
                            android:layout_width="@dimen/imageSizeTooSmallBTCLogoForMin"
                            android:layout_height="@dimen/imageSizeTooSmallBTCLogoForMin"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="@dimen/dimen_2dp"
                            android:layout_marginStart="@dimen/dimen_2dp" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="@dimen/dimen_2dp"
                            android:layout_marginStart="@dimen/dimen_2dp"
                            android:text=")"
                            android:textColor="@color/white"
                            android:textSize="@dimen/bid_ask_current_trades_size"
                            android:textStyle="bold" />
                    </LinearLayout>

                </RelativeLayout>

                <View
                    android:layout_width="@dimen/dimen_1dp"
                    android:layout_height="match_parent"
                    android:background="@color/white" />

                <LinearLayout
                    android:id="@+id/txt_buy_info_ll2"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="0.5"
                    android:background="@color/color_wallet_background"
                    android:padding="@dimen/dimen_10dp">

                    <include
                        android:id="@+id/ll_buy_info"
                        layout="@layout/include_layout_buy_new" />
                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/ll1"
                android:layout_margin="@dimen/dimen_10dp"
                android:orientation="vertical">

                <LinearLayout
                    android:id="@+id/ll2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/llTop"
                        layout="@layout/common_edittext_header_for_bid_ask_new" />
                </LinearLayout>

                <include
                    android:id="@+id/activity_market_rates"
                    layout="@layout/activity_market_rates_inner_layout_ask"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>

        </RelativeLayout>

    </ScrollView>

    <LinearLayout
        android:id="@+id/llLast"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/ask_rules"
            android:textColor="@color/white"
            android:textSize="@dimen/textSizeTooMin" />

        <TextView
            android:id="@+id/txtMsgBidAsk"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dimen_5dp"
            android:gravity="center"
            android:text="@string/BidAskMsg"
            android:textColor="@color/white"
            android:textSize="@dimen/textSizeTooMin"
            android:textStyle="italic" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_ask"
            style="@style/button_style"
            android:layout_marginBottom="@dimen/dimen_10dp"
            android:layout_marginLeft="@dimen/dimen_10dp"
            android:layout_marginRight="@dimen/dimen_10dp"
            android:text="@string/ask" />
    </LinearLayout>
</RelativeLayout>

activity_market_rates_inner_layout_ask.xml is given below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/rlTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/dimen_3dp"
    android:orientation="horizontal"
    android:weightSum="1">

    <ProgressBar
        android:id="@+id/progressBar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.1"
        android:background="@drawable/progress_drawable"
        android:indeterminate="false"
        android:max="100"
        android:visibility="invisible" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.9"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtLocal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/localPrice"
            android:textColor="@color/white"
            android:textSize="@dimen/bid_ask_current_trades_size" />

        <TextView
            android:id="@+id/txtVirtual"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/localPrice"
            android:textColor="@color/white"
            android:textSize="@dimen/bid_ask_current_trades_size" />

        <TextView
            android:id="@+id/txtRate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/ratePrice"
            android:textColor="@color/white"
            android:textSize="@dimen/bid_ask_current_trades_size" />
    </LinearLayout>
</LinearLayout>

<RelativeLayout
    android:id="@+id/rlProgress"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rlTitle"
    android:layout_gravity="center"
    android:visibility="gone">

    <ProgressBar
        android:id="@+id/progressBar2"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/progress_color"
        android:indeterminate="true" />
</RelativeLayout>

<ScrollView
    android:id="@+id/scrollViewChild"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rlTitle"
    android:fillViewport="true"
    android:fitsSystemWindows="true"
    android:scrollbarThumbVertical="@drawable/scrollbar_thumb_color">

    <LinearLayout
        android:id="@+id/llRV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvSell"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rvBuy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dimen_5dp" />
    </LinearLayout>
</ScrollView>

here I want to scroll the scrollViewChild , I have used
rvSell.setNestedScrollingEnabled(false);
 rvBuy.setNestedScrollingEnabled(false);

But only parent scrollview is scrolling not child.

A: try this:
 recycler.setLayoutManager(new LinearLayoutManager(linear_.getContext(),
            LinearLayoutManager.VERTICAL, false){
        @Override
        public boolean canScrollHorizontally() {
            return false;
        }

        @Override
        public boolean canScrollVertically() {
            return false;
        }
    });

and instead of ScrollView use NestedScrollView

A: In your inner xml, Try:
<android.support.v7.widget.RecyclerView
            android:id="@+id/rvSell"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:overScrollMode="never"/>

<android.support.v7.widget.RecyclerView
            android:id="@+id/rvBuy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dimen_5dp"
            android:nestedScrollingEnabled="false"/>


text:
Q: the meaning of lightweighted object Please, gurus, give me a detailed explanation of, in the Object-Oriented programming world, what is lightweight object? And in other computer science fields, what does lightweight means then? Is lightweight a design pattern? Is lightweight good, is bad?

A: There are many meanings for lightweight, but normally it means the object which has less amount of data or which process less amount of data. Sometimes a thread is called as a lightweight process as it does a less things than a process do. Its processing is also fast than the process. A lightweight object is one which has less amount members and which are of basic types (int, float) as member variables. A light function is the one which does very less things compared to others. Normally these are inline functions. (in C context).
There is no such patterns as lightweight pattern. But Normally the systems should be consists of lightweight objects so that the maintaining those objects could be easy.
The advantages are simple debugging, maintenance and easy understanding of code. The disadvantage could be lots of objects.
There is no lightweight pattern as such but the term is fairly used in the industry.

A: Lightweight X tend to be used in the case where we have a somewhat well known structure X. Lightweight X is then a version of X using fewer resources in some way or the other - or is subtly different from X in some way.
The term, as is the case for most computer science, is not well-defined and is loosely used.


text:
Q: Update mysql with C# and PHP hi i have mysql db and php file called upd.php i want update my database record with c# and php i used bellow code[Method 1] everythings is ok and work fine
PHP Code:
<?php
$servername = "localhost";
$username = "Crypted";
$password = "appCrypted";
$dbname = "Crypted";

// Post Method
//$hwInfo = $_POST["hwInfo"];
$trial = $_GET["trial"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET trial='$trial' WHERE hwInfo='4871-1598-0155-1531'";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

C# Code:
string urlAddress = "http://localhost.ir/ClassSRM/upd.php";
            using (WebClient client = new WebClient())
            {
                NameValueCollection postData = new NameValueCollection()
                    {
                      { "trial", "10" }
                };
                Console.WriteLine(urlAddress);
                Console.WriteLine(postData);

                string pagesource = Encoding.UTF8.GetString(client.UploadValues(urlAddress, postData));
            }

now if i enter this link http://localhost.ir/ClassSRM/upd.php?trial=3000 my record update successfully, but i want send hwInfo from c# to upd.php, i used bellow Code [Method 2] but nothing work
<?php
$servername = "localhost";
$username = "Crypted";
$password = "appCrypted";
$dbname = "Crypted";

// Post Method
 //$hwInfo = $_POST["hwInfo"];
$trial = $_GET["trial"];
$hwInfo = $_GET["hwInfo"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET trial='$trial' WHERE hwInfo='$hwInfo'";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

C# Code:
string urlAddress = "http://localhost.ir/ClassSRM/upd.php";
            using (WebClient client = new WebClient())
            {
                NameValueCollection postData = new NameValueCollection()
                    {
                      { "hwInfo", hwInfo },
                      { "trial", "10" }
                };
                Console.WriteLine(urlAddress);
                Console.WriteLine(postData);

                string pagesource = Encoding.UTF8.GetString(client.UploadValues(urlAddress, postData));
            }

A: I know it is old question but it may help somebody. Your example works but I made some change in PHP code, I use POST method, here my working example:
<?php
$servername = "localhost";
$username = "Crypted";
$password = "appCrypted";
$dbname = "Crypted";

$trial = isset($_POST['trial']) ? $_POST['trial'] : '';
$hwInfo = isset($_POST['hwInfo']) ? $_POST['hwInfo'] : '';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET trial='$trial' WHERE hwInfo='$hwInfo'";
echo "sql: " . $sql;
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>


text:
Q: How to fade in a background image change in jQUery? So I have a div that changes its background image when a user hovers over it and also shows text hen a user hovers over the image. Is there a way so that the div's background fades into the new background on hover?
Here's my current code so far http://jsfiddle.net/nGhMz/

A: You can not fade a background image, but you can position an element behind using relative and absolute positioning, as well as z-index.
You can then fade that element in the background.
var imgSrc = 'new/image.png';
container.css({backgroundImage: 'url("' + imgSrc  +'")'});
container.find('img').show().fadeOut(1000, function() { $(this).attr({src: imgSrc}) });

A: I mis-interpreted your question the first time around...
I have re-worked your example to get the effect you are looking for. Not sure if it is the cleanest way. It uses one image as an overlay and fades it out.
http://jsfiddle.net/nGhMz/7/
Hope this helps.
Bob


text:
Q: Open modal from other component in ReactJS Hey I have one question about ReactJS, because I try make modal using react-bootstrap and open it in another component. But nothing happens, please look on my code and give me some advices. I try invoke fuunction from LoginModal component using onClick="LoginModal.handleShow" but this no working.
import React, { Component } from 'react';
import {
  Popover,
  Tooltip,
  Modal
} from 'react-bootstrap';

class LoginModal extends React.Component {
  constructor(props, context){
    super(props, context);
    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.state = {
        show: false
    }
}
handleShow() {
    this.setState({ show: true })
}
handleClose(){
    this.setState({ show: false })
}
render() {

    return (

          <Modal show={this.state.show} onHide={this.handleClose}>
             <Modal.Header closeButton>
               <Modal.Title>Modal Heading</Modal.Title>
             </Modal.Header>
             <Modal.Body>

This is modal body

             </Modal.Body>
          </Modal>

    )
  }
}
export default LoginModal

And App component which is rendered
import React, { Component } from 'react';
import LoginModal from './components/Login/Login'
import {
  Navbar,
  NavItem,
  Nav,
  Button
} from 'react-bootstrap';
import {
  BrowserRouter as Router,
  Route,
  Switch,
 } from 'react-router-dom'

class App extends Component {

render(){
    return (
      <Router>

           <LoginModal></LoginModal>
             <Navbar inverse collapseOnSelect>

                 <NavItem>
                   <Button onClick={LoginModal.handleShow}>Login</Button>
                 </NavItem>

              </Navbar>

                <Switch>
                    <Route exact path="/" component={Home}/>
                </Switch>

        </Router>
    )
  }
}
export default App;

A: Use ref keyword to take reference of LoginModal. Then call handleShow from the reference.
class App extends Component {

 loginModalRef = ({handleShow}) => {
   this.showModal = handleShow;
 }

 onLoginClick = () => {
  this.showModal();
 }

 render(){
    return (
       <Router>

           <LoginModal  ref={this.loginModalRef} ></LoginModal>
             <Navbar inverse collapseOnSelect>

                 <NavItem>
                   <Button onClick={this.onLoginClick}>Login</Button>
                 </NavItem>

              </Navbar>

                <Switch>
                    <Route exact path="/" component={Home}/>
                </Switch>

        </Router>
    )
  }
}

Here I prepare stackblitz snippet for you to test it online. https://stackblitz.com/edit/react-bxn5kj?file=index.js


text:
Q: How can I vet my HTML email signature code I'm new to HTML and I am designing an HTML email signature for the first time. I believe the code is properly written but I've had some issues. I attempted to get clearer images by saving each slice at twice the resolution then downsizing using HTML. However, in some email clients each image would have added padding around each image cell making the email signature look broken apart. Other browsers and clients would have images and text showing up blurry.
I gave up and stuck to the same image size and resolution in both the image size and the HTML coding which seems to work better. Is there anything wrong with my code?

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

This email may contain confidential and/or proprietary information. If you are not the intended addressee or have received this e-mail in error, please inform the sender immediately and destroy this e-mail. Unauthorized copying and/or forwarding of this email is strictly prohibited.

A: There's something over and above all of this which is that: does it work on mobiles? Most people read emails on their phone (70-80%), so if it's 516px wide what will happen is that your email will be reduced in size to fit (you will want to fit to at least 300px, if not 280px to cover the smallest).
Otherwise, assuming the email environment you use automatically uploads the images, to remove the gaps you would use the following set of defaults (a HTML email CSS reset needs to be inline, not in


text:
Q: I want to find Java open source projects with many unit testcases We are doing some research on automatic debugging for java programs. We want to find some Java open source projects with large set of unit testcases (Junit).
Anyone has some recommendations?
Thank you so much.
Zhongxian

A: if you go here you can use regex as your search query to find lots of projects with lots of unit tests or any mix you desire:  http://google.com/codesearch

A: Lucene (@http://wiki.apache.org/lucene-java/HowToContribute)

A: Android CTS has more than 10000 tests.

A: Spring Framework.


text:
Q: jsonschema.exceptions.ValidationError: 'os-fault.json' is not of type 'object' I want to create JSON file the schema is 'http://json-schema.org/draft-04/schema#'.
This is JSON file that I write.
{
    "cloud_management" : {
        "driver": "universal"
    },
    "node_discover": {
        "driver": "node_list",
        "args": [
            {
                "ip": "{my_ip}",
                "auth": {
                    "username": "{my_username}"
                }
            },
            {
                "ip": "{my_2nd_ip}",
                "auth": {
                    "username": "{my_username}"
                }
            }
        ]
    },
    "services": {
        "memcached": {
            "driver": "system_service",
            "args": {
                "service_name": "memcached",
                "grep": "memcached"
            }
        },
        "rabbitmq": {
            "driver": "system_service",
            "args": {
                "service_name": "rabbitmq",
                "grep": "rabbitmq"
            }
        }
    },
    "power_managements": [
        {
            "driver": "libvirt",
            "args": {
                "connection_uri": "qemu+unix:///system"
            }
        }
    ]
}

The {my_ip}, {my_2nd_ip} and {my_username} will be converted to real value.
I check the validity of this file with JSON schema validator (the link of the site: https://www.jsonschemavalidator.net/), and it says 'No Error found. JSON validates against the schema'.
However, when I run the program I got this error like this.
Traceback (most recent call last):
  File "kill_service.py", line 18, in <module>
    main()
  File "kill_service.py", line 8, in main
    cloud_management = os_faults.connect(cloud_config = 'os-fault.json')
  File "/usr/local/lib/python3.8/dist-packages/os_faults/__init__.py", line 147, in connect
    jsonschema.validate(cloud_config, CONFIG_SCHEMA)
  File "/usr/lib/python3/dist-packages/jsonschema/validators.py", line 934, in validate
    raise error
jsonschema.exceptions.ValidationError: 'os-fault.json' is not of type 'object'

Failed validating 'type' in schema:
    {'$schema': 'http://json-schema.org/draft-04/schema#',
     'properties': {'cloud_management': {'additionalProperties': False,
                                         'properties': {'args': {'type': 'object'},
                                                        'driver': {'type': 'string'}},
                                         'required': ['driver'],
                                         'type': 'object'},
                    'node_discover': {'additionalProperties': False,
                                      'properties': {'args': {},
                                                     'driver': {'type': 'string'}},
                                      'required': ['driver', 'args'],
                                      'type': 'object'},
                    'power_managements': {'items': {'additionalProperties': False,
                                                    'properties': {'args': {'type': 'object'},
                                                                   'driver': {'type': 'string'}},
                                                    'required': ['driver',
                                                                 'args'],
                                                    'type': 'object'},
                                          'minItems': 1,
                                          'type': 'array'},
                    'services': {'additionalProperties': False,
                                 'patternProperties': {'.*': {'additionalProperties': False,
                                                              'properties': {'args': {'type': 'object'},
                                                                             'driver': {'type': 'string'},
                                                                             'hosts': {'items': {'type': 'string'},
                                                                                'minItems': 1,
                                                                                'type': 'array'}},
                                                              'required': ['driver',
                                                                           'args'],
                                                              'type': 'object'}},
                                 'type': 'object'}},
     'required': ['cloud_management'],
     'type': 'object'}

On instance:
    'os-fault.json'

My JSON file name is 'os-fault.json'.
When the program checks the validity of JSON file with

jsonschema.validate(cloud_config, CONFIG_SCHEMA),

it detect some errors in my JSON file. But I can't find out any error in that file.
Thanks for your help.

A: The error you're getting is misleading because it's not running verification against the contents of your JSON file because you haven't passed it what it expects.
os-faults expects a dict object for the cloud_config argument, which requires you to load the JSON file first. If you want to pass the .json file directly, you have to use the config_filename argument instead, like this.
import os_faults

cloud_management = os_faults.connect(config_filename="os-fault.json")
cloud_management.verify()

If you want to do it by loading JSON and specifying the cloud_config parameter, you have to load your os-fault.json file first and then pass it like this.
import json

import os_faults

with open("os-fault.json", "r") as f:
    config = json.load(f)

cloud_management = os_faults.connect(cloud_config=config)
cloud_management.verify()


text:
Q: How to save custom data in sales_flat_creditmemo table prgramatically Magento 1 I have created a new field in sales_flat_creditmemo table. Please help me in saving the custom data to a newly created field in the table in magento 1. I have tried this but its not saving the data. I'm trying to save the data using sales_order_creditmemo_save_after observer event
$creditMemos = Mage::getResourceModel('sales/order_creditmemo_collection');
$creditMemos->addFieldToFilter('increment_id', $incrementId);
$creditMemos->load();

foreach ($creditMemos as $creditMemo) {
    $creditMemo->setRefundtype('test');
    $creditMemo->save();
}

A: try to use :
saveAttribute();

another one :
$test='test'
->setData('refundtype', $test);

and one more question :
What`s the name of your database column that you created ?
refundtype ?
 or
refund_type ??


text:
Q: RBAC in Node.js I am just starting with Node.js and Express and I am a bit confused on how the get the access controls I want.
What I have are 3 user types:

*

*Admin

*Provider

*General

The admin and general I can do, the problem is that providers can only access one "article" while an "article" can have multiple providers. Is there an easy way to get this functionality?
Edit: User 'X' can only access article 1 and users 'Y' & 'Z' can both access article 2.


text:
Q: Custom Field label translation is not working What I want to achieve?
I want to create CustomField label translations for other languages on Account object.
What is the issue?
Even though I created some translations and I changed my user's locale and language settings, I still cannot see any translations on the Record Detail page.
What I checked so far?
I've checked and confirmed using Tooling API that translations are present. They are also present in the Setup -> User Interface -> Translate
Worth mentioning
The person that is responsible for creating translations has the System Admin profile and she was also added to the language translators group for this specific language. She is using an external tool called XL-Connector in Excel for this purpose.
Update 1
I tried to manually refresh translation by adding a single character to it, saving, and then reverting back this change and now the translation is visible. However I want to avoid such situations in the future, do you know how to "force" refresh the translations? It looks like salesforce is not reflecting to these changes.


text:
Q: If not variable condition is not working I'm trying to check whether the variable value is false or true, here is my code
$print_ready_flag = $_GET['print_ready']; // i'm passing it as either true or false

echo $print_ready_flag ; // I'm getting correct value

What i'm trying to do is,
if ($print_ready_flag == false) {
     file_name = "albumpdf_" . $Order['products_name'] . "_" . $OrderId . "_" . $OrderPId . ".pdf";
}

when doing like above expression is evaluating, But when i tried

if (!$print_ready_flag) {,
if (!(bool)$print_ready_flag)

. expression is not evaluating. Is there any way to evaluate the expression with out using comparison operator.

A: $print_ready_flag = $_GET['print_ready'];

echo $print_ready_flag ; // I'm getting correct value
$print_ready_flag = filter_var($print_ready_flag, FILTER_VALIDATE_BOOLEAN);
if ($print_ready_flag == false) {
  file_name = "albumpdf_" . $Order['products_name'] . "_" . $OrderId . "_" . $OrderPId . ".pdf";
}

A: Well your all conditions are looks fine. you must need to add php `error_reporting() in your code, this will help you to find syntax and warnings.
You have a typo here:
// missing $ sign
file_name = "albumpdf_" . $Order['products_name'] . "_" . $OrderId . "_" . $OrderPId . ".pdf";

And its better to use print_ready=0 instead of print_ready=false for $_GET.
Otherwise, you must need to check with === for value+dataType


text:
Q: Android: Importing resources on featureModule vs library module
featureModule = apply plugin: 'com.android.dynamic-feature'
libraryModule = apply plugin: 'com.android.library'
Problem - Using any library resources in feature module requires full package name qualifier which eventually creates a problem for databinding generated classes in feature module.
Description - I have this above app structure. When I am trying to use any library resource in any featureModule it requires to specify the resource with full package name qualifier because by default I have the feature resource R as the main import.
So for any kotlin class let say activity code looks like this
feature-1/TestActivity.kt
internal class TestActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityTestBinding = DataBindingUtil.setContentView(this, R.layout.activity_test)
        binding.testName.text = getText(R.string.abc_test) // this resource is present in core-lib module
    }
}

The above will lead to an unresolved reference error which you can resolve by using full-name so instead of R.string.abc_test use com.blah.core-lib.R.string.abc_test.
R.layout.activity_test
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/test_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/spacing_medium"
        android:text="@{@string/abc_test}" />
</layout>

But for XML-databinding it creates a bigger problem. Since R.layout.abc_test is in feature module it's not able to access the library resource. I can resolve this by using a utility class & let the utility class return the string with full-package name qualifier but this problem sort of restricts many feature of databinding where I can't use the resource directly in the XML itself.
PS: This all works fine if I convert my feature module to a library module. Even at the code level I don't end up using full package name qualifier if it's a library module.
Does anyone have any better suggestions to resolve this problem for feature modules?


text:
Q: Does 'xinput list' 'Virtual core pointer's id is always '2'? Hi I'm newbie to Ubuntu.
I need to know Virtual core pointer Id to use in shell file (.sh extension) Chrome. I used command --touch-devices=2 it is working fine. But I am not sure Virtual core pointer value will be always 2. (I know actual hardware device id will vary as Logitech Optical USB Mouse id=9 will not necessarily be always 9.)
⎡ Virtual core pointer id=2 [master pointer (3)]
⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)]
⎜ ↳ Logitech Optical USB Mouse id=9 [slave pointer (2)]
⎜ ↳ SynPS/2 Synaptics TouchPad id=11 [slave pointer (2)]
⎣ Virtual core keyboard id=3 [master keyboard (2)]
↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)]

I want to use generic command as
<some_command> --touch-devices=$(xinput --list --id-only 'Virtual core pointer')

but it's not working.
Please suggest how should I approach?

A: Here is how I figured out what to do:
xinput --list
xinput --list| grep "Virtual core pointer"
xinput --list| grep "Virtual core pointer" | awk '{print $5}'
xinput --list| grep "Virtual core pointer" | awk '{print $5}' | cut -d= -f2

So, your answer is:
<some_command> --touch-devices=$(xinput --list| grep "Virtual core pointer" | awk '{print $5}' | cut -d= -f2)

Pipes are fun, but it would be better to just use awk for the tasks, that grep and cut are supposed to do:
<some_command> --touch-devices=$(xinput --list | awk '/Virtual core pointer/ { print(substr($5, 4)); exit; }')

Good programming practice! Determine the number from what the system tells you is true NOW, rather than hard-coding a number that was right once-upon-a-time.


text:
Q: Request Entity Too Large error on chunked plupload with plupload-handler-php example I'm pulling my hair out. Using plupload with chunking on a php backend. Chunked (or non chunked for that matter) goes fine until I use files > 100mb.
I'd like to be able to use files until 1Gb. Keep getting the error, and then the retries kick in and percentage is at 0% again and restarting.
There is also no preflight OPTION request. I even made a quick NodeJS backend by using node-pluploader, that handles chunks, but same problem and errors there (although that did send preflight OPTION).
Any advice would be greatly appreciated
Additional Apache directives
LimitRequestBody 0

PHP settings
file_uploads          On
max_file_uploads          20
max_execution_time          3600
memory_limit          640M
post_max_size          600M
upload_max_filesize          500M

js
var uploader = new plupload.Uploader({
    runtimes : 'html5,silverlight,html4',
    browse_button : 'pickfiles',
    url : '<?php echo SITE_URL; ?>admin?sub=upload',
    silverlight_xap_url : '<?php echo SITE_URL; ?>lib/Moxie.xap',
    multi_selection : false,
    max_retries: 10,

    filters : {
        max_file_size : '1024mb',
        chunk_size: '10mb',
    },

    init: {

        FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
                $('#document-file').html(file.name);
            });
        },

        UploadProgress: function(up, file) {
            $('#spinner-progress').html( " " + file.percent + "%" );
        },

        Error: function(up, err) {
            console.warn("Error #" + err.code + ": " + err.message);
        },

        UploadComplete: function(up, files) {
            console.log(files[0]);
        }
    }
});

uploader.init();

uploader backend
<?php
require_once(LIB.SLASH."PluploadHandler.php");

PluploadHandler::no_cache_headers();
PluploadHandler::cors_headers();

if (!PluploadHandler::handle(array(
    'tmp_dir' => UPL_TMP_PATH,
    'target_dir' => UPL_TMP_PATH
))) {
    die(json_encode(array(
        'OK' => 0,
        'error' => array(
            'code' => PluploadHandler::get_error_code(),
            'message' => PluploadHandler::get_error_message()
        )
    )));
} else {
    die(json_encode(array('OK' => 1)));
}

I'm using an unchanged plupload-handler-php example

A: Turned out to be a forced setting in ngnix config. The client_max_body_size was forced to 128m by a Plesk default template (default/domain/nginxDomainVirtualHost.php). On overruling this setting Plesk returned a "duplicate" error which eventually turned me to this answer. Make a custom template, update vhosts. Problem solved!


text:
Q: Using python random.choice in combination with list.append() Lately, I've had some problems with Python's random.choice function.
I would expect the example script I've added to print out a list that consists of 3 items. Each of those items should be a list that contains two integers and one string.
For example: [[1, 4, 'a'], [2, 1, 'b'], [3, 4, 'c']]
from random import choice

pair = [
[1, 2], [1, 3], [1, 4],
[2, 1], [2, 3], [2, 4],
[3, 1], [3, 2], [3, 4],
[4, 1], [4, 2], [4, 3]
]

list = [0, 0, 0]

list[0] = choice(pair)
list[0].append('a')
list[1] = choice(pair)
list[1].append('b')
list[2] = choice(pair)
list[2].append('c')

print(list)

Most of the times the script works as expected. Sometimes however, it prints out something like this:
[[3, 2, 'a', 'c'], [4, 3, 'b'], [3, 2, 'a', 'c']]
Two of the items in the list not only consist of one string too many, but they are identical for some reason.
First I believed this had something to do with the append function.
However when I removed the random.choice component like this:
list = [0, 0, 0]
list[0] = [1, 2]
list[0].append('a')
list[1] = [2, 3]
list[1].append('b')
list[2] = [3, 4]
list[2].append('c')

print(list)

It still worked without flaws.
Same for the random.choice function, which didn't cause any problems by itself:
from random import choice

pair = [
[1, 2], [1, 3], [1, 4],
[2, 1], [2, 3], [2, 4],
[3, 1], [3, 2], [3, 4],
[3, 1], [3, 2], [4, 3],

list = [0, 0, 0]

list[0] = choice(pair)
list[1] = choice(pair)
list[3] = choice(pair)

print(list)

Next I tested what would happen when the list contained only one item and list.append and random.choice were only executed once
from random import choice

pair = [
[1, 2], [1, 3], [1, 4],
[2, 1], [2, 3], [2, 4],
[3, 1], [3, 2], [3, 4],
[4, 1], [4, 2], [4, 3]
]

list = [0]

list[0] = choice(pair)
list.append('a')

print(list)

This script behaved like I'd expect as well. Apparently my problem only occurs when random.choice and list.append are used executed several times on different items in a list, however I don't know how to explain it. Could someone explain what's happening and how to solve it?

A: First I open the REPL prompt and run your first block of code
>>> from random import choice
>>>
>>> pair = [
... [1, 2], [1, 3], [1, 4],
... [2, 1], [2, 3], [2, 4],
... [3, 1], [3, 2], [3, 4],
... [4, 1], [4, 2], [4, 3]
... ]
>>>
>>> list = [0, 0, 0]
>>>
>>> list[0] = choice(pair)
>>> list[0].append('a')
>>> list[1] = choice(pair)
>>> list[1].append('b')
>>> list[2] = choice(pair)
>>> list[2].append('c')
>>>
>>> print(list)
[[4, 1, 'a'], [3, 4, 'b'], [1, 2, 'c']]

Looks ok, but what happens if you inspect pair
>>> pair
[[1, 2, 'c'], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4, 'b'], [4, 1, 'a'], [4, 2], [4, 3]]

So by appending to the lists that choice(pair) returns, you have inadvertently modified pair.
This is because choice(pair) doesn't copy the sublist.
If you mean to make a copy of the sublist, use
list[0] = choice(pair)[:]

or
list[0] = choice(pair).copy()


text:
Q: C# Stackoverflow in recursive deleting directory operation I'm currently rewriting a file deletion tool with safe deleting algorithm and stuff.
Wenn I'm trying to browse through a directory recursivly and to delete all files in there and all subdirs etc. the debugger will throw a stackoverflow exception.
   private void wipeFile(string file)
   {
        bool ret = false;
        switch (m_algo)
        {
            case Algorithms.fastAlgo:
                ret = FastWipe.WipeFile(file);
                break;
            case Algorithms.safeAlgo:
                ret = CleanWipe.WipeFile(file, m_timesToWrite);
                break;
        }
        handleFileWiped(file, DateTime.Now, ret);
    }

    /// <summary>
    /// Wipes a directory recursively
    /// </summary>
    /// <param name="directory">Given subdir</param>
    private void deepWipe(string directory)
    {
        foreach (string file in Directory.GetFiles(directory))
        {
            wipeFile(file);
        }
        foreach (string subdir in Directory.GetDirectories(directory))
        {
            deepWipe(directory);
        }
        try
        {
            Directory.Delete(directory);
            handleDirectoryWiped(directory, DateTime.Now, true);
        }
        catch { handleDirectoryWiped(directory, DateTime.Now, false); }
    }

A: Change this:
 foreach (string subdir in Directory.GetDirectories(directory))
 {
     deepWipe(directory);
 }

to:
 foreach (string subdir in Directory.GetDirectories(directory))
 {
     deepWipe(subdir);
 }


text:
Q: Custom margins in console printing C# How can I format my string to have custom margins for columns, so it would like like below?
I know that "\t" puts a tab into a string but the width is fixed, and I would like to have a possibility of custom columns width
By extensions:
                    [count]   [total size]   [avg size]   [min size]   [max size]
    jpg              10        21.5MB         45KB         30KB         230KB
    png              1         1.5MB          1.5MB        1.5MB        1.5MB
    gif              13        4.5MB          ...          ...          ...
    doc              1         120KB          ...          ...          ...
    txt              5         5KB            ...          ...          ...
    mp3              30        96MB           ...          ...          ...
    [other]          0         0B             ...          ...          ...

By sizes:
                    [count]   [total size]   [avg size]   [min size]   [max size]
          . <= 1KB   10        21.5MB         ...          ...          ...
    1KB < . <= 1MB   1         1.5MB          ...          ...          ...
    1MB < . <= 1GB   13        4.5MB          ...          ...          ...
    1GB < .          ...       ...            ...          ...          ...

Counts by first leter:
    A   C   R   ...
    5   3   1   ...

Ordered by name:
                    [size]           [path]
    aaa.png          1.5MB
    bbb.jpg          30KB
    ccc.mp3          2.3MB
    ...

Ordered by sizes (from biggest):
                    [size]
    ccc.mp3          2.3MB
    aaa.png          1.5MB
    bbb.jpg          30KB
    ...


text:
Q: Database problem: how to diagnose and fix the problem? I created an application which stores values into the database and retrieves the stored data. While running an application in run mode everything seems to work fine (the values are stored and retrieved successfully) but when I run in the debug mode the process throws IllegalStateException and so far haven't found a cause.
The method which retrieves an object Recording is the following:
public Recording getRecording(String filename) {

    Recording recording = null;
    String where = RECORDING_FILENAME + "='" + filename + "'";
    Log.v(TAG, "retrieving recording: filename = " + filename);

    try {
        cursor = db.query(DATABASE_TABLE_RECORDINGS, new String[]{RECORDING_FILENAME, RECORDING_TITLE, RECORDING_TAGS, RECORDING_PRIVACY_LEVEL, RECORDING_LOCATION, RECORDING_GEO_TAGS, RECORDING_GEO_TAGGING_ENABLED, RECORDING_TIME_SECONDS, RECORDING_SELECTED_COMMUNITY}, where, null, null, null, null);

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            //String filename = c.getString(0);
            String title = cursor.getString(1);
            String tags = cursor.getString(2);
            int privacyLevel = cursor.getInt(3);
            String location = cursor.getString(4);
            String geoTags = cursor.getString(5);
            int iGeoTaggingEnabled = cursor.getInt(6);
            String recordingTime = cursor.getString(7);
            String communityID = cursor.getString(8);
            cursor.close();
            recording = new Recording(filename, title, tags, privacyLevel, location, geoTags, iGeoTaggingEnabled, recordingTime, communityID);
        }
    }
    catch (SQLException e) {
        String msg = e.getMessage();
        Log.w(TAG, msg);
        recording = null;
    }
    return recording;
}

and it is called from another class (Settings):
private Recording getRecording(String filename) {
    dbAdapter = dbAdapter.open();
    Recording recording = dbAdapter.getRecording(filename);
    dbAdapter.close();
    return recording;
}

While running through the code above everything works fine but then I notice an exception in another thread:
alt text http://img509.imageshack.us/img509/862/illegalstateexception.jpg
and don't know neither what is the possible cause of this exception nor how to debug the code from that thread to diagnose the cause.
I would be very thankful if anyone knew what is the possible issue here.
Thank you!

A: Looks like that cursor.close() is inside an "if" - that's when SQLiteCursor.finalize() will throw an IllegalStateException (I googled for it). You migh be getting an empty recordset, for instance, if some other process/thread didn't have the time to commit.
Close it always, even if it's result set is empty.
I'd also advice you to access fields by names, not indices, for future compatibility. And do both close()s in finally{} blocks.


text:
Q: UIView rounded corners and drop shadow leaves tiny wrong pixel(s) on 4 edges I want a UILabel with rounded corners and drop shadow (on the bounds, not on the text)
I almost have this working, except for this pesky few pixels of the wrong color on all 4 edges ("remainder" of the "rounding"):

This is my custom reusable view:

I've set the various views to different colors to be able try see which view is misbehaving.
The top-level view is where I do the drop shadow (backgroundColor = green):
    view.layer.shadowColor = UIColor.blackColor().CGColor
    view.layer.shadowOpacity = 0.2
    view.layer.shadowOffset = CGSizeMake(3, 3);
    view.layer.shadowRadius = 3

Note that the pesky wrong pixels are indeed green.
The middle view ("BackgroundView") is where I do the rounded corners (backgroundColor = red):
    backgroundView.layer.cornerRadius = 3
    backgroundView.layer.masksToBounds = true

If I do this these edges turn from green to white. I don't know where the white is coming from:
view.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.0)

If I try an unelegant hack and set the top-level view's backgroundColor to the pink background, then it messes up with the bottom corner for my drop shadow like this:

I'm new to Swift and iOS, and I know that surely, I'm doing something n00b'ish.
Update: I'm trying to make this a custom reusable view (xib + swift file). I find that using this method, I have to use more than 1 view, and I can't quite get it right, but if I just try to manually make a one-off view (drop shadow + rounded corner) in Main.storyboard, it works just fine (and even, with just 1 view!). Why is that?

A: You need to set a shadowPath to the view's layer with a rounded rect path (CGPathCreateWithRoundedRect)


text:
Q: Microsoft Report Viewer Showing hidden columns on exporting to excel I'm using Microsoft Report Viewer in an ASP.Net application on the 4.0 framework.  I have the report showing fine inside the webpage, but I was recently requested to hide several columns.  I found out that through editing the Column Visibility by right clicking on the column in the .RLDC file would allow me to hide it, but I need to be able to show the hidden columns upon Exporting to Excel.  As far as I can tell Microsoft Report Viewer exports exactly what it has shown to Excel.
Does anyone know how to access or change the columns properties upon the export to excel click event on Microsoft Report Viewer 2010?

A: Your best bet is to add your own export functionality.
Set ShowExportButton="False" in the ReportViewer and add a new button in your page that hides the columns and then exports the report to excel.


text:
Q: How to save table data in database I am inputting data in my table in jsp but only one row saved in database. When I add another row in my table, it did save but only the first row saved. Please help me how to solve my problem. I am new here.
This is my jsp code:

    Subject Code
    Description
    Lecture
    Lab
    Units
    Schedule

        <INPUT type="checkbox" name="chk"/>

         <INPUT type="text" name="subjCode" />
         <INPUT type="text" name="description" />
         <INPUT type="text" name="lec" />
         <INPUT type="text" name="lab" />
         <INPUT type="text" name="units" />
         <INPUT type="text" name="sched" />

This is my code for the controller:
 try (PrintWriter out = response.getWriter()) {

        String subjCode = request.getParameter("subjCode");
        String description = request.getParameter("description");
        String lec = request.getParameter("lec");
        String lab = request.getParameter("lab");
        String units = request.getParameter("units");
        String sched = request.getParameter("sched");

        try
        {

                Class.forName("com.mysql.jdbc.Driver").newInstance();
                   Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
                Statement st= conn.createStatement();
                st.executeUpdate("insert into student (subjCode, description, lec, lab, units, sched) values('"+subjCode+"', '"+description+"', '"+lec+"', '"+lab+"', '"+units+"', '"+sched+"')");

        out.println("Data is inserted");

        }

    }

This is my js code when you want to add another row:


text:
Q: How can you save a scene in JavaFX and recall it later with the same selection? I've been searching the internet and stackoverflow for several hours for a solution to my question.
To the current problem:
I have a interface which makes it easier for the user to edit a SQLite database.
In my main interface the user has the possibility to set a filter for the display of the data with the help of several combo boxes.
If a new record is to be created, I open a new interface which allows the user to generate the data by just a few entries.
For this, I first close the main interface and then call the create interface.
However, if the user wants to cancel the creation process, the main interface should be loaded again with the previously made selection options and the create inteface should close.
Unfortunately I do not know how to achieve this.
I tried to accomplish this by imitating the last input of the user in the main interface initialize attempt. However, this is not possible because several combo boxes are required for the user selection and react completely dynamically to the previous selection.
I´m glad for every comment or helpfull link


text:
Q: IPython / pandas: Is there an canonical way to detect rapid changes in a timeseries? Noob data analyst, analyzing some gas concentrations over a timeseries of a couple of thousand points (so small). I graphed it with Matplotlib, and there are some easy to see points where things change rapidly.
What is the canonical / easiest way to home in on those points?

A: import pandas as pd
from numpy import diff, concatenate
ff = pd.DataFrame( #acquire data here
      columns=('Year','Recon'))
fd = diff(ff['Recon'], axis=-1)
ff['diff'] = concatenate([[0],fd],axis=0)
ff['rolling10'] = pd.rolling_mean(ff['diff'],10)
ff['rolling5'] = pd.rolling_mean(ff['diff'],5)
ff.plot('Year',['rolling5','rolling10'],subplots=False)

But note! my test data was evenly sampled. Looks like rolling_* don't apply to irregular time series yet, though there are some workarounds: Pandas: rolling mean by time interval


text:
Q: Unable to remove carriage returns Greetings!
I have been tasked to create a report off files we receive from our hardware suppliers. I need to grep these files for two fields 'Test_Version' and 'Model-Manufacturer' ; for each field, I need to capture their corresponding values.
In a previous post, I found help to create a basic report like so:
    find . -name "*.VER" -exec egrep -A 1 'Test_Version=|Model-Manufacturer:' {} ';'

Model-Manufacturer:^M
R22-100^M
Test_Version=2.6.3^M
Model-Manufacturer:^M
R16-300^M
Test_Version=2.6.3^M

However, the data that's output is riddled with DOS carriage returns "^M". My boss wants "Model-Manufacturer" to show like "Test_Version" i.e
Model-Manufacturer:R22-100
Test_Version=2.6.3
Model-Manufacturer:R16-300
Test_Version=2.6.3

Using sed, I attempted to remove the "^M" characters for "Model-Manufacturer"  but to no avail:
find . -name "*.VER" -exec egrep -A 1 'Test_Version=|Model-Manufacturer:' {} ';' | sed 's/Model-Manufacturer:^M//g'

This command has not effect. What am I missing here?

A: Give this a try:
sed '/Model-Manufacturer:/s/\r//g'

If you also have newlines and you want to combine the two lines into one, you can use one of the techniques shown in the answers to your previous question.

A: you can remove the carriage returns using dos2unix if you have it. Or using tr
tr -d '\r' < file

A: If you're using Bash as your shell, or creating the script in vi, you should be able to do:
sed -e 's/<Ctrl-V><Ctrl-M>//g'
to remove the CRs.
Ctrl-V (the keystroke on your keyboard) inserts the next keystroke literally, and Ctrl-M is carriage return.


text:
Q: reverse_lazy doesn't add language prefix when using django-localeurl I am using https://github.com/carljm/django-localeurl package to make my site multilingual.
settings.py
LANGUAGE_CODE = 'en'
_ = lambda s: s
LANGUAGES = (
    ('lt', _("Lithuanian")),
    ('en', _("English")),
)

PREFIX_DEFAULT_LOCALE = False

any_other_file.py
from django.utils import translation

def my_view(request):
    translation.activate('en')
    print reverse('some_url_name')   # /my-url/
    translation.activate('lt')
    print reverse('some_url_name')   # /lt/my-lithuanian-url/

    # so far so good
    translation.activate('en')
    redirect(reverse_lazy('some_url_name'))   # redirects to /my-url/
    translation.activate('lt')
    redirect(reverse_lazy('some_url_name'))   # tries to redirect to /my-lithuanian-url/ without /lt/ prefix which results in Http404 error

How can I fix all lazy url reverse functions used in many places in the project?


text:
Q: S.O.L.I.D Essentials missing points? I've read so many articles about this but still I have 2 questions.
Question #1   - Regarding Dependency Inversion :

It states that high-level classes should not depend on low-level
  classes. Both should depend on abstractions. Abstractions should not
  depend on details. Details should depend on abstractions.

for example  :
public class BirthdayCalculator
{
    private readonly List<Birthday> _birthdays;

    public BirthdayCalculator()
    {
        _birthdays = new List<Birthday>();// <----- here is a dependency
    }
...

The fix : put it in a ctor.
public class BirthdayCalculator
{
    private readonly IList<Birthday> _birthdays;

    public BirthdayCalculator(IList<Birthday> birthdays)
    {
        _birthdays = birthdays;
    }

*

*If it will be in ctor - I'll have to send it each and every time I use the class. So I will have to keep it when calling the BirthdayCalculator class. it it ok to do it like that ?

*I can argue that , after the fix , still  - IList<Birthday> _birthdays should not by there ( the Birthday in IList) - but it should be as IList<IBirthday>. Am I right ?
Question #2   - Regarding Liskov Substitution :

derived classes must be substitutable for their base classes

or more accurate :

Let q(x) be a property provable about objects x of type T. Then q(y)
  should be true for objects y of type S where S is a subtype of T.

(already read this )
example  :
public abstract class Account
{
     public abstract void Deposit(double amount);
}

I have a class :
public class CheckingAccount : Account
{
     public override void Deposit(double amount)
    {    ...
        _currentBalance += amount;
    }
}

and the bank wants to open a Mortgage account  - so  :
public class MortgageAccount : Account
{

    public override void Deposit(double amount)
    {
        _currentBalance -= amount; //<-----notice the minus
    }
}

The problem arises when there is a function which accepts mortage as  Account and do deposit.
public class Bank
{
    public void ReceiveMoney(Account account, double amount)
    {
        double oldBalance = account.CurrentBalance;
        account.Deposit(amount); //oopssss?????
    }
}

so here  , it violates the LSP.
But  I don't understand.
every overridden method will do different code when overridden so it will never be 100% replaceable !
the definition did NOT talk about " logic should continue as in base class ( always deposit(add) positive numbers)"
example:
What if both CheckingAccount  class and MortgageAccount  class were depositing positive numbers but MortgageAccount  also log to db ? does it still breaks LSP ? What is the boundry for breaks/not-brakes LSP ?
the definition should define whatis that boundry. and it isn't saying anything about it.
what am i missing ?

A: LSP says that any promises the base class makes, subclasses must also make.  In the Account case, yes, that means Deposit subtracting from a Mortgage's balance is rather messed up.  One workaround for this would be if you consider the balance to be the difference between the amount the customer owes you and how much you owe him.  (I'm about 54% sure that's the original meaning of "balance" anyway.)  A positive balance might mean the customer has money, while a negative one might mean he owes money.  If you can't resolve it so that you can treat the two accounts similarly, then they should not be related -- or at least, the "Deposit" method should not be defined on the base class.
As far as DIP, what it doesn't really mention is that it's not meant to apply to every line of code.  Eventually you have to have a concrete class somewhere.  The point is to limit reliance on the specifics of those concrete classes to sections of code that absolutely have to know about them, and keeping the number and size of those sections as small as possible.  That means using as generic an interface as you can get away with, as much as you can.  For example, if you don't need all the guarantees that List makes (order of enumeration, presence of duplicates, nulls, etc), then you might declare _birthdays as an IEnumerable instead.  If the constructor is the only thing that knows that your IEnumerable is actually a List, then you're more-or-less adhering to the principle.
(Be warned, though: this doesn't mean you can adhere to DIP by simply declaring everything as an Object and downcasting as needed.  Downcasting itself could be considered a violation of DIP, as you're no longer relying on the interface you've been provided; you're trying to get a more specific one.)

A:
If it will be in ctor - I'll have to send it each and every time I use the class. So I will have to keep it when calling the BirthdayCalculator class. it it ok to do it like that?

I would retrieve the list of birthday's once, make one BirthdayCalculator, and pass that around.  You should only need to instantiate a new BirthdayCalculator if your list of birthdays change, or if it maintains state somehow.

I can argue that , after the fix , still - IList<Birthday> _birthdays should not by there ( the Birthday in IList) - but it should be as IList<IBirthday>. Am I right ?

This depends.  Is Birthday just a data object?  Is there any logic contained within it?  If it is just a bunch of properties / fields, then an interface is overkill.
If Birthday does have logic, then I would go with IEnumerable<IBirthday>.  List<Birthday> is not assignable to IList<IBirthday>, so you could have issues there.  If you don't need to manipulate it, stick with IEnumerable.

Regarding your second question, the only thing I have a problem with is your naming convention.  You don't make deposits to a Mortage.  I think if you were to rename that method it might make more sense.
Also, a checking account and a mortage account are two very different animals.  One is a deposit account, where as the other is a loan.  I would be very careful with trying to use them interchangeably.
Edit
Others have noted that you could make _currentBalance in MortageAccount a negative value, then add to it.  If that is easier for you to understand, then go for it.  However, the internals of how a MortageAccount handles its balance is not important, so long as GetBalance or whatever method you use the check / display it, handles it properly.

A: #1

*

*Yes, you will have to call that every time you create the object.  This is where Factories and Inversion of Control frameworks comes in handy, to remove all the plumbing you'd have to do.

*Yes, you should be using an IBirthday interface.
#2
Your logic is flawed here.  When you deposit money into an account you're adding money to it.  The mortgage account doesn't have money in the account (a positive balance), and you're not removing money from it by depositing.  The mortgage account has a negative balance, and depositing into the account lowers the balance (adding to a negative balance).

A: Regarding LSP:
As I see it, LSP is mostly about (public) contract of a hierarchy.
You have an account (object), you can credit/debit money to it (contract).
For mortgage account Credit will result in subtraction and Debit will result in addition.
For checking account it's the other way around.
The important thing is that given an account you can always ask it to do credit/debit actions and that all subclasses of an account object will support those operations.

A: Dependency Inversion:

If it will be in ctor - I'll have to send it each and every time I use the class. So I will have to keep it when calling the BirthdayCalculator class. it it ok to do it like that ?

You need it not when using the object but when constructing the BirthdayCalendar object. Moving the IList<Birthday> to the construction interface ensures that all the dependencies of BirthdayCalendar are same as the dependencies of the caller (i.e., no new ones), and that's what we're trying to achieve.

I can argue that , after the fix , still - IList<Birthday> _birthdays should not by there ( the Birthday in IList) - but it should be as IList<IBirthday>. Am I right ?

That's not related directly to the dependency inversion principle. You have offloaded the dependency to the caller and now you're asking about the details of this dependency. It might be a good idea to use IBirthday to access the internals of you list instead of Birthday, but that a question of your interfaces, unrelated to the dependency inversion.

every overridden method will do different code when overridden so it will never be 100% replaceable !
  the definition did NOT talk about " logic should continue as in base class ( always deposit(add) positive numbers)"
example:
  What if both CheckingAccount class and MortgageAccount class were depositing positive numbers but MortgageAccount also log to db ? does it still breaks LSP ? What is the boundry for breaks/not-brakes LSP ?
  the definition should define whatis that boundry. and it isn't saying anything about it.

Liskov Substitution Principle is applicable to base class vs. derived class relation.
Your example deals with 2 classes inheriting from a shared base, so your relation is derived class1 vs. derived class2. This is the exact opposite of what LSP is talking about, exactly for the reasons you mentioned - the logic is different in both derived classes. LSP is a measure for validity of the inheritance that you defined. If you can answer positively to the question is my derived class object can be used transparently everywhere my base class object is used?, you're not breaking the LSP. Otherwise, you are breaking it.

A: With regard to the first point, it's fine to use a specific low-level class as a private implementation detail of the other class; the code might be more SOLID if one were to say IList<Birthday> _birthdays = new List<Birthday>; but performance would probably be slightly better with List<Birthday> _birthdays = new List<Birthday>.  If you want to use IBirthday rather than Birthday, that's fine too, if you use the IBirthday every time you would be inclined to use Birthday except when invoking constructors or static methods.  Note that you'll need to be consistent in whether you use Birthday vs IBirthday, and List<T> vs IList<T>.
Note that private members need not adhere to the same rules as public members.  If a type were to accept a parameter of type List<T>, that would force outside code to use that type.  Switching from List<T> to IList<T> would likely require making many changes in many different assemblies, and make old versions of assemblies incompatible with new ones.  By contrast, if a class has a private member of type List<T> which is never shared with outside code, the effects of changing it to use IList<T> would be confined to within the class itself, and would have no effect upon consumers of that class.


text:
Q: Search all database with varchar and INT fields with wildcard mysql query Trying to get a wildcard search to pick up on any text in org_name field and also to pick up any INT fields that have a 1 in them are entered into the form,
e,g If someone types Childminder in the form I want all records with the childminder INT field with a 1 in it to show up on the results...
$sql_result= "SELECT * FROM table WHERE org_name LIKE '%" . $org_name . "%'

OR carer LIKE '1'
OR childminder LIKE '1' ";

A: Not sure why you would do such things, but sounds like a candidate to the manual query concatenation (hint: don't do this, it hurts). PDO does not support binding column names, so you're out of luck if you're trying to have any help from libraries / other estabilished solutions.
Update
If your schema does not change and you're concerned about SQLi, you could have some matching mechanism that would take search query and array of available ("matchable") columns and process them, reporting matching columns. Then you would just make query from the safe data. Sample code:
$columns = array(/* ... */);
$query = '/* ... */';
$matches = array();
foreach($columns as $column)
    {
    if(preg_match('/'.$column.'/', $query))
        {
        $matches[] = $column;
        }
    }

$sqlQuery = 'you select';
foreach($matches as $match)
    {
    $sqlQuery .= ' OR '.$match.' = 1';
    }

Not exact code, but you should get the idea.


text:
Q: jquery error - could not find what is wrong Firebug console says

phone is not defined

var dataString = 'name=' + name + '&phone=' + phone + '&email=' + email ;

error in this line
var dataString = 'name=' + name + '&phone=' + phone + '&email=' + email ;

If i swap phone with email then it shows email not defined, but i have input tag for all those fields.
What am I doing wrong?

A:
but i have input tag for all those
  fields.

name, phone and email have to JS variable and not just input tags. Make sure all of them are JS variables and in scope.

A: Try this
in jQuery
var name = $("#name");;
var phone = $("#phone");
var email = $("#email");

var dataString = 'name=' + name + '&phone=' + phone + '&email=' + email ;

Plain Old JavaScript
var name = document.getElementById("name");;
var phone = document.getElementById("phone");
var email = document.getElementById("email");

var dataString = 'name=' + name + '&phone=' + phone + '&email=' + email ;

And Please make sure your input types haves the ids name,phone and email
P.S : Just having input types wont have them magically associate themselves with variables with the same name in js