text:
Q: Windows 7 slower than death. Dell Inspiron 17 R 3521 I have windows 7 on my Dell Inspiron 17R 3521
The laptop came with Windows 8 as the default software and naturally enough (my opinion) I hated it. So I installed windows 7 dual boot with ubuntu 14.04 and what I have now is a laptop that takes 5 minutes or more to get full up and running which is crazy if we take into account the specs of the laptop (or at least that's what I think)
This is the System as windows sees it.
Processor: Intel(R) Core(TM) i7-3537U CPU @ 2.00 Ghz 2.50 Ghz
Installed memory(RAM): 8,00 GB (7,89 GB usable)
System type: 64-bit Operating System

It also has switchable graphics:
Intel(R) HD 4000
AMD Radeon (TM) HD 8XXX Series.

I thought... THOUGHT (apparently was wrong) that the tinny little bit that says i7 would make a huge difference compared to my other computers... but it didn't.
Is this delay slowness natural for my system? Is there something I can do to improve it? I don't have a million start up processes, the heavier one must be Avast antivirus.
When I'm in ubuntu... it is fast enough, and much faster than it is with windows.
Don't know if this is all the information you need to tell me what's the problem if any.
Please help me make my laptop stand on its "feet".
Ty in advance.

A: Well it depends on which route you want to go. I would say first minimize what starts up by using MSCONFIG.  I only have around 3 items checked for mine personally.  If it is still slow from this you can determine if you are maxing out your memory. If so then you could increase your paging file size or physically install more memory.
If all of this seems to be good, I recently got a new SSD instead of an old HD and that increased my system speed ten fold easily. Could be a relatively easy solution but of course will cost you money.  These are all just some tips of where I would try frist.

A: I agree with Eric, except that I want to add that if it is not completely new, and you have experienced it once having been smooth under windows 7, a reinstall might be a good thing to try before buying a SSD. (And with windows 7 you will most likely have to do it anyways when migrating the system to a new disk.)
Also as a side note, while the i7 line is the one intel markets as more "high end", the u-suffix denotes that it is an ultra low voltage edition, which is good for your battery life, but also implies that you shouldn't expect to be doing heavy number-crunching. Although this is most likely not where your problem lies.


text:
Q: Can components be temporarily registered in an Autofac container? I'm building a plugin for a 3rd party application and my plugin uses Autofac to wire up various components.  The container is built at application startup, but the host application invokes my commands at a later time.
When a command is invoked, the host application provides a few instances of types that it defines and that my components will need to use.  I'd like to register these instances in the container so that it can take care of wiring up the components that depend on these instances.
I'm aware that I can use a ContainerBuilder to update an existing container, but I'd like to remove these registrations when the command has completed as these instances will no longer be valid.  Is this possible?
Maybe a better approach is to use 2 containers... The command could create a new container to register these instances and other components could be resolved from the application scoped container.
How could I hook up the 2 containers so that resolve calls bubble up to the application scoped container?
Are there any gotchas to be aware of with this approach?  I imagine there may be component lifetime issues...
Edit:  Now I've done a bit more research and testing and and it turns out I can just use the BeginLifetimeScope(Action<ContainerBuilder>) overload to register the host application provided instances for the nested lifetime only.  For some reason I thought that adding registrations to the nested lifetime would result in them being added to the root container but that doesn't seem to be the case.

A: As noted in my edit above, it turns out that BeginLifetimeScope(Action<ContainerBuilder>) is exactly what I need.  For some reason I thought that adding registrations to the nested lifetime would result in them being added to the root container and therefore being resolvable after the nested lifetime scope ends, but that doesn't seem to be the case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ruby on rails custom action for form_for I'm trying to use form_for for a custom action. My code right now does not cause any errors, it just doesn't do anything. I've been stuck on this for a while, any help would be great :)
routes.rb
 resources :posts do
     member do
     patch :confirm
   end
 end

_feed.html.erb
<% if @feed.any? %>
  <% @feed.each do |feed| %>

  <form class="form-inline">

    <%= form_for @post, url: confirm_post_path(feed), method: :patch do |f| %>

                  # form fields

            <%= f.submit "Confirm", class: "btn-primary btn-xs form-control" %>

    <% end %>

  </form>

posts_controller.rb
def confirm
    @post = Post.find_by(id: params[:id])
    @post.toggle!(:confirm)
    @post.save
    redirect_to root_url
end

pages_controller.rb
def home
  if logged_in?
    @feed = current_user.feed.paginate(page: params[:page])
  end
end

model user.rb
def feed
  Post.where("user_id = ?", id)
end

A: In _feed.html.erb you are using nested form (form tag in form tag), so inner form which is written in erb isn't generated.
And I don't get it why you are using form_for with @post.
Here is mine solution.
_feed.html.erb
<% if @feed.any? %>
    <% @feed.each do |feed| %>

            <%= form_tag confirm_post_path(feed), class: 'form-inline', method: :patch do |f| %>

                # form fields

                <%= submit_tag "Confirm", class: "btn-primary btn-xs form-control" %>

            <% end %>

    <% end %>
<% end %>


text:
Q: How to fix version mis-matching for docker-compose Here is a very similar question. But the problem is that some people said that docker version is too old, some people said that docker version is not old enough. My question is that after I checked the version of my docker and docker-compose, I cannot find version 1.21 which is reported by the ERROR. Where can I find it?
I am trying to run Crystalnix/omaha-server.

I followed the steps:
$ sudo apt-get update
$ sudo apt-get install docker.io
$ sudo apt-get install python-paver python-pip
$ sudo pip install -U docker-compose
$ git clone https://github.com/Crystalnix/omaha-server.git
$ cd omaha-server
$ sudo paver up_local_dev_server

Then I received error:
docker-compose -f docker-compose.dev.yml -p dev up -d db
ERROR: client and server don't have same version (client : 1.21, server: 1.18)

From Srini Koganti's Answer, I found that the error may be caused by docker API version used by docker-compose being higher than that that of docker daemon listening to serve.

Then I check:
docker-compose --version
docker-compose version 1.13.0, build 1719ceb

Also:
docker version
Client version: 1.6.2
Client API version: 1.18
Go version (client): go1.2.1
Git commit (client): 7c8fca2
OS/Arch (client): linux/amd64

I can found the version 1.21 nowhere, so what is the cause of this problem? And how to fix it?

A: You have to upgrade your Docker version, since you have a really old version.
The easiest way to install last Docker Engine version is using official installation script of Docker.
To do this, you only have to execute this command, which will retrieve and execute the script.
wget -qO- https://get.docker.com/ | sh


text:
Q: writing unmanaged DLL consumable by C#/.NET code I need to implement a small part of my application logic in native code.
To test PInvoke capabilities I created a simple solution with an unmanaged C++ Win32 Dll and a WPF project that consumes the dll functions using PInvoke.
The problem I run into is that i receive exception about "unbalancing the stack" and "possible signature mismatch"
Here is my code:
1) C++ (dll)
#include <stdio.h>
#include <Windows.h>

extern "C"
{
    __declspec(dllexport) int add(int a, int b)
    {
        return a+b;
    }
}

2) C#:
public partial class MainWindow : Window

{
    [DllImport("MyLibrary.dll")]
    static extern int add(int a, int b);
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnVersion_Click(object sender, RoutedEventArgs e)
        {

            var res = add(3,2);
        }
    }

The code throws an exception stating "This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature."
Where is my mistake?

A: solved :) it seems i forgot __stdcall keyword in c++ function definition It should have been: __declspec(dllexport) int __stdcall add(int a, int b)

A: Try this signature for the unmanaged function:
extern "C" __declspec(dllexport) int add(int a, int b)

THe issue was to do with C++ name mangling. Without extern "C" the name gets mangled and the C# DLL cannot find it.


text:
Q: Colors look different from device to simulator I have this UIWebView that reads from an HTML file with this style:
<style type="text/css">
    body {
        padding: 0 10px 0 10px;
        background-image: linear-gradient(bottom, rgb(9,57,48) 0%, rgb(54,97,71) 0%, rgb(120,169,118) 80%);
        background-image: -o-linear-gradient(bottom, rgb(9,57,48) 0%, rgb(54,97,71) 0%, rgb(120,169,118) 80%);
        background-image: -moz-linear-gradient(bottom, rgb(9,57,48) 0%, rgb(54,97,71) 0%, rgb(120,169,118) 80%);
        background-image: -webkit-linear-gradient(bottom, rgb(9,57,48) 0%, rgb(54,97,71) 0%, rgb(120,169,118) 80%);
        background-image: -ms-linear-gradient(bottom, rgb(9,57,48) 0%, rgb(54,97,71) 0%, rgb(120,169,118) 80%);

        background-image: -webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0, rgb(9,57,48)),
        color-stop(0, rgb(54,97,71)),
        color-stop(0.8, rgb(120,169,118))
        );
    }
</style>

when i'm running it on the iPhone Simulator everything goes well and it looks like that:

the problem is when i'm running it on the device, it looks like that (check the buttom of the image):

How can make this blurry white end to disappear?

A: Change your white color stop to be at 100% (1.0) for your gradients.


text:
Q: complete form validation in php I have this php code associated with a database and I need here to make a complete email and name validation
based on this code how can I do that because my code has some issues here
1)name key doesn't have (//) or any symbols to be a correct name
2)email key is valid email because what we did here just make ensure that there is @ symbol and if I type the email hhhh@hhh.com or even without( .com ) it will be valid also ?!!
if(array_key_exists("submit",$_POST)){
  $link = mysqli_connect("localhost","root","123456789","users");

  if(mysqli_connect_error()){
    die("There is a problem in connecting to database");
  }

  if(!$_POST['name']){
    $error .="
Your Full name is required

";
  }

  if(!$_POST['email']){
    $error .="
Your email address is required

";
  }

  if(!$_POST['password']){
    $error .="
Your password is required

";
  }

  if($error !=""){
    $error = "
There were errors in your form

".$error;
  }
}

A: You can use this function for the validation:
 function filtervariable($string,$type,$method) {
    //function for sanitizing variables using PHPs built-in filter methods
    $validEmail = false;

    if ($method == 'sanitize') {
        $filtermethod = 'FILTER_SANITIZE_';
    } elseif ($method == 'validate') {
        $filtermethod = 'FILTER_VALIDATE_';
    } else {
        return;
    }
    switch ($type) {
        case 'email':
        case 'string':
        case 'number_int':
        case 'int':
        case 'special_chars':
        case 'url':
        $filtertype = $filtermethod.strtoupper($type);
        break;
    }

    if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
        list($local,$domain) = explode('@',$string);

        $localLength = strlen($local);
        $domainLength = strlen($domain);

        $checkLocal = explode('.',$domain);

        if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
            $validEmail = true;
        } else {
            $validEmail = false;
        }
    }
    if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
        return filter_var($string, constant($filtertype));
    } else {
        return false;
    }
}

And use it like this:
$email = filtervariable($registeremail,'email','validate');
It will return "true" on success and "false" on failure.


text:
Q: Question about enumitem, suspend/resume enumeration, last item of list, nested list How do I suspend / resume an item of a list, multiple levels, if it is the last item of the list?
\documentclass{article}

\usepackage{enumitem}

\begin{document}
\begin{enumerate}
    \item first level
    \begin{enumerate}
        \item second level
        \begin{enumerate}
            \item third level
            \begin{enumerate}
                \item fourth level

                Text outside of enumerate
            \end{enumerate}
        \end{enumerate}
    \end{enumerate}
