XmlSerializer extraTypes memory leak

Question: I'm developing some application, wich calls lot of XmlSerializer constructor with  extraTypes parametr. I've find out, that each call encrease application memory for  about 100KB and 2 descriptors (sometimes  more).
Code example:
this code encrease application memory for 100KB and 2 handlers per each call
while (true)
            {
                Console.ReadLine();
                new XmlSerializer(typeof (object), new Type[] {});
            }

this code encrease application memory for 43024KB and 2004 handlers
 for (var i = 0; i < 1000; i++)
            {
                new XmlSerializer(typeof (object), new Type[] {});
            }

so just siplest example of console application:
internal class Program
    {
        private static void Main(string[] args)
        {
            //this code encrease application memory for 43024KB and 2004 handlers
            for (var i = 0; i < 1000; i++)
            {
                new XmlSerializer(typeof (object), new Type[] {});
            }
            Console.WriteLine("Finished. Press any key to continue...");

            Console.ReadLine();
        }
    }

Is it a bug in XmlSerializer or im doing something wrong?
P.s. same with optimize code on and Release build
Comment: Duplicate of [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer)
Answer: Ok, there is already an answer on msdn https://blogs.msdn.microsoft.com/tess/2006/02/15/net-memory-leak-xmlserializing-your-way-to-a-memory-leak/
Shot answer is: no, it is not a bug, it is a feature ;)
XmlSerializer creates a TempAssembly per each call of constructor with extraTypes parametr. And "an assembly is not an object on the GC Heap, the GC is really unaware of assemblies, so it won't get garbage collected"
Solution is to cache XmlSerializer's in some dictionary and use only one object per type instead of creating new XmlSerializer each time u need it
Comment: Yep, another approach for you is to process your code in new AppDomain and unload appDomain after processing. Thus you'll get rid of this temp assemblies.
Just debugged XmlSerializer and saw exactly what you've said in your answer, nice question

XmlSerializer extraTypes memory leak


How can I make it so my web page displays a "wait" type of cursor when I have an array with a length > 0?

Question: When my application loads or fetches data I add an entry to an array called "loading"
I then have the following that displays in my status bar:
|

It shows a vertical bar for every item loading.
Is there a way that I could also change my cursor so that when there's some loading
activity (when loading.length > 0) then the cursor changes to :
cursor:wait;

Answer: If you are using ui.router, you can use the $stateChangeStart, $stateChangeSuccess and $stateChangeError to trigger when and when not to show the loading cursor. If you are using routes, simply use $routeChangeStart, $routeChangeSuccess and $routeChangeError in replacement.
//loading controls
document.body.style.cursor='default';

$scope.$on('$stateChangeStart', function() {
  document.body.style.cursor='wait';
});
$scope.$on('$stateChangeSuccess', function() {
  document.body.style.cursor='default';
});
$scope.$on('$stateChangeError', function() {
  document.body.style.cursor='default';
});

You can also use these state changes to trigger a loading icon.
//loading controls
$scope.isViewLoading = false;
document.body.style.cursor='default';
$scope.$on('$stateChangeStart', function() {
  $scope.isViewLoading = true;
  document.body.style.cursor='wait';
});
$scope.$on('$stateChangeSuccess', function() {
  $scope.isViewLoading = false;
  document.body.style.cursor='default';
});
$scope.$on('$stateChangeError', function() {
  $scope.isViewLoading = false;
  document.body.style.cursor='default';
});

Loading...

Answer: You can use ng-style or ng-class
For example, create custom style:
$scope.state = 'wait';

$scope.mySyle = {
  'cursor': state
}

Now, we can change our $scope.state during the time and out style will change respectively.
For ng-class - the same thing, just create style into css file and switch ng-class value.
Here is a references:

ng-class - use when the set of CSS styles is static/known ahead of time
ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.

(took from THIS POST)


Call to undefined function register_custom_styles()

Question: I have been trying to add a custom css file based on a condition. That's why I wanted to register that css file. But getting fatal error saying
Fatal error: Call to undefined function register_custom_styles() in /home/learnenglish/public_html/wp-content/themes/learn/functions.php on line 899
Here is the code in the below:
if ( is_user_logged_in() ) {
    if (!register_custom_styles()) {
        add_action( 'wp_enqueue_scripts', 'register_custom_styles' );
        function register_plugin_styles() {
            wp_register_style( 'custom', get_stylesheet_directory_uri( '/custom.css' ) );
            wp_enqueue_style( 'custom' );
        }
    }

}

Comment: @developerme He mentioned in his question that where he write this function check this line.
/home/learnenglish/public_html/wp-content/themes/learn/functions.php on line 899
Answer: Just try This
if ( is_user_logged_in() ) {
    add_action( 'wp_enqueue_scripts', 'register_custom_styles' );
}

function register_custom_styles() {
    wp_register_style( 'custom', get_stylesheet_directory_uri('/custom.css' ) );
    wp_enqueue_style( 'custom' );
}

Comment: You are calling `register_custom_styles`, but you created function `register_plugin_styles`. Your answer is wrong.
Answer: The problem is, the function you are calling is not defined, and which one you've defined is with another function name
    if ( is_user_logged_in() ) {
        if (!register_custom_styles()) {
            add_action( 'wp_enqueue_scripts', 'register_custom_styles' );
            function register_custom_styles() { // change here to register_custom_styles
                wp_register_style( 'custom', get_stylesheet_directory_uri( '/custom.css' ) );
                wp_enqueue_style( 'custom' );
            }
        }
}

change the function name and it will work
Answer: Please try This function. the function register_custom_styles you are calling is not defined, and which one you've defined is with another function name.
 if ( is_user_logged_in() ) {
        if (!register_plugin_styles()) {
            add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );
            function register_plugin_styles() {
                wp_register_style( 'custom', get_stylesheet_directory_uri( '/custom.css' ) );
                wp_enqueue_style( 'custom' );
            }
        }

}

Comment: You are calling `register_custom_styles`, but you created function `register_plugin_styles`. Your answer is wrong.
Comment: Sorry That is my mistake!!


Need help to understand the following number theory proof

Question: Prove that there exist infinitely many integers n such that $n, n + 1, n + 2$ are each the sum of the squares of two integers:
Solution: First solution: Let a be an even integer such that $a^2 + 1$ is not prime. (For example, choose a ≡ 2 (mod 5), so that $a^2 + 1$ is divisible by 5.) Then we can write $a^2 + 1$ as a difference of squares $x^2 − b^2$, by factoring $a^2 + 1$ as rs with $r ≥ s > 1$, and setting x = (r + s)/2, b = (r − s)/2. Finally, put n = $x^2 − 1$, so that $n = a^2 + b^2$, $n + 1 = x^2$, n + 2 = $x^2 + 1$
I got lost in the following part:
Then we can write $a^2 + 1$ as a difference of squares $x^2 − b^2$, by factoring $a^2 + 1$ as rs with $r ≥ s > 1$. What is rs?. Can someone expand this proof, so it looks clearer?
Comment: That's a somewhat weird proof $a^2 + 1$ *can* be prime by setting $s=1$ and $r=a^2 + 1$.  And we can either have $a^2 +1$ be odd or $a^2 + 1$ be divisible by $8$  we just need $a^2 +1 = r*s = (\frac {r+s}2 + [r-\frac{r+s}2])([\frac{r+s}2 - s]-\frac{r+s}2)$ so that $r$ and $s$ are both even or both odd.
Comment: This problem has already been addressed there. Do not ask repeated questions.   https://math.stackexchange.com/questions/2170494/infinitely-many-n-such-that-n-n1-n2-are-each-the-sum-of-two-perfect-squa
Answer: If $a^2 +1$ is not prime, then it can be written as a product:
$$a^2 + 1 = rs,$$ where $r \geq s \gt 1$.
$r$ and $s$ are simply these factors here.
Comment: how can you expand this further by explaining  why we can do the next setting?
Comment: Well, I hope you agree that we *can* define $x$ in the way that you have written in your question, and also $b$. I will leave it to you to work out why $x$ and $b$ are integers (this is important; if they weren't integers then you'd be stuffed). You can then define the integer $n$ in the way in which you have written, giving you the desired trio $n, n+1, n+2$, completing the proof. It's an elegant proof - particularly because proofs like this are (in my purely undergraduate experience) often done by contradiction, and this isn't.
Comment: Maybe $x=\frac{r+s}{2}, b=\frac{r-s}{2}$ is the key here?
Comment: It's certainly a key part of the proof, although (without trying to sound condescending) I currently am not seeing what is difficult to understand about defining $x$ and $b$ like this.
Comment: There is another confusing part so $a \equiv 2 mod 5$, but if we choose a = 2 then $a^2+1$ is prime.
Comment: @ElChavoDelOcho You need to show that you have infinitely many choices of $a$; just take $a\equiv2\pmod{5}$ with $a>2$.
Comment: That part is showing to you that there are infinite choices of even $a$ such that $a^2 + 1$ is not prime.
Comment: @MattS , if you don't understand what's confusing about it, then you might not be the best person to answer the question... I find I can help people much better when I "get" where they're stuck.
Comment: @GTonyJacobs This is true. If I had initially thought that was the problem, I wouldn't have answered. The question as posed asked about $r$ and $s$, which was something I did think I understood.
Comment: Looking more closely at the proof, how is it clear that $x$ and $b$ are integers? Must $r$ and $s$ have the same parity?
Comment: I believe $r$ and $s$ must both be odd, as $a^2 +1$ is odd.
Comment: If $a^2 + 1$ is odd then $r$ and $s$ are both odd.  However the proof would work just as well if $r$ and $s$ are both even i.e.  $a^2 + 1$ is divisible by $8$.
Comment: And the proof will also work if $s =1 $ and $r = a^2 + 1$.  So $a^2 +1$ *could be prime.  Letting $a^2 + 1 = 17$ you get $80 = 8^2 + 4^2$ and $81 = 9^2 + 0^2$ and $82 = 9^2 + 1^2$.
Comment: Ah. I didn't see the part where $a$ is even.
Answer: Just follow the instructions:

Pick some even $a$ such that $a^2+1$ is not a prime, for instance some $a\equiv 2\pmod{5}$.
Fine, let us pick $a=22$;
Write $a^2+1$ as $r\cdot s$ with $r\geq s >1$.
Fine, $22^2+1 = 97\cdot 5$;
Write $a^2+1$ as a difference of squares through the previous decomposition.
Fine, $22^2+1 = (51+46)(51-46) = 51^2-46^2$.

