Q:

Two Internet Modems, Different Subnets, One Access Point

I have several Unifi AC Lite APs around our building. We are provided two internet modems by our service provider: one for our private internet and one for public use. Both currently have DHCP enabled. The private network is currently on 192.168.250.x subnet and public is on 192.168.1.x subnet. Could we configure the network so that I can use the Unifi Access Points to access both networks? I.e. I would like for clients on the public network to get routed to the public internet modem, and clients on the private network to get routed to our private internet. The key being that we don't have to redeploy more access points around the building just for the public network. What hardware/configuration would be required if this is possible?

A:

You'll want to use VLANs. I hope the "Lite" APs aren't limited in that regard.
You'll use three VLANs:

VLAN 1: Public
VLAN 2: Private
VLAN 3: Management

We'll create isolated channels ("virtual cables") through a single cable. The AP management will be out of band with other traffic, which is good.
When setting up a wireless network in UniFi's management software, you can set which VLAN the network should connect to. You can of course also set different levels of security for them.
You'll also need something VLAN-enabled at the other end of the trunk connection. This can be a managed switch or a regular Linux PC/device. Depending on how enterprise it has to be, you could go for a cheap "smart managed" switch (only web-based management) or a router that can do OpenWrt.
The simplest solution would be as follows:

The access point will connect to LAN1 (VLANs 1 & 2, both tagged, also VLAN 3, untagged)
The management network is at LAN2 (VLAN 3, untagged)
The "public" modem (router, really) goes to LAN3 (VLAN 1, untagged)
The "private" router goes to LAN4 (VLAN 2, untagged)
The switch's management interface also belongs to VLAN 3

First set everything up, then connect all networks. Otherwise, the DHCP services might interfere with each other.
The traffic that leaves LAN1 can be distributed using normal switches. They don't have to be VLAN-aware/enabled.


Q:

What is the frequency distribution for luminosity classes in the Milky Way Galaxy?

I'm working on a game concept that does some mild simulation of realistic stellar classes and luminosities. In particular, I'd like to roughly model the general frequencies of the classes and luminosities of the stars in the Milky Way.
Several sources, including Wikipedia's entry on stellar classifications, show a chart that includes the frequency distribution for spectral classification: the OBAFGKM categorization. So that's fine.
What I'm having trouble finding is any frequency distribution chart similar to that one but for the Yerkes luminosity categories: Ia+, Ia, Iab, Ib, II, III, IV, V, sub-dwarf and dwarf. I have a copy of the Hipparcos database, which contains a "Spectral Types" field, but it's highly incoherent text. Still, I could write some code to parse the values in that field to try to get a rough count of luminosity categories in those roughly 116,000 stars... but I'm a little perplexed that no such chart appears to exist already somewhere in Internetland. (Either that or my search-fu is weaker than usual.)
If anyone can point me to a chart of the frequency distribution for the luminosity categories noted above, or suggest a reasonably simple way for me to calculate those values myself, I'd appreciate it.
EDIT: Out of curiosity, I went ahead and did my own simple parsing of the spectrum fields from the Hipparcos dataset.
Out of 116472 rows, only 56284 (fewer than half) provided luminosity class data in the Spectrum field. Those 56284 rows broke down this way:
Ia0     16     0.03%
Ia     241     0.43%
Iab    191     0.34%
Ib     694     1.23%
I       17     0.03%
II    1627     2.89%
III  22026    39.13%
IV    6418    11.40%
V    24873    44.19%
VI      92     0.16%
VII     89     0.16%
Note: Around 1000+ rows gave an either/or value for luminosity class (e.g., "M1Ib/II"). In these cases, I counted only the first value provided. This probably skewed the results slightly compared to counting both luminosity classes.
I'm still very curious to know whether anyone else has produced or located a similar table of frequencies for the luminosity classes, if only to see how my very trivial analysis compares.

A:

Here is how you do it "properly" for the Hipparcos data. As Warrick correctly points out, what you have done in your question is massively biased towards giant and supergiant stars, which actually form the very small minority of stars.
You must form a volume limited sample. To do this, sort the stars by distance (1/parallax) and choose a cut off point. Your sample will always be incomplete, but the greater your distance cut off, the more incomplete it will be and it will become incomplete for more intrinsically luminous stars.
You have a philosophical problem to solve here in terms of what you are trying to achieve. The vast majority of stars in the Galaxy are faint M dwarfs with an absolute magnitude of $>10$. As Hipparcos is only complete to around magnitude 10-11, you will only get these M dwarfs in your subsample if you limit yourself to 10pc. But you will find that this sample contains no evolved stars (too rare) and no white dwarfs (too faint).
EDIT:
This has piqued my interest again, so I have a practical (approximate) solution, based on a two-part process. The first part involves a paper I wrote (actully an undergraduate experiment) based on the nearest 1000 stars to the Sun (from the Gliese & Jahreiss catalogue CNS3). This sample is roughly complete down to mid M-dwarfs, so everything else I say, and the results I give, only applies to a sample of stars more massive than that.
If you look at this volume-limited sample of 1000 nearby stars you can straight away say something about the relative numbers of different types of stars in the Galactic disk (saying something about stars anywhere else in the Galaxy is filled with much more uncertainty). A colour-magnitude diagram is shown below, and from this we see that:
The Sun is among the brightest of stars - brighter than 95% of other stars.
About 6% of the population are white dwarfs (though a few faint, old white dwarfs may still be missing from the sample). This makes sense. If you integrate a typical mass function assuming only stars more massive than about 1$M_{\odot}$ have even had time to become white dwarfs, then this is what you get.
Only 0.9% of the population are giants. The reason for this is that only a small proportion of stars are massive enough to have evolved into giants on the lifetime of the Galaxy. But once they are there, their lifetimes are short compared to the main sequence phase and most have become white dwarfs (see above).
There are a handful of objects, maybe 0.5%, that could be classified as subdwarfs, between the main sequence and the white dwarfs.
So, in broad terms: 92.5% of stars (above $\sim 0.2M_{\odot}$) are main sequence (class V), 6% are white dwarfs, 1% are giants (class III) and 0.5% are subdwarfs (class VI).

There are no very massive stars or supergiants in the immediate solar neighbourhood. That is because they are very rare. To get a better estimate we need to look at a larger volume limited sample. To do this I took all the stars (about 7000) from the Hipparcos catalogue that are closer than 50pc and assumed this was complete to just below a solar luminosity and assumed that those stars with an absolute magnitude brighter than the Sun (1949 stars with $M_V<4.5$ represent 5% of the total population in this volume. The absolute magnitude vs colour diagram for this sample is shown below.
Of these 1949 luminous stars, I find roughly 190 are giants - giving a giant fraction of $5\times 190/1940=0.5$%, in reasonable agreement with the nearby star sample based on smaller numbers. There are still NO supergiants, even in this larger sample. Thus supergiants have a frequency of $\leq 5 \times 1/1949 = 0.0025$%. i.e. less than 1 star per 40,000 is a supergiant.

A:

There are other techniques to construct what you're interested in than making a volume limited sample. What you're trying to construct is called a "luminosity function," it's the distribution in luminosity normalized so that the area under the curve integrates to the volume density of stars. Constructing a volume limited sample is, perhaps the simplest method of addressing the problem @RobJeffries describes, known as Malmquist bias. Another technique, known as $1/V_{\mathrm{max}}$, can be summarized as binning by luminosity, then weighting each star by the true volume it could occupy and still be in the luminosity bin. If you have a minimum flux for stars in the sample, $F_{\mathrm{min}}$, no maximum flux, and a maximum distance $d_{\mathrm{max}}$, then the weighting for each star will be:$$w_i  = \frac{3}{\Omega \operatorname{min}\left(d_{\mathrm{max}}, \sqrt{\frac{L_i}{4\pi F_{\mathrm{min}}}}\right)^3\,\Delta L_i},$$ where $\Omega$ is the solid angle on the sky of the survey, $d_{\mathrm{max}}$ is the maximum distance allowed, $L_i$ is the luminosity of the individual star labeled with index $i$, and $\Delta L_i$ is the width of the luminosity bin star $i$ is in.
You'll also need to figure out where your sample comes from. It is well known that the population of stars in the Milky Way varies by location:

At present the galaxy is thought to contain two or three luminous populations (e.g. Wyse 1992). The thin disk and stellar halo correspond to Baade's Pop. I and II, respectively. Still under debate is the existence of a thick disk population which might correspond to the thick disks seen in some other disk galaxies.

If you limit your study to a single star cluster you can even discover its age. Constructing a Hertzsprung-Russell (HR) diagram, a bivariate distribution on which luminosity is along one axis, and measuring where the stars are pealing away from the main sequence is one way to measure the age of a star cluster.


Q:

performance hit when eager loading entity using nhibernate with mvc

I have a web app that I am building using asp mvc with nhiberante 3.0.
I have the following code for querying my data -
ICriteria rowCount = session.CreateCriteria(typeof(entity1));

rowCount.SetResultTransformer(CriteriaSpecification.DistinctRootEntity)
                .SetProjection(Projections.RowCount());

ICriteria query = session.CreateCriteria(typeof(entity1));

query.SetFetchMode("entity2", FetchMode.Eager);
query.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);
query.SetFirstResult((pageIndex - 1) * pageSize);
query.SetMaxResults(pageSize);

query.Future<entity1>();

return new PagedList<entity1>(query.List<cshearin>(), pageIndex, pageSize, rowCount.List<Int32>().FirstOrDefault());

Now this is returning the correct data to my view, but the performance is awful.  If I do not eager load entity2, the performance is great.  The only problem with that is the view is then doing working with the data which I've read is not good practice.
Is it ok to have the view do this little bit, or is that bad practice?  If it is bad practice, is there a better way that I can build this class for my data access?
Thanks for any thoughts.
EDIT - my mappings are pretty straightforward.  Here is a simplified version.
entity1 -
<class name="entity1">
    <id name="entity1_id">
      <generator class="guid.comb"></generator>
    </id>

    <property name="column"></property>
    <property name="column"></property>\

    <bag name="entity2" cascade="all">
      <key column="entity2_fk" />
      <one-to-many class="entity2"/>
    </bag>

  </class>

and entity2 -
<class name="entity2">
    <id name="entity2_id">
      <generator class="guid.comb"></generator>
    </id>

    <many-to-one name="entity1" column="entity2_fk" />

    <property name="columnx"></property>
    <property name="columny"></property>

  </class>

I will also have to look into using projections to pass to my view - that may be a valid answer.

A:

You should find the reason of bad performance. Use a tool like Profiler (Sql Server) to see the queries generated by NH, or let NH write it to the console (show_sql) or log.
You may:

need an index on the foreign key to get entity2
make use of batch-size to get entity2 in batches instead one by one.
order by creation date to read newest data first, it may already be in the cache of the DBMS.


Q:

How to detect cross thread access in .NET (enforce thread affinity)?