\end{enumerate}
\end{document}

Specifically, how do I move "Text outside of enumerate" outside one level (equal to the third level), outside two levels (equal to the second level), outside three levels (equal to the first level)?
I am unable to simply enclose "Text outside of enumerate" inside a \end{enumerate} and \begin{enumerate}[resume] because there are issues with starting an enumerate environment and then immediately ending it without any items.
I have also investigated the usage of \item[]. If I try using it at the end of the list, it appears a blank vertical line is produced, similar to \phantom but with a vertical blank line.

A: I am not sure if this is what you want:
\documentclass{article}

\usepackage{enumitem}

\begin{document}

\begin{enumerate}
    \item first level
    \begin{enumerate}
        \item second level
        \begin{enumerate}
            \item third level

            \begin{enumerate}
                \item fourth level

               \hspace*{\dimexpr-\leftmargini+\labelsep-\labelwidth\relax}
 Text outside of enumerate

               \hspace*{\dimexpr-\leftmargini-\leftmarginii+\labelsep-\labelwidth\relax}
Text outside of enumerate

               \hspace*{\dimexpr-\leftmargini-\leftmarginii-\leftmarginiii+\labelsep-\labelwidth\relax}
Text outside of enumerate
            \end{enumerate}
        \end{enumerate}
    \end{enumerate}
\end{enumerate}

\end{document}

A: Perhaps I am misunderstanding the requirements, but can't you just move the text outside of the enumerate environment:

Notes:

*

*I added \setlist[enumerate]{align=left} to make it clearer that the text is aligned with the label.

Code:
\documentclass{article}

\usepackage{enumitem}
\setlist[enumerate]{align=left}%

\begin{document}
\begin{enumerate}
    \item first level
    \begin{enumerate}
        \item second level
        \begin{enumerate}
            \item third level
            \begin{enumerate}
                \item fourth level
            \end{enumerate}
             Text outside of enumerate
        \end{enumerate}
        Text outside of enumerate
    \end{enumerate}
    Text outside of enumerate
\end{enumerate}
\end{document}

A: your question is difficult to understand. if you like to the sentence in your example out of enumeration, than just put this sentence after enumeration.
in case, that this sentence is somewhere middle of enumeration in like to have, that after it enumeration continue to with enumeration, then for such a task is useful package mdwlist:
\documentclass{article}
\usepackage{mdwlist}

    \begin{document}
\begin{enumerate}
    \item first item
    \item second item
    \item third item
    \suspend{enumerate}
Text outside of enumerate
    \resume{enumerate}
    \item fourth item
    \item fifth item
    \end{enumerate}
\end{enumerate}
    \end{document}

on above principle you can suspend enumerate list inside of an enumeration.


text:
Q: Google map | jQuery | Zoom level produces error I have created a Google Map Object in my page and I want to change the Google map zoom level by entering the zoom level in a text box.
The code I use is the following:
var zoom = parseInt($('#gm_zoom').val(), 10);
map.setZoom(zoom);

Where #gm_zoom is the text input where I enter the zoom level and map is my Google Map Object.
Do you see anything wrong in this code? When I de-comment this portion of code I get the following in my Chrome console:
<error>
    Vd
    Q.trigger
    Af
    H.set
    (anonymous function)
    Af
    (anonymous function)
    Q.trigger
    Af
    (anonymous function)
    Q.trigger
    Af
    H.set
    ...
    (repeated many times)
    ...
    (anonymous function)
    gmap_build_sc
    manage_events
    Q.trigger
    Af
    H.set
    (anonymous function)

Any idea on how to solve that issue ?
Note : In the same function I try to update the zoom level I also change the map type, latitude, and longitude with no error. Only the above code produces the problem!


text:
Q: Sort and number rows by fields I have my data.frame:
name  session_start
Mike  100
Mike  50
York  300
Mike  200
York  100

I need to number rows by name and ascending session_start column, like this:
name  session_start  number
Mike    50            1
Mike    100           2
Mike    200           3
York    100           1
York    300           2

P.S sorry for  my english

A: We can sort df with order first and then create new column with ave:
df <- df[order(df$name, df$session_start), ]

df$number <- ave(df$session_start, df$name, FUN = rank)

# > df
#   name session_start number
# 2 Mike            50      1
# 1 Mike           100      2
# 4 Mike           200      3
# 5 York           100      1
# 3 York           300      2

A: Dummy solution using data.table
library(data.table)
# Example data
d <- data.table(name = c("Mike", "Mike", "York", "Mike", "York"),
                session_start = c(100, 50, 300, 200, 100))
# Solution
d[, number := order(session_start), name]


text:
Q: Unreachable Statement in Java I am working in BlueJ for my university course, and I have been set a basic assignment where we need the user to input certain information about a DVD, such as director, name, running time, etc.
I am coding in Java, and used Genio too. The following code is how I got and set the information within the variables;
 public void getDVDInfo() {
    //Ask for info
    System.out.println("Please Enter the Film Info:");
    System.out.println("Film Name: ");
    System.out.println("Film Director: ");
    System.out.println("Lead Actor/Actress: ");
    System.out.println("Running Time: ");
}

public void setDVDInfo() {
    //set user input to variables
    filmName = Genio.getString();
    director = Genio.getString();
    leadActor = Genio.getString();
    runTime = Genio.getInteger();
}

This all works according to the compiler I used within BlueJ, but when i coded the function to return the information to the user, like so;
  public String seeDVDInfo() {
    return filmName;
    return director;
    return leadActor;
}

public int seeRunTime() {
    return runTime;
}

it came up with a compiler error at return director; that is was an unreachable statement. i don't understand where this is coming from, it all looks right, can anyone help me?
Thanks in advance xx

A: Problem is here:
public String seeDVDInfo() {
    return filmName;
    return director;
    return leadActor;
}

*

*You cannot have multiple return statements in a method in Java.

*Once you return filmName;, there is no way for other statements to execute, so it is throwing Unreachable Statement error.

See this thread to know why Unreachable Statement is an error in Java.

A: If, this, is really the method in your code:
public String seeDVDInfo() {
    return filmName;
    return director;
    return leadActor;
}

Then, the problem is that a method is finished with the a return statement. It will exit the method with the provided value.
You have different ways to solve the issue, depending on the information you want to provide/use:
 public String seeDirector() {
     return director;
 }
 public String seeFilmName() {
     return director;
 }
 public String leadActor() {
     return director;
 }

Taking into account that java is an OOP language, I would suggest creating a class Film that contains/ encapsulates this info that can be returned. So actually it will look something like this:
public class Film {
    private String director;
    private String filmName;
    private String leadActor;

    public Film(String director, String filmName, String leadActor) {
        this.director = director;
        this.filmName = filmName;
        this.leadActor = leadActor;
    }

    public String getFilmName() {
         return filmName;
    }

    public void setFilmName(String filmName) {
         this.filmName = filmName;
    }

    public String getDirector() {
         return director;
    }

    public void setDirector(String director) {
         this.director = director;
    }
    public String getLeadActor() {
         return leadActor;
    }

    public void setLeadActor(String leadActor) {
         this.leadActor = leadActor;
    }
}

A: You have an error - the first return code will run and return the value of filmName, quitting the method, so other return calls cannot be reached.
A method can only return one object. You can use a complex object to hold some data and return it.
I suggest you create DvdInfo class:
public class DvdInfo {
    String filmName;
    String director;
    String leadActor;
// getters & setters...
}

And use it as the return type:
public DvdInfoseeDVDInfo() {
    new DvdInfo(filmName, director, leadActor);
}

A: The first statement in the seeDVDInfo method 'return filmName' returns the filmName variable and exits the seeDVDInfo method... Thus, the other 2 statements will never be run. Therefore, return director and return leadActor are 'unreachable'....
public String seeDVDInfo() {
    return filmName;
    return director;
    return leadActor;
}

From the Java Tutorials:
A method returns to the code that invoked it when it completes all the statements in the method, reaches a return statement, or throws an exception (covered later), whichever occurs first.

http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

A: This is because once you return from the method , whatever code left after return statement will be unreachable , so it won't compile.
Here, i will try to explain you with 3 scenarios.
Scenario 1:
For the Code,
public void helloWorld() {
  System.out.println("Hello");
  return;
  System.out.println("World");
 }

The Prited Line which marked as bold letter won't compile.
Scenario 2:
public void helloWorld() {
   System.out.println("Hello");
 if(true) {
      return;
  }
   System.out.println("World");
}

This Compiles Successfully.
The most general logic in these rules are, code surrounded by a block is unreachable if the conditional expression deciding it evaluates to false and then the block is decided as unreachable. Then it becomes an error.
Only for 'if' construct the rule is different. The conditional expression is not evaluated and decided. Whatever may be the expression inside the if condition, it is not evaluated to decide if the code block is reachable and so we will not get error even if we have a constant value 'false' as conditional expression in if statement. This is treated special to give a facility for the developer. Developers can use a flag variable in the if statement with default final values as false or true. Just by changing the flag variable from false to true or vice-versa developers can recompile the program and use it differently.
Scenario 3:
public void helloWorld() {
   System.out.println("HelloWorld");
 while(true) {
      return;
  }
  System.out.println("World");
}

This Gives Unreachable Exception Compilation Error, as explained above.

A: You cannot have multiple returns in one method, this is why next row after return is unreachable
  public String seeDVDInfo() {
    return filmName;
    //return director;
    //return leadActor;
}

A: Your're trying to return three Strings -> that fails.
Use this instead:
public List<String> seeDVDInfo() {
    List<String> dvdInfos = new ArrayList<>();
    dvdInfos.add(filmName);
    dvdInfos.add(director);
    dvdInfos.add(leadActor);
    return dvdInfos;
}


text:
Q: How to bind into a dropdown values from a json item Im a having a long night here
The result of the webservice is in json. However data returned comes with diagnosic data.
How do I get the result set only?
Here is my code:
http://jsfiddle.net/bkyg23cx/

$(document).ready(function ()
{
    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://website.com",
        data: data,
        dataType: "json",
        success: function (data)
        {
            alert('Total results found: ' + data.result.total);
            $.each(data.result.records, function (value)
            {
                $("[id$='uxRegion']").append($("<option></option>").val(value.province).html(value.province));
            });
        }
        error: function ajaxError(response)
        {
            alert(response.status + ' ' + response.statusText);
        }
    });
});

Here is the problematic json value

{
  "value1": "etetetetete",
  "value2": true,
  "result": {
    "records": [
      {
        "province": "Star world"
      },
      {
        "province": "CNN"
      }
    ],
    "fields": [
      {
        "type": "text",
        "id": "province"
      }
    ],
    "hash": "hash value"
  }
}

A: You can set data.result.records as a local variable records, just like below:
success: function (data) {
    var records = data.result.records;

    alert('Total results found: ' + records.length);

    $.each(records, function (value) {
        $("[id$='uxRegion']").append($("<option></option>")
                             .val(value.province)
                             .html(value.province));
    });
}

And You don't have total property on result object, you should use .length.


text:
Q: Why am I getting a syntax error in MySQL when I used Group By? Why am I getting an error on the last line?
SELECT
    *
FROM
    datawarehouse.shipments
WHERE
    ControlBranch = 'SFO'
        AND ShipmentCreateDateUTC >= '2020-03-01'