This gives that $51^2-1$ is the sum of two squares, $22^2+46^2$, so $51^2-1,51^2$ and $51^2+1^2$ are three consecutive numbers belonging to $\square+\square$. Is it a bit clearer now?
Comment: sorry I am so slow. Why does your math process entail that $51^2 - 1$ is the sum of two squares?
Comment: @ElChavoDelOcho: consider $$22^2+1 = 51^2-46^2$$ and add $46^2-1$ to both sides.
Comment: where are you using this 'setting x = (r + s)/2, b = (r − s)/2'?
Comment: @ElChavoDelOcho: $51=\frac{97+5}{2},\;46=\frac{97-5}{2}$.
Comment: x = (r + s)/2, b = (r − s)/2.  . How do we know x and b  are integers?
Comment: @ElChavoDelOcho: $a$ is even, hence $a^2+1$ is odd and both $r$ and $s$ are odd, so both $r-s$ and $r+s$ are even.
Comment: 7 is not even and $7 \equiv 2 mod 5$
Comment: @ElChavoDelOcho: so? The instructions tell to consider some $a$ which is even and $\equiv 2\pmod{5}$.
Comment: got it. I wonder how the author of this proof was able to come up with this solution.
Comment: @ElChavoDelOcho: they idea "unrolled": if we manage to construct $N$ such that $N^2-1$ is the sum of two squares we are done, since $N^2-1,N^2,N^2+1$ provide a solution. On the other hand it is not difficult to find solutions to $N^2-1=A^2+B^2$, since it is equivalent to $A^2+1 = (N-B)(N+B)$.
Answer: Let  $a^2 + 1$ be odd and $a^2 + 1$ not be prime.  The proof glibly assumes such numbers are easy to find by pointing out any $2 + 5k$ will be such a number.
Since $a^2 + 1$ is not prime nor then $a^2 + 1 = r*s$ for some odd $r, s$ and $s \le r$.
Let $x$ be the midpoint between $s$ and $r$.  (In other words $\frac {r+s}2$).  This midpoint is an integer because $r$ and $s$ are both odd.
Let $b = x-s = r-s$.  This means $r = x+b$ and $s= x-b$.  That's not surprising as $x$ is the midpoint and $b$ is the distance each is from the midpoint.
Consider the three consecutive numbers $n = x^2 -1$, $n+1 = x^2$ and $n + 2 = ^2 + 1$.
Obviously $n+1 = x^2 + 0^2$ is the sum of two squares. And so $n+2=x^2 + 1^2$.
But $n$ is as well because:
$a^2 + b^2 = (a^2 + 1) + b^2 - 1$
$= r*s + b^2 -1= (x+b)(x-b) + b^2 - 1$
$= x^2 -b^2 + b^2 -1 = x^2 - 1 = n$
So $n$ is the sum of $a^2+ b^2$.


How do I alter a view query to use "OR"?

Question: The following is the content of the $query object that is passed to a view.

[where] => Array(
  [0] => Array(
    [clauses] => Array(
      [0] => node.type in ('%s')
      [1] => node.status  0
      [2] => node.promote  0
      [3] => node.sticky  0
    )
    [args] => Array(
      [0] => test
    )
    [type] => AND
  )
)
[having] => Array()
[group_operator] => AND

I want to override it by using hook_views_query_alter(). The default operators are all AND, but I want to get the following query

[0] => node.type in ('%s') AND
[1] => node.status  0 AND
[2] => node.promote  0  OR
[3] => node.sticky  0

How do I make the last operator to use "OR"?
db_query("SELECT content_id, count(*) AS cnt FROM {votingapi_vote} WHERE value =1 AND value_type = '%s'" , "option");

How do I use the query in hook_views_query_alter()?
Comment: Related/duplicate: [Alter a Views query to use "OR"](http://drupal.stackexchange.com/questions/3868/alter-a-views-query-to-use-or).
Comment: You should specify how you want the query. WHERE (x AND y) OR z Is not the same as WHERE x AND (y OR z)
Answer: This is untested, but I think what you want to do within your alter function is along the lines of this:
function mymodule_views_query_alter(&$query) {
  unset($query->where[0]['clauses'][2]);
  unset($query->where[0]['clauses'][3]);

  $query->where[1] = array(
    'clauses' => array(
      0 => 'node.promote <> 0',
      1 => 'node.sticky <> 0',
    ),
    'type' => 'OR',
  );
}

This is essentially moving the promote and sticky clauses into a new where grouping, and by setting the type to 'OR', it should work the way you outline in your question.
Comment: i am sorry. the code can't work/ $query is an object.
Comment: i altered $query['where'] to $query->where, it still can't work.
Comment: unset($query['where'][0]['clauses'][2]);
  unset($query['where'][0]['clauses'][3]);
those lines can work.
Comment: I updated the answer to make $query an object. Like I said, untested code :)
Comment: the code still can't work. it can execute  unset($query->where[0]['clauses'][2]);
  unset($query->where[0]['clauses'][3]);
those lines/
Answer: I think you can use db_or, for example if you are creating a new where clause you can use something like this
function mymodule_views_query_alter(&$query) {
  if ('name' == $view->name && 'page' == $view->current_display) {
    $or = db_or()
    ->condition('table.column', $value, 'NOT IN')
    ->condition('table.column', $value, 'NOT IN');
    $query->add_where(1,$or);
  }
}

For your problem you may need to use foreach and find the exact case to use db_or
Answer: I realize this is old but I thought I'd answer it for anyone who needs it.
Views 7.x-3.x. does this through the UI. You simply add the filters and then through the filter UI, you can order the filters and add additional groups of filters that you can arrange in AND or OR relationships.
In this case I would add a second group in an AND relationship with the first group but with an OR relationship with the contents of the group, which would consist of: node.promote <> 0 OR node.sticky <> 0.


How to correct javascript button's redirect?

Question: I'am trying to add some js to my page, I create from it's a button and the aim of creating it is to redirect to another page but it is not working. Can you help me to solve it?
The situation is: the button is visible on my front-end (.jsp in Java EE), but there is no redirect. No matter what I write in URL simply no action is being made form click.
    buttonAbort.innerHTML = 'Anuluj';
    buttonAbort.style.cssFloat = 'left';
    buttonAbort.style.width = '70px';
    buttonAbort.style.height = '30px';
    buttonAbort.style.backgroundColor = 'red';
    button.setAttribute("id","buttonAbort");

    let buttonAbortById = document.getElementById("buttonAbort");
    buttonAbortById.onclick = function href() {
        location.href="/projekt/edytujStatus";
    }

Comment: Where are you appending the button to the page?
Answer: You most likely have a mistake in your code.
You probably want to do
buttonAbort.setAttribute("id","buttonAbort");

instead of
button.setAttribute("id","buttonAbort");

Comment: I would add that I see no reason to assign the id to button (`buttonAbort.setAttribute("id","buttonAbort")`) and then to find the button by id (`let buttonAbortById = document.getElementById("buttonAbort")`) at all. IMHO, `buttonAbort.onclick = …` would be enough.


Generating thumb nail image of a web page in a link

Question: I want to generate a preview thumbnail image of a web page using the link for the page. How can i do this? I'm comfortable with C#.NET, Javascript/JQuery.
Regards
NLV
Answer: Place an Image control in you webpage and set the ImageUrl to the snapshot.aspx page. NOw you can set some querystring options for the page.
snapshot.aspx?site=www.google.come&width=100&height=80&capWidth=800&capHeight=600
<code>site    This tells the page which site to capture
width   width of the thumnail
height  height of the thumbnail
capWidth    What Width should the Site capture be (the thumbnail is based on this size)
capHeight   What Height should the Site capture be.
</code>
And here is the code
<code>    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Windows.Forms;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Threading;

public partial class snapshot : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = ((string.IsNullOrEmpty(Request.Params["site"])) ? "www.google.com":Request.Params["site"]);
        int width = ((string.IsNullOrEmpty(Request.Params["width"])) ? 200 : int.Parse(Request.Params["width"]));
        int height = ((string.IsNullOrEmpty(Request.Params["height"])) ? 140 : int.Parse(Request.Params["height"]));
        int capWidth = ((string.IsNullOrEmpty(Request.Params["capWidth"])) ? 800 : int.Parse(Request.Params["capWidth"]));
        int capHeight = ((string.IsNullOrEmpty(Request.Params["capHeight"])) ? 600 : int.Parse(Request.Params["capHeight"]));

        string address = "http://" + url;
        Bitmap thumbnail = WebsiteThumbnailImageGenerator.GetWebSiteThumbnail(address, capWidth, capHeight, width, height);

        Response.ContentType = "image/jpeg";
        thumbnail.Save (Response.OutputStream, ImageFormat.Jpeg);
    }
}

public class WebsiteThumbnailImageGenerator
{
    public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
    {
        WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
        return thumbnailGenerator.GenerateWebSiteThumbnailImage();
    }

    private class WebsiteThumbnailImage
    {
        public WebsiteThumbnailImage(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
        {
            this.m_Url = Url;
            this.m_BrowserWidth = BrowserWidth;
            this.m_BrowserHeight = BrowserHeight;
            this.m_ThumbnailHeight = ThumbnailHeight;
            this.m_ThumbnailWidth = ThumbnailWidth;
        }

        private string m_Url = null;
        public string Url
        {
            get
            {
                return m_Url;
            }
            set
            {
                m_Url = value;
            }
        }

        private Bitmap m_Bitmap = null;
        public Bitmap ThumbnailImage
        {
            get
            {
                return m_Bitmap;
            }
        }

        private int m_ThumbnailWidth;
        public int ThumbnailWidth
        {
            get
            {
                return m_ThumbnailWidth;
            }
            set
            {
                m_ThumbnailWidth = value;
            }
        }

        private int m_ThumbnailHeight;
        public int ThumbnailHeight
        {
            get
            {
                return m_ThumbnailHeight;
            }
            set
            {
                m_ThumbnailHeight = value;
            }
        }

        private int m_BrowserWidth;
        public int BrowserWidth
        {
            get
            {
                return m_BrowserWidth;
            }
            set
            {
                m_BrowserWidth = value;
            }
        }

        private int m_BrowserHeight;
        public int BrowserHeight
        {
            get
            {
                return m_BrowserHeight;
            }
            set
            {
                m_BrowserHeight = value;
            }
        }

        public Bitmap GenerateWebSiteThumbnailImage()
        {
            Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();
            m_thread.Join();
            return m_Bitmap;
        }

        private void _GenerateWebSiteThumbnailImage()
        {
            WebBrowser m_WebBrowser = new WebBrowser();
            m_WebBrowser.ScrollBarsEnabled = false;
            m_WebBrowser.Navigate(m_Url);
            m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();
            m_WebBrowser.Dispose();
        }

        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser m_WebBrowser = (WebBrowser)sender;
            m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
        }
    }
}
</code>
Comment: I dont want to use any third party tool.
Answer: You can also simply use one of 1000 webservices availible:
http://www.websnapr.com/
http://www.thumbalizr.com/
http://snapcasa.com/
http://thumbnails.iwebtool.com/
http://www.artviper.com/tools.php#thumbnails
Comment: these are mainly php arent they? he wasnt like a .net module so he can hook it up to his sql i think
Comment: also js only things... generated by the service itself. but no thirdparty things wanted, so ... useless ;)


Confusion on the definitions of product topology