I'm writing a special data structure that will be available in a .NET library and one of the features of this data structure is that is will be thread safe provided that only one thread writes data to it, and only one thread reads data from it (the reader thread and the writer thread can be different).
The question is how can I enforce that all Read operations are executed by the same thread?
My solution would be capture the System.Threading.Thread.ManagedThreadID and store it in a private member upon the first Read. Then, on subsequent reads to check the ManagedThreadID against the saved one and if they are different to throw an exception.
Is that enough, or is there a different more reliable mechanism for doing this.
Note: There is a requirement that this library be usable without a Windows.Forms context..

A:

When I run into this situation I use a class I wrote called ThreadAffinity.  It's entire purpose is to record the current thread and throw on invalid accesses from a different thread.  You have to manually do the check but it encapsulates the small amount of work for you.
class Foo {
  ThreadAffinity affinity = new ThreadAffinity();

  public string SomeProperty {
    get { affinity.Check(); return "Somevalue"; }
  }
}

Class
[Immutable]
public sealed class ThreadAffinity
{
    private readonly int m_threadId;

    public ThreadAffinity()
    {
        m_threadId = Thread.CurrentThread.ManagedThreadId;
    }

    public void Check()
    {
        if (Thread.CurrentThread.ManagedThreadId != m_threadId)
        {
            var msg = String.Format(
                "Call to class with affinity to thread {0} detected from thread {1}.",
                m_threadId,
                Thread.CurrentThread.ManagedThreadId);
            throw new InvalidOperationException(msg);
        }
    }
}

Blog post on the subject:

http://blogs.msdn.com/jaredpar/archive/2008/02/22/thread-affinity.aspx


Q:

What does "storm–the–gates populism” mean?

I was drawn to the words "storm-the-gates populism" in the following passage of the New York Times’ (February 15) article that came under the title, "Donald Trump escalates rhetoric before South Carolina primary":

"If Mr. Trump wins the primary on Saturday, as every public poll shows
  him on track to do, it will be after reverting to the storm-the-gates
  populism that led to his political rise and refusing to back down amid
  criticism."

I googled for the clue to fathom out the meaning of "storm-the-gates populism" and picked up the following three related sources:

Storm the Gates of Hell is the fourth studio album by Christian metal band Demon Hunter, released on November 6, 2007, which apparently seems to be irrelevant to the case.
When we storm the gates of hell, the church is marching into all the hells in this world, ready to reclaim every square inch for Christ. And when we storm the gates of hell, Christ promises we cannot fail. We will prevail! It’s time to put the devil on the run. The phrase pulai hadou (gates of hell) is a Jewish expression meaning "realm of the dead." — Ligoniel Ministries.
In Matthew 16, Jesus asks his disciples the question: “Who do people say that the Son of Man is?” Then Cephas pipes up: “You are the Christ, the Son of the living God.” Jesus commends his outspoken disciple: “You are Peter, and on this rock I will build my church, and the gates of hell shall not prevail against it” . – ibid.

Given the above input, still I’m not able to come to the clear notion of "storm–the-gates populism." Is "storm the gates" totally irrelevant to "storm the gates of hell"?  What does it mean? Is it a well-estabished phrase, or a political buzzword?

A:

"Let's storm the gates of the castle!"

is what the townspeople in all those old Turner Classic movies shout to each other when they're fed up with being treated poorly. This is where the author's reference stems from.
One specific example are the disgruntled villagers with pitchforks and torches who, outraged and angry, rush Dr. Frankenstein's castle...you know that scene. It's been in millions of movies. That's a storm-the-gates mentality.
Another is the lyrics to the song "Burn Down The Mission" by Elton John:
Bring your family down to the riverside
Look to the east to see where the fat stock hide
Behind four walls of stone the rich man sleeps
It's time we put the flame torch to their keep

"Storming the gates" is shorthand for the common people taking back control. It's a mob composed of people without power, who gather together to attack the more powerful, with the goal being an overthrowing, rebellion or revolution.
So storm-the-gates populism, for example, would be the 90% of Americans who have just 25 percent of the country's wealth banding together to attack the 10% of Americans who hold 75 percent of the wealth.
It is not an official phrase, as far as I know. But I happened to "get it," and I thought it was a really nice turn of a phrase by the author.


Q:

How can I minimize the max of the sum of my columns?

The problem that I'm trying to solve is simple (I guess :)), but because I'm new to z3 I'm always getting compile errors.
My problem:
[ [var_0_1, var_0_2, var_0_3,...]
, [var_1_1, var_1_2, var_1_3,...]
, [var_2_1, var_2_2, var_2_3,...]
]

My objective is to sum the value of the columns and then discover the max of all the sums and after that minimize that value and do that all over again until It's impossible to minimize more the max of the sum of all columns...
I hope that you understand my problem because my English is not very good :)
Thanks in advance!

A:

Initially, I thought that you were trying to solve some minmax() problem because you stated that you wanted to solve

minimize(max(sum(var01,Var11,Var21),sum(var02,Var12,Var22), etc...))

in the comments. However, further requirements elicitation made it clear that it couldn't possibly be an instance of minmax(), so I ditched the idea and didn't think about it any further.

Now, your self-posted solution is an instance of maxmin() in disguise. I am not sure whether that really solves your initial problem. However, if that is the case, then I would advice you to try to use the following encoding instead of the ite-based solution [references: tacas15, tacas15_extended].

(note: cost ought to be a new variable of the same type as the cost_i, which is declared for the purpose of solving the maxmin() goal. Every other cost_i is demoted from objective to a simple term)
I believe that this approach has some chance to perform better than the other one.

EDIT: source code example with a = 0:
goal = Real("cost")
for y in zip(*time):
    s.add(sum(y) <= goal)
result = s.minimize(goal)

If you want to replicate the case in which a = 50:
goal = Real("cost")
for y in zip(*time):
    s.add(sum(y) <= goal)
s.add(50 <= goal)
result = s.minimize(goal)


Q:

ngRoute set base url for all routes

Is it possible to add a base url to all routes in an AngularJS app? Essentially changing its location on the server (kind of, if that makes sense... so it would be accessed not via / but via /something/).
To add some context, I am trying to place an existing Angular app behind some authentication  such that the app would now be accessed at address say http://mysite/secure after successful login.
The problem is if I was to load the app at http://mysite/secure it works fine (the server will obviously serve up the correct page), but clicking any link would result in a page reload and route to http://mysite/#newpage instead of http://mysite/secure/#newpage.
Without adding /secure/ to all of the routes and link element is this possible? Cheers, sorry if that is not worded well.

A:

The location for the base href must have trailing /. For example:
<base href="location" />

will not work. It must be in this format:
<base href="location/" />

A:

Setting the <base> HTML5 tag might help.  From the documentation here:

Relative links
Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.
Running Angular apps with the History API enabled from document root is strongly encouraged as it takes care of all relative link issues.


Q:

Finding the Nth element in a list of all possible numbers

This is an extension of my question found here:
Given some number of digits, each with a have a specified range from 1 to some number, what would be the Nth element in the list of all permutations of them found by first modifying the inner most digits.
For example, given 3 digits, the first one having a range of [1..3], second having [1..2] and third [1...4], the list would be
1 1 1
1 1 2
1 1 3
1 1 4
1 2 1
1 2 2
1 2 3
1 2 4
2 1 1
2 1 2
2 1 3
 ...

How would you find the Nth element of these types of sets? Conversely, given a number, how would you find the position in this set?

A:

Let $S$ be the list of the number of possible value for each position in the list , and let $n$ be the position in the list. Let $i$ be the length of the elements of the list initially. The process for obtaining the element is:
$q = n/(prod_{x=0}^{i}S_i)$
$n = n\bmod prod_{x=0}^{i}S_i+1$
$i = i-1$
And each successive value of $n$ is the $i$th digit of the element.
Given an element the position is $\sum_{x=0}^{\text{length of the elements of the list}}\prod_{x=0}^{i}\times(\text{xth digit of the element from left to right}-1)$
Basically this problem is a degenerate case (a general case) of converting into bases, except that 1 is used for 0, 2 for 1, (so 1111 in this list would map to 0000), etc. I'll post a proof soon. Not sure if it is correct; will verify this later. Also the output/input might be zero-indexed (starting from zero).


Q:

read plist iphone sdk

I am trying to read a plist file using this -
NSData *data = [NSData dataWithContentsOfFile:SettingsFilePath];

NSPropertyListFormat format;
NSArray *array = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:nil];

but its not working.. is there any other way of doing this?

A:

try with this way -
  NSArray *arr= [[NSArray alloc] initWithContentsOfFile:plistPath];


Q:

How to call a function repeatedly with 5 seconds delay? (ASP.NET with C#)

I have a some piece of code in Default.aspx.cs file which is written within Page_Load function like this:
protected void Page_Load(object sender, EventArgs e)
{
    //code stars here
    ...
    //code ends here
}

What i want is that this piece of code will run continously with 5 seconds delay. How can I do this here?
Thank You.

A:

Looking at your comments I see your actually building a chat facility, which makes more sense regarding the continous requests every 5 seconds.
I would recommend using ASP.NET Web Methods and AJAX technology to achieve this.
Using jQuery.ajax you can make a request every 5 seconds in javascript to return new chat messages
Something like the following would be a good start for your javascript/jquery:
setInterval(function () {
                    $.ajax({
                        url: "/Chat.asmx"
                            , type: "POST"
                            , contentType: 'application/json; charset=utf-8'
                            , data: '{ ConversationID: "' + ConversationID + '"}'
                            , dataType: 'json'
                            , success: function (data) {

                                //do something with data

                            }
                    });
                }, 5000);

Chat.asmx would then be your Web Method. Look into ASP.NET Web Methods for more info:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
A quicker method, but not as recommended, would be to use jQuery.load where you could have the chat messages in a repeater on a standalone .aspx page and keep loading this into a div on your page like:
setInterval(function () {
     $(".chatmessages").load("ChatConversation.aspx?id=" + ConversationID);
}, 5000);

See jQuery.load for more info on this


Q:

IWindsorContainer - when to call Release()

When I have resolved a component using container.Resolve(), and I have finished using it, should I call Release()?
At the moment I call Dispose on any IDisposable that the container has got for me. Should I not call Dispose() on the object, but instead call Release() on the container instead? Does it do the same thing?
Thanks
David

A:

Short answer:

Release what you Resolve (explicitly, or implicitly - via typed factory)
Dispose what you create and own. (and you don't own what container creates, so don't dispose it - container will).

Long answer: I wrote a blogpost going into more details
The documentation on lifestyles goes into more depth as well


Q:

Why I get error when I try to initialize an array?

I want to initialize an array with n+1 elements and assign the first element with value, so:
  #include <iostream>

  using namespace std;

  double arry(int n,double s0);
  int main()
  {
    arry(10,24.543);
   return 0;
   }

  double arry(int n,double s0){
  double s[n+1]={};
  s[0]=s0;
   for(int i=0;i<11;i++){
    cout<<i<<"="<<s[i]<<endl;
      }
  }

It seems to be right, but when I run it, i got an error  message in the line 13 as follows:

error: variable-sized object 's' may not be initialized

Can anybody fix it?  Much appreciated.

A:

 double s[n+1]={};

s[n+1] is not allowed in C++. You should use a compile time constant. Like, s[10]; or,
#define INDEX 10
double s[INDEX + 1]={};


Q:

Maven distributionManagement or Server (User and Password) as parameter

I have a remote repository using Nexus.
These Repositories asks for login, I would prefer to expose these repositories with login.
This is my settings.xml
<settings>

<servers>
    <server>
        <id>dev-repo</id>
        <username>user</username>
        <password>password</password>
    </server>
</servers>

</settings>

And the developers are using a pom.xml with:
<distributionManagement>
            <repository>
                <id>dev-repo</id>
                <url>http://ip:port/nexus/content/repositories/dev-repo/</url>
            </repository>
    </distributionManagement>

With that configuration everything is OK, but I prefer they have to pass the login in the mvn command or the command ask with a prompt the login instead hard code the login in settings.xml
Any ideas?
Thank you in advance.

A:

It's quite easy: The settings.xml file allows variables. Replace user and password by named variables:
<servers>
    <server>
        <id>dev-repo</id>
        <username>${user}</username>
        <password>${password}</password>
    </server>
</servers>

And then, provide explicit values when invoking to Maven:
mvn -Duser=... -Dpassword=... install


Q:

When you close off the mouth of a vacuum cleaner, is it using more energy?

When you close off the mouth of a vacuum cleaner it seems that you let the cleaner do more work (I always have the feeling something is gonna be burned inside) and thus let it use more energy. Now I'm not an expert in the field of vacuum cleaners, so I was wondering if this is actually true. Any expert who can tell me the answer?

A:

Most vacuum cleaners have a universal motor and use a centrifugal pump.
So, with NO air going through, it has a partial vacuum created, and
maintains it, but without doing any work.   It can burn the motor up,
because that air movement also cools the motor, but that isn't because
the motor has extra 'load', it's just lack of cooling.
There is some load due to leakage and viscosity, and the motor does
(at least MINE does) speed up when airflow is blocked.   A wattmeter
on the vacuum shows energy use dropping from 660 W to 520W.
It isn't dramatically less because the faster-moving motor is losing more
energy to air viscosity outside the vacuum flow path.   It doesn't lose
any energy to air viscosity IN the flow path, when the flow is zero.


Q:

Hide a .desktop file on the Desktop [Ubuntu 13.04]

I have made a .desktop launcher for my dock. I try to put a "." after the name of file, but he doesnt hide. Exemple : .Firefox.desktop If i delete it, my Firefox icon in my dock can't be open. I have to hide my desktop file, Thanks !

A:

To show or hide a .desktop file in a given desktop environment we should use its corresponding entry keys:
OnlyShowIn=<environment>;
NotShowIn=<environment>;

Hence the follwing entry will only show the desktop file in GNOME (e.g. classic), and KDE but not in Unity:
OnlyShowIn=GNOME;KDE;

Or, alternatively we may wish to define en exclusion with
NotShowIn=Unity;


Q:

Cache all database queries in rails 2.3

How can I cache all of my queries.
first request:
@user = User.all

second request
@user = User.all # Cached

Are there any useful plugins to do this?
I'm on production mode. I can't seem to see any cached phrase to confirm that my rails app is caching.

A:

in your config/environments/production.rb

config.action_controller.perform_caching = true

caching is disabled by default for development and test, and enabled for production.
Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
For example:

 class UsersController < ActionController

 def index
   # Run a find query
   @users = User.all

   ...

   # Run the same query again
  @users = User.all

   end

 end

The second time the same query is run against the database, it’s not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it’s pulled from memory.
Check it at your console

User Load (?ms)  SELECT User.* FROM User
Completed 200 OK in ?ms (Views: ?ms | ActiveRecord: ?ms)

You can compare it with first time load and second time load.
You can use Dalli gem from https://github.com/mperham/dalli for store your cache to memcached server.


Q:

How to find/highlight HTML tags in a large block of text that aren't one of a list of allowed tags?

I have a large dataset containing lots of rich-text edited content blobs which are being migrated to another system.  The new system is stricter than the old when it comes to allowed HTML tags and we need to be able to identify what tags in the data would be cut or encoded and included in the content in a bad way on entry, before we migrate the data.
So for example given this HTML:

My page

Lorem ipsum<marquee>SURPRISE!</marquee>

We wouldn't be interested in the "h1" and "p" tags (which are listed in an exception list somewhere,) but ideally we'd want to be able to see the "marquee" tag highlighted so in a visual spot check the bad tags can be easily identified and manually dealt with (right now we don't anticipate there being many bad tags in the dataset.)
It's easy to strip unwanted tags (thinking simple PHP/Python/whatever) - but we don't want to do that and potentially lose data.
Equally it's easy to encode tags, but we don't want to import ugly useless tags as part of the content.
What's the best way of doing this kind of thing?  I can't help but think there's a simple solution I'm missing or that I'm thinking about it the wrong way.

A:

CSS may be your friend in this case
   * {
     text-decoration: line-through;
    }
   h1, p <list other allowed tags> {
    text-decoration: none;
    }


Q:

bash: wget in a loop, strange addresses

I wrote a small bash script that downloads plugins from wordpress plugin directory based on a plugin-name list. It works, but it seems like wget is called more times than neeeded with strange arguments.
#!/bin/bash

pluginlist="list" #plugin list, line by line

outputdir="output"

urlprefix="http://downloads.wordpress.org/plugin"

ua="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/20070802 SeaMonkey/1.1.4"

if [ ! -f "$pluginlist" ]; then

    echo List \file "$pluginlist" does not exist\!;
    exit
fi

while read plugin_name; do

    wget -U $ua -O $outputdir/$plugin_name."zip" $urlprefix/$plugin_name."zip"

done <$pluginlist

echo \done

Sample output:
--2015-11-23 22:47:45--  http://(x11;/
Resolving (x11; ((x11;)... failed: Name or service not known.
wget: unable to resolve host address ‘(x11;’
--2015-11-23 22:47:45--  http://u;/
Resolving u; (u;)... failed: Name or service not known.
wget: unable to resolve host address ‘u;’
--2015-11-23 22:47:45--  http://linux/
Resolving linux (linux)... failed: Name or service not known.
wget: unable to resolve host address ‘linux’
--2015-11-23 22:47:45--  http://i686;/
Resolving i686; (i686;)... failed: Name or service not known.
wget: unable to resolve host address ‘i686;’
--2015-11-23 22:47:45--  http://en-us;/
Resolving en-us; (en-us;)... failed: Name or service not known.
wget: unable to resolve host address ‘en-us;’
--2015-11-23 22:47:51--  ftp://rv/1.8.1.6)
           => ‘output/add-meta-tags.zip’
Resolving rv (rv)... failed: Name or service not known.
wget: unable to resolve host address ‘rv’
--2015-11-23 22:47:56--  http://gecko/20070802
Resolving gecko (gecko)... failed: Name or service not known.
wget: unable to resolve host address ‘gecko’
--2015-11-23 22:47:56--  http://seamonkey/1.1.4
Resolving seamonkey (seamonkey)... failed: Name or service not known.
wget: unable to resolve host address ‘seamonkey’
--2015-11-23 22:48:06--  http://downloads.wordpress.org/plugin/add-meta-tags.zip
Resolving downloads.wordpress.org (downloads.wordpress.org)... 66.155.40.188, 66.155.40.186, 66.155.40.187, ...
Connecting to downloads.wordpress.org (downloads.wordpress.org)|66.155.40.188|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://downloads.wordpress.org/plugin/add-meta-tags.zip [following]
--2015-11-23 22:48:07--  https://downloads.wordpress.org/plugin/add-meta-tags.zip
Connecting to downloads.wordpress.org (downloads.wordpress.org)|66.155.40.188|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 271770 (265K) [application/zip]
Saving to: ‘output/add-meta-tags.zip’

output/add-meta-tag 100%[=====================>] 265.40K   182KB/s   in 1.5s

2015-11-23 22:48:09 (182 KB/s) - ‘output/add-meta-tags.zip’ saved [271770/271770]

FINISHED --2015-11-23 22:48:09--
Total wall clock time: 25s
Downloaded: 1 files, 265K in 1.5s (182 KB/s)

So it's getting a lot of strange addresses before it gets the correct one. I have no idea why this happens.

A:

You need to quote your user agent string:
wget -U "$ua" -O $outputdir/$plugin_name."zip" $urlprefix/$plugin_name."zip"

Otherwise, bash will split this on spaces and pass it to wget as multiple args... which it is trying to treat as URLs.


Q:

Smallest number in 2d array not working correctly

I am trying to find the smallest number in the array.
When i execute this code, it shows "23" as smallest.
I am not able to find the mistake, can anyone help me out?

Here is the code to find the smallest number in 2d array which i tried.
When i execute this code, it shows "23" as smallest.
I am not able to find the mistake.
public class arraymin {
    public static void main(String args[])
    {
        int arr1[][]=new int[][]{{23,32,10,44},{44,33,22,11}};
        int minvalue=arr1[0][0];
        for(int i=0;i<arr1.length;i++)
        {
            for(int j=0;j<arr1.length;j++)
            {
                if(arr1[i][j]<minvalue)
                {
                   minvalue= arr1[i][j];
                }
            }
        }
        System.out.println("Min Value is: "+minvalue);
    }
}

A:

You inner loop should be
for(int j=0;j<arr1[i].length;j++)

since the number of columns is different than the number of rows.
And the full code:
public class arraymin {
  public static void main(String args[])
  {
    int arr1[][]=new int[][]{{23,32,10,44},{44,33,22,11}};
    int minvalue=arr1[0][0];
    for(int i=0;i<arr1.length;i++)
    {
        for(int j=0;j<arr1[i].length;j++)
        {
            if(arr1[i][j]<minvalue)
            {
               minvalue= arr1[i][j];
            }
        }
    }
    System.out.println("Min Value is: "+minvalue);
  }
}

Your current code only checks the first two columns in each row, so out of 23,32,44 and 33, 23 is the smallest number.


Q:

How much would you revalue your hand after finding a "double fit?"

Suppose you hear your partner open one spade. You, the responder (North) have:
(s)Kxx (h)xx (d)xxx (c)AKxxx, and respond two clubs. Opener now bids three clubs, showing you a "double fit" in spades and clubs.
You have ten high card points, and presume that opener has at least 13, for a total of at least 23. Normally, that's not quite enough for game, but the double fit has increased the value of your hands. Can you go directly to four spades on the theory that the double fit is worth 2-3 points, thereby bringing you to 25-26 (adjusted)? Or should you stop at three spades and let partner decide based on whether he has a minimum or more?
Suppose you were opener, and heard partner (responder) stop at 3 spades. You have (s) AQJxx (h)Kxx (d)xx (c) QJx. You assume that he has a bare 10, and you have only 13. Can you go to 4S on the basis of the double fit?

A:

Let's give partner a fitting minimum for the first auction; one that fits nicely but is otherwise as weak as possible:
S: AJxxx
H: x
D: KJX
C: QTxx

This hand by partner has only 11 HCP, evaluates to exactly 13 total points as opener, and there are excellent chances to make 4S, especially with an attacking diamond lead being up to partner's holding.
Let's also consider a non-fitting maximum hand for partner, with the maximum possible non-working values:
S: Qxxxx
H: AQ
D: AQ
C: xxxx

Again 4S has a good play, with one sure loser in trumps and good chances that the rest of the hand can be managed for only two losers.
These two hands illustrate the principle that if one's own values are strongly fitting, as in the hand given, and especially when one is the weaker hand of the partnership, one can be aggressive. Practice visualizing typical fitting minimum and non-fitting maximum hands for partner in the bidding, and evaluate your own holding against those when deciding whether to bid or invite game/slam. Caveat: Be very careful to not place cards in partner's hand when doing so. It is easy to engage in wishful thinking when doing this exercise, so you must consciously restrain your self until that becomes second nature.
Let's try the flip side; partner's fitting minimum could be something like:
S: xxx
H: x
D: KJTx
C: Axxxx

This is about as bad a hand as partner could come down with, 8HCP and 10 total points, yet 4S is not hopeless despite the mismatch in the red suits. Even small additions like ST or C9 start looking like big cards. Vulnerable at IMPS bidding this game is mandatory, and perhaps also non-vulnerable at IMPS, but at MatchPoints I'd rather play 3S and trust partner to bid game herself when holding a hand like
S: Kxx
H: xx
D: xxx
C: AKxxx

Update:
The three distinctive marks of a weak player are:

not counting;
still not counting; and
thinking that hand evaluation ends with counting points, when in fact it only begins with counting points.

Note that the examples of hand visualization given above all start with counting - of points, distribution, potential losers and winners - of things that cannot yet be seen in partner's hand but must be visualized. One begins to approach expert status only when this process starts to become second nature.  In many senses an expert performs this visualization first; decides on the appropriate call based on this visualization; determines what the value of the hand is based on the call and bidding system; and only then decides how that value is apportioned as HCP and distribution and fitting points.


Q:

Haskell - Map of functions that take the same map

I am currently writing a programming language in Haskell. This programming language is similar to Factor, being a concatenative stack-based language. However, after getting quite far, I hit a brick wall: I have a Data.Map of type:
Map.Map String ([YodaVal] -> YodaVal, Int)

But I need the functions stored in the map to take the map as a parameter, so I can preserve environment when recursing, and also to possibly allow recursive function definitions, and recursive definitions of Haskell --> Yoda functions. However, the type would then look like:
type Env = Map.Map String ([YodaVal] -> Env -> [YodaVal] -> YodaVal, Int)
 Which of course expands to:
Map.Map String ([YodaVal] -> Map.Map String ... -> [YodaVal] -> YodaVal, Int)

A:

You can describe infinite types with a newtype:
newtype Env = Env {getEnv :: Map String ([Val] -> Env -> [Val] -> Val, Int))}

This will typecheck, and the runtime representation will be as if there were no wrapper.


Q:

How to create a function that returns a generic protocol type?

In the following code, I have a generic protocol Var and it have a private implementation class LambdaVar. Now I want to have a function that return an instance of the LambdaVar without expose it publicly.
But I can't find a way to define a function that return a generic protocol type.
public protocol Var {
    typealias ValueType
    var value : ValueType { get }
}

struct LambdaVar<T> : Var {
    let _get : Void -> T
    init(_ f : Void -> T)
    {
        _get = f
    }
    var value : T {
        get {
            return _get()
        }
    }
}

public func transform<T : Var, U>(v : T, f : T.ValueType -> U) -> Var<U> {
    return LambdaVar<U>() { f(v.value) }                       // ^^^^^^ what to put here?
}

Error:
Playground execution failed: <EXPR>:26:67: error: cannot specialize non-generic type 'Var'
public func transform<T : Var, U>(v : T, f : T.ValueType -> U) -> Var<U> {
                                                                  ^
<EXPR>:26:67: error: protocol 'Var' can only be used as a generic constraint because it has Self or associated type requirements
public func transform<T : Var, U>(v : T, f : T.ValueType -> U) -> Var<U> {

A:

You should create simple wrapper type of Var like SequenceOf<T>:
struct VarOf<T>:Var {
    let f:Void->T
    init<V:Var where V.ValueType == T>(_ v:V) {
        f = { v.value }
    }
    var value:T {
        return f()
    }
}

func transform<T : Var, U>(v : T, f : T.ValueType -> U) -> VarOf<U> {
    return VarOf(LambdaVar<U>({ f(v.value) }))
}

let intVar = VarOf(LambdaVar({ 12 }))
let floatVar = transform(intVar, { Float($0) })
floatVar.value // -> 12.0


Q:

jQuery UI draggable has jerky transition on drop

I have a simple drag and drop functionality that I'm attempting to get working. I have cards that are draggable and can be dropped on top of other cards to swap positions with the other card. Here's a fiddle with the functionality in place: https://jsfiddle.net/vj0a9gp8/1/
The drag and drop code is pretty simple:
$(function() {
  $(".card").  draggable({
    revert: true
  }).  droppable({
    hoverClass: "card-hover",
    drop: function(event, ui) {
      swapNodes($(this).get(0), $(ui.draggable).get(0));
    }
  });
});

function swapNodes(a, b) {
  var aparent = a.parentNode;
  var asibling = a.nextSibling === b ? a : a.nextSibling;
  b.parentNode.insertBefore(a, b);
  aparent.insertBefore(b, asibling);
}

Basically when a card is dragged and then dropped onto another, the swapNodes function traverses up the dom and places them where they belong. This all works great. The issue, which you can see in the fiddle, is that when the drop occurs the dropped card kind of jerks off screen before animating in to place and it looks poorly overall. I've tried playing around with draggable.position to address and fix this functionality but all I've managed to do is make it worse. Any ideas?

A:

When you drag your element, it changes the left and top position. When you drop it, you change its position in the DOM, but you never specify a new top and left, so it still keeps the one set when dragging it. The animation is there because you have a revert to true, which puts back the original position and animates it.
Easy solution would be to set revert to 'invalid' (so only if there's no drop) and set the left and top in your swap function. Like this
revert: 'invalid'
...
b.style.left = '';
b.style.top = '';

https://jsfiddle.net/huw2Lkgb/1/


Q:

Format number with multiple dot grouping separators

I need to verify if a String displayed is numeric. The format of the value is 123.345.678,99.
I.e., the grouping separators are dots and the decimal separator is a comma.
I've tried the DecimalFormatter where I set the separators:
 DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance();
    DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
    symbols.setGroupingSeparator('.');
    symbols.setDecimalSeparator(',');
    formatter.setDecimalFormatSymbols(symbols);
    formatter.setGroupingUsed(true);

    System.out.println(formatter.format(incoming));

However, in this case, I'm getting

java.lang.IllegalArgumentException: Cannot format given Object as Number

I've tried also to add
formatter.applyPattern("###,###,###.##");

but it didn't help.
Any ideas?
I could also use regexp I guess but wanted first to make use of this DecimalFormatter if possible.

A:

I'd lose the currency, and just explicily create a new DecimalFormat with the relevant symbols. Once you have that, you should use it to parse the incoming string, not to format it:
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
dfs.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(dfs);

System.out.println(df.parse(stringToTest));


Q:

Java Optimization Questions

A lot of questions popped up while I was looking at my code. I would like to know what people think about some code snippets. For each one, I am wondering what is more optimized, and what is better practice or cleaner. Most likely, any possible optimization is on the scale of nanoseconds, I am just wondering theoretically. :)
1)The first one is a frequently called routine that needs  to report an error. Right now it looks like this
if(success)
 //Stuff
else
 reportInternalError();

Is any benefit to changing it to
if(success) {
 //Stuff
 return;
}
reportInternalError();

2)reportInternalError() is supposed to only report the error the first time it happens, and it can potentially be called very frequently. Currently, it is like this
if(!reported) {
 //Report error
 reported = true;
}

I am thinking about changing it to
if(reported)
 return;
//Report error
reported = true;

3)The last one is about duplicated code. I am using the exact same code twice, and I am trying to figure out a better way of writing it.
try {
 //Stuff
} catch(){
}

while(loop) {
 try {
     //Same Stuff
 } catch(){
     loop = false;
 }
}

Versus
first = true;
do {
 try {
     //Stuff
 } catch() {
     if(!first)
         loop = false;
 }
 first = false;
} while(loop);

Thanks!

A:

Don't worry about it. At this day and age, computer power is a lot cheaper than brain power, so optimize your code for readability, not for maybe gaining a few microseconds here and there.
Besides, the JVM's JIT compiler will most likely do these optimizations for you. And even if it doesn't, it has become so complex that modifications that look like performance gains, may actually slow you program down. Josh Bloch gave an excellent presentation on this subject at Devoxx last year.

A:

I would put a premium on readability and maintainability over micro-optimizations.  The gains from micro-optimization are really negligent (and often nil given the sophistication of today's compilers, JITs, and processors).
My choices:
1)
I try to put the normal case along the main code path and the exception cases in the branches:
if (! success) {
    reportInternalError();
}

// Stuff

2)
I favor the original approach.  The other way assumes the method will always to just want to return, but what if it needs to do more stuff in the future? I don't want that extra stuff to go in the branch:
if (! reported) {
    // Report error
    reported = true;
}
// extra stuff to do

3)
The refactored version seems more maintainable to me. I'm on the fence about replacing targetExceptionWasThrown with a simple break:
boolean isFirstIteraton = true;
boolean targetExceptionWasThrown = false;
do {
    try {
        //Stuff
    } catch() {
        if (! isFirstIteraton) {
            targetExceptionWasThrown = true;
        }
    }
    isFirstIteraton = false;
} while (! targetExceptionWasThrown);


Q:

Blue Dot Menu MVC - Use Server Control in MVC

I am using an MVC app to integrate Intuit Anywhere and an MVC app. I see there is a server control for the blue dot menu:
            <!-- Blue Dot Menu -->
            <div runat="server" id="blueDotDiv">
                <ipp:bluedot></ipp:bluedot>
            </div>

How do I integrate this server control inside of an MVC site?

A:

There is an Azure MVC Web Role template that you can use as a reference:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0200_DevKits_for_Intuit_Partner_Platform/0300_Windows_Azure_Program_for_Intuit_Anywhere/0003_Intuit_Anywhere_Azure_Web_Role_Templates
The div that wraps the Blue Dot menu in the ASP.NET WebForms sample project is used to control its visibility on the server side (hidden when user is connected), but you can implement hiding the control any way you want.
When the button is clicked, it calls the server side resource you have specified in the intuit.ipp.anywhere.setup javascript function, which in turn calls the AppMenu API to retrieve the content of the menu:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0025_Intuit_Anywhere/0020_Connect/0010_From_Within_Your_App/Add_the_Connect_Button
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0025_Intuit_Anywhere/0060_Reference/0010_AppMenu_API


Q:

Cравнение дат разных форматов в python

У меня есть 2 даты в виде строк. Зная изначально формат дат я бы сравнил так:
import time
date1 = "1/1/2013 12:00:00 AM" # дата формата "%m/%d/%Y %H:%M:%S %p"
date2 = "1/1/2016"             # дата формата "%m/%d/%Y"
format1 = "%m/%d/%Y %H:%M:%S %p"
format2 = "%m/%d/%Y"
if time.strptime(date1, format1) > time.strptime(date2, format2):
   pass

Как я могу их сравнить если изначально не знаю формата дат?

A:

Воспользуйтесь dateutil.parser:
from dateutil.parser import parse as dt_parse

Демо:
In [145]: dt_parse('1/1/2013 12:01:01 AM')
Out[145]: datetime.datetime(2013, 1, 1, 0, 1, 1)

In [146]: dt_parse('1/1/2013 12:33:33 AM')
Out[146]: datetime.datetime(2013, 1, 1, 0, 33, 33)

In [147]: dt_parse('1/1/2016')
Out[147]: datetime.datetime(2016, 1, 1, 0, 0)

In [148]: dt_parse('2017-05-10')
Out[148]: datetime.datetime(2017, 5, 10, 0, 0)

In [149]: dt_parse('28.02.2000')
Out[149]: datetime.datetime(2000, 2, 28, 0, 0)

дальнейшее сравнение дат проблем вызвать не должно


Q:

Extending maps from a submodule

I want to prove the following statement:
Let $M, L$ be $R$ - modules. If for every $(N, \phi: N \to L)$, where $N$ is a finitely generated submodule of $M$, $\phi$ can be extended to a map from $M \to L$, then any arbitrary submodules of  $M$ satisfy this as well.
My strategy: This reminds me of the Baer's criterion for injective module. Take an arbitrary submodule $N$, and $g: N \to L$, the idea for the proof is to consider all pairs $(\tilde N, f: \tilde N \to L)$, where $N \subset \tilde N$ is a submodule of $M$ and $f$ is the extension of $g$. Then use Zorn's lemma, we can find a maximal such element. Need to show this maximal element is $M$. Then I get stuck. Is this doable?

A:

This is false.  For instance, let $k$ be a field $R=k\oplus V$ where $V$ is an infinite-dimensional $k$-vector space, with multiplication on $R$ defined by $(a,v)\cdot(b,w)=(ab,aw+bv)$.  Let $M=R$ and construct $L$ as follows.  Start with $L_0=V$, which is an ideal of $R$.  For each finite dimensional subspace $W\subset V$ and each $R$-linear homomorphism $f:W\to L_0$, pick a linear complement $W^\perp$ to $W$ inside $V$, adjoin a generator to $L_0$ which is annihilated by $W^\perp$ and which is acted on by $W$ according to $f$.  Let $L_1$ be the module obtained by adjoining all these new generators.  Repeat the same process, adjoining generators to $L_1$ to obtain a module $L_2$, and so on.  Let $L$ be the direct limit of the $L_n$.
By construction, if $N$ is any finitely generated submodule of $M$, any homomorphism $N\to L$ extends to $M$.  Indeed, if $N$ is not $0$ or all of $M$, then $N$ is a finite-dimensional subspace of $V$, and then the image of our homomorphism $N\to L$ is contained in some $L_n$ and by construction we can extend it to a homomorphism $M\to L_{n+1}$.  On the other hand, note that every finitely generated submodule of $L$ is finite-dimensional over $k$ (by construction, every element of $L_0$ and every new generated we adjoined is annihilated by a complement of some finite-dimensional subspace of $V$ and thus generates a finite-dimensional submodule).  Thus the identity map $V\to V=L_0\subset L$ cannot be extended to a homomorphism $M\to L$, since if it were then its image would be a cyclic submodule of infinite dimension.

Here's another way to get a counterexample.  Let $R$ be any von Neumann regular ring which is not semisimple (for instance, an infinite Boolean ring).  Then every finitely generated ideal in $R$ is a direct summand, but there are non-finitely generated ideals which are not.  So, taking $M=R$ and $L$ to be a non-finitely generated ideal, every homomorphism from a finitely generated submodule of $M$ extends to all of $M$, but the identity map $L\to L$ does not extend to $M$.


Q:

How to obtain the value of a control added dynamically into Windows Form c#?

I read some articles and don't managed solved my problem, My problem is in the moment when I try obtain the value of the controls (CheckBox and ComboBox) added dynamically into Windows Form, I need know when the CheckBox is checked (or unchecked) and if the ComboBox is empty (or not) when I press a button, this button call a method in which I validate if all components are empty, I add the controls the following way:
 CheckBox box;
 ComboBox cmBox;
 for (int i = 1; i <= sumOfRegisters; i++)
 {
    box = new CheckBox();
    box.Name = "CheckBox" + i;
    box.Text = "Some text";
    box.AutoSize = true;
    box.Location = new Point(10, i * 25); //vertical

    cmBox = new ComboBox();
    cmBox.Name = "ComboBox" + i;
    cmBox.Size = new System.Drawing.Size(302, 21);
    cmBox.TabIndex = i;
    cmBox.Text = "Some Text";
    cmBox.Location = new Point(270, i * 25);

    this.groupBox.Controls.Add(cmBox);
    this.groupBox.Controls.Add(box);
}

"I add the values from database in the case of the ComboBox, I omitted this part."
I try obtain the value with a foreach:
foreach (Control ctrl in groupBox.Controls)

The problem is I don't have idea how to know if the Control (CheckBox and ComboBox) is checked or empty (as the case).
Really thanks for any help, I  appreciate your time.

A:

You are throwing away your reference to each dynamically allocated control after adding it to grbMateias.
One option is certainly to store those references, for example in a List<Control>.
List<ComboBox> comboBoxes = new List<ComboBox>();

for (int i = 1; i <= sumOfRegisters; i++)
{
    box = new CheckBox();
    comboBoxes.Add(box);
    // etc.
}

You can however just iterate the controls in grbMateias
 foreach(Control ctl in grbMateias.Controls)
 {
     if (ctl is CheckBox)
     {
         // Use the checkbox
     }
     else if (ctl is ComboBox)
     {
         // Use the ComboBox
     }
 }

or using Linq
var comboBoxes = grbMateias.Controls.OfType<ComboBox>();
var checkBoxes = grbMateias.Controls.OfType<CheckBox>();

A:

You could use the as operator, like so:
foreach (Control ctrl in groupBox.Controls)
{
    CheckBox checkBox = ctrl as CheckBox;
    ComboBox comboBox = ctrl as ComboBox;

    if (checkBox != null)   // Control is a CheckBox
    {
        if (checkBox.Checked)
        {
            // CheckBox is checked
        }
        else
        {
            // CheckBox is not checked
        }
    }
    else if (comboBox != null)  // Control is a ComboBox
    {
        if (comboBox.Items.Count == 0)
        {
            // ComboBox is empty
        }
        else
        {
            // ComboBox isn't empty
        }
    }
}


Q:

Why Stockfish 9 fails to see the draw?

I can reach a draw with White in the below position. The Stockfish 9, however, gives 28.1 points for black after Kf3,Ba1,Ke4,Bb2,Kd3.
[FEN "8/p7/kpP5/qrp1b3/rpP2b2/pP4b1/P3K3/8 w - - 0 1"]

1. Kf3 Ba1 2. Ke4 Bb2 3. Kd3 Ba1 4. Ke4 Bb2 5. Kd3 Ba1 6. Ke4 Bb2 7. Kd3 Ba1 8. Ke4

Why Stockfish 9 fails to see the draw?

A:

...... Stockfish isn't designed for solving a position like this. It's being written to play a good game of chess. Your position is not a position that SF should give an equal score.
The engine doesn't understand there's no mating possibility if White does nothing but moving the king. It gives a high score for Black because of the extra materials. Humans wouldn't even consider with any of the pawn capture, but SF has no idea.
Unfortunately, SF doesn't have the power to solve chess.


Q:

Generating function. Problem with understanding.

Let $F_0, F_1, F_2, ...$ be the Fibonacci numbers and let $f$ be the function defined
$$f(x) = \frac{x}{1-x(1+x)}$$
Solution:
The function $f$ is called the "generating function of the sequence $F_0, F_1, F_2, ...$
it is a "formal" algebraic expression in the sense that it behaves in a natural algebraic
way but the $x$ never takes a numerical value, the powers of it merely acting as
'place-markers' in the power series$^1$. Bearing that in mind, we see that
$$f(x) = F_0 + F_1x + F_2x^2 + F_3x^3 + ....$$
$$xf(x) =  F_0x + F_1x^2 + F_2x^3 + ....$$
$$x^2f(x) = F_0x^2 + F_1x^3 + ....$$
But we know that $F_2 = F_1 + F_0, F_3 = F_2 + F_1$, etc., and so subtracting the second
and third lines from the first gives us
$f(x)(1 - x(1 +x)) = f(x) - xf(x) - x^2f(x) = **F_0 + (F_1 - F_0)x** = x$
Please understand me it. I highlight what the most confuesed me.

$^1$ So what is x? f(x) is function or not? I'm so confused.

A:

This is a subtle point. The idea is that when you were manipulating the power series for $f(x)$ you never said anything about whether or not the series converged -- in other words, you were formally manipulating the series. A formal power series is just a power series used without talking about convergence.
To answer your question, $f(x)$ is not a function. In the (paraphrased) words of Herbert Wilf, a formal power series is a "clothesline on which we hang up a sequence of numbers for display". We use $f(x)$ to keep track of the Fibonacci numbers; that's all. In the same vein, you could use the series
$$
g(x) = 0! + 1!\cdot x + 2!\cdot x^2 + \cdots + n!\cdot x^n + \cdots
$$
to keep track of the factorial numbers even though the series converges only for $x=0$.


Q:

Adding elapsed TimeInterval to Date()

I'm trying to add the elapsed time to a Date() object (its for the resume button of a timed operation).
Below is the resume portion of the code responsible for calculating the altered startDate. I'm expecting it to add the elapsed TimeInterval to startDate.
This is the code:
print(startDate)
let elapsed = resumeTime - startDate.timeIntervalSinceReferenceDate
print(elapsed)
startDate.addTimeInterval(elapsed)
print(startDate)

This is the output when I paused the timer for about 3 seconds after about 2 minutes of runtime.
Output:
2016-11-17 08:24:15 +0000
110.831687986851
2016-11-17 08:26:06 +0000

The second printed date should be more like:
2016-11-17 08:24:18 +0000

The definition for addTimeInterval is:

Add a TimeInterval to this Date.

Isn't this exactly what I want? Am I interpreting this incorrectly?
Note, resumeTime is defined when the pause button is tapped. It is set like this:
resumeTime = Date.timeIntervalSinceReferenceDate

Thanks.

A:

This is the output when I paused the timer for about 3 seconds after about 2 minutes of runtime.

Although, your elapsed time is  2 min.
Make sure that you start elapsed in the right place, also make sure that this line generates the desired timestamp:
resumeTime = Date.timeIntervalSinceReferenceDate

Here is example of code very similar to yours, addTimeInterval does work well.
let resume = Date().timeIntervalSinceReferenceDate + 2

print(startDate)
let elapsed = resume - startDate.timeIntervalSinceReferenceDate
print(elapsed)
startDate.addTimeInterval(elapsed)
print(startDate)

Output
2016-11-17 08:53:34 +0000
2.00815904140472
2016-11-17 08:53:36 +0000


Q:

Makefile from one source Directory trying to access a cpp file from other Directory

I've an issue with object creation for a cpp files residing in 2 different directories as show below:
- Project-xyz
  - Hello
    - Hello.cpp
  - World
    - Main.cpp
    - World.cpp
    - Makefile

For better clarity here is how the code looks (just a dummy code).
hello/Hello.h
#ifndef HELLO_H
#define HELLO_H

void HelloPrint();

#endif // HELLO_H

hello/Hell.cpp
#include <iostream>
#include "Hello.h"

void HelloPrint()
{
  std::cout <<"Hello" << std::endl;
}

world/World.h
 #ifndef WORLD_H
 #define WORLD_H

 void WorldPrint();

 #endif // WORLD_H

world/World.cpp
#include <iostream>
#include "World.h"

void WorldPrint()
{
 std::cout <<"World!" << std::endl;
}

world/Makefile
Using a makefile given in here. Which is working fine. But it doesn't create any obj files.
# set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors

# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=

# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')

# find headers
HEADERS := $(shell find . -name '*.h')

OUTPUT := HelloWorld

# Everything depends on the output
all: $(OUTPUT)

# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)

clean:
     $(RM) $(OUTPUT)

I'm  looking at a solution which uses the makefile which generates the obj files in specific directory as shown here.
Now I'm trying to generate the obj files for hello/hello.cpp file in world/objdir/hello.o using the Below make file. Which is not working.
How to get it working?
world/Makefile
GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir $(OBJDIR)

$(OBJDIR)/%.o: %.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
    $(GCC) $(LDFLAGS) -o $@ $^
clean:
    @rm -f $(TARGET) $(wildcard *.o)
    @rm -rf $(OBJDIR)

When i try to run the make it throws the following error.
g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4

It is not able to generate the obj files for the hello/Hello.cpp file and hence throwing this error.
Any help from the makefile Masters is appreciated! :)