ORDER BY id DESC
GROUP BY ShipmentNumber;

What I'm trying to accomplish is order by id Desc, Group by ShipmentNumber, and then pull all the fields.

A: Well, first of all the query won't work because you are grouping something, and then showing everything with an * syntax. You need to show the column that you are grouping and then use aggregating functions with the rest (SUM, COUNT, AVG, etc) so it shows the value grouped.
After that, you need to check the instruction order that SQL Server uses. The Order by goes always at the end of the instructions. So, the correct order of your query is like this:
SELECT id, COUNT(*) -- The count is an example
FROM datawarehouse.shipments
WHERE
    ControlBranch = 'SFO'
    AND ShipmentCreateDateUTC >= '2020-03-01'
GROUP BY ShipmentNumber
ORDER BY id DESC;

Also, even if it's not relevant, you can have a better understanding of how the engine works behind the curtain (the order of execution) checking this link:
https://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/


text:
Q: Click will a) scroll to div, b) open said div and c) load html from another page into that div. How? I already have the "scroll to" and toggle functions in place:
$("a.view").click(function(){
    $("#content").slideToggle("slow");
    return false;
});

And the scrolling is taken care of via this handy little plugin.
Now how do I load some html from another page into this newly opened div called #content. I've tried a few things here and there but just can't seem to get it to work.
Any ideas please?

A: Pretty trivial using jQuery.
$('#content').load('path/file.html', function() {
   // done
});

You may also "partial" load data, for instance
$('#content').load('path/file.html #container', function() {
   // done
});

will only load the element with the id `#container' out of file.html.
Ref.: .load()


text:
Q: Author_name not showing up in Django syndication rss feed I have a Django-based site. It has a feed which uses the django syndication framework). Although I've specified author_name in the feed's definition, no author appears in the feed itself. An author is required to submit the feed to all the directories I've checked with.
My feeds.py looks like this:
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Rss201rev2Feed

from Audits.models import Audit
from django.urls import reverse

class SubscriptionFeed(Feed):
    feed_type = Rss201rev2Feed
    title = "Audio feed title"
    link = "/listen/"
    description = "A description of the audio feed."

    author_name = "Example feed author"
    author_email = "example@gmail.com"

    def items(self):
        return Audits.objects.all().filter(published=True).exclude(audio_file='').order_by('-year_integer', '-month_integer')

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.abstract

    def item_link(self, item):
        return reverse('Podcast-Pages', args=[item.pk])

    def item_author_name(self, item):
        return "Example Item Author"

A: The specification for RSS2.0 on http://www.rssboard.org/rss-specification doesn't list author as required nor optional attribute of the feed -- only for items.
The source of the Rss201rev2Feed doesn't implement the feed author either, but the Atom1Feed does!
You can either use feed_type = Atom1Feed in your feed definition, or add an author attribute on your custom feed type:
class iTunesFeed(Rss201rev2Feed):
    def add_root_elements(self, handler):
        super().add_root_elements(handler)
        if self.feed['author_name'] is not None:
            handler.startElement("author", {})
            handler.addQuickElement("name", self.feed['author_name'])
            if self.feed['author_email'] is not None:
                handler.addQuickElement("email", self.feed['author_email'])
            if self.feed['author_link'] is not None:
                handler.addQuickElement("uri", self.feed['author_link'])
            handler.endElement("author")


text:
Q: Error C2011: 'XX' : 'class' type redefinition I have this compiler error (C2011) with this piece of code. I don't know what is wrong with it.
The namespace (Ogre) doesn't have a definition for PlaneMovement. I also tried a different name and still the same errors.
#include <Ogre.h>

using namespace Ogre;

class PlaneMovement
{
public:
    PlaneMovement(Degree startingAngle, Real velocity = 2, Real gravity = 2);
    Vector2 updateMovement(const FrameEvent& evt);
private:
    Degree currentAngle;
    Real currentVelocityX;
    Real currentVelocityY;
    Real gravity;
    bool top;
};

A: Include guards:
#ifndef FILE_H
#define FILE_H

//file contents here

#endif

Header files should have include guards for this exact reason - multiple inclusion in the same translation unit can lead to a multiple definition.
The alternative is using
#pragma once

but this isn't supported by all compilers.

A: If someone else faces this situation, it may be when library includes in property of project and header files from this library include in projects file.

A: Incorrect Forward Declaration
Another possible cause, if you're a goof like me, could be that you used enum instead of class when forward declaring a class.
File1.h
namespace MyNamespace { enum NotActuallyAnEnum; }

File2.h
class NotActuallyAnEnum

{
...
}

This will produce something like the following error:
error C2011: 'enum' type redefinition

Obviously the fix is to correct the forward declaration:
namespace MyNamespace { class NotActuallyAnEnum; }

A: You might also get this error if you have multiple branches of your project on your development station and use a symlink to point to one of them.
Let's suppose you have two different branches of your solution called Project1 and Project2 and you let a symlink called Project point to either Project1 or Project2.
The idea is that you could switch between branches and the project would always appear to be Project to your application and possibly some other tools that expect it there.
Disclaimer: yes, version control can switch between branches, but this way you will not have to rebuild the whole application every single time you switch branches. Besides both branches can still be under version control.
Okay, so opening Project would open either Project1 or Project2 depending on the symlink. The symlink could be removed/created by some simple mklink_1 and mklink_2 like script files.
Here comes the pitfall:
If you don't pay attention and directly open the solution at location 1 or 2 directly (instead of following the directory symlink with Visual Studio), the pre-processor might be tricked into mixing Project1\MyHeader.h (or MyProject2\MyHeader.h) with MyProject\MyHeader.h!
Even those are technically the same file, the preprocessor doesn't know about the symlink. So here the #pragma once would not save you!


text:
Q: Encoding conversion of a fetch response Inside a React Native method I'm fetching a xml encoded in ISO-8859-1.
As long as the fetching is completed I'm trying to convert it to UTF-8.
Here the code:
const iconv = require('iconv-lite');

fetch('http://www.band.uol.com.br/rss/colunista_64.xml', {
      headers: {
        "Content-type": "text/xml; charset=ISO-8859-1"
      }
})
.then(res=>res.text()})
.then(text => {
   const decodedText = iconv.decode(Buffer.from(text, 'latin1'), 'latin1')
  , output = iconv.encode(decodedText, 'utf8')
   console.log(output.toString())
})

The problem is: all especial characters of the body is being replaced by "¿½"
For the conversion, I'm using the package iconv-lite
What is the better workaround for this problem?

A: The best workaround is to use res.arrayBuffer() instead res.text(), as long the Buffer constructor accepts ArrayBuffer
The code:
fetch('http://www.band.uol.com.br/rss/colunista_64.xml')
      .then(res => res.arrayBuffer())
      .then(arrayBuffer => iconv.decode(new Buffer(arrayBuffer), 'iso-8859-1').toString())
      .then(converted => console.log(converted))

A: As pointed out by Hellon Canella Machado you can't use res.text() and must use an ArrayBuffer as a workaround.
Since res.arrayBuffer() doesn't work with fetch in React Native you can use the XMLHttpRequest API.
import iconv from 'iconv-lite';
import { Buffer } from 'buffer';

function fetchXML() {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();

    request.onload = () => {
      if (request.status === 200) {
        resolve(iconv.decode(Buffer.from(request.response), 'iso-8859-1'));
      } else {
        reject(new Error(request.statusText));
      }
    };
    request.onerror = () => reject(new Error(request.statusText));
    request.responseType = 'arraybuffer';

    request.open('GET', 'http://www.band.uol.com.br/rss/colunista_64.xml');
    request.setRequestHeader('Content-type', 'text/xml; charset=ISO-8859-1');
    request.send();
  });
}

fetchXML().then(response =>
    console.log(response)
);

Also make sure that you have the packages buffer and stream installed.

A: let axiosConfig = {
    responseType: 'arraybuffer',
    responseEncoding: 'binary',
  }

const htmlPage = await axios.get(`http://www.band.uol.com.br/rss/colunista_64.xml`, axiosConfig);
const decoder = new TextDecoder('iso-8859-1');
decoder.decode(pageHtml.data)

A: The solution is actually rather simple. Just use axios instead of fetch. Axios  works out of the box in react native, without any special dependencies. It converts the encoding of a response to UTF-8 automatically for each request by default without any configuration.
npm install axios

Example:
import axios from 'axios';

let response = await axios.get(url);
console.log(response);

Thats it! The response.data is auto converted to UTF-8 from whichever encoding the archaic site uses.


text:
Q: Ruby does not detect after installing using RVM My configurations
Ubuntu 14.04 amd64
I followed this tutorial to install Ruby

*

*Successfully installed ruby.

*Closed the Terminal.

*Checking

ruby -v

shows

The program 'ruby' can be found in the following packages:
 * ruby
 * ruby1.8
Try: sudo apt-get install <selected package>

4.Runs the command

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"

from the tutorial and then check with ruby -v and it works !!( Shows the version )
5.I tried a many times by closing the terminal and typing ruby -v command every time it shows ruby is not installed and typed the same command from the tutorial then it detect the ruby.
How can avoid this ?

A: The instructions on making rvm work in gnome-terminal can be found here, quoting the instructions:

For RVM to work properly, you have to set the 'Run command as login
  shell' checkbox on the Title and Command tab inside of
  gnome-terminal's Settings page


text:
Q: Chisel code showing wrong output This is the code for byte selector
class Comp extends Module {
val io = IO(new Bundle {
val in = Input(UInt(25.W))
val out = Output(UInt(25.W))
val i = Input(UInt(4.W))
val out0   = Output(UInt(5.W))
val out1   = Output(UInt(5.W))

})

val r8 = Wire(UInt(5.W))
io.out := Reverse(io.in)
for (i <- 0 to 20 by 5)

{

io.out0 := io.out (i+4, i)

when(io.out0 === 31.U) {
r8 := 0.U
}.elsewhen(io.out0 === 0.U) {
    r8 := 31.U
}.elsewhen(io.out0 === 17.U) {
    r8 := 14.U
}.elsewhen(io.out0 === 14.U) {
    r8 := 17.U
}.otherwise {
    r8 := 27.U
}

io.out1 := r8
}

This only selects the byte 20 to 24 i.e. when i = 20 and not the rest of the bytes. Everytime I get the output as 27 which is when the for loop selects the most significant 5 bits. Can somebody help?

A: The scala for loop is like GENERATE in VHDL, you have to see it as a multiple declaration of :
io.out0 := io.out (i+4, i)

You can see it as following code :
io.out0 := io.out (4, 0)
io.out0 := io.out (8, 5)
io.out0 := io.out (14, 10)
io.out0 := io.out (18, 15)
io.out0 := io.out (24, 20)

The symbol ':=' is a connection between signal. Each line of above code is seen as new connection erasing the old connection.
Then only the last connection will be really used.
To do the connections as you want, you have to change (I think) the declaration of io.out and use an index like following:
for ( i <- 0 to 20 by 5)
{
io.out(i) := io.out (i+4, i)
}

With io.out declared as a Vector (Vec())


text:
Q: Ошибка при выполнении cmake Я запускаю команду:
sudo cmake --build . --target test-lite-client

Сборка доходит до 33%, после чего завершается ошибкой:
    /home/name/lite-client/tdutils/td/utils/tests.cpp: In member function 'virtual td::Status td::RegressionTesterImpl::verify_test(td::Slice, td::Slice)':
/home/name/lite-client/tdutils/td/utils/tests.cpp:39:72: error: 'sha256' was not declared in this scope
     auto hash = PSTRING() << format::as_hex_dump<0>(Slice(sha256(result)));
                                                                        ^
make[3]: *** [tdutils/CMakeFiles/tdutils.dir/build.make:739: tdutils/CMakeFiles/tdutils.dir/td/utils/tests.cpp.o] Error 1
make[2]: *** [CMakeFiles/Makefile2:1944: tdutils/CMakeFiles/tdutils.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:107: CMakeFiles/test-lite-client.dir/rule] Error 2
make: *** [Makefile:164: test-lite-client] Error 2

Вот начальное содержимое файла tests.cpp (последняя строка - проблемная):
#include "td/utils/tests.h"

#include "td/utils/base64.h"
#include "td/utils/crypto.h"
#include "td/utils/filesystem.h"
#include "td/utils/Parser.h"
#include "td/utils/PathView.h"
#include "td/utils/port/path.h"

namespace td {
struct TestInfo {
  string name;
  string result_hash;  // base64
};
StringBuilder &operator<<(StringBuilder &sb, const TestInfo &info) {
  // should I use JSON?
  CHECK(!info.name.empty());
  CHECK(!info.result_hash.empty());
  return sb << info.name << " " << info.result_hash << "\n";
}

class RegressionTesterImpl : public RegressionTester {
 public:
  static void destroy(CSlice db_path) {
    unlink(db_path).ignore();
  }