Question: All the books I have read so far defined the product topology $\tau$ on the finite Cartesian product of spaces $(X_i, \tau_i)_{i \le n}$ for some $n \in \mathbb{N}$ by the topology generated by the basis
$$
B = \{\prod_{i \le n} U_i ~|~ \forall i \le n: U_i \in \tau_i\}
$$
(Is the generated topology called the box topology?)
But I recently encountered a weird definition on ProofWiki, where the topology is defined by using the canonical projection maps:
$$
\tau
=
\{ \pi_i^{-1}[U] ~|~ i \le n,~ U \in \tau_i\}
$$
to make the preimages of open subsets of each space also open in the product space.
But in my knowledge, the preimage of $U$ under $\pi_i : \prod_k X_k \to X_i$ is
$$
X_1 \times \cdots \times X_{i-1} \times U \times X_{i+1} \times \cdots \times X_n
$$
that looks like a cylinder.
I doubt this is even a topology because the intersection of any two preimages from different $i$'s does not belong to $\tau$.
The only way I can relate $\tau$ with a topology is taking it as a subbasis for the Cartesian product $\prod_k X_k$.
Is there something I am missing here? Is $\tau$ indeed a topology as in the ProofWiki definition?
Comment: And, yes, the second definition is the general one, and yields a subbasis of the product topology. The point being that the product topology is the coarsest one that makes all projection continuous.
Comment: on finite product, box topology and product topology coincides...
Comment: If you are referring to the ProofWiki definition (if not, please clarify), it looks correct to me. They define the product topology as the **initial topology**  in which those preimages are open - that is to say, the coarsest (set-theoretic smallest) topology in which those preimages are open.
Comment: @AndreasCaranti Thank you for the comment. Then, isn't it wrong to say the set is a product topology?
Comment: The product topology is the topology with the fewest open sets that makes every projection continuous. In other words it's the category-theoretic product.
Comment: @AndreasCaranti Yes, I understood. But I am saying that we have to find the coarsest topology containing $\tau$, and $\tau$ itself in the post is not a topology.
Comment: As you correctly stated, it is a subbase for the product topology. A base will be provided, as usual, by the finite intersections of the members of the subbase.
Comment: ProofWiki does not claim that that collection is a topology.
Comment: @AndreasCaranti I think I got it now. Thank you for the clarification!
Answer: If we have a countable family of spaces $(X_i, \tau_i), i \in \Bbb N$ then the ProofWiki definition is a special case of the general product (for any number of spaces). There we consider all projections $\pi_i: X \to X_i$, where $X = \prod_{i \in \Bbb N} X_i$ (as a set), and define the product topology $\tau_p$ to be the smallest topology on $X$ such that all $\pi_i$ become continuous. Basic facts:

Sets of the form $\pi_i^{-1}[U_i]$, where $i \in \Bbb N$ and $U_i \in \tau_i$, together form a subbase for $\tau_p$.
It follows that the standard base (from that subbase) consists of all sets of the form $$\pi_{i_1}^{-1}[U_{i_1}] \cap \ldots \cap \pi_{i_m}^{-1}[U_{i_m}]$$ where $\{i_1, \ldots, i_m\} \subseteq \Bbb N$ is finite.
That set thus looks like (for the $\Bbb N$_case): $$X_1 \times \ldots \times U_{i_1} \times \ldots \times U_{i_2} \times \ldots \times U_{i_m} \times X_{{i_m}+1} \times \ldots$$ where all intermediate factors (not equal to some $U_{i_j}$) just are all full spaces $X_j$ for the right indices. Quite messy notation, but that's what the intersection means: finitely many coordinates are constrained (in that the points $(p_n)_n$ in the product must have $p_{i_j} \in U_{i_j}$ for a finite set of indices and corresponding open sets) and the others are free to choose in the correct factor space.

But when the index set is $\Bbb N$ and we have such a finite set of indices, we can just take that finite set to be $\{1, \ldots, k\}$ for some finite $k$ and we can just take it to be of the easier form
$$U_1 \times U_2 \times \ldots U_k \times X_{k+1} \times X_{k+2} \times \ldots$$ provided we allow for $U_i = X_i$ sometimes; then we can make all basic open subsets in this shape (cilinder sets) and then we're back at the OP's form of basic open sets. The OP's form is just a spacial case of the ProofWiki form and all ProofWiki's forms can be written as the OP's type. So they define exactly the same base and the same topology, even though they may look different at first sight....
Comment: Thank you for the elaborated answer! 1) It seems you expanded the discussion to countably infinite-dimensional product spaces and stated that the Cartesian products of a finite collection of non-entire open sets form a subbasis. 2) And $\tau_p$ is the smallest one in the sense that we can generate a topology taking it as a subbasis. Is this understanding correct?
Comment: @Hermis14 In *any* product the set of "boxes" $\prod_{i \in I} U_i$, where only at most finitely many $i$ are not $X_i$, is a basis for its topology. The subbasis are the ones where exactly *one* is not $X_i$, and these are of the form $\pi_i^{-1}[U_i]$. And finally the smallest topology containing a collection is precisely the topology that has that collection as a subbasis.


How can I display a confirmation message after someone subscribes via simplenews?

Question: I want to show a message after users submit their email in Simplenews block.
Currently when the user clicks on the subscribe button, the page is refreshed and no message shows ups.
Instead, I prefer to show a message with javascript in modal or something.
Any help/suggestions?
Answer: Consider using the Rules module to implement this. And enable the Simplenews rules module (a sub-module of Simplenews).
Then create a rule like so:

Event: "A user has been subscribed".
Action: "Show a message on the site" (located within "System").
Comment: Thanks for your answer, is there any response or event that i can show the message in  custom modal(custom javascript)
Comment: i created what you said above and save the rule . but when anonymous user subscribe nothing happen


IIS 7 on Windows 2008 Server R2 - won't start and can't remove