A:

Adding vpath %.cpp ../hello along with @gaoithe's solution has solved this issue.
vpath %.cpp ../hello
GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
OBJ+=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(notdir $(wildcard ../hello/*.cpp))))
TARGET=HelloWorld

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir $(OBJDIR)

$(OBJDIR)/%.o: %.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
    $(GCC) $(LDFLAGS) -o $@ $^
clean:
    @rm -f $(TARGET) $(wildcard *.o)
    @rm -rf $(OBJDIR)

now
$ ls objdir/
 Hello.o  main.o   World.o

Experts need to evaluate the new makefile and confirm if this is a scale able solution?
Any inputs on optimising/enhancing the current makefile and help in reducing the build time is highly appreciated.


Q:

Comando en Linux

Necesito crear un archivo, asignandole por contenido un listado de los comandos del sistema operativo LINUX.
Tengo dicha pregunta en un parcial y no se como se resuelve. Alguien que me pueda dar una mano? Se agradece info!

A:

Intenta usar el comando que quieres seguido > y el nombre del archivo en donde se almacenara los resultados del comando, el archivo lo creara el sistema, intenta algo como:
help > archivo.txt

ls > archivo2.txt

y se creara un archivo en la ruta donde abriste la consola de comandos.


Q:

How can one know if a Proc is a lambda or not in Ruby

Suppose I have created a lambda instance, and I want later to query this object to see if it is a proc or a lambda. How does one do that? the .class() method does not do the trick.
irb(main):001:0> k = lambda{ |x| x.to_i() +1 }
=> #<Proc:0x00002b931948e590@(irb):1>
irb(main):002:0> k.class()
=> Proc

A:

Ruby 1.9.3 and higher
You are looking for Proc#lambda? method.
k = lambda { |x| x.to_i + 1 }
k.lambda? #=> true
k = proc { |x| x.to_i + 1 }
k.lambda? #=> false

Pre 1.9.3 solution
We are going to make ruby native extension.
Create proc_lambda/proc_lambda.c file with following content.
#include <ruby.h>
#include <node.h>
#include <env.h>

/* defined so at eval.c */
#define BLOCK_LAMBDA  2
struct BLOCK {
    NODE *var;
    NODE *body;
    VALUE self;
    struct FRAME frame;
    struct SCOPE *scope;
    VALUE klass;
    NODE *cref;
    int iter;
    int vmode;
    int flags;
    int uniq;
    struct RVarmap *dyna_vars;
    VALUE orig_thread;
    VALUE wrapper;
    VALUE block_obj;
    struct BLOCK *outer;
    struct BLOCK *prev;
};

/* the way of checking if flag is set I took from proc_invoke function at eval.c */
VALUE is_lambda(VALUE self)
{
    struct BLOCK *data;
    Data_Get_Struct(self, struct BLOCK, data);
    return (data->flags & BLOCK_LAMBDA) ? Qtrue : Qfalse;
}

void Init_proc_lambda()
{
    /* getting Proc class */
    ID proc_id = rb_intern("Proc");
    VALUE proc = rb_const_get(rb_cObject, proc_id);

    /* extending Proc with lambda? method */
    rb_define_method(proc, "lambda?", is_lambda, 0);
}

Create proc_lambda/extconf.rb file:
require 'mkmf'
create_makefile('proc_lambda')

In terminal cd to proc_lambda and run
$ ruby extconf.rb
$ make && make install

Test it in irb
irb(main):001:0> require 'proc_lambda'
=> true
irb(main):002:0> lambda {}.lambda?
=> true
irb(main):003:0> Proc.new {}.lambda?
=> false


Q:

Best html editor for a non technical user

I have set up a simple web page for a family member and now they want to be able to edit the page themselves.
My primary web authoring tool is gvim which is obviously out of the question for a non techie.
Does anyone have any recomendations for a simple effective WYSWYG html editor
There are no requirments for javascript, forms, or any fancy stuff -- just pure presentation!

A:

KompoZer (http://kompozer.net/), free, useful and simple.


Q:

Background music cancelled when capturing audio in AVCaptureSession

I would like background music to continue playing when I am inside my iOS app. However when ever I enter my app the background music is cancelled. I isolated the problem to the audio part of the AVCaptureSession:
var audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio);
var audioInput = AVCaptureDeviceInput.FromDevice(audioDevice);
captureSession.AddInput(audioInput);

I tried setting the AudioSession immediately after in two ways:
AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.AmbientSound;
AudioSession.SetActive(true);

or like this:
AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.MediaPlayback;
AudioSession.OverrideCategoryMixWithOthers = true;
AudioSession.SetActive(true);

But neither worked.

A:

Have you tried explicitly creating an instance of the session object and setting MixWithOthers, as described here? I'm thinking the Xamarin equivalent would be something like
AVAudioSession session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.PlayAndRecord, AVAudioSessionCategoryOptions.MixWithOthers | AVAudioSessionCategoryOptions.DefaultToSpeaker);

Alternatively, as suggested in the link above, try setting the following in your AppDelegate:
AudioSession.Category = AudioSessionCategory.PlayAndRecord;
AudioSession.AudioShouldDuck = true;
AudioSession.OverrideCategoryDefaultToSpeaker = true;

...and then creating your AVCaptureSession like this:
AVCaptureSession session2 = new AVCaptureSession();
session2.AutomaticallyConfiguresApplicationAudioSession = false;


Q:

Reference request for generalization of groups with out identity element?

In other words what do we call a magma which is  associative and has divisibility  property but not existence of identity? Or a groupoid when it loses the identity property?
A reference on such objects would be very helpful.
There is a table of various generalizations of groups here & here

A:

I think such structures are called nonunital semigroups. See, for example,
ftp://ftp.math.ethz.ch/EMIS/journals/MPRIA/2000/pa100i2/pdf/100210ai.pdf (Non-Unital Semigroup Crossed Products, by N.S. Larsen) and http://www.hindawi.com/journals/aaa/2014/463918/ (Solution of Several Functional Equations on Nonunital Semigroups Using Wilson’s Functional Equations with Involution, by J. Chung and P. K. Sahoo).
Nonunital rings, which are more popular than simply nonunital semigroups, are discussed in answers to this MO question: What are the reasons for considering rings without identity?


Q:

Finding GRASS module after upgrading QGIS (Mac)?

I upgraded from QGIS 2.10.1 PISA to QGIS 2.18 last week (via KyngChaos), and since then have not been able to run GRASS within QGIS - it appears not to be able to find the module.
I had a look at this related question, and I have located the processing options (screengrab below) and tried to find the correct grass folder paths for my system, however, I can just see the QGIS application in my applications folder - no further folder structure to locate the correct file?
Amending the current file paths to the suggested paths I can find (/Applications/QGIS.app/Contents/MacOS/grass or /Applications/GRASS/GRASS-7.x.app/Contents/MacOS) results in a 'Wrong value for parameter "GRASS folder" message.
Can anyone offer any advice? I am a QGIS newbie running on Mac OS Sierra.

A:

I have figured this out and thought it best to post the answer for future users.
Firstly, I right clicked on my QGIS application and selected 'Show Package' to show the subfolders within the application (apologies if this is obvious to most users but it wasn't to me!)
In doing this I managed to locate the exact path of my GRASS installation, which is /Applications/QGIS.app/Contents/MacOS/grass7.
I replaced both GRASS folder locations shown in the screengrab above (within my original question) with the correct path, but only ticked 'Activate' on GRASS GIS 7 commands. (As I assume these supersede the standard GRASS commands.)
This still didn't fix the problem, however I then noticed in Plugins > GRASS > Grass Options, under the General tab there is an option to insert a custom file path to the Grass installation, so I pasted the same file path in here.
After restarting QGIS I now have working GRASS again.


Q:

How do I mirror a JPEG file in macOS

How do I  mirror a jpeg file, swift, macOS?
Using something like CGImageSourceCreateWithURL would be good. I would like to change a property and then write the file out again. Not sure if this is possible.
Another way appears to be drawing the image and then write this out to a file. The image needs to be scaled with a -1 scale and transformed so that it still appears in the destination correctly. I've not been able to find a swift example of doing this. This is an example that is not in swift. I cannot reproduce it in swift. Also using an NSImage requires decoding and then encoding the JPEG file. A solution that does not do this would be better.
Flip NSImage on both axes
Edit:
A vImage may be a middle ground. This will need to be populated by reading the JPEG but the data could be flipped without "drawing" it at a scale of -1. I think an NSImage could be made using initWithContentsOfURL or initByReferencingURL and a CGImage made from the NSImage using CGImageForProposedRect. The vImage made from the CGImage?

A:

To mirror a NSImage using vImage mirroring routines, you can do something like:
extension NSImage {
    func mirrored() -> NSImage? {
        guard
            let cgImage = cgImage(forProposedRect: nil, context: nil, hints: nil),
            let colorSpace = cgImage.colorSpace else {
                return nil
        }

        var format = vImage_CGImageFormat(bitsPerComponent: UInt32(cgImage.bitsPerComponent),
                                          bitsPerPixel: UInt32(cgImage.bitsPerPixel),
                                          colorSpace: Unmanaged.passRetained(colorSpace),
                                          bitmapInfo: cgImage.bitmapInfo,
                                          version: 0,
                                          decode: nil,
                                          renderingIntent: cgImage.renderingIntent)

        var source = vImage_Buffer()
        var result = vImageBuffer_InitWithCGImage(
            &source,
            &format,
            nil,
            cgImage,
            vImage_Flags(kvImageNoFlags))

        guard result == kvImageNoError else { return nil }

        defer { free(source.data) }

        var destination = vImage_Buffer()
        result = vImageBuffer_Init(
            &destination,
            vImagePixelCount(cgImage.height),
            vImagePixelCount(cgImage.width),
            UInt32(cgImage.bitsPerPixel),
            vImage_Flags(kvImageNoFlags))

        guard result == kvImageNoError else { return nil }

        result = vImageHorizontalReflect_ARGB8888(&source, &destination, vImage_Flags(kvImageNoFlags))
        guard result == kvImageNoError else { return nil }

        defer { free(destination.data) }

        return vImageCreateCGImageFromBuffer(&destination, &format, nil, nil, vImage_Flags(kvImageNoFlags), nil).map {
            NSImage(cgImage: $0.takeRetainedValue(), size: size)
        }
    }

}

Thus, taking a screen snapshot of the above in my editor, I then mirrored the image, resulting in:


Q:

Deriving values from loop operation

This is language agnostic, but I am interested in the successful answer's problem solving process. I have the following three columns:
3   0   1
3   1   2
3   2   3

2   0   2
2   1   3

1   0   3

What common operation will always derive the third column from the first two columns? If it helps this question is derived from a loop. I have data that needs to be grouped in sets of 4, if a set has four, no need to fill it out. if the set has less than 4, the first column, I need to loop through, iteration in column 2, and fill the set out assigning col#s, column 3, to the class of the items. Again, more interested in process than just the answer. Thanks for your help!

A:

It looks like the answer is 4 - a + b:
a  b  4-a+b
_  _  _
3  0  1
3  1  2
3  2  3
2  0  2
2  1  3
1  0  3

In any language that supports two-dimensional arrays, you do not need to go through the thinking and figuring out the math: it's not worth being fancy where a simple lookup table would do the job:
int[][] lookup = new int[][] {
    new int[0]
,   new int[] { 3 }
,   new int[] { 2, 3 }
,   new int[] { 1, 2, 3 }
};


Q:

Using NSNumberFormatter to format currency in output UILabel

NSNumberFormatter * fmt;
NSNumber          * n;

fmt = [ [ NSNumberFormatter alloc ] init ];
n   = [ NSNumber numberWithFloat: 10 ];

[ fmt setFormatterBehavior: NSNumberFormatterBehavior10_4 ];
[ fmt setCurrencySymbol: @"$" ];
[ fmt setNumberStyle: NSNumberFormatterCurrencyStyle ];

 // NSLog( @"%@", [ fmt stringFromNumber: n ];

[ fmt release ]

-(IBAction)buttonPressed1:(id)sender
 {
double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue];

SumCurrency.text = [NSString stringWithFormat:@"%0.0f", currency];

 }

How do I get the SumCurrency.text formated as 1,999 instead of 1999
Please help .. I am new to Objective - C , but my project is almost 95 % on interface builder .
I just need help with above code to implement .. Please I am struggling a lot with this .
Regards ,
Newbie.

A:

I got the answer .. But for anyone's future refernce
-(IBAction)buttonPressed1:(id)sender
{
    double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue];
    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithInt:currency]];
    SumCurrency.text = [NSString stringWithFormat:@"Converted:%@",numberAsString];
}