  explicit RegressionTesterImpl(string db_path, string db_cache_dir) : db_path_(db_path), db_cache_dir_(db_cache_dir) {
    load_db(db_path);
    if (db_cache_dir_.empty()) {
      db_cache_dir_ = PathView(db_path).without_extension().str() + ".cache/";
    }
    mkdir(db_cache_dir_).ensure();
  }

  Status verify_test(Slice name, Slice result) override {
    auto hash = PSTRING() << format::as_hex_dump<0>(Slice(sha256(result)));

Как это можно решить?

A: попробуй
sudo apt install zlib1g-dev


text:
Q: How can I transfer [content] from one page to another? There is a link on the page of the MODx site. By clicking on this link I turn to another page. Want to transfer all [content] from the first page to a new page and display it. Thank you.

A: Which version of MODx are you using? Evolution or Revolution? Also a link to page you are  referring to would help.
In MODx manager if you right click on a resource (page) there is an option to create a duplicate page. You can link to this copy from the first page.
However I suspect this isn't what you're asking so more details please if you need a better response.

A: Try adding [content] to a template and using the template in all pages you create.


text:
Q: Необходимо написать функцию date_range, которая возвращает список дат за определенный период период Необходимо написать функцию date_range, которая возвращает список дат за период от start_date до end_date. Даты должны вводиться в формате YYYY-MM-DD. В случае неверного формата или при start_date > end_date должен возвращаться пустой список.
На данный момент написать код:
from datetime import datetime, timedelta

start_date=input('Введите начальную дату в формате YYYY-MM-DD: ')
end_date=input('Введите дату окончания в формате YYYY-MM-DD: ')
def date_range():
    start_dt=datetime.strptime(start_date,'%Y-%m-%d')
    end_dt=datetime.strptime(end_date,'%Y-%m-%d')
    days=[]
    while start_dt<=end_dt:
        start_dt+=timedelta(days=1)
        print_datetime=datetime.strftime(start_dt,'%Y-%m-%d')
        days.append(print_datetime)
        #print(print_datetime)
    return(days)
date_range()

Введите начальную дату в формате YYYY-MM-DD: 2018-01-01
Введите дату окончания в формате YYYY-MM-DD: 2018-01-04

Данный код возвращает следующее:
['2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05']

Подскажите логику и как изменить, чтобы стартовая и конечная даты попали в список, спасибо.


text:
Q: Tape Drive Backups Not sure if this falls in the ServerFault category, but I need to spec up a Tape Drive Backup Machine and I am not sure in regards of the technology and how Dat Drives are compared. Can someone give me some hints? What is considered to be a good backup machines and what sort of specs should it have to be considered sufficient?

A: DAT currently maxes out at 320GB, has been there for ~3 years. It doesn't seem like anyone id developting new drives or capacities.
LTO currently maxes out at 2500GB, and 6400 & 12800GB models are on their way (at speeds of 160, 315, and 472 MB/s respectively).
I can't imagine why anyone would buy a DAT drive these days, the capacity and speed is horrible compared to the alternatives. Cloud based backup solutions would likely be cheaper per the benefit.
As for the rest of the backup server, any modern server from a reputable name would be sufficient to make the tape drive the bottleneck. For example, a HP ML350 with an Ultrium 448 Internal SAS (LTO-6 drive) could be had for $3500
Depending on your exact needs this could be higher, I really don't know enough about your situation to give an accurate price, this is pretty much a realistic minimum). Contact a local consultant or an HP reseller for a better quote. HP ReNew equipment is cheaper too...


text:
Q: Percentage of total changes on applying filter I have a data table with three dimensions and one measure. For each row, I am trying to calculate the percentage of total (calculated by taking the sum of rows) using a calculated field.
As seen in the screenshot attached, For the column titles 'Dec-19' I want the values to be a percentage of current value / grand total (calculated at the bottom as 122,187)
Screenshot of DataTable:

So e.g. for the Column B value of 2000, the Dec-19 column should be (97/122,187) * 100 = 0.079.
I have achieved this by creating a calculated field with the formula: SUM (sales) / MAX ({EXCLUDE (Column B): Sum (sales}), where sales is the measure used in the datatable.
However, upon application of filter on column B, the percentage value changes. e.g. if I select the value 2000 in my filter for column B, I get the percentage as 100%. It seems as if the percentage is being calculated based on only the rows in the filter.

A: Since you haven't included any sample data, I created some sample data like this, hope this resemble yours.

Thereafter, I built a cross-tab view in tableau, somewhat like yours

If that is the scenario, use a calculated field, say CF like this, instead of yours
([Sales])/
{FIXED [Col1], DATETRUNC('month', [Col3]) : sum([Sales])}

Dragging it in the view

and thus, filtering won't affect your calculation


text:
Q: Windows message with 0x3B code While logging off in Windows XP the system is sending the message with code 0x3B to the main window of the application. It was received together with 0x11 WM_QUERYENDSESSION message. Here is the log of incoming messages for WndProc:
Message processing: Id = 0x3B, wParam = -2147483637, lParam = 0, result = 0
Message processing: Id = 0x11, wParam = 0, lParam = -2147483648, result = 0
Form closing event handler. Reason:WindowsShutDown
Message processed: Id = 0x11, wParam = 0, lParam = -2147483648, result = 1
Message processed: Id = 0x3B, wParam = -2147483637, lParam = 0, result = 1
Message processing: Id = 0x3B, wParam = -2147483639, lParam = 0, result = 0
Message processing: Id = 0x16, wParam = 1, lParam = -2147483648, result = 0
Form closed event handler. Reason:WindowsShutDown
Message processing: Id = 0x46, wParam = 0, lParam = 1239312, result = 0
Message processed: Id = 0x46, wParam = 0, lParam = 1239312, result = 0
Message processing: Id = 0x47, wParam = 0, lParam = 1239312, result = 0
Message processed: Id = 0x47, wParam = 0, lParam = 1239312, result = 0
Message processing: Id = 0x86, wParam = 0, lParam = 0, result = 0
Message processing: Id = 0x7F, wParam = 2, lParam = 0, result = 0
Message processed: Id = 0x7F, wParam = 2, lParam = 0, result = 852077
Message processing: Id = 0x7F, wParam = 2, lParam = 0, result = 0
Message processed: Id = 0x7F, wParam = 2, lParam = 0, result = 852077
Message processed: Id = 0x86, wParam = 0, lParam = 0, result = 1
Message processing: Id = 0x6, wParam = 0, lParam = 0, result = 0
Message processed: Id = 0x6, wParam = 0, lParam = 0, result = 0
Message processing: Id = 0x1C, wParam = 0, lParam = 2620, result = 0
Message processed: Id = 0x1C, wParam = 0, lParam = 2620, result = 0
Message processing: Id = 0x8, wParam = 0, lParam = 0, result = 0
Message processed: Id = 0x8, wParam = 0, lParam = 0, result = 0
Message processing: Id = 0x2, wParam = 0, lParam = 0, result = 0
Message processed: Id = 0x2, wParam = 0, lParam = 0, result = 0
Message processing: Id = 0x82, wParam = 0, lParam = 0, result = 0
Message processed: Id = 0x82, wParam = 0, lParam = 0, result = 0
My application has a bug in Windows XP during logging off. It doesn't close. And the reason is:
Message processed: Id = 0x3B, wParam = -2147483637, lParam = 0, result = <b>3</b>

instead of 1
Any ideas what does this message mean? And why is it processed incorrectly?

A: My Google-fu reveals this to be an undocumented message - WM_CLIENTSHUTDOWN.  This may be of interest, but all it does is send WM_QUERYENDSESSION / WM_ENDSESSION to the window and its children.  The return value of 3 (MCSR_DONOTSHUTDOWN) indicates that the window, or one of its children, is vetoing the request.


text:
Q: Subversive install in Eclipse not showing any option to commit or checkout
I am using ADT to develop Android application in Linux Mint. Because of the backup and restore of the source code I thought of using SVN in Eclipse, so I went to

Subversive - http://eclipse.svnkit.com/1.7.x through the "install new software" and install.

This shows me two option

Core SVNKit Library (required)
    Optional JNA Library (recommended)

Which I installed now I am confused how to checkout my code from my repository or commit my code to it. I don't see any option to do it.

A: Ok, SVNKit is the connector (client) to connect your SVN, with installing it you can checkout,commit or update your codes.
As far as i know JNA is a little library for native access to shared libraries to make things easier. From wiki:
Java Native Access provides Java programs easy access to native shared libraries
without using the Java Native Interface. JNA's design aims to provide native access in
a natural way with a minimum of effort. No boilerplate or generated glue code is
required.

So i think you should install both, but JNA is optional as FAQ says :)


text:
Q: Get count of rows based on criteria - date field in specific year, grouped by text field I have a excel report published daily which I need to summarize and provide the trend analysis. This report has list of work items with created date, work item type. How can I get count of work items created in 2011, 2012? Also, how do I get counts by work item type? So far I've been able to load the excel data and get number of rows by doing following -
library(gdata)
wi20121812 = read.xls("WorkItemReport20121812.xls")
nrow(wi20121812)

Sample Data
   > dput(head(workItemReport2))
structure(list(DocType = structure(c(6L, 7L, 6L, 6L, 8L, 6L), .Label = c("TYPE10WI",
"TYPE11WI", "TYPE12WI", "TYPE13WI", "TYPE14WI", "TYPE1WI", "TYPE2WI",
"TYPE3WI", "TYPE4WI", "TYPE5WI", "TYPE6WI", "TYPE7WI", "TYPE8WI",
"TYPE9WI"), class = "factor"), CreatedDate = structure(c(7L,
22L, 146L, 181L, 153L, 191L), .Label = c("1/10/12 15:43 AM/PM ",
"1/10/12 16:06 AM/PM ", "1/10/12 5:28 AM/PM ", "1/10/12 5:56 AM/PM ",
"1/11/12 19:51 AM/PM ", "1/11/12 5:26 AM/PM ", "1/12/11 21:58 AM/PM ",
"1/12/12 11:08 AM/PM ", "1/12/12 5:41 AM/PM ", "1/12/12 9:56 AM/PM ",
"1/13/12 14:01 AM/PM ", "1/13/12 15:08 AM/PM ", "1/13/12 15:11 AM/PM ",
"1/13/12 8:51 AM/PM ", "1/16/12 10:27 AM/PM ", "1/16/12 10:28 AM/PM ",
"1/16/12 16:37 AM/PM ", "1/16/12 7:52 AM/PM ", "1/18/12 15:02 AM/PM ",
"1/18/12 16:03 AM/PM ", "1/18/12 16:13 AM/PM ", "1/19/11 19:23 AM/PM ",
"1/20/12 10:48 AM/PM ", "1/20/12 12:23 AM/PM ", "1/20/12 8:38 AM/PM ",
"1/23/12 5:53 AM/PM ", "1/24/12 15:18 AM/PM ", "1/24/12 8:23 AM/PM ",
"1/24/12 8:58 AM/PM ", "1/25/12 11:38 AM/PM ", "1/25/12 5:28 AM/PM ",
"1/26/12 13:48 AM/PM ", "1/26/12 15:53 AM/PM ", "1/26/12 15:58 AM/PM ",
"1/26/12 16:13 AM/PM ", "1/26/12 16:18 AM/PM ", "1/26/12 7:33 AM/PM ",
"1/27/12 7:48 AM/PM ", "1/3/12 17:48 AM/PM ", "1/3/12 18:33 AM/PM ",
"1/3/12 9:07 AM/PM ", "1/30/12 11:22 AM/PM ", "1/30/12 22:52 AM/PM ",
"1/30/12 23:10 AM/PM ", "1/31/12 19:54 AM/PM ", "1/31/12 20:39 AM/PM ",
"1/31/12 5:42 AM/PM ", "1/31/12 9:42 AM/PM ", "1/4/12 14:02 AM/PM ",
"1/4/12 9:52 AM/PM ", "1/5/12 13:42 AM/PM ", "1/5/12 17:42 AM/PM ",
....
....
"9/6/12 9:02 AM/PM ", "9/7/12 11:48 AM/PM ", "9/7/12 12:58 AM/PM ",
"9/7/12 13:52 AM/PM ", "9/7/12 15:07 AM/PM ", "9/7/12 15:12 AM/PM ",
"9/7/12 15:22 AM/PM ", "9/7/12 15:47 AM/PM ", "9/7/12 15:52 AM/PM ",
"9/7/12 8:42 AM/PM ", "9/7/12 9:32 AM/PM ", "9/8/11 23:43 AM/PM "
), class = "factor")), .Names = c("DocType", "CreatedDate"), row.names = c(NA,
6L), class = "data.frame")
>

A: The one part of your question that remains unanswered, "how to get counts of work item types" is quite easy.
res <- table(wi20121812[, "WorkItemType"])

This will give you a simple table that tells you how often each WorkItemType occurred. If you need to have it in proportions, rather than absolute counts, run prop.table() on the result:
prop.table(res)

Or do it both at once:
res <- prop.table(table(wi20121812[, "WorkItemType"]))

A: You could use ddply from the plyr package:
res = ddply(df, "year", summarise, amount = length(year))

or use count form the same package (which is even easier):
res = count(df, "year")

where df is a data.frame containing your data, and year is the column name of the column  which contains the categorical variable detailing in which year that row was created.


text:
Q: Rewrite url with #params to query params with nginx I want to add a nginx rewrite rule which will change #params to query params.

ex :  from https://x.app.com/callback#x=1 to
  https://x.app.com/callback?x=1

A: That is not possible - the part with # and after are never sent to the web server (per HTTP specification), only the client (web browser) has access to it.
The only way of using the # part is client-side javascript, unfortunately - that is why I would recommend not using it.


text:
Q: Can't make successful connection to mysql database using java So the purpose of this database is to execute the queries needed for a website that will be accessing this, here is the code:
package dodRus;
//STEP 1. Import required packages
import java.sql.*;

public class Connect_Database {
 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/?user=root";

 //  Database credentials
 static final String USER = "root";
 static final String PASS = ;

 public static void main(String[] args) {
 Connection conn = null;
 Statement stmt = null;
 try{
    //STEP 2: Register JDBC driver
   Class.forName("com.mysql.jdbc.Driver");

    //STEP 3: Open a connection
   System.out.println("Connecting to database...");
   conn = DriverManager.getConnection(DB_URL,USER,PASS);

   //STEP 4: Execute a query
    System.out.println("Creating statement...");
    stmt = conn.createStatement();
    String sql;
    sql = "INSERT INTO Inventory " + "VALUES (shirt,1234,5)";
    stmt.executeUpdate(sql);

 }catch(SQLException se){
    //Handle errors for JDBC
    se.printStackTrace();
 }catch(Exception e){
//Handle errors for Class.forName
    e.printStackTrace();
 }finally{
    //finally block used to close resources
    try{
       if(stmt!=null)
          stmt.close();
    }catch(SQLException se2){
    }// nothing we can do
    try{
       if(conn!=null)
          conn.close();
    }catch(SQLException se){
       se.printStackTrace();
    }//end finally try
  }//end try

}
 }

and here is the error:

java.sql.SQLException: No database selected
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3020)
    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1074)
    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1008)
    at dodRus.Connect_Database.main(Connect_Database.java:30)

Obviously it is not making a successful connection to the database but I can't figure out why

A: You need to include the database name in your DSN string.
static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/<name_of_database>?user=" + USER + "&password=" + PASS;

See the Connector/J documentation.


text:
Q: Record video with HTML input type file capture camcorder from webcam In my company, i had the task to build a website, where users can record a video,
that will be send to the server, some stuff will be done and the user finally gets an email with
a link to a microsite with that video embedded.
After some research, i came to the conclusion, that it is impossible, at least at the moment,
to capture a video with getUserMedia on iPad.
So the solution is quite simple, i just use a input-element with accept="video/*;capture=camcorder".
<input type="file" accept="video/*;capture=camcorder">

So far, so good. As I've read on this page, that it is also possible to capture a video from webcam with this technique, i thought that it is an adequat cross-browser solution.
But after some testing, i can just select an already recorded video on desktop browsers.
Did I misinterprete that article? Or am I just doing it wrong?
Cheers,
Mohammer

A: In short you ended up using HTML Media Capture Standard which works by overloading the <input type="file"> element and adding new values for the accept parameter.
The great thing about it is that it works great on most mobile browsers (except for recording only the mic on iOS). Support is implemented at least in:

*

*Safari and Chrome on iOS 6+

*Internet and Chrome on Android 3+

Which pretty much covers anyone, however, depending on the device, you will end up with .mp4 (Android), .mov (iOS) and .3gp files.
The not so great thing about it is that it defaults to a plain old file selector when used on a desktop OS instead of opening Photo Booth for example.
Surprisingly the standard's draft included an image of how video capturing through some sort of Photo Booth app would look on a desktop:

Which is why on the desktop a Flash video recording client + media server is the only solution that works well across browsers and platforms.
There are also commercial solutions including HDFVR (HTML Media Capture + Flash) and Pipe which does a lot more including the conversion to .mp4, pushing to your S3/FTP and webhooks.

A: I think that's a typo.
the right way is
<p>Capture Video: <input type="file" accept="video/*" id="capture" capture="camcorder">

The 'capture' attribute only affects mobile file upload, as far as I know.
source: http://mobilehtml5.org/ts/?id=23


text:
Q: R - keep random rows per group, but different numbers per group The function sample_n() from package dplyr allows to randomly keep a specific number of rows. Combine with group_by(), you can for instance keep 2 observations per group:
mtcars %>%
  select(vs, drat) %>%
  group_by(vs) %>%
  sample_n(2)

# A tibble: 4 x 2
# Groups:   vs [2]
     vs  drat
  <dbl> <dbl>
1     0  3.07
2     0  3.9
3     1  4.22
4     1  3.08

Question: is there an easy way to select a different number of observations per group? For instance, if I want to keep 2 observations for the first group, and 3 for the second one. If I give a vector to the function sample_n(), it only uses the first value (result is the same as above).
mtcars %>%
  select(vs, drat) %>%
  group_by(vs) %>%
  sample_n(c(2,3))

Thanks in advance.

A: create list-columns of each groups using group_nest(), add a column with the number of samples you want in each group,  then map these two columns to the sample_n() function:
library(tidyverse)

mtcars %>%
  select(vs, drat) %>%
  group_nest(vs, keep= TRUE)  %>%
  add_column(mysamples = c(2,3)) %>%
  mutate(sampled  = map2(data , mysamples, ~ sample_n(.x, .y))) %>%
  .$sampled %>%
  bind_rows()

# A tibble: 5 x 2
     vs  drat
  <dbl> <dbl>
1     0  3.15
2     0  4.22
3     1  3.7
4     1  4.93
5     1  3.08
>


text:
Q: strange behavior on c++ string append I have a strange problem with c++ string object in my class on the line s.append(ptr2str ....);
class cRegexMatches {
public:
    char *ptr2str;
    int   *pOffsets;
    cRegexMatches() { ptr2str = NULL; pOffsets=NULL;}
    void update(char *p, int *offsets) {
        ptr2str = p; pOffsets = offsets;
        printf("ptr2str=%p %s|\n", p, p);
    }
    string operator [] (int id) {
        string s;
        printf("operator[] %p %s|", ptr2str, ptr2str);
        int i;
        for (i=0; i<4; i++) printf(" %d", pOffsets[i]);
        printf("\n");
        if (!ptr2str) return s;
        if (pOffsets[2 * id + 1] == 0) return s;
        int len = pOffsets[2 * id + 1] - pOffsets[2 * id];
        printf("size %d %ld before %s\n", s.size(), len, ptr2str + pOffsets[2 * id]);
        s.append(ptr2str + pOffsets[2 * id], len);
        cout << s << endl;
        return s;
    }
};

It runs fine with the follow code.
int main(int argc, char *argv[]) {
    char *p = "10.20.0.111:8080";
    int pInts[] = {0, 16, 0,16};
    regmatches.update(p, &pInts[0]);
    string s =  regmatches[0];
    int i;
    for (i=0; i<s.size(); i++) {
        printf("%c\n", s.c_str()[i]);
    }
    return 0;
}

But in my project,  the line s.append(ptr2str + pOffsets[2 * id], len); seems to corrupt the first byte to be \x00, according to the debug statement printf(..) before s.append and the cout ... afterwards.
Any idea what caused the strange behavior?  Thanks!
UPDATE 1
Thanks to @user657267's suggestion,  here is a brief description on how the code was used in my project.  It looks very innocent.
cRegexMatches globalVar;

//p points to some c string
//pInt points to an array of integers, in my case, it's 0,  16, 0, 16
globalVar.update(p, pInt);
cout << globalVar[0]

For now, I found a workaround:  I changed the line s.append(ptr2str + pOffsets[2 * id], len); to return string(ptr2str + pOffsets[2 * id], len); and it worked fine.  But I am still curious on what caused the strange behavior.

A: I believe that the problem might be your definition of the string in main.
char* p = "10.20.0.111:8080";

should be
char p[] = "10.20.0.111:8080";

Only the second definition reserves memory on the stack.


text:
Q: Removing the Dollar Sign for Knockout Binding Expression I have a TextBox which is bind to a knockout model. Now, in the TextBox user can enter the cost like "0.00", "4.95" etc. But they can also enter the dollar sign like this: "$50.00" and "$6.00".
When the user enters the dollar sign the model breaks since it expects a decimal value. I was wondering if there is someway I can remove the dollar sign inside the data-bind expression below:
<input type="text" id="cost" data-bind="value: selectedChoiceValue" />

A: Try escaping the $ in the string.
Example:
\$5.00

A: var price = $("#cost").val().replace("$", "");
But it should be noted that the data attribute is read-only.  Meaning if you update the value in the data attribute after page load and then try to retrieve it via $("#cost").data("bind") it will not return the updated value.
If you must modify then retrieve an updated data attribute, you have to use .attr("data-bind")

A: You could also use
var without_dollar_sign = $("#cost").val().replace(/\$/g, '');
$("#cost").val(without_dollar_sign)

A: Bind the field to a writable computed. If the validation is successful, write the new value to your numeric observable; if not, do some error handling. The read component of your computed can do some formatting or not, as you like.

function toNumber(stringValue) {
  if (stringValue[0] == '$') {
    stringValue = stringValue.substr(1);
  }
  var result = parseFloat(stringValue);
  return result;
}

vm = {
  cost: ko.observable(0),
  costAsString: ko.pureComputed({
    deferEvaluation: true,
    read: function() {
      return '$' + vm.cost();
    },
    write: function(newValue) {
      var numberValue = toNumber(newValue);
      if (isNaN(numberValue)) {
        alert('Invalid number');
        var revert = vm.cost();
        vm.cost('');
        vm.cost(revert);
      } else {
        vm.cost(numberValue);
      }
    }
  })
};
ko.applyBindings(vm);

<input type="text" id="cost" data-bind="value: costAsString" />

Value is:

A: Honestly, I think the best way is to just user an html5 number input field:
<input type="number" id="cost" data-bind="value: selectedChoiceValue" />

If you want a knockout solution, You could use an observable/computed combo like Roy J's answer, or you could use a single observable and subscribe and trottle:

var vm = function(){
  this.selectedChoiceValue = ko.observable('');

  // Just to make sure things do go crazy
  this.selectedChoiceValue.extend({ rateLimit: 10 }); // in ms

  this.selectedChoiceValue.subscribe(function(newValue){
    // Assuming you'll want to also parse out other invalid characters
    newValue = yourFunctionToParseTheInput(newValue);

    // Update this value to be the parsed valued
    this.selectedChoiceValue(newValue);

  }, this);
}

function yourFunctionToParseTheInput(value) {
  return value.replace('$', '');
}

ko.applyBindings(vm);

$<input type="text" id="cost" data-bind="value: selectedChoiceValue, valueUpdate:['afterkeydown']" />

Restricting input to textbox: allowing only numbers and decimal point has some good ways to parse the input value as well.


text:
Q: Get Errors From FactoryGirl.lint I inherited a number of FactoryGirl factories that don't really work and I'm trying to bring them up to snuff.  Part of that has been the use of FactoryGirl.lint.  So far, however, I have been able to find which factories fail and, for any individual one, run
x = FactoryGirl.build :invalid_factory
x.valid? # returns false as expected
x.errors # prints out the validation errors for that object

What I'd like to do is avoid having to do that for each factory.  Is there a way to quickly get FactoryGirl.lint to write out the errors which each invalid factory?  A flag to pass, a parameter to set?  The documentation is extremely sparse on .lint

A: Loop through FactoryGirl.factories to perform your check on each factory.
FactoryGirl.factories.map(&:name).each do |factory_name|
    describe "#{factory_name} factory" do