Question: I stopped IIS7 via the IIS Manager, and now can't restart it! I get the "Cannot start service W3SVC on computer '.'" message. Following that up, I went to try to remove IIS and reinstall.... but when I get to the Windows Features list, IIS is not listed to either Remove OR Add!
Still shows up in IIS manager, but I can't start it.
Anyone got any useful ideas/clues?
Comment: First step for troubleshooting *anything* on Windows Server is to poke around in the Event Log. Something in there will hopefully give you far more information about what's going on when you try to start it.
Comment: yeah - in this case, sadly, it's not really telling me anything beyond that the service couldn't start and that the originator was Microsoft-Windows-WAS. I have found the new location for uninstalling IIS (it's under Roles not Features in Server manager!), so goign to go with that
Answer: In the end, reinstalled, repaired .Net framework and created the c:\inetpub\temp\appPools folder (which was missing). MSDN Article


adjustment of lift measure

Question: Lift is a measure widely used in many domains. However, it is known to have a problem for infrequent counts. What are the solutions for this type of problem?
In frequent pattern mining hyper-lift was suggested by Hahsler and Hornik (http://arxiv.org/pdf/0803.0966v1.pdf), but after some search it seems, it is either not used in other domains (or it is just used under other names). Moreover, it is almost the only article that discusses it (apart from R package arules).
What is the reason? Is this measure reliable?
What is a common used adjustment of the lift that is not affected by the problem of infrequency (becomes too volatile for smaller counts)?
Answer: Lift is a measure of correlation in a 2x2 contingency table. It tries to asses how much the occurrence of one item "lifts" the other. Given item A and B:
$$
Lift = \frac{P(A\cup B)}{P(A)P(B)} = \frac{confidence(A\rightarrow B)}{support(B)}
$$
As mentioned, Lift can have problems. One problem is if the counts are imbalanced. In Han, Kamber, Pei (2012), they describe 3 other metrics to be considered in pattern matching:
$$
\begin{align}
allConfidence(A,B) &= min \big\{P(A|B), P(B|A)\big\} = \frac{support(A\cup  B)}{max\big\{support(A), support(B)\big\}}\\
maxConfidence(A,B) &= max \big\{P(A|B), P(B|A)\big\}\\
Kulczynski(A,B) &= \frac{1}{2}\big(P(A|B) + P(B|A) \big)\\
\end{align}
$$
They all range from [0, 1] where positive association is 1, negative association is 0, and neutral association is 0.5. Here is a positive association example.
<code>          A    not A       lift   allConf    maxConf    Kulc.
B      10000    1000       9.26      0.91      0.91     0.91
not B   1000  100000
</code>
Here is a negative association example.
<code>          A    not A       lift   allConf    maxConf    Kulc.
B        100    1000       8.44      0.09      0.09     0.09
not B   1000  100000
</code>
Here is a neutral association example.
<code>          A    not A       lift   allConf    maxConf    Kulc.
B       1000    1000       5.75       0.5        0.5     0.5
not B   1000  100000
</code>
The three new metrics perform well under the unbalanced data sets. They differ in some other data sets. One example is:
<code>          A    not A       lift   allConf    maxConf    Kulc.
B       1000     100       9.18      0.09      0.91      0.5
not B  10000  100000
</code>
From one point of view, only $\frac{AB}{AB + A\bar{B}}=\frac{1000}{1000+10000}=9.09\%$ of A transactions contain B transactions, indicating negative assocation. Conversely, $\frac{AB}{AB +\bar{A}B}=\frac{1000}{1000+100}=90.9\%$ of B transactions contain A transactions, indicating a postive assocation. So depending on your needs in this situation, one of these three metrics should cover it.
The reference for this post is Section 6.3 of the text Data Mining, Concepts and Techniques 3rd ed. by Han, Kamber, Pei.

adjustment of lift measure


How to practice unstable "wonky" beats on guitar without drums

Question: Lately I've been getting into "wonky" music,

a subgenre of electronic music known primarily for its off-kilter or "unstable" beats, as well as its eclectic blend of genres including hip hop, electro-funk, chiptune, jazz fusion, glitch, and crunk.

as well as J Dilla beats and "drunk swing".
I'd like to explore this on rhythm guitar, without a drummer.
How do I reproduce and practice Wonky beats accurately at a steady tempo? Wonky beats have the rhythmic equivalent of scalar microtones which makes counting kind of difficult.
Comment: Have you got a link to a good clear example of wonky beats?
Comment: https://open.spotify.com/playlist/6GZZzXWc7QfecxM85804b7?si=FOvpBpzERAeJjiIy82PCMw
Comment: Nice. But I've listened to half a dozen and can't find anything wonky! Well - There's a delayed synth hi-hat on the left in They Act Brand New. and a synth-flute-thing on Can't Get Used To Those which is playing a bit early, but it's all sequenced. The backing tracks are loops. It's all enjoyable, btw. Especially Special ReQuest. Name a track to concentrate on which you think has unstable beats.
Answer: Just yesterday I stumbled upon a video that covers this topic - it makes uses of quintuplet / septuplets swing:

You can write your own patterns in a DAW/sequencer, and play along.
Expanding, as from here:

Quintuplet swing subdivides the beat into quintuplets. The first note is three quintuplets long and the second note is two quintuplets. This corresponds to a swing ratio of 3:2 or 60%. It has a more powerful and angular sound than the standard triplet swing.
In septuplet swing , the first note is four septuplets and the second note is three septuplets. This corresponds to a swing ratio of 4:3 or roughly 57%. It has a really hip, lop-sided feel.

You can practice runs of 5/7 notes over a steady 4/4, using ghost notes to skip some beats, or other similar techniques.
Answer: (Answering an old question:)
Dividing beats and measures in ways that don't quantize neatly is nothing new. Jazz don't mean a thing if it ain't got that swing; Viennese waltz warps the second beat of the measure in ways that are difficult to pin down; French baroque practice has its own sort of swing in the form of notes inegales, performing equal-value notes unequally.
In all these situations, despite these distortions of individual beats or subdivisions of beats, an overall steady tempo is maintained. The key to staying on tempo (and often, to executing these "wonkinesses" without overthinking them) is to focus on the "big picture." Even if four beats in a measure are four different lengths, if each measure is exactly the same length, then one can focus on that periodicity—feel the "bigger groove" of the measures. Even if the rhythmic distortion is changeable, one can lock onto the "milestones" of the larger structure that stay regular.


Finding Fourier coefficients $a_n$ of $\ln|\sin(\frac{x}{2})|$

Question: $\ln|\sin(\frac{x}{2})| = -\ln2 + \sum_{n=1}^{\infty} \frac{\cos{nx}}{n}$ where $x\neq2k\pi$ for any integer k.
I'd like to find $a_n$ and here is my stuck.

\begin{align*}
\frac{1}{\pi}\int_{-\pi}^{\pi}\ln|\sin\frac{x}{2}|\cos(nx)dx &= \frac{2}{\pi}\int_{0}^{\pi}\ln(\sin\frac{x}{2})\cos(nx)dx\\
&= \frac{2}{\pi}\Big[2\int_0^\frac{\pi}{2}\ln(\sin(x))\cos(2nx)dx\Big]\\
&= \frac{4}{\pi}[\frac{1}{2n}\sin(2nx)\ln(\sin(x))\Big|_0^\pi - \frac{1}{2n}\int_{0}^{\pi}\sin(2nx)\cot(x)dx]\\
&= \frac{4}{\pi}(-\frac{1}{2n}\Big[\sin(2nx)\ln(\sin(x))\Big|_0^\pi - 2n\int_0^\pi \ln(\sin(x))\cos(2nx)dx\Big])\\
&= \frac{4}{\pi}\int_0^\pi \ln(\sin(x))\cos(2nx)dx
\end{align*}

And it seems I'm back to square one. Plese give me a hint.
Comment: Do you want to prove that the $\log{|\sin{\frac{x}{2}}|}=-\log{2}+\sum_{n=1}^\infty \frac{\cos{nx}}{n}$ or do you want to explicitly compute the Fourier coefficients?
Comment: for the integral I get $-1/n$ but have not got a method for it yet
Comment: Want to show the coefficient $a_n$ is $\frac{1}{n}$
Comment: @GarethMa It helps, thank you. So I now have $a_n = -\frac{1}{n}$, but the problem obviously shows that it's $\frac{1}{n}$. I don't know what is going wrong.
Answer: Recall the Riesz-Fischer theorem (and of course your function is measurable) lets us find the $n$-th Fourier coefficient under the assumption that the Fourier series converges in $L^2$. We can find the $n$-th coefficient, call it $F_n$ by:
\begin{equation*}
F_n = \frac{1}{2\pi} \int_{-\pi}^{\pi}f(x)e^{-inx}dx
\end{equation*}
I understand this integral may be disgusting (and perhaps impossible) to calculate but there may be some simplifications to be had. But something to think about regardless.
Comment: Thank you so much. BTW, this probably is beyond the course I'm now taking. I will study the theorem later.
Comment: Yea no worries! You could still maybe try to plug in f(x) and try to solve but it looks like a terrible integral lol good luck mate
Answer: I am sorry if I am confusing you all. The problem was actually a typo. It must be $\ln|\sin(\frac{x}{2})| = −\ln2 - \sum_{n=1}^{\infty} \frac{\cos(nx)}{n}$ and $a_n = -\frac{1}{n}.$
Comment: The edit the question, instead of posting this as an answer.


Infinitesimal generator of the standard Brownian motion

Question: As explained in this Wikipedia page, the infinitesimal generator of the standard Brownian motion is $\frac{1}{2}\Delta$ and for the Brownian motion it has an extra $\partial_t f$ term. Can anybody please explain how one can reach to $\frac{1}{2}\Delta$ from $Af(x) := \lim_{t \downarrow 0} \frac{\mathbb{E}^x(f(X_t))-f(x)}{t}$ in the standard Brownian motion, for a person who is not that much familiar with the stochastic math?
In the first answer here, the Brownian motion was studied. I would appreciate if i can have the proof (not deep stochastic math) for the standard Brownian motion.
And two points which might be covered in the answer of the question above:

Unlike the Brownian case, in the standard case we have $\mathbb{E}^x(B_t-x)=-x$.
In the equation (1) in that answer, how "one can show $\frac{d}{dt} P_t f(x) = A P_tf(x)$                 "  ?

Thanks in advance.
Comment: $\mathbb{E}^x[B_t - x] = x$ implies that $\mathbb{E}^x[B_t] = 2x$. I think you've made a sign error. Regardless, it makes little sense to talk about the generator of a standard Brownian motion where "standard" includes the requirement that the process starts at $0$. The generator captures behaviour of the transition semigroup which requires you to be able to start your process at different points. (i.e. by definition $\mathbb{E}^x$ is the expectation for the law of Markov process in question started at point $x$).
Comment: If you've understood the need to consider the family of processes $(B_t^x)_{x \in \mathbb{R}^d}$ where $B_t^x$ is a Brownian motion started at $x$ when finding the generator then the accepted answer at the other question shows you how to show that the generator is given by the Laplacian in the one dimensional case. You get the multivariate version in pretty much the same way, using the multivariate taylor expansion.
Comment: Also btw $\mathbb{E}^x$ refers to the expectation with respect to the law of the process started from $x$ and hence if $B_t$ is a Brownian motion then $\mathbb{E}^x[B_t - x] = 0 \neq - x$; you can't postulate this to have a different value.
Comment: I think the definition of standard used there doesnt include the assumption that $B_0 = 0$ and instead refers to the other properties (such as the form of the covariance) that determine the properties of the transition functions associated to $B$.
Comment: Thanks.
And yes you are right, it should be $-x$.
Comment: Thanks for the answers. It seems that i should read a lot more about the basics. So you mean that the statement in the Wikipedia page does not mathematically make sense, as we don't define the generator for the standard case at all?
Answer: I'm in the process of learning this myself, and I did the following.
So in the 1D case, we want to show that $Af(x) := \lim_{t\rightarrow 0} \frac{\mathbb{E}^x[f(B_t)] - f(x)}{t} = \frac{1}{2}f''(x)$.
A Taylor expansion about $f(x)$ gives
\begin{align}
\mathbb{E}^x[f(B_t)] &\approx \mathbb{E}^x[ f(x) + (B_t-x) f'(x) + \frac{1}{2}(B_t-x)^2 f''(x)]\\
&= f(x) + \mathbb{E}^x[B_t-x] f'(x) + \frac{1}{2} \mathbb{E}^x[(B_t-x)^2] f''(x)\\
&= f(x) + \frac{t}{2} f''(x)
\end{align}
where the last equality comes from the properties of a Brownian motion with $B_0=x$, $\mathbb{E}^x[B_t-x] = 0$ and $\mathbb{E}^x[(B_t-x)^2] = t$.
Plugging back into $Af(x)$, the $f(x)$'s cancel and we get
$$ Af(x) = \lim_{t\rightarrow 0} \frac{\frac{t}{2}f''(x)}{t} = \frac{1}{2}f''(x)$$
(The t's trivially go away: $\lim_{t\rightarrow 0} \frac{t}{t} = \lim_{t\rightarrow 0} 1 = 1$)
You can extend this reasoning to the multidimensional case $x= (x_1, \dots, x_n)$, where the Taylor expansion becomes
$$\mathbb{E}^x[f(B_t)] = f(x) + \frac{t}{2} \sum_{i=1}^n \frac{\partial}{\partial x_i} f(x).$$
Comment: In the last formula, it should be second derivatives to get Laplacian !


Does this proof of "$AB$ and $BA$ have the same characteristic polynomial" assume $k$ algebraically closed?

Question: I am looking at Theorem 1.3.22 of this book. I was wondering whether it makes the assumption that the matrices are in an algebraically closed field $k$, and if so, where does it use such assumption.
Comment: No such assumptions are made.  The matrices $\begin{bmatrix}I&A\\0&I\end{bmatrix}$ etc. don't depend on $k$ algebraically closed.
Answer: When we say like "$n$ eigenvalues" you can understand that to mean:

the eigenvalues exist in $k$
the eigenvalues exist in some algebraic extension/closure of $k$

The proof itself doesn't reference the eigenvalues, just the matrices themselves.
Sometimes you'll see a proof begin with like: "fix an algebraic closure" or "fix an extension which contains all the eigenvalues." This is not necessary for this proof.
You can see similar statements to "$n$ eigenvalues." For instance: every quadratic has either 2 real roots, 1 repeated root with multiplicity, or 2 complex roots. There is an understanding that we know there are 2 roots even if they appear with multiplicity or appear not in $\mathbf{R}$ but in $\mathbf{R}[\sqrt{-1}]$.


Limit behavior of $\sum_{x=0}^m\binom{n}{x}$

Question: I am interested in sums of the form
$$A_n = \sum_{x=0}^m \binom{n}{x}.$$
When $m = n$ we clearly have $A_n = 2^n$. In the case where $m \neq n$, we have
$$A_n = 2^n - \binom{n}{m+1}{}_{2}F_{1}(1, m-n+1, m+2, -1),$$
where ${}_{2}F_{1}$ denotes the hypergeometric function.
What is the limiting behavior of $A_n$ for fixed $m$ as $n \rightarrow \infty$? Obviously we still have $A_n = \mathcal O(2^n)$, but can we say anything stronger than this (in terms of functions which are nicer than the hypergeometric function)?
Answer: Note that $A_n$ is a polynomial in the variable $n$ with the leading term $\frac{n^m}{m!}$. We also have a crude bound
$$ \binom{n}{m} \leq A_n \leq \binom{n+m}{m} $$
for non-negative integers $n$. The following post may also help:

Sum of 'the first k' binomial coefficients for fixed n


Antithetic variate for Chi-squared distribution?

Question: I am using antithetic sampling for variance reduction. I know for standard normal $z$, it's antithetic variate is $-z$ ($1-U$ for uniform etc).  But I cannot figure out what would be antithetic variate for samples from chi-squared distribution since I don't find symmetry.
Also for $t$ distribution, would it be $-t$? Since it is symmetric around the origin?
Comment: Your definition of an antithetic variable seems too limited to make the question answerable.  But if you follow the definition used at https://stats.stackexchange.com/questions/183453, an answer should be clear.
Comment: Yes: it's called the incomplete gamma function.  Statisticians know it better as the chi-squared quantile function or inverse chi-squared cumulative distribution.  Any general-purpose statistical software can compute it.
Comment: I understand that I can get a general antithetic variable for any distribution D following the steps : Step1) Generate u from U(0,1)  Step2) Get Value from inverse cdf  Dinv(u) Step3) Get value from inverse cdf  Dinv(1-u) and then take average. But i wanted to know if there is any definite closed form answer for chi-squared like there is for uniform and normal.
Answer: Using the definition of antithetic variable from Calculating integral with antithetic variables, that is, $x_i^*$ is the antithetic variable for $x_i$ when $F(x_i^*) + F(x_i)=1$, $F$ the cdf, the answer should be clear. For simulation of the chi-squared random variable $X$ use the inversion method, see How does the inverse transform method work?.
So the algorithm is, with $F$ the chi-squared cdf:

$U\sim \mathcal{U}(0,1)$
$V=1-U$
$X=F^{-1}(U)$
$X^* = F^{-1}(V)$ is the antithetic variable.


How to get resource identifier of styles.xml file?

Question: I want resource id of style file at runtime because I can able to access current package of application
here is styles.xml file

and fro with this code snippet I am trying to fetch my customtheme
int styleId = getActivity().getResources().getIdentifier("CustomDigitsTheme", "styles",getActivity().getPackageName());

but it returns 0. So is there any other way to get style resource .
I need runtime resource because I am making cordova plugin.
Comment: Possible duplicate of [How do I apply a style programmatically?](http://stackoverflow.com/questions/5051753/how-do-i-apply-a-style-programmatically)
Comment: No, it is not a duplicate of mentioned link
Answer: Try to change styles to style (R.style.CustomDigitsTheme):
int styleId = getResources().getIdentifier("CustomDigitsTheme", "style", getPackageName());
Comment: how do we refer the name if the style name is "Custom.DigitsTheme" should we write the name as Custom_DigitsTheme?
Comment: sorry my bad, there was a mistake in the name I defined


Como eu posso criar atualizar função no colab sem precisar restartar o kernel dele?

Question: Eu tenho minhas funções feitas fora do colab, em arquivos py, porém eu gostaria de alterar a função e não precisar restartar o kernel do colab. Para que essa função funcione no notebook  eu nesse momento estou precisando restartar todo o notebook, eu gostaria de passar algum parâmetro ou algo do gênero para que eu possa rodar a função, editar novamente e conseguir utilizar ela no estado atual dele.
Answer: A função "reload" da importlib pode forçar o modulo  a ser re-executado, e aí o processo Python do seu Kernel vai ter a nova função.
O problema é que importlib.reload sozinho sempre funciona para o módulo (no caso, seus arquivos .py) e não para a função sozinha -
Então, se você tem um arquivo "meuarquivo.py" e lá dentro "def minhafuncao(): ...",
precisa fazer essas duas coisas - eu recomendo deixar uma célula de rascunho próxima do ponto onde você está trabalhando com isso, e re-executar esta célula cada vez que alterar a função:
import meuarquivo  # só é necessário se "meuarquivo" não foi importado antes

from importlib import reload

reload(meuarquivo)

minhafuncao = meuarquivo.minhafuncao

Em vez da última linha, pode usar a sintaxe de import também, (mas
depois de executar o reload):  from meuarquivo import minhafuncao.
Se tiver mais de uma função ou constantes definidas no arquivo, o assignent
no notebook tem que ser feito para cada elemento que você usar, individualmente.
Por exemplo:  from meuarquivo import funcao1, funcao2, df_horarios
E por fim, se não quiser fazer o reassignment, pode também sempre usar o nome por extenso (qualified name) de tudo o que estiver no arquivo que você for atualizar.
Assim, se em todos os pontos em que você usa a função no notebook sempre usar meuarquivo.minhafuncao em vez de usar o from meuarquivo import funcao, só precisa mesmo fazer a chamada ao reload.
Answer: importlib é uma ótima opção, pois ela realmente atualiza a função podendo depois ser utilizada posteriormente, depois de importar sua função pode utilizar o seguinte comando:
import importlib
importlib.reload(suaFuncao)

Comment: O caso de uso informado na [documentação](https://docs.python.org/pt-br/3/library/importlib.html#importlib.reload) não é o de recarga de funções e sim recarga de módulos.


How to use groupby in linq sql

Question: I am trying to group a list and using ToDictionary to achieve this which works:
var levels = ids.GroupBy(f => f.Id).
    ToDictionary(g => g.Key, g => g.First().Name);

The problem is: in the string "Name" the last char is a number i.e. 2 or 5 or 7 etc.
I do NOT want to select the first but I want to select "Name" with the MAX number. How can i achieve this.  example of Name can be: "abd-hbb-les3" , "abd-hbb-les1" , "abd-hbb-les6"
Comment: You can order desc by name and take first element, can't you?
Comment: When you say you want to "select" the "name" with the max number, you mean inside the ToDictionary? or just the one with the max value altogether?
Answer: You could do this in the following way:
var levels = ids.GroupBy(f => f.Id).ToDictionary(g => g.Key,
    g => g.First( x=> x.Name.Last() == g.Max( y=> y.Name.Last())).Name);

assuming that it's really about the last letter so it's not possible to have a two (or more) digits at the end e.g.:
abd-hbb-les16 //will not work with the above code

Answer: For every group simply select the name with the maximum last character of the string. Like this:
var levels = ids.
    GroupBy(f => f.Id).
    ToDictionary(
        g => g.Key,
        g => g.First(i => i.Name.Last() == g.Max(j => j.Name.Last())).Name);

How to use groupby in linq sql


if $\mathrm{rank}(A)=m$ and $\mathrm{rank}(B)=n$, is that true that $\mathrm{rank}(A\otimes B)$ equal to $\mathrm{rank}(A)*\mathrm{rank}(B)$?

Question: Please help me...
if I have $A,B$ are matrices and $\mathrm{rank}(A)=m$ and $\mathrm{rank}(B)=n$, is that true that $\mathrm{rank} (A\otimes B)$ equal to $\mathrm{rank}(A) * \mathrm{rank}(B)$?
if false, what the true about $\mathrm{rank}(A\otimes B)$?
thx a lot.
Comment: Are you asking about the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product) of two matrices?
Comment: What was the point of introducing $m$ and $n$??
Comment: This property can be deduced from the more general statement that the eigenvalues of the product are all values $\lambda \cdot \mu$ with $\lambda$ an eigenvalue of $A$ and $\mu$ an eigenvalue of $B$.
Answer: Yes it is true. Using the fact that
$$
A\otimes B \cdot C\otimes D = AC \otimes BD
$$
we can use row and column operations to put $A\otimes B$ into a convenient diagonal form.
Comment: thx Yan Shuo Tan (y)


How can I make Windows Server 2012 running on KVM boot with virtio rather than IDE?

Question: I have Windows Server 2012 Essentials running on KVM in Ubuntu 14.04. I've had some problems detailed here Windows Server 2012 on KVM on Ubuntu 14.04. Runs well for a while and then slows down
I haven't made much progress on that but I thought I would try changing the disks from virtio to IDE in case there is a problem with virtio on Windows 2012. That didn't seem to help so I now want to go back to virtio for the better performance. The problem now is that it will only boot if the C: drive is IDE.  If I use virsh to set my C: drive to virtio then Windows starts to boot but comes up with the repair screen. If I go to a command prompt, diskpart reports no disks. It's obviously forgotten about the virtio driver which is a bit strange because I have d: e: and f: drives which are still running virtio so the driver is there and installed but just not recognized at boot time as it used to.
I originally installed the virtio drivers at the beginning of the install when I had the chance to hit a key and install a driver.
How can I get it to recognize the virtio driver again?
I'm basically in the situation as someone who installed it as IDE and now wants to move to virtio. This video seems to have a solution. https://www.youtube.com/watch?v=tlh4zxqfvhk&feature=youtu.be He boots on the install CD and gets back to that driver prompt, installs the driver and quits. When I try that and hit the "Install" button, it prompts me for my Windows registration code which I enter and then it told me to remove the CD and reboot. I never got the driver prompt.
Is it likely to be worth creating another partition, installing a minimum Windows 8, booting on that, making sure my original C: drive has the virtio drivers, then marking it as active and rebooting? I've seen that sort of procedure described.
Are there any other "tricks" to getting back to where I was.
Thanks
Comment: Did you load the virtio drivers _within_ startup repair?
Comment: I don't seem to have the opportunity to add drivers during repair. I'm going by memory here but the repair screen gives me options to "automatically repair" or some such words, go to a command prompt or shut down. The automatic repair spins for a few minutes but "Can't fix it".  I don't seem to be able to get to the equivalent of this http://serverfault.com/questions/423103/how-can-i-run-startup-repair-on-a-kvm-virtualized-windows-server?rq=1  That's 2008. I'm on 2012.
Comment: Reading a bit more...  Maybe I need to run startrep.exe from the repair command prompt.
Answer:
Attach a new VirtIO disk to your VM, whether it is online or offline.
When online, Windows will recognize the new disk and ask for drivers. Install virtIO drivers.
After successful driver installation, shutdown your VM.
With VM offline, remove the disk attached on step 1.
With VM offline, change type of original VM disk to VirtIO.
Boot your VM.

Windows won't complain, because you already have the drivers (installed on step 2).
Answer: I managed to fix it. In Device Manager, I uninstalled and deleted the virtio drivers for the other disks then let it detect the disks again and reinstalled the drivers. That somehow overwrote something and made it good because it then recognized my boot drive when I changed it to virtio.


What are good basic statistics to use for ordinal data?

Question: I have some ordinal data gained from survey questions.  In my case they are Likert style responses (Strongly Disagree-Disagree-Neutral-Agree-Strongly Agree).  In my data they are coded as 1-5.
I  don't think means would mean much here, so what basic summary statistics are considered usefull?
Comment: Common choices include - medians, modes, proportions or cumulative proportions in each group
Answer: I'm going to argue from an applied perspective that the mean is often the best choice for summarising the central tendency of a Likert item.
Specifically, I'm thinking of contexts such as student satisfaction surveys, market research scales, employee opinion surveys, personality test items, and many social science survey items.
In such contexts, consumers of research often want answers to questions like:

Which statements have more or less agreement relative to others?
Which groups agreed more or less with a given statement?
Over time, has agreement gone up or down?

For these purposes, the mean has several benefits:
1. Mean is easy to calculate:

It is easy to see the relationship between the raw data and the mean.
It is pragmatically easy to calculate. Thus, the mean can be easily embedded into reporting systems.
It also facilitates comparability across contexts, and settings.

2. Mean is relatively well understood and intuitive:

The mean is often used to report central tendency of Likert items. Thus, consumers of research are more likely to understand the mean (and thus trust it, and act on it).
Some researchers prefer the, arguably, even more intuitive option of reporting the percentage of the sample answering 4 or 5. I.e., it has the relatively intuitive interpretation of "percentage agreement".
In essence, this is just an alternative form of the mean, with 0, 0, 0, 1, 1 coding.
Also, over time, consumers of research build up frames of reference. For example, when you're comparing your teaching performance from year to year, or across subjects,
you build up a nuanced sense of what a mean of 3.7, 3.9, or 4.1 indicates.

3. The mean is a single number:

A single number is particularly valuable, when you want to make claims like "students were more satisfied with Subject X than Subject Y."
I also find, empirically, that a single number is actually the main information of interest in a Likert item.
The standard deviation tends to be related to the extent to which the mean is close to the central score (e.g., 3.0). Of course, empirically, this may not apply in your context. For example, I read somewhere that when You Tube ratings had the star system, there were a large number of either the lowest or the highest rating. For this reason, it is important to inspect category frequencies.

4. It doesn't make much difference

Although I have not formally tested it, I would hypothesise that for the purpose of comparing central tendency ratings across items, or groups of participants, or over time, any reasonable choice of scaling for generating the mean would yield similar conclusions.
Comment: Nice post! Do you have any thoughts on how different cultures / countries may use likert scales which would drastically impact these sorts of results?
Comment: I asked the question about [cultural differences in use of response scales on cogsci.stackexchange.com](http://cogsci.stackexchange.com/q/1033/52)
Comment: @chase There is research on this, but it's been a while since I've looked at it. Here's an example search on Google scholar http://scholar.google.com.au/scholar?q=cross+cultural+use+response+scales&hl=en&as_sdt=0&as_vis=1&oi=scholart
Comment: I agree with Mr. Jeromy Anglim's justification on the use of mean (i.e., weighted mean to be exact) as the most reliable **unbiased** more descriptive interpretation of ordered categorical variables such as the use of Likert scale where each of the data points contribute to the final average.
Answer: A frequency table is a good place to start. You can do the count, and relative frequency for each level. Also, the total count, and number of missing values may be of use.
You can also use a contingency table to compare two variables at once. Can display using a mosaic plot too.
Answer: For basic summaries, I agree that reporting frequency tables and some indication about central tendency is fine. For inference, a recent article published in PARE discussed t- vs. MWW-test, Five-Point Likert Items: t test versus Mann-Whitney-Wilcoxon.
For more elaborated treatment, I would recommend reading Agresti's review on ordered categorical variables:

Liu, Y and Agresti, A (2005). The
  analysis of ordered categorical data:
  An overview and a survey of recent
  developments. Sociedad de
  Estadística e Investigación Operativa
  Test, 14(1), 1-73.

It largely extends beyond usual statistics, like threshold-based model (e.g. proportional odds-ratio), and is worth reading in place of Agresti's CDA book.
Below I show a picture of three different ways of treating a Likert item; from top to bottom, the "frequency" (nominal) view, the "numerical" view, and the "probabilistic" view (a Partial Credit Model):

The data comes from the Science data in the ltm package, where the item concerned technology ("New technology does not depend on basic scientific research", with response "strongly disagree" to "strongly agree", on a four-point scale)
Answer: Conventional practice is to use the non-parametric statistics rank sum and mean rank to describe ordinal data.
Here's how they work:
Rank Sum

assign a rank to each member in each
group;
e.g., suppose you are looking at goals for each
player on two opposing football
teams then rank each member on
both teams from first to last;
calculate rank sum by adding the ranks per group;
the magnitude of the rank sum tells
you how close together the ranks are
for each group

Mean Rank
M/R is a more sophisticated statistic than R/S because it compensates for unequal sizes in the groups you are comparing. Hence, in addition to the steps above, you divide each sum by the number of members in the group.
Once you have these two statistics, you can, for instance, z-test the rank sum to see if the
difference between the two groups is statistically significant (I believe that's known as the Wilcoxon rank sum test, which is interchangeable, i.e., functionally equivalent to the Mann-Whitney U test).
R Functions for these statistics (the ones I know about, anyway):
wilcox.test in the standard R installation
meanranks in the cranks Package
Answer: I usually like to use Mosaic plot. You can create them by incoorporating other covariates of interest (such as: sex, stratified factors etc.)
Answer: Based on the abstract This article may be helpful for comparing several variables that are Likert scale. It compares two types of non-parametric multiple comparison tests: One based on ranks and one based on a test by Chacko. It includes simulations.
Comment: Hi @gung  I wasn't sure where to put the comment in this long thread. I added the cite here since the question posted today was closed, and this article seems useful (and covers issues I haven't seen elsewhere)
Comment: At present, this almost seems like a comment, @PeterFlom. Although the ACM digital library is probably less susceptible to link rot, would you mind saying something about the article, perhaps a precis of the helpful info it provides?
Answer: I agree with Jeromy Anglim's evaluation. Remember that Likert responses are estimates — you are not using a perfectly reliable ruler to measure a physical object with stable dimensions. The mean is a powerful measure when using reasonable sample sizes.
In business and product R&D, the mean is by far the most common statistic used with Likert scales. When using Likert scales I have usually chosen a measure that ideally fits the research question. For instance, if you are talking about "preference" or "attitudes" you can use multiple Likert-based indicators, with each indicator providing slightly different insight.
To evaluate the question "how will people in segment $i$ react to service offering $X$," I may look at (1) arithmetic mean, (2) exact median, (3) percentage most favorable response (top box), (4) % top two boxes, (5) ratio of top two boxes to bottom two boxes, (6) percentage within mid-range boxes... etc. Each measure tells a different piece of the story. In a very critical project, I use multiple Likert-based indicators. I will also use multiple indicators with small samples and when a specific cross tab has an "interesting" structure or looks information-rich. Ahhh... the art of statistics.
Answer: "Box scores" are often used to summarize ordinal data, particularly when it comes with  meaningful verbal anchors. In other words, you might report "top 2 box", the percentage that chose either "agree" or "strongly agree".


Bloomberg Server API and Ruby/Python

Question: Im looking to write a new application in ruby/python which uses a feed from bloomberg and am stuck trying to find any documentation for using (or even setting up) Bloomberg Server API with either of these languages.
Does anyone have any good links to tutorials for this or maybe some boilerplate code to get set up? Or is it best to just stick to the three main supported languages?
Answer: The Bloomberg Open API (BLPAPI) v3.5 release now includes a native Python SDK.
http://www.openbloomberg.com/2012/11/21/open-api-blpapi-v3-5-x-released/
Answer: Did you check out some questions at SO on this. It might help you

Bloomberg API request timing out
Asynchronous data through Bloomberg's new data API (COM v3) with Python?

Resolver is an spreadsheet implementation in IronPython and has a very good integration for Bloomberg API

http://www.resolversystems.com/documentation/apidocs/MarketData_Bloomberg.html
Answer: Here is a simple Client access API which I wrote with the help of the mentioned links as well as some others. Not everything is implemented but it is a good start.
https://github.com/bpsmith/pybbg
Comment: Care to write a summary here for the convenience of the readers here?

Bloomberg Server API and Ruby/Python


Neovim lua how to use mutable variables in keymappings

Question: I'm using neovide (a graphical interface for nvim), so I lost ctrl+[-+] to change the font size. I'm trying to rewrite it in my lua config but I'm pretty new to lua so I'm struggling to implement the function. Here's my code :
vim.g.font_size = 11
vim.o.guifont='FantasqueSansMono Nerd Font Mono:h'..vim.g.font_size
vim.keymap.set('n', '<C-->',
    ':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'FantasqueSansMono Nerd Font Mono:h'..vim.g.font_size..'\'<CR>')

What I'm trying to do, is to have a variable font_size that I can increment or decrement, then use the new value to update the size of the font. The first two lines work perfectly, they always set the correct font size when launching a new instance of neovide. The keymap on the other hand will decrement / increment font_size like intended but the second command of the mapping will always use the value written at line 1.
For instance, if I start neovide and press ctrl+-, the status line will show :let &guifont = 'FantasqueSansMono Nerd Font Mono:h11', but if I enter the following command : echo g:font_size, I get 10. Is there a way to fix this problem ? (or a more elegant way to fix it haha)
Answer: This line:
':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'Consolas:h'..vim.g.font_size..'\'<CR>'

Is building a string that uses the current version of vim.g.font_size at the time the string is built. That ends up being this string:
':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'Consolas:h11\'<CR>'

So your mapping looks like this:
vim.keymap.set('n', '<C-->', ':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'Consolas:h11\'<CR>'

See what's happening now?
Side note, Lua supports several string delimeters ("x", 'x', or [[x]]), so you don't have to escape your internal strings if you use a different outer delimeter, like this:
":let g:font_size = (g:font_size - 1)<CR>:let &guifont = 'Consolas:h11'<CR>"

The binding yoiu really want is this:
vim.keymap.set('n', '<C-->', ":let g:font_size = (g:font_size - 1)<CR>:let &guifont = 'Consolas:h'.g:font_size<CR>"

But if you really want the binding to be Lua, you'd dot his:
vim.keymap.set('n', '<C-->', ":luado vim.g.font_size = vim.g.font_size - 1; vim.o.guifont='Consolas:h'..vim.g.font_size<CR>")


Is there a way to grab the current select box option's value without submitting?

Question: I'm trying to build some functionality for a project, but I'm stuck with this:
I want to grab the value from a select box option, and use it in my php script
The thing is, I need to grab the currently selected option without the user having to post the data. So I suspect there is a little bit of ajax required here, which I am completely new to.
I'll give you an example to make things clearer:
        <select>
        <option value="United Kingdom">United Kingdom</option>
        <option value="Belarus">Belarus</option>
        <option value="Albania">Albania</option>
        </select>

User is presented with a select box
User chooses 'Belarus' from the drop-down
I need to be able to take the value 'Belarus' and assign it to a variable in php

I have no idea how to do this without them submitting the form.
Any help will be much appreciated
Thanks
Comment: it should $('#selectboxid').val() right ?
Answer: To send data to your PHP script using AJAX:
$('select').on('change', function () {
    var val = $(this).val();
    if (val != '') {
        $.get('path/to/script.php', {'select-name' : val}, function (serverResponse) {
            //this is the callback for this AJAX request, the server has handled the request and anything output by your PHP script will be available in the `serverResponse` variable
        });
    }
});

Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.
Answer: You can use jQuery ajax to partially submit data to the server. Try this
$.ajax({
   url: "urlOfThePage",
   type: "POST",//Based on your requirement you can set it to GET/PUT etc
   data: {
      paramName: $("select").val();//this will get the selected value from the dropdown
   },
   sucess: function(){
     alert("Data submitted");
   }
});

Answer: <select id="my-select">
    <option value="United Kingdom">United Kingdom</option>
    <option value="Belarus">Belarus</option>
    <option value="Albania">Albania</option>
</select>

and use jquery to get the value and pass it to the server:
var value = $("#my-select").val();
$.get('myscript.php', { select_value: value });


Ext4 physical volume with rescued data to LVM

Question: I have /dev/sdc where are rescued data from VG vg_data. I need convert /dev/sdc to LVM with this data. Is it possible?
Edit1:
- I formatted /dev/VG_DATA/data from xfs to ext4
- Copied from sdc1 to LVM data (I thinked)
After I run rsync from sdc1 to data lvm i got errors and /dev/sdb1 (lvm data) is gone to offline.
> 79.497864] sd 1:0:1:0: rejecting I/O to offline device [   79.497891] Aborting journal on device dm-2-8. [   79.497895] sd 1:0:1:0:
> rejecting I/O to offline device [   79.497899] JBD2: Error -5 detected
> when updating journal superblock for dm-2-8. [   79.497916] sd
> 1:0:1:0: rejecting I/O to offline device [   79.497953] sd 1:0:1:0:
> rejecting I/O to offline device [   79.497970] EXT4-fs error (device
> dm-2): ext4_journal_check_start:56: Detected aborted journal [
> 79.497983] sd 1:0:1:0: rejecting I/O to offline device [   79.498154] sd 1:0:1:0: rejecting I/O to offline device [   79.498169] sd 1:0:1:0:
> rejecting I/O to offline device [   79.498192] sd 1:0:1:0: rejecting
> I/O to offline device [   79.498203] sd 1:0:1:0: rejecting I/O to
> offline device

What is wrong with volume group? It is virtual mach. on hyper-v 08 r2
Edit 2 - from boot log
Sep 17 17:01:23 localhost lvm: 1 logical volume(s) in volume group "VG_DATA" now active
Sep 17 17:01:23 localhost systemd: Found device /dev/mapper/VG_DATA-data.
Sep 17 17:01:23 localhost systemd: Started LVM2 PV scan on device 8:17.
Sep 17 17:01:23 localhost systemd: Mounting /data...
Sep 17 17:01:23 localhost kernel: XFS (sda1): Ending clean mount
Sep 17 17:01:23 localhost systemd: Mounted /boot.
Sep 17 17:01:23 localhost kernel: EXT4-fs (dm-2): recovery complete
Sep 17 17:01:23 localhost kernel: EXT4-fs (dm-2): mounted filesystem with ordered data mode. Opts: (null)
Sep 17 17:01:23 localhost systemd: Mounted /data.

Comment: Hard to tell from the information given, but it looks like it fails mid-transfer with an offline device? This wouldn't be the first time I've seen devices drop from hyper-v 2008R2. Many people generally advise to not use this (and instead use 2012*) for this reason. How is this disk attached to the system? Directly, or with a virtual disk file? Also, what is the controller / disk emulation you are using for the VM?
Comment: It's 2TB vmdk connected via IDE or SCSI (tried both) virt. controller. Phys. disks are 5x 7.2k in HP Smartarray with Raid5.
Answer: Make a backup, especially if this is your only copy of this data.
Scan your disks for this PV then activate the VGs it contains. You do need all the PVs for this to work, although there might only be the one.
vgscan
vgchange -ay
Mount the LVs whose devices appear under /dev/vg_data/*
See your distro's documentation, such as Red Hat's Logical Volume Manager Administration manual.
Comment: added edit1....


Como gravar dados arquivo CSV sem apagar os dados já existentes

Question: Preciso salvar dados em arquivo CSV sem que ele apague os dados já existentes no arquivo, apenas crie uma nova linha com os dados informados
 material=str(input('Informe o material: '))

 mod_elasticidade=float(input('Informe o modulo de elasticidade do material:'))

 tensao_escoamento=float(input('Informe a tensao de escoamento do material:'))

 historico = open("historico.csv","w")

 linha=str(material)+";"+str(mod_elasticidade)+";"+str(tensao_escoamento)

 historico.write(linha)

 historico.close()

Answer: Basta trocar o w por a+, assim:
historico = open("historico.csv", "a+")

linha=str(material)+";"+str(mod_elasticidade)+";"+str(tensao_escoamento)

historico.write(linha)

historico.close()

ps: use o with, assim quando o bloco terminar ele fecha o arquivo sozinho, assim:
material = str(input('Informe o material: '))

mod_elasticidade = float(input('Informe o modulo de elasticidade do material:'))

tensao_escoamento = float(input('Informe a tensao de escoamento do material:'))

linha = str(material)+";"+str(mod_elasticidade)+";"+str(tensao_escoamento)

with open("historico.csv", "a+") as historico:
    historico.write(linha)

Comment: Troquei o "w" por "a+" não apaga as dados ja existentes no arquivo, porem ele grava as novas informações na mesma linha dos dados existentes, preciso que grava os dados na próxima linha em branco do arquivo e não na mesma linha
Comment: @FabioDalZotto mas era para o `a+` fazer isso, quem grava nas linhas existentes é o `a` sem o sinal de `+`, o sinal de mais move o ponteiro para o final, a não ser que seja um BUG, você deve ter feito algo a mais no seu script que falhou nisto, simplesmente isso não era para ocorrer.


When using column-count attribute, first column is cut and second column starts with unwanted padding

Question: I am creating a list of divs with css variables names using column-count attribute, first column is cut at the end (4px) and second column starts with small padding (4px). Do you know how to get rid of that and keep this functionality of splitting divs automatically into 2 columns?

    .components {
        &__variable-list {
        column-count: 2;
        column-gap: 2rem;
        padding-bottom: .5rem;
      }

      &__variable {
          padding: .25rem .5rem;
          font-size: .875rem;

          &:nth-child(odd) {
              background-color: #e4e4e4;
          }

          &:nth-child(even) {
              background-color: #fff;
          }
      }
    }

--cwc-tab-border-color

--cwc-tab-color

--cwc-tab-focus-color

--cwc-tab-hover-color

--cwc-tab-active-color

--cwc-tab-active-border-color

--cwc-tab-heading-active-color

--cwc-tab-no-padding-active-color

--cwc-tab-no-padding-border-color

--cwc-tab-disabled-color

--cwc-tab-single-color

Answer: You can fix that if you add break-inside: avoid; to your __variable class like so:

.components__variable-list {
  column-count: 2;
  column-gap: 2rem;
  padding-bottom: 0.5rem;
}

.components__variable {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  break-inside: avoid;
}
.components__variable:nth-child(odd) {
  background-color: #e4e4e4;
}

.components__variable:nth-child(even) {
  background-color: #fff;
}

--cwc-tab-border-color

--cwc-tab-color

--cwc-tab-border-color

--cwc-tab-color

--cwc-tab-border-color

--cwc-tab-border-color

--cwc-tab-color

--cwc-tab-border-color

--cwc-tab-border-color

--cwc-tab-color

--cwc-tab-border-color

Comment: thanks, but with these styles when there are just 2 items, they are displayed under each other and not in 2 columns
Comment: Sorry, didn't see that, iI updated my post. now it is working with an odd and even number,  and two entries.
Comment: thanks man, that works fine, if you can give upvote to the question I would be very grateful, I am sick of that my votes don't count when I am using this platform


How to position div without space

Question: I have six divs in my html document.
My problem is that last div has some top space which needs to be removed.
This is not a duplicate question.
This has nothing to do with inline-block spacing.
Please help.

<!DOCTYPE html>

Comment: Don't use `float: left` for this case. If you are using `float: left`, you need to `clear` as well.
Comment: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. See the [ask] page for help clarifying this question.
Comment: Added fiddle.Please check that. I dont want top space to be there for my last div
Comment: Remove `inline-block` and add `float: left`. If you have whitespaces in your html `inline-block` will add some space.
Comment: float:left and vertical-align:top adding both worked.but which one should be prefered.Please explain.
Comment: Possible duplicate of [How to remove the space between inline-block elements?](http://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements)
Comment: @SrikanthReddyKarnati Did it answer your question?
Comment: @gcampbell Not a valid dupe target. This is different.
Comment: @PraveenKumar "All divs should align properly without any spaces between them"?
Comment: @gcampbell True. Not a right dupe target. Let me repeat, not a right dupe target. `:)`
Comment: Use text-align or vertical-align (can't remember which off the top of my head)
Answer: This is a problem with inline-block. Use vertical-align: top to fix, as the default is baseline:

<!DOCTYPE html>

Answer: Just a small change in your css:
div {
padding: 0;
margin: 0;
border: 1px solid;
display: inline-block; /* Removed this */
width: 25%;
height: 25%;
position: relative;
float:left; /* Added this */
}

Answer: add to body font-size: 0; and add to your div
font-size: 12px;
    box-sizing: border-box;
    vertical-align: top;

about Box Sizing
Demo

<!DOCTYPE html>

Answer: You can try absolute positioning. Add position: absolute; to div:first-child

<!DOCTYPE html>

Answer: In html, spaces, tabulations and linebreak (while formatting your html document) are transcribe by a space.
So if you want no space between your div you should put comments between them :

  body {
    border: 1px solid;
    padding: 0;
    margin: auto;
    height: 500px;
    width: 500px;
  }
  div {
    padding: 0;
    margin: 0;
    border: 1px solid;
    display: inline-block;
    width: 25%;
    height: 25%;
    position: relative;
  }
  div:first-child {
    background: black;
  }
<!DOCTYPE html>

How to position div without space


Sorting accNo field which are from two different path

Question: <?xml version="1.0" encoding="UTF-8"?>
<accountList>
    <previousAccount>
        <account>
            <name>NASH</name>
            <accountStatus>REMOVED</accountStatus>
            <accNo>1</accNo>
        </account>
        <account>
            <name>ADOGA</name>
            <accountStatus>REMOVED</accountStatus>
            <accNo>8</accNo>
        </account>
        <account>
            <name>LUCAS</name>
            <accountStatus>HOLD</accountStatus>
            <accNo>09</accNo>
        </account>
        <account>
            <name>DONALD</name>
            <accountStatus>HOLD</accountStatus>
            <accNo>21</accNo>
        </account>
        <account>
            <Title>Miss</Title>
            <firstName>HILARI</firstName>
            <lastName>WOOD</lastName>
            <city>LONDON</city>
            <accNo>24</accNo>
        </account>
    </previousAccount>
    <account>
        <Title>Mr</Title>
        <firstName>RICHARD</firstName>
        <lastName>JOHN</lastName>
        <city>london</city>
        <accNo>02</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>xxx</firstName>
        <lastName>JOHN</lastName>
        <city>London</city>
        <accNo>17</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>HEWIT</firstName>
        <lastName>JOHN</lastName>
        <city>LONDON</city>
        <accNo>20</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>xxx</firstName>
        <lastName>JOHN</lastName>
        <city>LONDON</city>
        <accNo>21</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>KEVIN</firstName>
        <lastName>PETE</lastName>
        <city>LONDON</city>
        <accNo>07</accNo>
    </account>
</accountList>

xslt code

<xsl:stylesheet version="2.0"
        xsi:schemaLocation="http://www.w3.org/1999/XSL/Transform file:/C:/Users/n434947/Desktop/workspace/SonicXSLT/BA xslt page.xsd"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:fn="http://www.w3.org/2005/xpath-functions"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <xsl:output method="text"/>
    <xsl:variable name="newline">
 <xsl:text>
</xsl:text>
</xsl:variable>
    <xsl:template match="accountList">
        <xsl:for-each-group select="descendant::account" group-starting-with="*[firstName != 'xxx' or lastName != preceding-sibling::*[1]/lastName]">
            <xsl:sort select="accNo" order="ascending"/>
            <xsl:if test="previousAccount/account/accountStatus='REMOVED'">
            <xsl:value-of select="previousAccount/account[accountStatus='REMOVED']/accNo"/>
            </xsl:if>
            <xsl:value-of select="previousAccount/account[accountStatus='HOLD']/accNo"/>
            <xsl:value-of select="accNo"/>
            <xsl:text> </xsl:text>

            <xsl:value-of select="lastName"/>
            <xsl:text> </xsl:text>
            <xsl:value-of select="firstName"/>
            <xsl:value-of select="$newline"/>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

In my requirement ,I got to sort accNo which are all from two different X paths like below
accountList/previousAccount/account/accNo
accountList/account/accNo

I used descendant,which is not working fine for my requirement. Please help me to sort out this please.
Actual Output
02 JOHN RICHARD
07 PETE KEVIN
1
20 JOHN HEWIT
24 WOOD HILARI

Expecting output
   01 REMOVED   NASH
   02           JOHN RICHARD
   07           PETE KEVIN
   08 REMOVED   ADOGA
   09 HOLD      LUCAS
   20           JOHN HEWIT
   24 HOLD       DONALD

Comment: Please help me ,i tried to sort out by two select in for-each,,which not giving the proper results ...
Answer:
In my requirement ,I got to sort accNo which are all from two
  different X paths like below
accountList/previousAccount/account/accNo
accountList/account/accNo

Maybe you can do it where you don't have two different XPaths. If you reduce your XPaths above, by removing previousAccount you see that they basically the same. You just need to search descendants of accountList...
accountList//account/accNo

If you do this with an xsl:for-each or an xsl:apply-templates your sorting becomes easier. Any additional filtering, like firstName != 'xxx' can be added to the predicate.
I think this is what you were originally trying, but it fell apart with xsl:for-each-group.
Here's an example (also seen here). I'm completely guessing at the actual format of the output; especially the padding of the fields. I probably over complicated it a bit, but it should be a start at least.
XML Input
<accountList>
    <previousAccount>
        <account>
            <name>NASH</name>
            <accountStatus>REMOVED</accountStatus>
            <accNo>1</accNo>
        </account>
        <account>
            <name>ADOGA</name>
            <accountStatus>REMOVED</accountStatus>
            <accNo>8</accNo>
        </account>
        <account>
            <name>LUCAS</name>
            <accountStatus>HOLD</accountStatus>
            <accNo>09</accNo>
        </account>
        <account>
            <name>DONALD</name>
            <accountStatus>HOLD</accountStatus>
            <accNo>21</accNo>
        </account>
        <account>
            <Title>Miss</Title>
            <firstName>HILARI</firstName>
            <lastName>WOOD</lastName>
            <city>LONDON</city>
            <accNo>24</accNo>
        </account>
    </previousAccount>
    <account>
        <Title>Mr</Title>
        <firstName>RICHARD</firstName>
        <lastName>JOHN</lastName>
        <city>london</city>
        <accNo>02</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>xxx</firstName>
        <lastName>JOHN</lastName>
        <city>London</city>
        <accNo>17</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>HEWIT</firstName>
        <lastName>JOHN</lastName>
        <city>LONDON</city>
        <accNo>20</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>xxx</firstName>
        <lastName>JOHN</lastName>
        <city>LONDON</city>
        <accNo>21</accNo>
    </account>
    <account>
        <Title>Mr</Title>
        <firstName>KEVIN</firstName>
        <lastName>PETE</lastName>
        <city>LONDON</city>
        <accNo>07</accNo>
    </account>
</accountList>

XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:l="local" xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:function name="l:pad">
    <xsl:param name="input" as="xs:string"/>
    <xsl:param name="length" as="xs:integer"/>
    <xsl:sequence select="l:pad($input,$length,'right')"/>
  </xsl:function>

  <xsl:function name="l:pad">
    <xsl:param name="input" as="xs:string"/>
    <xsl:param name="length" as="xs:integer"/>
    <xsl:param name="align" as="xs:string"/>
    <xsl:variable name="inputLength" select="string-length($input)"/>
    <xsl:variable name="padding" select="if ($length > $inputLength) then
      for $x in 1 to ($length - $inputLength) return ' ' else ''"/>
    <xsl:sequence select="if ($align = 'right') then
      string-join(($padding,$input),'') else
      string-join(($input,$padding),'')"/>
  </xsl:function>

  <xsl:template match="/*">
    <xsl:for-each select=".//account[not(firstName = 'xxx')]">
      <xsl:sort select="accNo" data-type="number"/>
      <xsl:if test="not(position()=1)"><xsl:text>
</xsl:text></xsl:if>
      <xsl:value-of select="l:pad(
        l:pad(format-number(accNo,'00'),5),6,'left')"/>
      <xsl:value-of select="l:pad(
        concat(accountStatus,' '),10,'left')"/>
      <xsl:value-of select="l:pad(
        string-join((lastName,name|firstName),' '),20,'left')"/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Output (it wasn't obvious to me why "WOOD HILARI" was supposed to be excluded)
   01 REMOVED   NASH
   02           JOHN RICHARD
   07           PETE KEVIN
   08 REMOVED   ADOGA
   09 HOLD      LUCAS
   20           JOHN HEWIT
   21 HOLD      DONALD
   24           WOOD HILARI