A:

NSNumberFormatter * fmt;
NSNumber          * n;

fmt = [ [ NSNumberFormatter alloc ] init ];
n   = [ NSNumber numberWithFloat: 10 ];

[ fmt setFormatterBehavior: NSNumberFormatterBehavior10_4 ];
[ fmt setCurrencySymbol: @"$" ];
[ fmt setNumberStyle: NSNumberFormatterCurrencyStyle ];

 // NSLog( @"%@", [ fmt stringFromNumber: n ];

[ fmt release ];

use
SumCurrency.text = [ fmt stringFromNumber: n ];

and you are done with it


Q:

Why is regularization interpreted as a gaussian prior on my weights?

Going through this online class, the notes specify the following. (In the highlights):

I understand how we get a maximum likelihood interpretation. What I do not get is:
Why does using the Frobenious norm of the weight matrix $R(W)$ as a regularizer, lead to the interpretation of the weight matrix $W$ having a prior as being sampled from a gaussian? How is this arrived at? And what if the regularization term was something other than the frobenius norm?
(And to that last point, does this mean that every element in the matrix $W$ is sampled from a gaussian?)
Thank you.

A:

Since we're using MAP we are trying to maximize the probability of the parameters given the data.
$$
   P(W|x,y) = \frac {P(x,y|W) P(W)} {P(x,y)}