      # Test each factory
      it "is valid" do
        factory = FactoryGirl.build(factory_name)
        if factory.respond_to?(:valid?)
          # the lamba syntax only works with rspec 2.14 or newer;  for earlier versions, you have to call #valid? before calling the matcher, otherwise the errors will be empty
          expect(factory).to be_valid, lambda { factory.errors.full_messages.join("\n") }
        end
      end

This script from the FactoryGirl wiki shows how to automate the check with RSpec and use Guard to always verify factories are valid.


text:
Q: Laravel 4 - Form submit to update MySQL table i'm trying to update the data in my DB table called "users", specifically 3 columns. But now i'm just trying to communicate with a controller to get an echo!!
I have the following code:
My view file (dashboard.blade.php) has a form in it:

    {{ Form::open(array('action' => 'UsersController@putCoordinates')) }}

        {{ Form::text('city', null, array('id'=>'city', 'placeholder'=>'current city', 'required'=>'required')) }}

        {{ Form::text('markerLat', null, array('id'=>'markerLat', 'placeholder'=>'latitude', 'required'=>'required')) }}

        {{ Form::text('markerLng', null, array('id'=>'markerLng', 'placeholder'=>'longitude', 'required'=>'required')) }}

        {{ Form::button('Update', array('class'=>'button small addMe postfix', 'id'=>'addMe'))}}