Comment: Just noticed how old this question was! Oh well, hopefully it helps someone in the future.


How to set fastcgi_busy_buffers_size correctly?

Question: I am run few wordpress websites on single VPS server.
and i saw [emerg] "fastcgi_busy_buffers_size" must be less than the size of all "fastcgi_buffers" minus one buffer in /etc/nginx/nginx.conf:112" error when i checked nginx -t.
I am put fastcgi_buffers size as below each on server block.
fastcgi_buffers 64 16k; # default 8 4k
fastcgi_buffer_size 32k;

and i tested fastcgi_busy_buffers_size as 28 ~ 32k  on nginx.conf.
But no matter what i put it, i  can't find the same value.
Nginx keep getting the error below:
 [emerg] "fastcgi_busy_buffers_size" must be less than the size of all "fastcgi_buffers" minus one buffer in /etc/nginx/nginx.conf:112

 [emerg] "fastcgi_busy_buffers_size" must be equal to or greater than the maximum of the value of "fastcgi_buffer_size" and one of the "fastcgi_buffers" in /etc/nginx/nginx.conf:112

Can some one please let me know if there is a way to set the correct fastcgi_busy_buffers_size value?
Thank you.
Answer:
[emerg] "fastcgi_busy_buffers_size" must be less than the size of all "fastcgi_buffers" minus one buffer in /etc/nginx/nginx.conf:112
[emerg] "fastcgi_busy_buffers_size" must be equal to or greater than the maximum of the value of "fastcgi_buffer_size" and one of the "fastcgi_buffers" in /etc/nginx/nginx.conf:112