$$
$P(x,y)$ can be ignored since it's fixed for our data. So we are trying to maximize $log(P(x,y|W)) + log(P(W))$.  Let's look at $P(W)$.
If each element of $W$ is drawn independently from a unit Gaussian, the probability of the matrix is
$$
P(W) = \frac {1} {\sqrt{2 \pi}} \prod_{ij} exp\Big( -\frac {w_{ij}^2} 2 \Big)
$$
so $log(P(W))$ is
$$
-\frac 1 2 \sum_{ij}{w_{ij}}^2
$$
plus some constant terms. The log-likelihood is then
$$
  log(P(x,y|W)) - \frac 1 2 \sum_{ij} {{w_{ij}}^2}
$$
Since we are thinking in terms of losses we negate the log-likelihood and minimize. Now the first term is cross-entropy and the second term is $\frac 1 2 R(W)$.
If you have a (reasonable in some sense that I don't know how to define) more or less arbitrary penalty function you can obtain a density for it by integrating over its domain and then normalizing to obtain a density. In this case it's just easy to see that it's a Gaussian.
This does not mean that the elements of $W$ actually are sampled from a Gaussian. What it means is that you believe that's what $W$ looks like before you have any evidence to the contrary. In other words the prior on the elements of $W$ is a Gaussian.


Q:

Examples where an AWS Security Group is not sufficient as a firewall?

Currently I am using only an AWS security group for one of my EC2 instances but have given some thought to adding a firewall to that stack as well.  I'd be looking at using either iptables, or possibly migrating the entire system to ubuntu (not related to this problem) so might just end up using ufw.
If I leave this machine protected using only the security group, am I missing out on some protection?  I haven't been able to get a good feel for its level of protection when compared to a traditional *nix software firewall.

A:

If there's ever a bug or exploit in AWS's security groups implementation, you might wind up vulnerable where having iptables or something similar would've protected you.


Q:

JQuery colorbox without writing another JSP file for someting within a div of a JSP file?

I am using JQuery colorbox like that: There is a link(with a button) that has a class cboxElement. The html of  colorbox is at that link, I mean at another JSP file. When user click that link colorbox appears and everything is OK.
However how can I use colorbox for something within my page between div tags I mean without writing another JSP file that will be non-visible for users and it will appear after a user clicks a button)?
EDIT: I found that: If inline 'true' a jQuery selector can be used to display content from the current page. Example:
$("#inline").colorbox({inline:true, href:"#myForm"});