    {{ Form::close() }}

the route i created is:
Route::controller('users', 'UsersController');

And in the controller file (UsersController) i have the following function:
    public function putCoordinates() {
        echo "It works!";
    }

But so far, it doesn't seem to be working.. i've tried to change my openning form to:
{{ Form::open(array('url'=>'users/update', 'class'=>'form')) }}

but it didn't work, i dont get any error, i just press "update" and nothing happens..
Any help would be appreciated, i must be missing something very simple here.
Thanks!

A: Default method is POST, so you need to tell Laravel to create your form using the method PUT:
{{ Form::open(array('method' => 'PUT', 'action' => 'UsersController@putCoordinates')) }}

And, to create your submit button you must use:
{{ Form::submit('Update', array('class'=>'button small addMe postfix', 'id'=>'addMe'))}}


text:
Q: Libgdx and Box2d Rotate Texture along with CircleSgape I want to make a ball, so far I have rendered as simple texture on my circle and the ball rotates by the texture does not. Here is what I have so far:
    bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(new Vector2(240,320));
    body = world.createBody(bodyDef);
    CircleShape dynamicCircle = new CircleShape();
    dynamicCircle.setRadius(15f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicCircle;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.5f;
    fixtureDef.restitution = 0.8f;
    body.createFixture(fixtureDef);
    body.applyTorque(100000000);

And in render I have:
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(texture, body.getPosition().x,body.getPosition().y);
    batch.end();
    world.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);

Any ideas how I can make the texture rotate as well? Thanks in advance.

A:  batch.draw(texture, body.getPosition().x, body.getPosition().y, width/2, height/2, width, height, /*scaleX*/1, /*scaleY*/1, /*rotation*/ body.getAngle() * MathUtils.radToDegree, srcX, srcY, srcWidth, srcHeight, /*flipX*/false, /*flipY*/false);


text:
Q: Suddenly no internet After a recent update to Ubuntu 16, after rebooting will not connect to internet, although seems to be connected and does not complain, except journalctl shows "NM_IS_DEVICES failed". ifconfig looks normal. I don't know where else to look!
Adding more info:
I can ping the router and ping another machine on the local net but I can't ping www.google.com. On the router everything looks good, although I see that it lists as connecting to br0 on the Ubuntu machine, with a MAC address that I don't recognize. However it also shows this machine as having a static IP, and that shows the correct MAC address. Plus, it used to work; nothing on the router has been changed. The only thing that happened was that 16.04 was updated, causing a reboot. After the reboot is when the trouble began.


text:
Q: jQuery $.param'ed string parsing in Python (app engine) I have a JavaScript dictionary that I want to pass to a Python app on app engine, put into datastore, retrieve from datastore and finally return as JSON. What's the right way to do it?
Say it looks something like that:
dict = {'box': 'huge',
        'crayons': [{ 'color': 'blue', 'l': 12 },
                    { 'color': 'red', 'l': 2 },
                    { 'color': 'yellow', 'l': 7 }]};

I serialize it using jQuery:
data = $.param(dict);

getting something like:
box=huge&crayons%5B0%5D%5Bcolor%5D=blue&crayons%5B0%5D%5Bl%5D=12&crayons%5B1%5D%5Bcolor%5D=red&crayons%5B1%5D%5Bl%5D=2&crayons%5B2%5D%5Bcolor%5D=yellow&crayons%5B2%5D%5Bl%5D=7

I send it using $.ajax to app engine (Python, Flask) and put it into datastore as a serialized string. Later I want to deserialize it to a Python dictionary and translate it to JSON using simplejson.
I have no idea how to deserialize it to a Python dictionary though.
Edit: Or maybe I'm doing it wrong and need to pass the dictionary to app engine differently?

A: If you use $.param you lose type information when parsing the data. In your example the number 12 becomes the string '12'. Also boolean true would become string 'true'.  This could lead to problems when you get the data back from the server.
If maintaining type information is important to you, you might want to json encode the object before sending it to app engine (https://github.com/douglascrockford/JSON-js).  Then you could just put the data straight into the datastore and return it on request.

A: urlparse.parse_qs:
>>> import urlparse
>>> urlparse.parse_qs("box=huge&crayons%5B0%5D%5Bcolor%5D=blue&crayons%5B0%5D%5Bl%5D=12&crayons%5B1%5D%5Bcolor%5D=red&crayons%5B1%5D%5Bl%5D=2&crayons%5B2%5D%5Bcolor%5D=yellow&crayons%5B2%5D%5Bl%5D=7")
{'box': ['huge'],
'crayons[0][color]': ['blue'],
'crayons[0][l]': ['12'],
'crayons[1][color]': ['red'],
'crayons[1][l]': ['2'],
'crayons[2][color]': ['yellow'],
'crayons[2][l]': ['7']}

A: Well urlparse.parse_qs is pretty nice, but if you have nested structures, etc, there is jquery-unparam which will further parse all those nested objects for you.  It seems to work fairly well for me so far.
>>> from jquery_unparam import jquery_unparam
>>> jquery_unparam("a=1&b%5B%5D=2&b%5B%5D=3&b%5B%5D=4&c%5Bd%5D=5")
{'a': '1', 'c': {'d': '5'}, 'b': ['2', '3', '4']}

>>> from urlparse import parse_qs
>>> parse_qs("a=1&b%5B%5D=2&b%5B%5D=3&b%5B%5D=4&c%5Bd%5D=5")
{'a': ['1'], 'b[]': ['2', '3', '4'], 'c[d]': ['5']}

A: Use JSON.stringify(dict) to serialize your JavaScript dictionary, and json.loads(dict_string) to deserialize into a Python dictionary.
Thus, your JavaScript code would look something like this:
$.ajax({
    url: '/some/url',
    type: 'post',
    data: {
        'dict': JSON.stringify(dict)
    }
});

... and your Python code would look something like this:
import json

from google.appengine.ext import webapp

class MyRequestHandler(webapp.RequestHandler):
    def post(self):
        dict = json.loads(self.request.get('dict'))

A: json.loads(request.POST)
That's from simplejson and how I do it in django.


text:
Q: Awaiting code inside of anonymous function So I have some code that I need to execute when an form activates its Shown event, and I need to await that code. I am doing this:
form.Shown += async (sender, args) => await BufferOpen(CurrentPath, CurrentEncoding, 1024 * 1024 * 5, statusProgressForm.progressBar1);
                statusProgressForm.Show();

But the code still continues without awaiting the BufferOpen method. How can I do this with an anonymous function?
EDIT:
Ok, so I think I screwed up the original post. Sorry about that. What I'm really trying to do is show a form and THEN on the shown event perform intensive code, as before when I just did this:
form.Show();
DoIntensiveTasks();

The GUI on the form would not properly load and the labels and such wouldn't display properly. I need to wait until the form is completely shown then do stuff.

A: The problem is that because you used an expression lambda it's only performing the one expression as a part of that anonymous method, and thus the Show call isn't a part of that anonymous method.  All it takes is to use brackets to make it a statement lambda:
form.Shown += async (sender, args) =>
{
    await BufferOpen(CurrentPath, CurrentEncoding, 1024 * 1024 * 5, statusProgressForm.progressBar1);
    statusProgressForm.Show();
};


text:
Q: Execute python code with command line argument using VBA I'm trying to execute a python code with command line argument using VBA. My python file name is test.py. While I'm executing following command using command prompt
python test.py Sales

Then my python code process sales data & store the processed output in a table in SQL server.I can able to see the uploaded data in SQL server. I would like to execute this python script using VBA. So I wrote following code
Sub executePython1()
 Dim wsh As Object
 Set wsh = CreateObject("WScript.Shell")
 arg = "Sales"
 Dim shell_exec As Object
 Set shell_exec = wsh.Exec("""python.exe""" &
 """C:\x1\test.py """ & arg)
 MsgBox "Executed"
End Sub

After running the code I'm seeing "Executed" message but I'm unable to see any data in my SQL Server table. Can you help me to resolve this issue?
I'm working on Windows azure & running python 3.7


text:
Q: Headers sections and subsections I would like to put in the headers the section in the left header of odd (right-side) pages, and the subsection in the right header of even (left-side) pages (unless there is no subsection in which case I want the section in both places).
Thank you
\documentclass{book}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{sidenotes}
\usepackage{graphicx}
\usepackage{float}
\usepackage{esint}
\usepackage{lipsum}
\usepackage{booktabs}
\usepackage{wrapfig}
\usepackage{multirow}
\usepackage{enumitem}
% \usepackage{parskip}
\usepackage{emptypage}
\usepackage{subcaption}
\usepackage{fontawesome,blindtext}
\usepackage{multicol}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{amsmath, amsfonts, mathtools, amsthm, amssymb}
\usepackage{mathrsfs}
\usepackage{marginnote}
\usepackage{placeins}
\usepackage{cancel}
\usepackage{bm}
% horizontal rule
\newcommand\hr{
    \noindent\rule[0.5ex]{\linewidth}{0.5pt}
}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancypagestyle{plain}{%
    \fancyhf{} %
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\footrulewidth}{0pt}}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\subsectionmark}[1]{\markright{\thesubsection. #1}}
\fancyhf{}
\fancyhead[LEH,ROH]{\small\bfseries\thepage} %numeri pagina m.est.
\fancyhead[REH]{\bfseries\small\nouppercase{\thesubsection.}} %capitoli m.int.sx
\fancyhead[LOH]{\bfseries\small\nouppercase{\rightmark}} %sezioni m.int.dx
\fancyfoot[C]{\bfseries\nouppercase{\leftmark}}
\makeatletter

\begin{document}
\tableofcontents
\chapter{Hello}
\section{section}
\lipsum\lipsum\lipsum\lipsum\lipsum\lipsum

\chapter{Hello2}
\section{section}
\subsection{subsec}
\lipsum\lipsum\lipsum\lipsum\lipsum\lipsum
\end{document}

A: The question is a little confusing because you say "the section on the right and the subsection on the left". I take it you mean you want the section in the left header of odd (right-side) pages, and the subsection in the right header of even (left-side) pages (unless there is no subsection in which case you want the section in both places).
If I misunderstood, I think it'll be easy to change, however.
While it may be possible to do this using the builtin marking mechanisms (not sure), since you also need a mark for chapters (at the bottom), I think you'll want to load fancyhdr's companion extramarks package as well so you have more than two marks to use.
This defines a command \extramarks that works like \markboth but for differently named marks (leftxmark, rightxmark).
Here I suggest setting the right extra mark inside both \sectionmark and \subsectionmark commands, and then use \lastrightxmark in the headers on the right of even pages. It'll use whatever right extra mark was given last, so if a subsection command is not given after section, the section's marking will apply, but if a subsection title is given, the subsection's marking will apply.
Here's my suggested code.
\documentclass{book}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath, mathtools, amsthm, amssymb}
\usepackage{textcomp}
\usepackage{sidenotes}
\usepackage{graphicx}
\usepackage{float}
\usepackage{esint}
\usepackage{lipsum}
\usepackage{booktabs}
\usepackage{wrapfig}
\usepackage{multirow}
\usepackage{enumitem}
% \usepackage{parskip}
\usepackage{emptypage}
\usepackage{subcaption}
\usepackage{fontawesome,blindtext}
\usepackage{multicol}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{mathrsfs}
\usepackage{marginnote}
\usepackage{placeins}
\usepackage{cancel}
\usepackage{bm}
% horizontal rule
\newcommand\hr{
    \noindent\rule[0.5ex]{\linewidth}{0.5pt}
}

\usepackage{fancyhdr,extramarks}
% plain style for first page of chapters
\fancypagestyle{plain}{%
    \fancyhf{} %
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\footrulewidth}{0pt}
}