fastcgi_buffer_size rules how much memory will be allocated per FastCGI requests to accomodate its first stream of response, usually FastCGI response header. After this buffer is full, FastCGI buffer will shift to whatever allocated by fastcgi_buffers.
fastcgi_buffers rules how many blocks of memory, and its size, to be used to buffer the rest of the response, per requests.
fastcgi_busy_buffers_size rules how much memory can be actively sending responses to clients, and this value is bound to fastcgi_buffers and fastcgi_buffer_size, in which it should be:

equal to or greater than the maximum value between fastcgi_buffer_size and one fastcgi_buffers block (minimum busy buffer to send FastCGI response to the client)
fastcgi_busy_buffers_size >= max(fastcgi_buffer_size, fastcgi_buffers[size])

less than all fastcgi_buffers minus one (still to send FastCGI response data to the client, but you'll need to leave some blocks of fastcgi_buffers to accommodate writes for upstream responses)
fastcgi_busy_buffers_size < (fastcgi_buffers[count] - 1) * fastcgi_buffers[size]

Using your configuration:

fastcgi_buffers 64 16k; # default 8 4k
fastcgi_buffer_size 32k;

your fastcgi_busy_buffers_size should be between max(32k, 16k) = 32k (inclusive) up to (64 - 1) * 16k = 1008k (exclusive).
Furthermore, you'd probably want to align your buffers to your OS' page size to optimize your memory usage and avoid fragmentation.
Comment: This doesn't make sense? "`fastcgi_busy_buffers_size`[...]should be: **at least** equal to `fastcgi_buffer_size` + one `fastcgi_buffers` block (to send FastCGI response header + a portion of FastCGI response body to the client)", but the error says ""fastcgi_busy_buffers_size" must be **less than** the size of all "fastcgi_buffers" minus one buffer" (emphasis mine)


Como deixar uma div ao lado da outra?

Question: <!DOCTYPE html>

<meta charset="utf-8" />

Loren

Ipsulum

Comment: Você deveria elaborar mais a pergunta, mostre o que tentou, explique melhor a pergunta, não ponha só código e espere obter resposta. Você deverá usar `float:left`
Answer: Uma forma de os colocar lado a lado é com float:left. Aproveito para dizer a propriedade left não tem efeito para elementos posicionados de forma estática como é o seu caso, e que display:block é o display por defeito para um

Exemplo com float:left:

* {
    margin: 0;
    padding: 0;
    vertical-align: baseline;
}
body {
    width: 100%;
    background-color: black;
}
.loren{
    float:left; /*<---*/
    width: 50%;
}
.ipsulum{
    float:left; /*<---*/
    width: 50%;
}
p {
    margin: 5px;
    font-family: Arial;
    font-size: 15pt;
    font-weight: bold;
    background-color: gray;
    color: white;
}

Loren

Ipsulum

Outra forma de fazer o mesmo é com display:flex que implica criar um elemento que englobe os dois divs:

* {
    margin: 0;
    padding: 0;
    vertical-align: baseline;
}
body {
    width: 100%;
    background-color: black;
}
.loren{
    width: 50%;
}
.ipsulum{
    width: 50%;
}
p {
    margin: 5px;
    font-family: Arial;
    font-size: 15pt;
    font-weight: bold;
    background-color: gray;
    color: white;
}

.conteudo {
    display:flex; /*<--*/
}

Loren

Ipsulum

Documentação:

left
float
flex

Como deixar uma div ao lado da outra?


How to require Friends Online Presence as non-revocable permission on Facebook?

Question: I would like a new user of my canvas app to grant the "friends_online_presence" permission.
On the FB manual page, this permission is listed among the "User and friends Permissions" which should appear on the first page of the registration dialogue and should be non-revocable.
However, Facebook does the opposite - it redirects the user to the second page of the dialogue, where this permission is optional for the user.
If I try to make registration with other permissions from the list (i.e. friends_likes), it works as supposed - the permission is requested as non-revocable on the first screen.
Am I doing something wrong or this is actually a bug in their documentation?
Thanks!
Answer: Probably a bug in their documentation.  You can however, check to see which permissions the user accepted.  If you find they allowed your app, but not the friends permissions, you can give the user a specific screen telling them they can't use your app.


How to pre-populate fields in checkout?

Question: We have a product that is being sold with Drupal Commerce (using Drupal 7). This specific product is going to be advertised in more ways than just the Drupal site (e.g. email, other sites).
These other sites can have a form in which the user enters some basic information (Name, phone, email). This data is sent to Drupal (curl), a cart and session is created (anonymous unless the user is logged in our site) and the session ID is sent back to the calling website.
The user is redirected to our Drupal site, and the session is restored using the id that was passed.
Everything is working fine, but the user has enter the name, phone and email twice because Drupal tries to pre-populate the checkout fields with the user data, and in this case the user is anonymous, even though I have the user data from the first call.
Is it possible to add this information (name, email, phone) after calling commerce_cart_product_add() for anonymous users? The fields in checkout should get pre-populated even if the user is anonymous.
Answer: You can do one of two things: store the incoming data in the session somehow and alter it into the appropriate fields via hook_form_alter() or immediately create the relevant customer profiles for the session and reference them from the cart order you create. Default rules in Drupal Commerce will handle assigning those customer profiles to any user account that gets created during checkout for your anonymous sessions.

How to pre-populate fields in checkout?


Render a custom region inside node template

Question: I am attempting to render a menu assigned to a block right next to the body of a custom content type. I am using Drupal 7.
I have a custom region defined within my template .info file. I would like to render this region and the block assigned to it from within a custom node template ...
node--<my custom content type>.tpl.php
I needed to do this within the custom node template because I needed to break out the individual fields of the content type rather than just using
print render($content);
This is what I was trying to do ...

  <?php
    print render($content['title']);
    print render($content['field_banner_image']);
    print render($content['body']);
  ?>

<?php print render($page['MY-CUSTOM-REGION']); ?>

<?php print render($content['body']); ?>div>

However, my menu block does not render and I get the following error ...
Warning: Cannot use a scalar value as an array in include()[PATH TO MY CUSTOM NODE TEMPLATE]
Is it possible to render a region from within a custom node template?
Comment: I found a solution from http://drupal.stackexchange.com/questions/20054/can-regions-be-printed-within-a-node-template. Basically I need to add a function to the template.php file for my theme. Once I did that the node tamplate was "aware" of my custom region and I was able to render it. The above article has a very thorough and detailed explanation.
Comment: could you post your solution as an answer and check it? it will hep others to identify quickly the solution :)
Comment: @cayerdis don't repost answers, mark as duplicate.
Answer: You should load your menu yourself inside node, use:

hook_node_load
hook_node_view
hook_preprocess_node


condition for matrix that are linearly dependent

Question:
  Find condition for matrix that are linearly dependent.
Comment: Posting these kind of questions is not going to get you anywhere...
Answer: For the matrices to be linearly dependent, you need:
$$
\alpha\cdot \left( \begin{matrix} 1&2\\-1&0  \end{matrix}\right)+\beta\left(\begin{matrix} 2&-3\\-2&1 \end{matrix}\right)=\left(\begin{matrix} a&b\\c&d  \end{matrix}\right)
$$
This gives you the condition:
$$
\left(\begin{matrix} \alpha+2\beta&2\alpha+3\beta\\-\alpha-2\beta&\beta  \end{matrix}\right)=\left(\begin{matrix} a&b\\c&d \end{matrix}\right)
$$
From this, you get the conditions that $b+d=a=-c$ and then the values of $\alpha$ and $\beta$ that you need for the linear dependence are $\alpha=a-2d$, $\beta=d$.