I think this is what I am looking for but I couldn't find any example of it?

A:

Take a look at the example for inner HTML on this page. I believe that is what you're looking for.
If you look at the source of the page, you'll find this HTML:

This content comes from a hidden element on this page.

The inline option preserves bound JavaScript events and changes, and it puts the content back where it came from when it is closed.

        Click me, it will be preserved!

If you try to open a new ColorBox while it is already open, it will update itself with the new content.

Updating Content Example:

        Click here to load new content

This is the link that launches ColorBox on click:

Inline HTML

This is the binding for ColorBox:
$(".example8").colorbox({width:"50%", inline:true, href:"#inline_example1"});


Q:

What are the dangers of connecting the Micro-USB through an adapter straight to the mains?

I have a USB-Mains power adapter for charging up an iPod, which I thought I would use to power my Pi.
It looks like this: with USB one side, and Mains the other.

I was wondering if there are any dangers I need to be aware of when connecting my Pi to an adapter like this? I assume it is fused and everything, but better safe than sorry.
Just realising I may be answering my own question, but it has 1A, 5V output.

A:

Looks perfect to me (1000mA, 5V DC output). The point is that you are not connecting directly to the mains. The plug contains a transformer which converts the high-voltage AC input to low voltage DC output suitable as a USB power source. Directly connecting to the mains would be very dangerous!

A:

Many phone chargers use the same sort of plug - I have Apple and HTC chargers that work on this basis.
It would seem that, as long as the ratings are correct (which they appear to be on your model) doing this should be just fine.
After all people trust $500 smartphones to these plugs, so a $35 RPi is a much less risky proposition.

A:

There are dangers, and I don't see how they could be explained any better than by this blog post
To summarise:
The danger of this kind of adapters is their size. Main's electricity is in very close proximity to the low voltage output. It is perfectly possible to make these items safe, and there are official standards such as the CE mark that enforce minimum gaps and methods of designs that make these adapters perfectly safe. The problem is that not every manufacturer follows these guidelines, and some even claim to do so when they do not. You do not have to look far to find examples of products that fail unexpectedly, and it is possible for a failure to cause a fire.
Dangerous design could occur in any electronic device, but these devices are more prone to it because they are so small. I use them myself, but I ensure I get them from suppliers I consider reputable, and pay a bit more for them.


Q:

Sort Laravel pluck() by value not key?

I've got a form that has a few select elements populated by JSON. It looks something like below.
{
    "suppliers":
        {"1":"Amazon","2":"Apple"},
    "manufacturers":
        {"1":"Apple","2":"Lenovo"},
    "categories":
        {"2":"Tablet","3":"Laptop","4":"Desktop"},
    "status":
        {"1":"Ready to Deploy","2":"Deployed","3":"Damaged","4":"Destroyed"}
}