% fancy style elsewhere
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0.4pt}
\fancyhf{}
% page numbers, even pages left, odd pages right
\fancyhead[LEH,ROH]{\small\bfseries\thepage} %numeri pagina m.est.
% use the extra mark (could be section or subsection) on right of even pages
\fancyhead[REH]{\bfseries\small\nouppercase{\lastrightxmark}} %capitoli m.int.sx
% use the left mark (section) on left of odd pages
\fancyhead[LOH]{\bfseries\small\nouppercase{\rightmark}} %sezioni m.int.dx
% chapter in footer center
\fancyfoot[C]{\bfseries\nouppercase{\leftmark}}

% marking commands

% subsections change the right extra mark
\renewcommand{\subsectionmark}[1]{%
    \extramarks{}{#1\ \thesubsection}
}
% sections change the right mark, and right extra mark
\renewcommand{\sectionmark}[1]{%
    \markright{\thesection\ #1}
    \extramarks{}{#1\ \thesection}
}
% chapters set left mark and reset others
\renewcommand{\chaptermark}[1]{%
    \markboth{\chaptername\ \thechapter. #1}{}
    \extramarks{}{}
}

\begin{document}
\tableofcontents
\chapter{First Chapter}
\section{section without subsection}
\lipsum[1-20]

\chapter{Second Chapter}
\section{section with subsection}
\subsection{my subsection}
\lipsum[21-40]

\end{document}

In the chapter without subsections you get the section title and number on even pages:

In the chapter with subsections you get the subsection title and number there.

I think that's what you wanted if I understood you right.
Unrelated but I also moved the ams packages further up in your list, to avoid problems with the same command being defined multiple times, and removed amsfonts (since amssymb loads that anyway). I also removed the stray \makeatletter, which wasn't doing anything useful, and isn't good to have without \makeatother.
EDIT: If you want the subsection numbers on the left of the title instead of having the numbers always on the outside as I have them, you can use:
% subsections change the right extra mark
\renewcommand{\subsectionmark}[1]{%
    \extramarks{}{\thesubsection\ #1}
}
% sections change the right mark, and right extra mark
\renewcommand{\sectionmark}[1]{%
    \markright{\thesection\ #1}
    \extramarks{}{\thesection\ #1}
}

In all these commands, the #1 represents where the title goes, and the commands starting with \the (e.g., \thesubsection) represent the numbers.


text:
Q: Apache Camel -- Reference type constants in Spring DSL I'm trying to define a publish operation to Hazelcast topic using Spring DSL
<from uri="direct:inbound" />
        <onCompletion>
            <log message="onCompletion:- ${body}" />
            <setHeader headerName="${type:org.apache.camel.component.hazelcast.HazelcastConstants.OPERATION}">
                <simple>${type:org.apache.camel.component.hazelcast.HazelcastConstants.PUBLISH_OPERATION}</simple>
            </setHeader>
            <to uri="hazelcast:topic:foo" />
        </onCompletion>
        <log message="${body}" />

The above route works, but I have to use long SIMPLE scripts like "${type:org.apache.camel.component.hazelcast.HazelcastConstants.OPERATION}" to ref a constant value. Is there any simpler or short form for this?
I tried to define a spring bean for HazelcastConstants class and ref it through SIMPLE scripts as below but it's not working with MethodNotFoundException "Method with name: OPERATION not found on bean"
<bean id="hazelcastConstants" class="org.apache.camel.component.hazelcast.HazelcastConstants" />
... ...
<simple>${bean:hazelcastConstants.OPERATION}</simple>

A: Your bean workaround would work, if you defined a bean contained a method returning the constant in question, e.g.:
public class ContantRetriever() {
  public String getHazelCastOperation() {
   return org.apache.camel.component.hazelcast.HazelcastConstants.PUBLISH_OPERATION;
  }
}

Your Spring context:
<bean id="hazelcastConstants" class="yourpackage.ContantRetriever"/>
<simple>${bean:hazelcastConstants.getHazelCastOperation}</simple>

If that is no good for you, I am afraid you are stuck with the long form of accessing constants.


text:
Q: out of stack space (infinite loop?) error while working with matplolib and Django I am trying to show a graph which I am trying to plot in Matplotlib and then showing it with some hard coding in HTML template.But out of 3 attempts, it is working only once else it is throwing  TCL Out of stack space error. Below is my coding.
def similar_images(request):
n_groups = 5

means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)

means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)

fig, ax = plt.subplots() # somwhere here it is throwing this error

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {'ecolor': '0.3'}

rects1 = plt.bar(index, means_men, bar_width,
                 alpha=opacity,
                 color='b',
                 yerr=std_men,
                 error_kw=error_config,
                 label='Men')

rects2 = plt.bar(index + bar_width, means_women, bar_width,
                 alpha=opacity,
                 color='r',
                 yerr=std_women,
                 error_kw=error_config,
                 label='Women')

plt.xlabel('Shoe')
plt.ylabel('Week')
plt.title('Last Year sale details')
#plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D', 'E'))
plt.legend()

plt.savefig('/graph.png')

plt.close()

return render(request,'sales/Details.html')

Please, can someone help me here?
Below is the error.
Exception Type: TclError at /sales/similar_images/
Exception Value: out of stack space (infinite loop?)


text:
Q: Simple template code compiles in Visual Studio but not with LLVM What I'm trying to do is create a template function that stores a generic function pointer and information about how to cast to it's actual type. This is being used by my script binding API to make C++ function calls from Python for a game engine. In the process of porting this to OSX using XCode4 with LLVM, I have run into an error. This sample code compiles and runs fine in Visual Studio 2012, but gives me the error "No matching function for call to 'Call'" with LLVM.
#include <iostream>

void testfun (int i)
{
  std::cout << "Hello World " << i << std::endl;
}

typedef void BasicFunction ();

template <BasicFunction* fn, typename T0>
void Call (void(*f)(T0), T0 i)
{
  reinterpret_cast<decltype(f)>(fn)(i);
}

int main(int argc, const char * argv[])
{
  Call<reinterpret_cast<BasicFunction*>(testfun)>(testfun, 5);
  return 0;
}

Is this non standard code? A bug with LLVM? Or is there just a better way to accomplish the same task? Note: The function pointer must come first in the template so that the function information can be deduced automatically.

A: Clang is correct. I believe 14.3.2p1 rules out this:

A template-argument for a non-type, non-template template-parameter
  shall be one of:
— a constant expression (5.19) that designates the address of an
  object with static storage duration and external or internal linkage
  or a function with external or internal linkage, including
  function templates and function template-ids but excluding non-static
  class members, expressed (ignoring parentheses) as &
  id-expression, except that the & may be omitted if the name refers
  to a function or array and shall be omitted if the corresponding
  template-parameter is a reference; or

The important part is expressed (ignoring parentheses) as & id-expression. The expression must have an &, however you cannot take the address of an rvalue. So this pretty much rules out any casts.
Also, from 5.19p2 reinterpret_cast is illegal in constant expressions:

A conditional-expression is a core constant expression unless it
  involves one of the following as a potentially evaluated subexpression
— a reinterpret_cast (5.2.10);


text:
Q: Carving Out exactly humans From Image I want to carve out the exact human out of the image currently im able to create a box around the humans
the code that I'm  using is as follows:
import cv2
import numpy as np
import imutils

protopath = r"C:\Users\Admin\MobileNetSSD_deploy.prototxt"
modelpath = r"C:\Users\Admin\MobileNetSSD_deploy.caffemodel"
detector = cv2.dnn.readNetFromCaffe(prototxt=protopath, caffeModel=modelpath)

CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
           "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
           "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
           "sofa", "train", "tvmonitor"]

def main():
    image = cv2.imread(r'E:\trial2.jpg')
    image = imutils.resize(image,300)

    (H, W) = image.shape[:2]

    blob = cv2.dnn.blobFromImage(image, 0.007843, (W, H), 127.5)

    detector.setInput(blob)
    person_detections = detector.forward()

    for i in np.arange(0, person_detections.shape[2]):
        confidence = person_detections[0, 0, i, 2]
        if confidence > 0.5:
            idx = int(person_detections[0, 0, i, 1])

            if CLASSES[idx] != "person":
                continue

            person_box = person_detections[0, 0, i, 3:7] * np.array([W, H, W, H])
            (startX, startY, endX, endY) = person_box.astype("int")
            cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)

    cv2.imshow("Results", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
main()

What i want
I want to outline the humans exactly
Any help or tips will be greatly appreciated
Edit 1: Suggested by Sunil Kumar
import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread(r'E:\trial3.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)

# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)

# Add one to all labels so that sure background is not 0, but 1
markers = markers+1

# Now, mark the region of unknown with zero
markers[unknown==255] = 0
markers = cv2.watershed(img,markers)
img[markers == -1] = [255,0,0]
cv2.imshow("Results", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

and the current output that I'm getting

A: What you are looking for is instance segmentation, which is much more accurate than object detection:
While object detection only outputs a bounding box around each person (as you already noticed). Instance segmentation attempts to output an exact mask for each instance - which is what you are looking for.
I would try out the following instance segmentation frameworks:

*

*Mask RCNN

*Pixel Consensus voting


text:
Q: Using recursive pattern loop with node.js ive been trying to use node.js to iterate through an array of cities and make an iterative request to google for directions on each (i then JSON.parse to abstract the drive times).  I need to find a way to do this synchronously as otherwise i will just be requesting all the info from google on each city at once.  I found a good pattern to use at http://tech.richardrodger.com/2011/04/21/node-js-%E2%80%93-how-to-write-a-for-loop-with-callbacks/ but cannot get the callback to work.  As you can see, im using a 'show' function to test the same.  My code is as follows:
var request = require('request');
var fs = require('fs');
var arr = ['glasgow','preston','blackpool','chorley','newcastle','bolton','paris','york','doncaster'];
//the function I want to call on each city from [arr]
function getTravelTime(a, b,callback){
 request('https://maps.googleapis.com/maps/api/directions/json?origin='+a+'&destination='+b+'&region=en&sensor=false',function(err,res,data){
 var foo = JSON.parse(data);
 var duration = foo.routes[0].legs[0].duration.text;
 console.log(duration);
 });
};

function show(b){
 fs.writeFile('testing.txt',b);
};

function uploader(i){
 if( i < arr.length ){
   show( arr[i],function(){
   uploader(i+1);
   });
 }
}
uploader(0)

The problem I have is that only the first city from the array is output and the callback/iteration never proceeds.  Any ideas where im going wrong please?

A: Thanks for the pointers, was clearly down to my poor understanding of callbacks in javascript.  Just reading JavaScript patterns by O'Reilly and hit the 'Callback pattern' sections - doh!
For anyone who doesn't know, this is how the code will work:
var arr = ['glasgow','preston','blackpool','chorley','newcastle','bolton','paris','york','doncaster'];

function show(a,callback){
    console.log(a);
    callback();
}

function uploader(i){
  if( i < arr.length ){
    show(arr[i],
         function(){
          uploader(i+1)
         });
   };
}
uploader(0)

A: I was also facing issues like this, so I've written a recursive callback function which will act as a for loop but you can control when to increment. The following is that module, name as syncFor.js and include this in your program
module.exports = function syncFor(index, len, status, func) {
    func(index, status, function (res) {
        if (res == "next") {
            index++;
            if (index < len) {
                syncFor(index, len, "r", func);
            } else {
                return func(index, "done", function () {
                })
            }
        }
    });
}

//this will be your program if u include this module
var request = require('request');
var fs = require('fs');
var arr = ['glasgow', 'preston', 'blackpool', 'chorley', 'newcastle', 'bolton', 'paris', 'york', 'doncaster'];
var syncFor = require('./syncFor'); //syncFor.js is stored in same directory
//the following is how u implement it

syncFor(0, arr.length, "start", function (i, status, call) {
    if (status === "done")
        console.log("array iteration is done")
    else
        getTravelTime(arr[i], "whatever", function () {
            call('next') // this acts as increment (i++)
        })
})

function getTravelTime(a, b, callback) {
    request('https://maps.googleapis.com/maps/api/directions/json?origin=' + a + '&destination=' + b + '&region=en&sensor=false', function (err, res, data) {
        var foo = JSON.parse(data);
        var duration = foo.routes[0].legs[0].duration.text;
        callback(); // call the callback when u get answer
        console.log(duration);
    });
};


text:
Q: Is it possibile change date format in Piwik? is there a way to show another format date in piwik dashboard ? For example like this dd-mm-YYYY ? Thanks and excuse for my english.

A: It is currently not possible to modify it. We might allow you to do it in the future (or even use the default date format for you language setting).
Feel free to add a new ticket to http://dev.piwik.org to request this feature.
Disclosure: I'm a Piwik dev.


text:
Q: R shiny tooltips when a user put his cursor on a buble(gene) Hello I have built this R shiny app using kegg packages and a xml file from the website. The app runs but i would like to add toolips when the user puts his cursor on an observation (gene presented in a buble). If you see in the code below I have created a dataframe named gene_info_df which has the information i want to show at the "description" variable. Could you please help me with that if you have any idea? thank you
if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")
BiocManager::install(version = "3.15")
BiocManager::install("KEGGgraph")
if (!requireNamespace("BiocManager", quietly = TRUE))
  install.packages("BiocManager")
BiocManager::install("KEGGREST")
BiocManager::install("EnrichmentBrowser")
library("KEGGREST")
library("EnrichmentBrowser")

library(KEGGgraph)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Pathway testing"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "geneInput",
        label = "Genes",
        choices = c("hsa05212"),
      ),
      selectizeInput(
        inputId = "searchme",
        label = "Search Bar",
        multiple = FALSE,
        choices = c("Search Bar" = "", paste0(LETTERS,sample(LETTERS, 26))),
        options = list(
          create = FALSE,
          placeholder = "Search Me",
          maxItems = '1',
          onDropdownOpen = I("function($dropdown) {if (!this.lastQuery.length) {this.close(); this.settings.openOnFocus = false;}}"),
          onType = I("function (str) {if (str === \"\") {this.close();}}")
        ))
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput(outputId="genePlot", width = 1400, height=900)
    )
  )
)
gene_info <- keggGet("hsa05212")
## a function to parse the data
parseIt <- function(x) {
  nr <- length(x$GENE)
  GeneID <- x$GENE[seq(1, nr, 2)]
  d.f <- do.call(rbind, strsplit(x$GENE[seq(2, nr, 2)], "; "))
  colnames(d.f) <- c("SYMBOL","DESCRIPTION")
  data.frame(GeneID, d.f)
}
gene_info_df <- parseIt(gene_info[[1]])
# Define server logic required to draw a histogram
server <- function(input, output) {

  output$genePlot <- renderPlot({
    # Retreive KEGG data
    mapkKGML <- system.file(sprintf("extdata/%s.xml", input$geneInput),package="KEGGgraph")
    wntKGML <- system.file(sprintf("extdata/%s.xml",input$geneInput), package="KEGGgraph")

    #Format KEGG data into useable format
    mapkG <- parseKGML2Graph(mapkKGML,expandGenes=TRUE)
    mapkGall <- parseKGML2Graph(mapkKGML,genesOnly=FALSE)

    mapkGsub <- subGraphByNodeType(mapkGall, "compound")

    wntG <- parseKGML2Graph(wntKGML, genesOnly=TRUE)
    graphs <- list(mapk=mapkGsub, wnt=wntG)
    merged <- mergeGraphs(graphs)
    #Defining functions for ploting the node graph
    makeAttr <- function(graph, default, valNodeList) {
      tmp <- nodes(graph)
      x <- rep(default, length(tmp)); names(x) <- tmp

      if(!missing(valNodeList)) {
        stopifnot(is.list(valNodeList))
        allnodes <- unlist(valNodeList)
        stopifnot(all(allnodes %in% tmp))
        for(i in seq(valNodeList)) {
          x[valNodeList[[i]]] <- names(valNodeList)[i]
        }
      }
      return(x)
    }

    # Block of code responsible for setting the attributes of the plot
    outs <- sapply(edges(merged), length) > 0
    ins <- sapply(inEdges(merged), length) > 0
    ios <- outs | ins
    ## translate the KEGG IDs into Gene Symbol
    if(require(org.Hs.eg.db)) {

      ioGeneID <- translateKEGGID2GeneID(names(ios))

      tmp <- c()

      for (i in ioGeneID) {
        if (is.na(mget(sprintf("%s",i),  org.Hs.egSYMBOL, ifnotfound = NA))) {
          tmp <- append(tmp,sprintf("%s",i))
        }
        else {
          tmp <- append(tmp,mget(sprintf("%s",i),  org.Hs.egSYMBOL))
        }
      }
      nodesNames <- sapply(tmp, "[[",1)
    } else {
      nodesNames <- names(ios)
    }
    names(nodesNames) <- names(ios)

    nAttrs <- list();
    nAttrs$fillcolor <- makeAttr(merged, "lightgrey", list(orange=names(ios)[ios]))
    nAttrs$label <- nodesNames
    plot(merged, "neato", nodeAttrs=nAttrs,
         attrs=list(node=list(fillcolor="lightgreen",
                              width="0.75", shape="ellipse"),
                    edge=list(arrowsize="0.7")))

  })
}

# Run the application
shinyApp(ui = ui, server = server)