How can I sort by value (name) instead of the key (id)? I've tried everything I can think of and I've searched every phrase I can think of, but it's still not sorting alphabetically like I need. Note the orderBy below will sort it in the correct order if viewing the JSON directly in the browser, but in the form my select elements are still ordered by key.
public function getFormData()
{
    $suppliers = DB::table('supplier')->orderBy('sup_name','asc')->pluck('sup_name','id');
    $manufacturers = DB::table('manufacturer')->orderBy('man_name','asc')->pluck('man_name','id');
    $categories = DB::table('category')->where('parent_id', 1)->orderBy('cat_name','asc')->pluck('cat_name', 'id');
    $status = DB::table('status')->orderBy('status','asc')->pluck('status', 'id');

    return json_encode(compact('suppliers', 'manufacturers', 'categories', 'status'));
}

Edit:
Using the following syntax from @Snapey I was able to get the sort order correct
public function getFormData()
{
    $suppliers = DB::table('supplier')->orderBy('sup_name','asc')->get(['sup_name','id']);
    $manufacturers = DB::table('manufacturer')->orderBy('man_name','asc')->get(['man_name','id']);
    $categories = DB::table('category')->where('parent_id', 1)->orderBy('cat_name','asc')->get(['cat_name', 'id']);
    $status = DB::table('status')->orderBy('status','asc')->get(['status', 'id']);
    return json_encode(compact('suppliers', 'manufacturers', 'categories', 'status'));
}

New output:
{
    "suppliers":
        [{"sup_name":"Amazon","id":1},{"sup_name":"Apple","id":2}],
    "manufacturers":
        [{"man_name":"Apple","id":1},{"man_name":"Lenovo","id":2}],
    "categories":
        [{"cat_name":"Desktop","id":4},{"cat_name":"Laptop","id":3},{"cat_name":"Tablet","id":2}],
    "status":
        [{"status":"Damaged","id":3},{"status":"Deployed","id":2},{"status":"Destroyed","id":4},{"status":"Ready to Deploy","id":1}]
}

Unfortunately, now I get "object Object" in my select elements and the values are off.
Here's the function that builds my select elements:
function refreshData(newId, modalId) { //refreshes select elements on update
  $.ajax({
    url: '/json/collection.json',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        if(modalId){
            switch(modalId){
                case "supplierModal":
                    refreshSelect('inputSupplier', data.suppliers, newId);
                    break;
                case "manufacturerModal":
                    refreshSelect('inputManufacturer', data.manufacturers, newId);
                    refreshSelect('inputManufacturerModel', data.manufacturers, newId); //modal window select
                    break;
                case "statusModal":
                    refreshSelect('inputStatus', data.status, newId);
                    break;
                case "categoryModal":
                    refreshSelect('inputCategory', data.categories, newId);
                    break;
            }
        }else{
            refreshSelect('inputSupplier', data.suppliers);
            refreshSelect('inputManufacturer', data.manufacturers);
            refreshSelect('inputStatus', data.status);
            refreshSelect('inputCategory', data.categories);
            refreshSelect('inputManufacturerModel', data.manufacturers); //refresh modal window select element
        }
    }
  });
}

function refreshSelect(name, data, newId) {
    // Select by id
    let $elem = $('#' + name);
    // Get current value
    let oldValue = $elem.val();
    // Get option with value 0, which is the first element
    let emptyOption = $elem.children('option').first();
    // Empty the element and add the option. We are back to initial state
    $elem.html(emptyOption);
    // Append elements retrieved from backend
    $.each(data, function(key, value) {
        if(oldValue === key || newId === key){
            $elem.append('<option value="' + key + '" selected="selected">' + value + '</option>');
        }else{
            $elem.append('<option value="' + key + '">' + value + '</option>');
        }
    });
    if(newId){
      $elem.val(newId);
    }else{
      $elem.val(oldValue);
    }
}

A:

Include the id as a named element rather that using it as the array index. For instance;
 $suppliers = DB::table('supplier')->orderBy('sup_name','asc')->get(['sup_name','id']);

then in the json you will have an id attribute
Edit: for your additional question
something like
$.each(data, function(key, value) {
  if(oldValue === value.id || newId === value.id){
    $elem.append('<option value="' + value.id + '" selected="selected">' + value.sup_name + '</option>');
}else{
   $elem.append('<option value="' + value.id + '">' + value.sup_name + '</option>'); } });

because now, each item in the array is an object with sup_name and id as attributes


Q:

New datatype which can have numbers upto 100 digits

Note: This was an interview question and may not have an actual use case currently
The question was to design a class that can store numbers which are very very large say each number can have 100 digits. This new class is a datatype like int.
What are the different types of constructors, overloads and other functions that you would write.
How can this be further extended to support really large floating point numbers.
How this can be given to others so that they can reuse the same component with their own additional functionality.
My answer consisted of 2 approaches
1. using array of integers to store every say 10 digits
2. using string itself to store the number and perform operations on individual numbers.
What would be the best approach?

A:

Nice question :)
First of all, using a string representation is just not professional. You can do the mathematical operations at the level the word of the machine instead much more efficiently. Especially if you are going to use base 2.

What are the different types of
  constructors, overloads and other
  functions that you would write.

You need a set of constructors like a default one, copy constructor, construction from native integer types. The last part is the tricky part actually in C++, mixing signed/unsigned arithmetic in C++ is not so-simple as it looks like. You can benefit from this video by the creators of safeint(used by Microsoft). Also, you could need to construct your bignum from raw memory(byte-block). A destructor would be needed if your bignum is dynamic, otherwise it is trivial to implement.
Input/Ouput standard facilities are a must for such a library to ease using it. Providing a way to accept numbers in popular bases is a plus also. For the operations, your type should behave just like simple native type. This means you need to overload almost all the operators that you could overload:
Arithmetic operators
Comparison operators/Relational operators
Logical operators
Bitwise operators
Compound-assignment operators
etc..

The content of the library is an open-ended question.
The most important thing to remember is that C++ has some weired rules concerning the conversion between signed and unsigned numbers. Care must taken!

How can this be further extended to
  support really large floating point
  numbers.

big floats are not that easy.
Basically, you choose the radix you want to work with. Representing the number scientifically means having base and exponent parts. Which are integers in fact.

How this can be given to others so
  that they can reuse the same component
  with their own additional
  functionality.

Try to make it non-intrusive. i.e. when I take int off, and put instead of it my_bigint, then it should work! typedeffing should be just enough to switch between your type and native types. Let others write functions on top of the type, make it a black box. I prefer headers when using libraries, so I would write the library header-only.

My answer consisted of 2 approaches 1.
  using array of integers to store every
  say 10 digits 2. using string itself
  to store the number and perform
  operations on individual numbers.

Strings are not really suitable. What you need is to choose base 2**n as your base in most cases. There are libraries which use other bases, but it is not a good idea in my opinion, MAPM is one of those.

A:

The best approach would be to propose they use am existing, tried and tested C++ wrapper for a bignum library like GMP.

A:

See Wikipedia article about Arbitrary-precision arithmetic.


Q:

Can we edit bios properties from desktop?

Can we edit bios properties from desktop? without going to bios
like to set first boot device etc.

A:

Windows (your operating system) and your motherboard are entirely different things.  The BIOS is integrated directly into the motherboard to act like a springboard (throwing master CPU control to the OS once it's prepared the system) for when it boots up.  Windows, on the other hand, is on your harddrive and doesn't know anything about the motherboard except what the motherboard wants to tell it.
In short, no, you can't.  The operating system doesn't have such low-level control over the system.  If it did, you'd see a lot more viruses popping up and trashing your BIOS, right?

A:

There was some efforts in that direction years ago, like the Award BIOS Editor.

Awdbedit is a BIOS editor for Award
  BIOSes. It supports unpacking,
  replacing, and repacking of components
  within a BIOS image, and allows
  settings to be changed and tweaks to
  be applied to the actual BIOS
  itself.

Such programs are usually made for a specific brand of BIOS chip. Furthermore, as pointed out in other answers, it's more and more difficult, or even impossible to access the BIOS from the OS. It can also be a cause of instability.

A:

No ( the shortest answer ever :)


Q:

Creating an XML document using namespaces in Java

I am looking for example Java code that can construct an XML document that uses namespaces. I cannot seem to find anything using my normal favourite tool so was hoping someone may be able to help me out.

A:

There are a number of ways of doing this. Just a couple of examples:
Using XOM
import nu.xom.Document;
import nu.xom.Element;

public class XomTest {

    public static void main(String[] args) {
        XomTest xomTest = new XomTest();
        xomTest.testXmlDocumentWithNamespaces();
    }

    private void testXmlDocumentWithNamespaces() {
        Element root = new Element("my:example", "urn:example.namespace");
        Document document = new Document(root);
        Element element = new Element("element", "http://another.namespace");
        root.appendChild(element);
        System.out.print(document.toXML());
    }
}

Using Java Implementation of W3C DOM
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class DomTest {

    private static DocumentBuilderFactory dbf = DocumentBuilderFactory
            .newInstance();

    public static void main(String[] args) throws Exception {
        DomTest domTest = new DomTest();
        domTest.testXmlDocumentWithNamespaces();
    }

    public void testXmlDocumentWithNamespaces() throws Exception {
        DocumentBuilder db = dbf.newDocumentBuilder();
        DOMImplementation domImpl = db.getDOMImplementation();
        Document document = buildExampleDocumentWithNamespaces(domImpl);
        serialize(domImpl, document);
    }

    private Document buildExampleDocumentWithNamespaces(
            DOMImplementation domImpl) {
        Document document = domImpl.createDocument("urn:example.namespace",
                "my:example", null);
        Element element = document.createElementNS("http://another.namespace",
                "element");
        document.getDocumentElement().appendChild(element);
        return document;
    }

    private void serialize(DOMImplementation domImpl, Document document) {
        DOMImplementationLS ls = (DOMImplementationLS) domImpl;
        LSSerializer lss = ls.createLSSerializer();
        LSOutput lso = ls.createLSOutput();
        lso.setByteStream(System.out);
        lss.write(document, lso);
    }
}

A:

I am not sure, what you trying to do, but I use jdom for most of my xml-issues and it supports namespaces (of course).
The code:
Document doc = new Document();
Namespace sNS = Namespace.getNamespace("someNS", "someNamespace");
Element element = new Element("SomeElement", sNS);
element.setAttribute("someKey", "someValue", Namespace.getNamespace("someONS", "someOtherNamespace"));
Element element2 = new Element("SomeElement", Namespace.getNamespace("someNS", "someNamespace"));
element2.setAttribute("someKey", "someValue", sNS);
element.addContent(element2);
doc.addContent(element);

produces the following xml:
<?xml version="1.0" encoding="UTF-8"?>
 <someNS:SomeElement xmlns:someNS="someNamespace" xmlns:someONS="someOtherNamespace"  someONS:someKey="someValue">
  <someNS:SomeElement someNS:someKey="someValue" />
 </someNS:SomeElement>

Which should contain everything you need. Hope that helps.