Is it Possible to Automatically Resilver a ZFS Array On Hotswap

Question: I'm trying to learn about ZFS for a NAS I'm planning on building. I'm trying to understand if the following scenario would be possible to set up. Disclaimer: I know very little about ZFS, so forgive me if I say something stupid.

I have 4 drives in a zpool configured in raidz2 (RAID 6)
One drive fails
I would like to be able to remove the drive that failed, plug in a new drive and have the system automatically resilver the array without issuing any commands or rebooting.

From what I have gathered zpool set autoreplace=on <pool> would allow the drive the be replaced, but you would still need to issue the scrub command to start the resilver process, right? Also, I have no idea if hotswapping is supported, or not.
I realize that issuing a single command on the rare occasion that a disk fails is not the end of the world. But, in my opinion it would be a lot nicer if it was automated, and I'm pretty sure it can be done with hardware RAID.
Comment: No, you do not need to run scrub when autoreplace is on.
Comment: Thanks everyone for the helpful responses. I must have been reading some old or misleading info on autoreplace. I appreciate it.
Answer: Set autoreplace=on for your pool and use like or similar disks. Resilvering occurs automatically when that flag is set on the pool. If a hot-spare is defined in the pool, it will also rebuild automatically if autoreplace is on.
There's nothing more to really consider.
Answer: The autoreplace ZFS pool property is exactly that.
From the ZFS Administration Guide, about the :

If set to on, any new device found in the same physical location as a device that previously belonged to the pool is automatically formatted and replaced.

Also beware, if physically replacing the faulty disk with a new properly working one will trigger the resilvering of the new disk, this would not solve any configuration tweaking done on the other disks, such as adjusting the size of the disk (it is not rare to downsize disks a bit to avoid having the new one being a few KB too short compared to other in the vdev).
In fact, as much as sexy it is to just plugin a new disk and suddenly watching the lights of the other disks flashing like a Christmas tree, it would not cost you much to sit a few more minutes while carefully preparing your new disk before executing zpool replace (my 2 cents). I would say that it make more sense in case of some already prepared hot-spare.
Edit: ashift was a bad example (thanks @ewwhite).
Comment: `ashift` is set at the pool level... You don't have to "prepare" your disks.


"Object 'freq' not found" error applying colour in UpSetR

Question: If I run this reprex, I get the required output:
``` r
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))

upset(fromList(listInput), order.by = "freq")
```

If I apply a colour, I get the following error.
``` r
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))

upset(fromList(listInput), order.by = "freq",
      queries = list(list(query = intersects, params = list("one"), color = "orange", active = T)))
#> Error in eval(expr, envir, enclos): object 'freq' not found
```

I've looked at the colouring "example 5" in the vignettes, but can't spot my misstep.
Answer: Add a column of integers to the dataframe inputted into upset.
library(UpSetR)
listInput <- list(one = c(1, 2, 3, 5, 7, 8, 11, 12, 13),
                  two = c(1, 2, 4, 5, 10),
                  three = c(1, 5, 6, 7, 8, 9, 10, 12, 13))
df <- fromList(listInput)
df$n <- sample(1:nrow(df))

upset(df, order.by = "freq",
      queries = list(list(query = intersects,
                          params = list("one"),
                          color = "orange")))

Comment: Can it also colour where "one" intersects with nothing?
Comment: @Carl I completely revised my answer. See the proposed solution. Hope it can help you.


Run a check on every page load programmatically

Question: Drupal 7.
I have a site with Single Sign On (SSO) implemented. The implementation of the features is complete and the site is running perfectly.
Now, I have a requirement where I am supposed to check whether the session of the central server (on root of the domain and not using Drupal) is alive. I can do this by checking the availability of the session cookie on the root domain. And if the session is not active the user is logged out of Drupal.
I tried implementing it inside hook_init() but it only works for non-cached pages, whereas I want my code to be triggered on every page.
I also had a look at hook_boot() which runs even on cached pages. But, it is called while Drupal is still in bootstrap mode; even before themes and modules are loaded into memory. Which would mean that I would not be able to check the status of the user (whether the user is logged in?), because the user module and the included file session.inc would not be present in the memory while the execution of this hook.
So my question is which function (or hook) should I use which would execute on all pages(cached and non-cached) and which would give me access to common user properties (e.g. global $user object, user_is_logged_in() function etc)?
Comment: How are you caching pages for logged in users?  Naively, they are only cached for anonymous users, at least via core drupal anyway.
Answer: (I'm assuming Drupal 6)
Looking at bootstrap.inc, hook_boot is called on all pages, as long as agressive caching hasn't been turned on.
At this point the global $user variable should already exist (page_get_cache, which is called before hook_boot, makes use of it for example). module.inc has also been included, so you can use the functions included in that file to check for module existance and load them if necessary.
So, hook_boot looks like a good choice.
Comment: With drupal 7, as long as `page_cache_invoke_hooks` is true (equivalent of agressive caching), boot_hook should get called, and the global `$user` varaible is already set at that point, so it should work the same.
Comment: Sorry, I should have mentioned I'm using Drupal 7. However, your suggestion makes sense, and I would look at `drupal_page_get_cache` which is the D7 alternative for `page_get_cache`. I appreciate your prompt response.


IIS Not serving some documents to some users / locations

Question: I have a complicated problem that I will try to explain.
We have a portal based website that is accessible from outside of our organisations infrastructure via username and password. Certain types of files are not accessible on the website to certain people in certain locations. The problem is not user specific; in sites where you can access the files, you can do it as any user, in sites you can not access the files, you can not access them on any user. The sites that can access / download the files do not appear to have anything in common - some work from some corporate buildings, some dont, some work from some home networks, some don't.
The only common factor I can see, is that when it does not work, it is for specific files only. Mainly .doc .xls .ppt .gif.
The mimetypes in IIS appear to be setup correctly and have not changed.
The setup of the server side of things is quite complicated.
There is a front end server that serves most pages, when one of the images (gif - jpg work fine) or a doc from the page are called, you either get an image placeholder or a gateway not found message. The files that are called, reside on another webserver which has a virtual directory on a further seperate server (a nas device).
The 2 webservers are Windows 2000 (iis5) and the nas with the data is windows 2003.
This is a new problem, up until now there have been no similar issues since the inception a couple of years ago.
Nothing obvious is showing in any of the event logs
IIS logs don't show anything obvious either - in fact, I have compared the get commands from a number of different client requests and all match up just fine - ie ones that work look like ones that fail.
Another thing to bear in mind, is that the system must know the file is there, as you get a bad gateway error. When testing with a fake file that doesnt exist, you get a 404.
I am sure there is info I have missed or you will need, to help me, so please ask.
I look forward to your ideas and responses.
Regards
Kip
Comment: Further info:

This only appears to happen to links that are referred on port 8080 and accessed via a network with a proxy server.
Answer: Based on your comment/update, it sounds like the proxy server is nerfing the downloads. Do you have access to the proxy settings?
Comment: Its a few different sites in question that are having the problem - so unless they all made changes to their proxy at the same time, I am unsure how this could be it (although I wish it was it) Unfortunately these other sites are out of my scope of control.
Answer: Well, as with any "new" problem, the second step (after you've checked all trivialities) is to see what changes were made immediately prior to the problem.
In said case, as warren said, i'd go dig in the proxy settings. Perhaps some service pack or update was installed that mangled some settings? Some more details about what proxy you use would help.


Javascript mouseover function

Question: I have this code
This is the script in my head

This is the HTML part

My home, the front page and the main page

HOME

WORK

PORTFOLIO

ABOUT

CONTACT

I want to change the text in this area: "#ll p" whenever the user hover on the anchor tags.
For example. When the user hover on anchor tags which has a content of "HOME" then the JavaScript compare it via if and else (I don't know if there is another way but I'm open on any suggestion) so this is it: if the #hmenu li a value is equal to Home then then #ll p content should be change into "you hover the work anchor" and so the rest.
Comment: Add classes/ids to your menu items. It will make this much easier.
Answer: How about
$('#hmenu li').hover(function() {
    $('#ll p').text('you hover the '+$(this).text()+' anchor');
}

Answer: If you want to add text and then return to original text, you can store your value in data tag. Look at this sample:
http://jsfiddle.net/PjJfk/
Answer: Adding to @alexg and @Jay:
It sounds like you want the functionality of the title attribute but, instead of a popup, the title text goes to a predefined box.
I would recommend using the title attr because this will still work if js is disabled.
Then I suppose you could use hover (mouseenter / mouseleave) actions like:
mouseenter: remove the title from the link but use it for the contents of '#ll p'
mouseleave: restore the original title to the link and the original contents of #ll p
I'm not really a jQuery guy, but something like :
$(function() {
 var text, title;
 $('#hmenu li a').hover(
  function() {
     var $p = $('#ll p'), $a = $(this);
     text = $p.text();
     title = $a.attr('title');
     $a.attr('title','');
     $p.text(title);
  },
  function() {
     $('#ll p').text(text);
     $(this).attr('title', title);
  }
 )
});

#hmenu becomes

HOME

WORK

PORTFOLIO

ABOUT

CONTACT

See http://jsfiddle.net/heey3/

Javascript mouseover function


How to redirect users to log in page when they try to access the order page, but not when they try to check out

Question: I'm using Checkout Login module that adds an inline login form to the account information checkout pane. No anonymous users have to activate their accounts to complete checkout or payment, which is all I want. However, after the PayPal redirects users back to my site, and users try to access the order (order history) page, the following message appears:

You are not authorized to access this page.

Is there a way I can re-direct users to login page when they try to access the order page, rather than the above message appearing?
In short, I want my users to be redirected to login page when they try to access order (order history) page, but not when they try to checkout.
Answer: That's one of the main features of the LoginToboggan module.

When the Present login form on access denied (403) is enabled in its setting form, any access denied page will display a login page. Upon login, users are redirected back to the previously requested path.
Answer: Yes, You can handle it with Rules, create a rule in admin/config/workflow/rules/reaction/add and in react on event select commerce order is view (or completing the checkout process) then add condition that if user not logged in  on action Redirect user to login page.
Comment: Thanks zhilevan for the advice. I forgot to mention that I also want my users to be redirected to the same 'order history' page once they log in. The module: LoginToboggan did the job for me ..


Slow dropdown menu for foriegn key

Question: I have created a backend website and is in production. It is using jawsdb and one of my models have 15000 records. The problem is when I click on the dropdown list of another model in admin panel it to select a model, it takes too much time for the list to appear and the search bar on the dropdown list hangs as well while writing. Is it because of cheap heroku plans and jawsdb. I could nt have messed up in the code.
Comment: are you showing all of them in that select box ? (in front)
Answer: Add the foreign key field with 15000 records to autocomplete_fields
class ModelWithLotsOfRecordsAdmin(admin.ModelAdmin):
    ordering = ['some_field']
    search_fields = ['some_field']

class ModelWithTheForeignKeyAdmin(admin.ModelAdmin):
    autocomplete_fields = ['foreign_key']

The dropdown will then not render all the options will load them asynchronously when searched
Comment: the menu becomes weird after this
Comment: it doesn't appears but it works, you can write and select a record

Slow dropdown menu for foriegn key


How to use Master interface in ibe package in golang

Question: I'm trying to generate private key using the Extract() in the Master interface of the ibe package, here's the link of the package,"https://godoc.org/v.io/x/lib/ibe#Master". In the package, the input of Extract is id, and consist of {0,1}*, so I convert Mac id to binary string first, and then use the binary string to generate correspond private key.
My code is like this.
package main
import (
"fmt"
"v.io/x/lib/ibe"
)

var Macid = "00055DNEFF"
var id string
var PrivateKey string

func stringToBin(Macid string) (id string) {
    for _, c := range Macid {
        id = fmt.Sprintf("%s%b", id, c)
    }
    return
}
type Master string
func (master Master) Extract(id string) (PrivateKey, error) {
    return PrivateKey
}

func main() {
    fmt.Println("MacID is " + Macid + ", public key is" + stringToBin(Macid) + ", private key is" + ibe.Extract(id))

}

But I always got errors

$ go build pkg.go
command-line-arguments
./pkg.go:27: PrivateKey is not a type
./pkg.go:33: undefined: ibe in ibe.Extract

I'm all new to go, and I have read the tour of go, but I couldn't get it.
Can anyone help me with this? Thank you.
Comment: Here's the interface I'm trying to use in ibe._// Master is the interface used to extract private keys for arbitrary identities._
    'type Master interface {
     Extract(id string) (PrivateKey, error)
     Params() Params
    }'
Answer: There are 2 implementations of Master provided in the ibe package (bb1 and bb2).
These can be accessed using either ibe.SetupBB1() or ibe.SetupBB2()
package main

import (
    "fmt"

    "log"

    "v.io/x/lib/ibe"
)

var Macid = "00055DNEFF"

func stringToBin(Macid string) (id string) {
    for _, c := range Macid {
        id = fmt.Sprintf("%s%b", id, c)
    }
    return
}

func main() {
    bb2Master, err := ibe.SetupBB2()
    // or
    // bb1Master, err := ibe.SetupBB1()
    if err != nil {
        log.Fatal(err)
    }

    id := stringToBin(Macid)
    privateKey, err := bb2Master.Extract(id)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("MacID is %v, private key is %v", Macid, privateKey)

    // etc...
    // privateKey.Decrypt(C, m)
}

Comment: Yes, thank you for your answer, I figured that out. But I found that, the private keys I extracted each time are not the same. That is frustrating...I looked into that and found several random() in the Setup()s and Extract()s. I'm now reading the paper( http://crypto.stanford.edu/~dabo/papers/bfibe.pdf ) trying to find out that how the keys like that can even working...
Comment: Hi Joshua, I try to follow your code to print the ciphertext and decrypted text using the functions, but I always can't get them. I checked the original ibe library and I think it just can't print those two texts, right?
Answer: @Joshua Wales
package main

import (
"fmt"

"log"

"v.io/x/lib/ibe"
)

var Macid = "00055DNEFF"

func stringToBin(Macid string) (id string) {
for _, c := range Macid {
    id = fmt.Sprintf("%s%b", id, c)
}
return
}

func main() {
bb1Master, err := ibe.SetupBB1()

if err != nil {
    log.Fatal(err)
}

id := stringToBin(Macid)
privateKey, err := bb1Master.Extract(id)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("MacID is %v, private key is %v", Macid, privateKey)

m := []byte("HelloAuthentication")
overhead := bb1Master.Params().CiphertextOverhead()
C := make([]byte, len(m)+overhead)

if err := bb1Master.Params().Encrypt(Macid, m, C); err != nil {
    log.Fatal(err)
}

fmt.Printf("Ciphertext is : ", bb1Master.Params().Encrypt(Macid, m, C))

if err := privateKey.Decrypt(C, m); err != nil {
    log.Fatal(err)
}

fmt.Printf("Decrypted text is : ", privateKey.Decrypt(C, m))

}

@


Linear algebra to solve equation for a circle

Question: I am stuck with how to solve this equation:
$$ax^2 + ay^2 + bx + cy + d = 0$$ given three points, $(-2,7), (-4,5)$, and $(4,-3)$.
My steps: 1. Set up three equations,
$$53a-2b+7c+d=0 \\
41a-4b+5c+d=0 \\
25a+4b-3c+d=0$$
2. Created augmented matrix and used my calculator to get rref form (this is what we've been studying and manual row reduction is painful). I get an answer in rref form. Are these the equations for $a, b, c, d$? The answer would be
$$a=x+1/29 \\
b=y-2/29 \\
c=x-4/29 \\
d=d.$$
I don't need the actual answer just confirmation that I'm using the right process, or to be told no and pointed in the right process.
Comment: Your initial approach in step $1$ looks fine, but following that, there shouldn't be any $x$ or $y$ in your solution. Where did those come from?
Comment: The RREF operation takes the matrix representing your system of three equations and gives you a new matrix representing an equivalent system of equations. So you should read the result rows back in the same form you wrote them, e.g. $1a+0b+0c+1/29d=0$.
Comment: Karl's comment here shows that $a = (-1/29)d$, and the other rows will similarly be multiples of $d$. This gives you an infinite family of solutions, i.e., you can choose $d$ to be just about anything, and the other constants will scale accordingly. This ties into @John's answer below ("you can choose $a$ to be whatever you like").
Comment: The RREF returned for example 1,0,0,1/29,0 for row 1. I guess I'm confused about what those numbers represent, and how to translate the answer into answers for a,b,c,d.
Answer: If it's a circle then $a$ cannot be zero, and you can divide through by it:
$$x^2 + y^2 + b'x + c'y + d' = 0$$
where the primes are the variables divided by $a$.
Then you have three equations with three unknowns. You can choose $a$ to be whatever you like.
Does this help?
Comment: You can multiply your original equation by any non-zero constant you like, and it will still be the same circle, so one of $a,b,c,d$ is arbitrary. Come to think of it, it's even easier to simply choose $a$ to be $1$.
Comment: The problem asks me to solve for a,b,c,d, so I am not sure what you mean by 'a can be whatever I like.' Also, you haven't eliminated a, I still have 1/a x b, c, and d. Sorry, I'm at the beginning of a Covid/independent class and might not be explaining this as well as I'd like.


How could the contextual filter "Content: Nid" return the TNID instead of NID?

Question: I am using the contextual filter "Content: Nid" in Views3, and I want it returns the TNID instead of the NID When the filter value is NOT available.
I tried the following code.
$node = node_load($argument);
$argument = $node->tnid;
return $argument;

I also tried the following code.
$node = node_load(arg(1));
$argument = $node->tnid; // bzw. $argument(1) = $node->tnid;
return $argument;

I used that code in Provide default value:PHP Code Field, but nothing worked.

I solved the problem by adding this code to the page.tpl.php.
$imagemenuview = views_get_view('projectimagemenu');
echo $imagemenuview->preview('block', array($node->tnid));

I am still interested in the solution using the contextual filter "Content: Nid" returning the TNID instead of the NID When the filter value is NOT available.
Comment: There is an argument "Content translation: Translation set node ID" when core *Content translation* module is enabled. Is it what you need?
Answer: This PHP code should work:
$node = node_load(arg(1));
return (isset($node->tnid) ? $node->tnid : $node->nid);

The better way (without evil eval()) is to provide own plugun of type 'argument default' which will do work. Look at Content ID from URL argument default plugin as an example.


Fastest way to run ridge regression on large datasets where n>>p

Question: Provided that you don't want to do any variable selection:
Is there any software which is faster than glmnet at vanilla ridge regression for large datasets?
Comment: N in the hundreds of thousands, p in the 100-1000 range. Not sparse.
Comment: N is rows. p is columns.
Comment: what are n and p?
Comment: sorry, I meant what do the symbols represent (different fields use different symbols)
Comment: This question appears to be off-topic because it is about software.
Answer: glmnet is an R package that will end up calling linear algebra routines from the BLAS and LAPACK libraries to do the actual computations.  These library routines can be optimized for a particular computer processor and parallelized to run on multiple processors and they can even be run on GPGPU accelerators to get improved performance.  The first thing to do is to check your installation of R and the BLAS/LAPACK libraries that it is using.  Chances are that you're using BLAS/LAPACK libraries that have not been optimized for performance.
Unfortunately, building software to use optimized BLAS/LAPACK libraries is not a very easy process for most users.  My advice would be to find someone who has experience with optimized linear algebra libraries to help you get your R setup configured to use optimized libraries.
Comment: For simple ridge regression you don't need anything as fancy as glmnet.  You really just need a fast linear least squares solver.
Comment: I'm not wedded to R, it just seems like glmnet legitimately is the fastest regularized regression package I've seen out there because it's coded in FORTRAN. I'm actually fairly eager to not use R.
Comment: THe quickest way to do this is to use the Cholesky factorization of $X^{T}X+\lambda I$ for each value of $\lambda$.  Since the $X^{T}X$ matrix is of size $p$ by $p$, and the matrix should be reasonably conditioned ($\lambda$ needs to be large enough to keep the matrix reasonably conditioned, or else the ridge regression isn't reducing the instability in the least squares problem.)  Computing the Cholesky factorization of a 1,000 by 1,000 matrix can easily be done in less than a second, so the time per value of $\lambda$ is less than a second.
Comment: Really? You'd think that cross-validation over lambda would be relatively involved.
Comment: To make sure that R is using multithreaded matrix operations, e.g. using the Intel MKL libraries, just install Microsoft Open R, or else just overwrite the Rblas.dll and Rlapack.dll files in your R-3.3.3/bin/x64 directory with the Intel MKL ones, https://www.dropbox.com/s/y4dttvsnr3m00kh/Rblas_MKL.zip?dl=0


How to add a new calculated field by using `hook_views_query_alter`?

Question: I have three node types that I have created relations between using the Relation module.
Seaon --> Player --> Week
The player node has a numeric field called cost.
The relationship between the player and the week has a numeric field called score.
The following is a views query (with some alias changes to make it a tad more intelligible) that I use to summarise data per season.
The view works fine but I need to add a calculated field that takes the sum of the weekly scores and divides it by the player cost.
SELECT  PLAYER.title AS PLAYER_title
        ,PLAYER.nid AS PLAYER_nid
        ,PLAYER_COST.field_cost_value AS PLAYER_COST_field_cost_value
        ,MIN(PLAYER.nid) AS PLAYER_nid_1
        ,'node' AS field_data_field_cost_node_entity_type
        ,MIN(PLAYER2WEEK.rid) AS PLAYER2WEEK_rid
        ,'relation' AS field_data_field_score_relation_entity_type
        ,SUM(PLAYER2WEEK__field_data_field_score.field_score_value) AS PLAYER2WEEK__field_data_field_score_field_score_value
FROM    {node} SEASON
INNER JOIN
        {field_data_endpoints} FDE
ON      node.nid = FDE.endpoints_entity_id
AND     (FDE.bundle = 'player_in_season'
AND     FDE.endpoints_entity_type = 'node'
AND     FDE.endpoints_r_index = '1')
INNER JOIN
        {field_data_endpoints} FDE2
ON      FDE.entity_id = FDE2.entity_id
AND     (FDE2.endpoints_entity_type = 'node'
AND     FDE2.endpoints_r_index !=  FDE.endpoints_r_index
AND     1 = '1')
INNER JOIN
        {node} PLAYER
ON      FDE2.endpoints_entity_id = PLAYER.nid
AND     FDE2.endpoints_entity_type = 'node'
LEFT JOIN
        {field_data_endpoints} PLAYER_FDE
ON      PLAYER.nid = PLAYER_FDE.endpoints_entity_id
AND     (PLAYER_FDE.bundle = 'has_weekly_score'
AND     PLAYER_FDE.endpoints_entity_type = 'node'
AND     PLAYER_FDE.endpoints_r_index = '0')
LEFT JOIN
        {relation} PLAYER2WEEK
ON      PLAYER_FDE.entity_id = PLAYER2WEEK.rid
LEFT JOIN
        {field_data_field_cost} PLAYER_COST
ON      PLAYER.nid = PLAYER_COST.entity_id
AND     (PLAYER_COST.entity_type = 'node'
AND     PLAYER_COST.deleted = '0')
LEFT JOIN
        {field_data_field_score} PLAYER2WEEK__field_data_field_score
ON      PLAYER2WEEK.rid = PLAYER2WEEK__field_data_field_score.entity_id
AND     (PLAYER2WEEK__field_data_field_score.entity_type = 'relation'
AND     PLAYER2WEEK__field_data_field_score.deleted = '0')
WHERE   (( (node.nid = '3' ) )
AND     (( (node.type IN  ('SEASON')) AND (node.status = '1') )))

From all the reasearch I've done, it looks like the correct option is to use hook_views_query_alter() to add the new field.
This is where I lose it, I have no idea how to write the code to build the new field.
Essentialy, based on the query above the field needs to be
SUM(PLAYER2WEEK__field_data_field_score.field_score_value) / PLAYER_COST.field_cost_value AS new_field

I just need some help in getting strated on the code in my custom module
This answer seems to meet my requirements conceptually, I am just lost on how to construct the function.
Answer: Turns out that I didn't need the hook at all. I was able to achieve the result by using a Math Expression within the views module


Finding a particular sequence

Question: You have a structure like this one:
$$0) \ a|b|c|d$$
You can notice that it is made by 4 letters and 3 slashes. Letters stand for generic integer numbers. Let's call this one, just for simplicity, a structure of level 3 (as the number of slashes). Now, you define the associated structures of level 2 (so with two slashes) to $0)$ as it follows:
$$1) \ a b|c|d$$
$$2) \ a|bc|d$$
$$3) \ a|b|cd$$
(When you see two close letters it's supposed to be a multiplication between them) Using the same rule, and fixed for example $1)$, you can get the associated structures of level 1. They are:
$$4) \ a bc|d$$
$$5) \ a b|cd$$
Those of first level associated with $2)$ and $3)$ are:
$$6) \ abc|d$$
$$7) \ a|bcd$$

$$8) \ ab|cd$$
$$9) \ a|bcd$$
But actually you can see that there are only three different structres of first level, because some identical are repeated. The 3 different ones are $4) 5) 7)$.
By summarizing this example, if you consider the number of structures for each levels you have:
$$1\rightarrow 3 \rightarrow 3$$
If you start with a four level structure, if I'm not wrong you should get:
$$1\rightarrow 4 \rightarrow 6 \rightarrow 4 $$
I'd like to generalize these examples in order to obtain a general result.
So, starting from a structure of level $N$ you get $N$ structures of level $N-1$, and then?
$$1\rightarrow N \rightarrow ? $$
Comment: This is not an answer, but it looks like the progressions $1\to3\to3$ and $1\to4\to6\to4$ are binomial coefficients. In this case, it is $\binom{3}{0}\to\binom{3}{1}\to\binom{3}{2}$ and $\binom{4}{0}\to\binom{4}{1}\to\binom{4}{2}\to\binom{4}{3}$. Have you investigated this ?
Comment: Really interesting, I didn't think about it; maybe one answer will prove it @Anthony
Answer: If you start with an $n$-level structure, you will get the sequence of binomial coefficients $\binom{n}k$ for $k=n,n-1,\ldots,1$, and if you allow no separators, you'll get $\binom{n}0$ at the end. The reason is straightforward: at level $k$ you can keep any $k$ of the $n$ possible separators.
Answer: It seems that essentially the structure of the $k$-th level are the ways to place $k$ slashes into $n$ positions (with $n+1$ being the number of lettters), i.e
$$\binom nk,
$$
as was already suggested in a comment.

Finding a particular sequence


Prove that $(\neg p \wedge \neg q) \vee (p \wedge q) \equiv (\neg p \vee q) \wedge (\neg q \vee p)$

Question:
Prove that $(\neg p \wedge \neg q) \vee (p \wedge q) \equiv (\neg p \vee q) \wedge (\neg q \vee p)$.

I need to prove it by using equivalent sentences.
Comment: truth table is one way to do it
Comment: Where did you get stuck? What did you try?
Comment: Yes , but i need to prove it by using equivalent sentences.
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. You should add your additional requirement into the question using the [edit] feature (including what you tried, of course)
Comment: Just use the distribution rule, and note that $\sim p\lor p$ and $\sim q\lor q$ are just $T$ and can be removed.
Comment: @GPX Please change the title by yourself, it's not edited by me, i just changed the question in the main body
Comment: @GPX Sorry that the original answer is not right, which is corrected a little to answer
Answer: Assuming you have this in your arsenal, try using a "first-inside outside-last" distribution for the propositions. Then simplify.
That is, think of it like addition and multiplication:
$(a+b) \cdot (c+d) = (a \cdot c) + (a \cdot d) + (b \cdot c) + (b \cdot d)$.
If that isn't allowed, try using truth tables as a simple way of approaching it.
Answer: Propositional Calculus
Use de Morgan's rules. Start like this:
$$(\neg p \wedge \neg q) \vee (p \wedge q) \equiv (\neg p \vee (p \wedge q)) \wedge (\neg q \vee (p \wedge q))$$
Now apply them again inside the parentheses and remove tautologies. Then you're done.

Truth table
You can make a truth table with two variables and two outcomes. It will have four rows, so it's not too much work.
The start will look like this:
$$\begin{array}{cc|c|c}
p & q & (\neg p \wedge \neg q) \vee (p \wedge q) & (\neg p \vee q) \wedge (\neg q \vee p) \\
\hline
T & T & &\\
T & F & &\\
F & T & &\\
F & F & &
\end{array}$$
The statement then says that the missing two columns are identical.
Answer: Using a table of truth you can prove that:
(1) w $\vee$ (p $\wedge$ q) ≡ (w $\vee$ p) $\wedge$ (w $\vee$ q)
Hint: use w = (~p ∧ ~q).
Here follows the steps
(2) (~p ∧ ~q) ∨ (p ∧ q) ≡ ((~p ∧ ~q) $\vee$ p) $\wedge$ ((~p ∧ ~q) $\vee$ q)
Using (1) we can say that
(~p ∧ ~q) $\vee$ p ≡ (~p $\vee$ p) $\wedge$ (~q $\vee$ p)
as (~p $\vee$ p) its a tautology,
(3)(~p ∧ ~q) $\vee$ p ≡ (~q $\vee$ p)
using (3) and (2):
(4) (~p ∧ ~q) ∨ (p ∧ q) ≡ (~q $\vee$ p) $\wedge$ ((~p ∧ ~q) $\vee$ q)
Using (1) we can say that
(~p ∧ ~q) $\vee$ q ≡ (~p $\vee$ q) $\wedge$ (~q $\vee$ q)
as (~q $\vee$ q) its a tautology,
(5)(~p ∧ ~q) $\vee$ q ≡ (~p $\vee$ q)
Using (4) and (5)
(6)(~p ∧ ~q) ∨ (p ∧ q) ≡ (~q $\vee$ p) $\wedge$ (~p $\vee$ q)
And there you go
Answer: $(\neg p\wedge\neg q)\vee(p\wedge q)=\neg((p\vee q)\wedge\neg(p\wedge q))=\neg((\neg p\wedge q)\vee(p\wedge\neg q))=(p\vee\neg q)\wedge(\neg p\vee q)$


Can you do a redirect in .htaccess, and preserve the URI?

Question: Is there a way to use .htaccess to redirect example.net to example.com, so that the URI example.net stays the same in the client's browser?
Answer: I found these examples from this link:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} domain2.com
RewriteCond %{REQUEST_URI} !subdirectory/
RewriteRule ^(.*)$ subdirectory/$1 [L]

or
RewriteEngine On
Options +FollowSymlinks
RewriteBase /
RewriteCond %{HTTP_HOST} domain2.com
RewriteCond %{REQUEST_URI} !mychatfolder/
RewriteRule ^(.*)$ http://www.domain1.com/subfolder/$1 [L]

I haven't tested these out though.
Answer: If I'm understanding your question correctly, what you want is two sites which appear exactly the same, but neither one redirects to the other. You want the person who visits example.net to see the same stuff as is on example.com, but they should still see example.net in their browser address bar.
There are a few ways of doing this. The simplest, of course, is to simply upload the same content to both sites, but this might make updating tricky. Another is to set one domain as an alias of the other; exactly how to do this will depend on your server configuration. It would be simpler, and would perhaps be better for SEO purposes, to redirect one domain to the other.
RewriteEngine On
RewriteRule ^(.*)$ http://www.example.com/$1 [R=302,L]
# 302 is a temporary redirect. Use it for testing purposes. Once you're sure it works, change it to 301.

Answer: If you want the domain example.net to point to example.com then the best way isn't rewriting it, but to park that domain to example.com and the app. for that is basically titled as Parked Domains that's in Domains section if your control panel is cPanel or if your web hosting account features an app. that can park a domain.


Converting xml to yaml with Ruby and Hpricot - what's going wrong here?

Question: I'm trying to output an xml file blog.xml as yaml, for dropping into vision.app, a tool for designing shopify e-commerce sites locally.
Shopify's yaml looks like this:
- id: 2
  handle: bigcheese-blog
  title: Bigcheese blog
  url: /blogs/bigcheese-blog
  articles:
    - id: 1
      title: 'One thing you probably did not know yet...'
      author: Justin
      content: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      created_at: 2005-04-04 16:00
      comments:
        -
          id: 1
          author: John Smith
          email: firstname.lastname@example.com
          content: Wow...great article man.
          status: published
          created_at: 2009-01-01 12:00
          updated_at: 2009-02-01 12:00
          url: ""
        -
          id: 2
          author: John Jones
          email: email@example.com
          content: I really enjoyed this article. And I love your shop! It's awesome. Shopify rocks!
          status: published
          created_at: 2009-03-01 12:00
          updated_at: 2009-02-01 12:00
          url: "http://somesite.com/"
    - id: 2
      title: Fascinating
      author: Tobi
      content: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      created_at: 2005-04-06 12:00
      comments:
  articles_count: 2
  comments_enabled?: true
  comment_post_url: ""
  comments_count: 2
  moderated?: true

However, sample myxml looks like this:

          <author>Rouska Mellor</author>
          <blog-id type="integer">273932</blog-id>
          Worn Again are hiring for a new Sales Director.

      To view the full job description and details of how to apply click "here":http://antiapathy.org/?page_id=83
          <p>Worn Again are hiring for a new Sales Director.</p>
      <p>To view the full job description and details of how to apply click <a href="http://antiapathy.org/?page_id=83">here</a></p>
          <created-at type="datetime">2009-07-29T13:58:59+01:00</created-at>
          <id type="integer">1179072</id>
          <published-at type="datetime">2009-07-29T13:58:59+01:00</published-at>
          <title>Worn Again are hiring!</title>
          <updated-at type="datetime">2009-07-29T13:59:40+01:00</updated-at>

I naively assumed converting from one serialised data format to another was fairly straightforward, and I could simply do this:
>> require 'hpricot'
=> true
>> b = Hpricot.XML(open('blogs.xml'))
>> puts b.to_yaml

But I'm getting this error.
NoMethodError: undefined method `yaml_tag_subclasses?' for Hpricot::Doc:Class
    from /usr/local/lib/ruby/1.8/yaml/tag.rb:69:in `taguri'
    from /usr/local/lib/ruby/1.8/yaml/rubytypes.rb:16:in `to_yaml'
    from /usr/local/lib/ruby/1.8/yaml.rb:391:in `call'
    from /usr/local/lib/ruby/1.8/yaml.rb:391:in `emit'
    from /usr/local/lib/ruby/1.8/yaml.rb:391:in `quick_emit'
    from /usr/local/lib/ruby/1.8/yaml/rubytypes.rb:15:in `to_yaml'
    from /usr/local/lib/ruby/1.8/yaml.rb:117:in `dump'
    from /usr/local/lib/ruby/1.8/yaml.rb:432:in `y'
    from (irb):6
    from :0
>>

How can I get the data output in the form outlined at the top of this question? I've tried importing the 'yaml' gem, thinking that I'm missing some of those methods, but that hasn't helped either:
Comment: epochwolf opened this issue on GitHub a month ago: http://github.com/why/hpricot/issues/#issue/16

Are your specs the same (Hpricot 0.8.1, Rails 2.3.2, Ruby 1.8.6 (OSX), RubyGems 1.3.4)?
Comment: Yeah, almost:

RubyGems - 1.3.5
Ruby 1.8.6
Hpricot 0.8.1
OS X
Rails 2.3.2
Comment: Just as a note for anyone searching for XML/HTML parsing, Hpricot is no longer used, and the defacto-standard is [Nokogiri](http://nokogiri.org). YAML parsing is built into Ruby using the [YAML](http://www.ruby-doc.org/stdlib-2.1.5/libdoc/yaml/rdoc/index.html) class.
Answer: I've found this. Maybe it could help.
http://brains.parslow.net/node/1623
Answer: Sorry, Josh, I think what you've found here is a limitation in the Hpricot and/or the YAML libraries, pure and simple.
I'm not sure Hpricot's ever supported YAML in this way. The method in question is dynamically added by the YAML library to the Object class, as well as other fundamental Ruby types, but doesn't show up in Hpricot::Doc's definition for some reason, even though Hpricot::Doc does seem to inherit indirectly from Object.
I can say that I've reproduced it as well, so it's not just you.
You can very easily add the missing method:
class Hpricot::Doc
  def self.yaml_tag_subclasses?
    "true"
  end
end
b = Hpricot.XML(open('blogs.xml'))

but you'll find that doesn't get you much further. Here's what I get:
--- !ruby/object:Hpricot::Doc
options:
  :xml: true

So we're not iterating over the container like we should.
At this point, to get YAML support using the YAML library, the brute-force way (maybe the only way) would be to add to_yaml methods to Hpricot's classes, to teach them how to output YAML correctly. Take a look at "/usr/lib/ruby/1.8/yaml/rubytypes.rb" (on a Mac, that'd be something like "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/yaml/rubytypes.rb") for examples of how that's done for each of the fundamental Ruby types. The classes you might need to add this to are defined on the C side: see "hpricot/ext/hpricot_scan/hpricot_scan.rl", in the method Init_hpricot_scan.


How does the Hopf fibration generalize to maps $S^{2n+1}\to \mathbb{CP}^n$?

Question: I've been reading about Hopf fibrations.
In the Wikipedia page, they state that the Hopf construction generalises to higher-dimensional projective spaces. More specifically, they write that

The Hopf construction gives circle bundles $p:S^{2n+1}\to\mathbb{CP}^n$ over complex projective space [sic]. This is actually the restriction of the tautological line bundle over $\mathbb{CP}^n$ to the unit sphere in $\mathbb{C}^{n+1}$."

I understand the "standard" $n=1$ case as follows: define $p:S^3\to S^2$ as:
$$p(x_1,y_1,x_2,y_2) = (2(x_1 x_2+y_1 y_2), 2(x_1 y_2-x_2 y_1),x_1^2+y_1^2-x_2^2-y_2^2),$$
so that $p(x_1,y_1,x_2,y_2)\in S^2$ whenever $(x_1,y_1,x_2,y_2)\in S^3$. We then use the standard diffeomorphism $S^2\simeq\mathbb{CP}^1$ to conclude that there is a projection $\tilde p:S^3\to\mathbb{CP}^1$ which, for all $(x_1,y_1,x_2,y_2)\in S^3$ and $\theta\in\mathbb R$, satisfies
$$\tilde p(\cos\theta\, x_1,\sin\theta\, y_1,\cos\theta\, x_2,\sin\theta\, y_2)
= \tilde p(x_1,y_1,x_2,y_2),$$
meaning that $\tilde p^{-1}(x)\simeq S^1$ for all $x\in\mathbb{CP}^1$.
While that is fine, it hinges on the Hopf map $S^3\to S^2$, which seems rather ad hoc. How does this mapping generalise to $\mathbb{CP}^n$?
Comment: To add to Gunnar's point, the stated mapping $p:S^3\to S^2$ is "better" viewed as taking values in the complex projective line rather than the unit sphere in real Cartesian $3$-space.
Comment: I think it's just by looking at the holomorphic projection $\mathbb C^{n+1} \setminus \{0\} \to \mathbb P^n$ and noting that it factors through the unit sphere. That is a circle bundle over projective space that is the restriction of the tautological line bundle to the unit sphere.
Comment: @AndrewD.Hwang in what sense? I thought I could just consider the mapping $S^3\to \mathbb{CP}^1$ by composition of the one $S^3\to S^2$ and the identification  $\mathbb{CP}^1\simeq S^2$? Isn't this just a more explicit version of what you are proposing?
Answer: You are right, the Hopf map $p : S^3 \to S^2$ is a very special construction. It is based on two ingredients:

$S^3$ can be regarded as the set $\{(z_0,z_1) \in \mathbb C^2 \mid \lvert z_0 \rvert^2 + \lvert z_1 \rvert^2 = 1\}$.

$S^2$ can be regarded as the set $\{(w,t) \in \mathbb C \times \mathbb R \mid \lvert w \rvert^2 + t^2 = 1\}$.

The Hopf map is then defined by using complex multiplication:
$$p(z_0,z_1) = (2\bar z_0 z_1,\lvert z_0 \rvert^2 - \lvert z_1 \rvert^2 ). \tag{1}$$
However, $S^2$ can be identified naturally with $\mathbb{CP}^1$ and then the  Hopf map corresponds to the quotient map
$$q : S^3 \to \mathbb{CP}^1, q(z_0,z_1) = [z_0:z_1]. \tag{2}$$
For details see Prove that Hopf maps on $S^3, S^2$ and $\mathbb{C} \mathbb{P}^1$ are smooth submersions and Proving that the Hopf Fibration is a fiber bundle.
But $(2)$ shows that the quotient map
$$q : S^{2n+1} \to \mathbb{CP}^n, q(z_0,\ldots,z_n) = [z_0:\ldots:z_n]. \tag{3}$$
is the desired generalization of the Hopf map.
Comment: so, if I understand correctly, is the point that we should really think of the Hopf map as $S^{2n+1}\to\mathbb{CP}^n$, with its specific form $S^3\to S^2$ being an "accident" of the identification $\mathbb{CP}^1\simeq S^2$?
Comment: @glS Yes, that is correct!
Answer: Let $X$ be a unital topological monoid. The Hopf construction converts the product $m:X\times X\rightarrow X$ into a quasifibration $\theta_m:X\ast X\rightarrow \Sigma X$, where $X\ast X$ denotes the join of $X$ with itself.
The generalised construction requires two ingredients: an action $\rho:Y\times X\rightarrow Y$ of $X$ on a space $Y$ together with a map $f:Y\rightarrow Z$ satisfying $f(y\cdot x)=f(y)$ for all $y\in Y$ and $x\in X$. The generalised Hopf construction returns from this data a quasifibration $\theta_{\rho,f}:Y\ast X\rightarrow C_f$, where $C_f$ is the mapping cone of $f$. The construction is due to Dold and Lashof.
Note that you can view the original Hopf construction as the special case of the generalised construction in which $X=Y$, with $X$ acting on itself via its product, and where $f:X\rightarrow\ast$.
The case you are interested in is realised as follows. Starting with the topological group $S^1$ you have $S^1\ast S^1\cong S^3$ and $\Sigma S^1\cong S^2$. The Hopf construction returns the Hopf map $\eta:S^3\rightarrow S^2$. There is an induced action of $S^1$ on $S^1\ast S^1\cong S^3$ and the generalised construction yields $S^1\ast S^1\ast S^1\cong S^5\rightarrow \mathbb{C}P^2$, where the complex projective plane is the cofibre of the Hopf map $\eta$. Iterating the construtcion we obtain maps $S^{2n+1}\rightarrow\mathbb{C}P^n$ for all $n$.
Actually the Hopf constructions accept more general input. For instance $X$ need only be a suitable H-space, and the action $\rho$ need only satisfy some of its requirements up to homotopy. Due to the fact that $S^1$ is a compact Lie group it is normally more convenient to choose smooth models and identifications and realise the Hopf maps as smooth fibre bundles.
I don't know of any analogue of the Hopf construction in the smooth category (by which I mean that the wiki article is misleading with its statement). Paul discusses the essentially ad hoc construction of the Hopf bundles.


C# How to find if an event is hooked up

Question: I want to be able to find out if an event is hooked up or not.  I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event.  I don't want to do this.
Here is some test code that I thought would work:
// Create a new event handler that takes in the function I want to execute when the event fires
EventHandler myEventHandler = new EventHandler(myObject_SomeEvent);
// Get "p1" number events that got hooked up to myEventHandler
int p1 = myEventHandler.GetInvocationList().Length;
// Now actually hook an event up
myObject.SomeEvent += m_myEventHandler;
// Re check "p2" number of events hooked up to myEventHandler
int p2 = myEventHandler.GetInvocationList().Length;

Unfort the above is dead wrong.  I thought that somehow the "invocationList" in myEventHandler would automatically get updated when I hooked an event to it.  But no, this is not the case.  The length of this always comes back as one.
Is there anyway to determine this from outside the object that contains the event?
Answer: If the object concerned has specified the event keyword, then the only things you can do are add (+=) and remove (-=) handlers, nothing more.
I believe that comparing the invocation list length would work, but you need to be operating inside the object to get at it.
Also, keep in mind that the += and -= operators return a new event object; they don't modify an existing one.
Why do you want to know if a particular event is hooked up? Is it to avoid registering multiple times?
If so, the trick is to remove the handler first (-=) as removing a handler that's not there is legal, and does nothing. Eg:
// Ensure we don't end up being triggered multiple times by the event
myObject.KeyEvent -= KeyEventHandler;
myObject.KeyEvent += KeyEventHandler;

Comment: if you do += KeyEventHandler more than once, will -= KeyEventHandler remove all or just the last, just the first?
Comment: `-=` will remove one; I don't know of any way to work out which one, given they're all equal.
Answer: There is a subtle illusion presented by the C# event keyword and that is that an event has an invocation list.
If you declare the event using the C# event keyword, the compiler will generate a private delegate in your class, and manage it for you.  Whenever you subscribe to the event, the compiler-generated add method is invoked, which appends the event handler to the delegate's invocation list.  There is no explicit invocation list for the event.
Thus, the only way to get at the delegate's invocation list is to preferably:

Use reflection to access the compiler-generated delegate OR
Create a non-private delegate (perhaps internal) and implement the event's add/remove methods manually (this prevents the compiler from generating the event's default implementation)

Here is an example demonstrating the latter technique.
class MyType
{
    internal EventHandler<int> _delegate;
    public event EventHandler<int> MyEvent;
    {
        add { _delegate += value; }
        remove { _delegate -= value; }
    }
}

Comment: One clarification that I was't certain of before I tried it is that the compiler-generated delegate has the same name as the event you declared in your code (or at least mine did).
Answer: It can be done, but it takes some hackery...  as mentioned above the compiler generates the implementation of the event, including its backing field.  Reflection lets you retrieve the backing field by name, and once you have access to it you can call GetInvocationList() even though you're outside the class itself.
Since you're asking to use reflection to get the event by name I assume you're also using reflection to get the Type by name--I'm whipping up an example that will show how to do it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string typeName = "ConsoleApplication1.SomeClass, ConsoleApplication1, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null";
            string eventName = "SomeEvent";

            Type declaringType = Type.GetType(typeName);
            object target = Activator.CreateInstance(declaringType);

            EventHandler eventDelegate;
            eventDelegate = GetEventHandler(target, eventName);
            if (eventDelegate == null) { Console.WriteLine("No listeners"); }

            // attach a listener
            SomeClass bleh = (SomeClass)target;
            bleh.SomeEvent += delegate { };
            //

            eventDelegate = GetEventHandler(target, eventName);
            if (eventDelegate == null)
            {
                Console.WriteLine("No listeners");
            }
            else
            {
                Console.WriteLine("Listeners: " + eventDelegate.GetInvocationList().Length);
            }

            Console.ReadKey();

        }

        static EventHandler GetEventHandler(object classInstance, string eventName)
        {
            Type classType = classInstance.GetType();
            FieldInfo eventField = classType.GetField(eventName, BindingFlags.GetField
                                                               | BindingFlags.NonPublic
                                                               | BindingFlags.Instance);

            EventHandler eventDelegate = (EventHandler)eventField.GetValue(classInstance);

            // eventDelegate will be null if no listeners are attached to the event
            if (eventDelegate == null)
            {
                return null;
            }

            return eventDelegate;
        }
    }

    class SomeClass
    {
        public event EventHandler SomeEvent;
    }
}

Comment: You could just return eventDelegate from the GetEventHandler method without doing that last null check.
Comment: I found this answer quite helpful even though the GetEventHandler() method came back with a null eventField.  (I suspect this is related to me passing a Castle-based dynamicproxy into the routine instead of the proxied object.)  I am/was in the process of demonstrating how dynamicproxies could be used to "automagically" implement INotifyPropertyChanged.
Comment: I get an error saying "Unable to cast the object of type 'CallStatechanged' to type 'System.EventHandler'"
CallStateChanged is the name of my event
Comment: GetField returns null. GetEvent returns the desired event but doesn't allow GetValue to be called as EventInfo doesn't contain this method.
Comment: Casting to `EventHandler` is not general enough, I suggest using `return (Delegate)eventField.GetValue(classInstance)`
Answer: You should be able to get the invocation list via the "event".  Roughly, it will be something like..
public delegate void MyHandler;
public event MyHandler _MyEvent
public int GetInvocationListLength()
{
   var d = this._MyEvent.GetInvocationList(); //Delegate[]
   return d.Length;
}

Comment: This will only work from inside the class where the event is declared; he's trying to do it outside.
Answer: I used your example and modified it a little bit. registering an event handler increases the number of invocations. even when using two different callback methods (as shown here) or using the same callback method.
private void SomeMethod()
{
    // Create a new event handler that takes in the function I want to execute when the event fires
    var myEventHandler = new EventHandler(OnPropertyChanged);

    // Get "p1" number events that got hooked up to myEventHandler
    int p1 = myEventHandler.GetInvocationList().Length; // 1

    // Now actually hook an event up
    myEventHandler += OnPropertyChanged2;

    // Re check "p2" number of events hooked up to myEventHandler
    int p2 = myEventHandler.GetInvocationList().Length; // 2

    myEventHandler.Invoke(null, null);
// each of the registered callback methods are executed once.
// or if the same callback is used, then twice.
}

private void OnPropertyChanged2(object? sender, EventArgs e)
{}
private void OnPropertyChanged(object? sender, EventArgs e)
{}

As others already mentioned, the access to eventhandler.GetInvocationList is limited to the class itself, you need to expose a property or method to retrieve the delegate list.
Like this:
protected Delegate[]? GetInvocations() => PropertyChanged?.GetInvocationList();

depending on your usage make it protected, internal or both.

C# How to find if an event is hooked up


Android Firebase Multiplayer Matchmaking

Question: I have written a Tic-Tac-Toe app and have also learned a good amount of Firebase in the last 2 weeks. However, I am thinking of adding Multiplayer Matchmaking and real-time turn-by-turn TicTacToe online using Firebase.
So here is what I am thinking:

There's a play button.
Click on it.
It will show a "Searching for opponents" TextView.

So I think I should do something to show it open state and then see another player that clicks and shows that open -- Two open then connect them. But what if there are more players? What if 5-6 players click at once when there's no one and it thinks it is empty?
I want that 2 players can be matched out of any number of players. As I am relatively intermediate in Firebase, can anyone help me a bit with the logic and also pretty good if with the workflow and a code snippet.
Thanks in advance,
Android Programmer :)
Comment: *I want that 2 players can be matched out of any number of players* -- Then build said `List` randomly pick out two objects.
Comment: This isn't quite a Firebase problem. How would you do the same thing with a normal list of User objects. Start with that
Comment: could you plz elaborate a bit plz sir :)
Comment: alright...will try that...thanx for help...maybe useful later on ;)
Answer: You can make 2 List

available Games
players available to join.

Then pick them up on First Come First Serve basis. Assign first player to first available game. Then Change the status of a player to busy (remove it from list) & also change the status of Game to ready (remove it from list)


Problema na utilização do char string

Question: Galera me ajuda: o exercício que estou tentando fazer é 4. Escreva um programa em que:
a) Seja lido um caractere que deve ser uma das vogais do alfabeto, podendo ser maiúsculas ou minúsculas.
b) Seja implementada uma função em que verifique qual vogal foi lida, imprima, na própria função, uma das seguintes mensagens, conforme o caso:

1ª vogal,
2ª vogal,
3ª vogal,
4ª vogal,
5ª vogal ou
Outro caractere

Alguém pode dizer o que estou fazendo de errado?
#include<stdlib.h>
#include<locale.h>

char VogaLida (char Vogal [], int TamanhoVetor);

int main (){

    setlocale(LC_ALL, "PORTUGUESE");

    char Vogal [] = {'a', 'e', 'i', 'o', 'u'};
    char VogalLida;

    printf("Informe uma vogal: ");
    gets(Vogal);

    VogalLida = VogaLida(Vogal, 5);

}

char VogaLida (char Vogal [], int TamanhoVetor)
{
    int i = 0;

    for (i = 0; i < 5; i++){

        if (i == Vogal[0]) {
            Vogal[0] = 'a' | 'A';
            printf("1ª Vogal\n");

            return 0;
        }
        else if (i == Vogal[1]){
            Vogal[1] = 'e' | 'E';
            printf("2ª Vogal\n");

             return 0;
        }

        else if (i == Vogal[2]){
            Vogal[2] = 'i' | 'I';
            printf("3ª Vogal\n");

             return 0;
        }

        else if (i == Vogal[3]){
            Vogal[3] = 'o' | 'O';
            printf("4ª Vogal\n");

             return 0;
        }

    }

        return 0;
}

Comment: Se a resposta do Christian resolveu o teu problema podes marcá-la como aceite. Senão podes dar uma resposta tua para explicar a solução.
Answer: Seu programa tá bugado cara, a lógica está com problemas.

Você está lendo um caractere com a função gets() e colocando no vetor que tinha os seus caracteres Vogal, sendo que você só precisa ler um caractere.
Depois que você chama o método VogalLida que faz a verificação das vogais porém você utiliza o i que é um número inteiro para fazer as comparações dentro do bloco for.
...

Na verdade, não tem como eu explicar tudo por aqui, então siga o raciocío:
1) Segundo o seu prinf() você só quer ler uma letra para verificar se ela é uma vogal. Então experimente o getc() e salve em uma variável char.
2)Faça a função VogalLida(char vogal) com o seguinte corpo:
void VogalLida(char vogal)
{
    switch(vogal)
    {
        case 'a': printf("1ª Vogal\n"); break;
        case ...;
        default: printf("Nao eh vogal\n");
    }
}

Agora é só implementar os demais casos, do jeito que você implementou você usou muitos recursos e acabou embolando a lógica.
Comment: Obrigado pela resposta Christian ! Depois que eu postei aqui minha dúvida eu consegue resolver e vi que minha lógica estava muito errada. Agradeço de qualquer maneira sua disposição em ajudar. Valeu.
Comment: Beleza cara, tamo aí pra ajudar. Mas depois dê uma olhada no [Tour](http://pt.stackoverflow.com/tour) para você entender um pouco melhor do StackOverflow e de como sinalizar seu agradecimento com as respostas, porque aí você me ajuda também!

Problema na utilização do char string


Why can't I add a UIScrollView to a UIImageView (with it working properly)

Question: I'm working on an app.  Here I describe a simplified version of a strange problem I am experiencing.
I have a storyboard created View Controller with a UIImageView also created in the storyboard.
I then have the following h and m files which aim to add a UIScrollView to the UIImageview and give the scrollview a container.
h file:
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIImageView *imageView;

@property (nonatomic, strong) UIScrollView* scrollView;
@property (nonatomic, strong) UIView* container;

@end

m file:
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *image = [UIImage imageNamed: @"new_phots_fake_port.png"];
    //Add the image to the imageView I created in the Storyboard
    [_imageView setImage:image];

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(60.0, 70.0, 522.0, 100.0)];
    [_scrollView setBackgroundColor:[UIColor yellowColor]];

    // Set up the container view to exist inside the scrollview:
    CGSize containerSize = CGSizeMake(5000.0f, 730.0f);
    _container = [[UIView alloc] initWithFrame:(CGRect){.origin=CGPointMake(0.0f, 0.0f),       .size=containerSize}];
    _container.backgroundColor = [UIColor redColor];
    // Tell the scroll view the size of the contents
    self.scrollView.contentSize = containerSize;
    [_scrollView addSubview:_container];

    [_imageView addSubview:_scrollView]; //This is what I want but doesn't allow scrolling

    //[self.view addSubview:_scrollView];  //This allows scrolling but makes the imageView      and Scrollview siblings.  I need scrollview to be a child of imageview
   }

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

So, the scrollview cannot seem to be added to the imageview (and function correctly).  Why?  What am I doing wrong?
Strangely, I also didn't use either of the delegate methods viewForZoomingInScrollView or scrollViewDidZoom.  I'm not sure why these were not needed.
Answer: You need to set userInteractionEnabled on the UIImageView
_imageView.userInteractionEnabled = YES;

Comment: You answered so fast that Stack Overflow won't yet allow me to accept your answer.  But I will.  Cheers


Iterative MLE, possibly changing distribution

Question: Edit: After a couple of days of googling, I have found no reference about using gradient descent (GD) methods to solve MLE for fixed distribution, not to mention the case where parameters may vary over the time. This is highly surprising to me. The only stuff I've found was on the GD methods used for MLE computation in case of supervised learning, e.g. linear of logistic regressions. But those methods do not seem to be directly applicable in my situation, as they focused on estimating of distribution of a target given features, where below there are no explicit features given. There's definitely a connection, but I am failing to see one.

Original:
In Auction problem I have asked about a problem where I am looking to estimate a fixed distribution parameters from data. There I have some parametrized distribution given by a CDF $F(\cdot|\theta)$, and at each step I do a draw by choosing $x$ which gives a success with probability $1 - F(x|\theta)$ and failure with probability $F(x|\theta)$.
Let's just say I have fixed $x$ and wait until the first time I get a successful trial. My MLE $\theta$ must maximize the log likelihood
$$
L(x, t|\theta) = \log\left(F^{t-1}(x|\theta)\cdot (1 - F(x, \theta))\right) = (t-1)\log F(x|\theta) + \log (1 - F(x, \theta))
$$
where $t$ is the step at which I get a success. What I thought of is that instead of solving $\nabla_\theta L= 0$ I could use $\nabla_\theta L$ to as in gradient descent (GD) methods to update my estimate of the parameters by $\theta \to \theta + \nabla_\theta L\cdot s$ where $s$ is some step size. If the distribution is fixed, then after enough iterations I should be able to converge to the optimal $\hat\theta$. I have noticed however, that in such case I do not have to wait for the first success to make an update. Reason is: in the situation above, on each failure I would have an update of
$$
\theta\to\theta + \nabla_\theta \log F(x|\theta) \cdot s
$$
and on each success
$$
\theta\to\theta + \nabla_\theta \log (1 - F(x|\theta)) \cdot s
$$
which in case success happens after $t$ steps amounts to the very change of $\theta$ as if we would have just updated it in one go after $t$ steps. That's assuming that the learning step $s$ says constant.
I'd like to know more about this procedure. Most likely it is being used, since it allows improving one's knowledge of the best parameters on the go, also one could change $x$ at each step. Do it have a name, what are good references on it? Finally, in case the distribution $F$ may change over time, this procedure provides a way to constantly update our estimate of $\theta_t$. For which perhaps some adjustment of the learning rate $s$ may be needed.
Comment: I think you may have made an error in your question.  The function you say you want to maximise includes the gradient operator.  Presumably what you mean is that you want to maximise the log-likelihood function (without the presence of the gradient operator) and you are later using that operator to find the critical points of the function?
Comment: @Ben you're correct, I'll fix that in the OP. what do you think about the described approach?
Answer: I think you may be overcomplicating the situation here, by failing to recognise the kinds of optimisation problems and standard methods that arise in these cases.  As presently written, your optimisation problem is a standard problem that can be solved using standard calculus methods and numerical methods.  The partial derivatives of your objective function are:
$$\begin{align}
\frac{\partial ML_{x,t}}{\partial \theta_k}(\theta)
&= \frac{t-1}{F(x|\theta)} \cdot \frac{\partial F}{\partial \theta_k}(x|\theta) - \frac{1}{1-F(x|\theta)} \cdot \frac{\partial F}{\partial \theta_k}(x|\theta) \\[12pt]
&= \bigg[ \frac{t-1}{F(x|\theta)} - \frac{1}{1-F(x|\theta)} \bigg] \frac{\partial F}{\partial \theta_k}(x|\theta) \\[12pt]
&= \frac{1}{F(x|\theta) (1-F(x|\theta))} \bigg[ (t-1) (1-F(x|\theta)) - F(x|\theta) \bigg] \frac{\partial F}{\partial \theta_k}(x|\theta) \\[12pt]
&= \frac{1}{F(x|\theta) (1-F(x|\theta))} \bigg[ (t-1) - t F(x|\theta) \bigg] \frac{\partial F}{\partial \theta_k}(x|\theta) \\[12pt]
&= \frac{t}{F(x|\theta) (1-F(x|\theta))} \bigg[ \frac{t-1}{t} - F(x|\theta) \bigg] \frac{\partial F}{\partial \theta_k}(x|\theta), \\[12pt]
\end{align}$$
which means that the gradient of the objective function is:
$$\nabla_\theta ML_{x,t} (\theta) = \frac{t}{F(x|\theta) (1-F(x|\theta))} \bigg[ \frac{t-1}{t} - F(x|\theta) \bigg] \nabla_\theta F(x|\hat{\theta}).$$
The critical points of the function occur when:
$$F(x|\hat{\theta}) = \frac{t-1}{t}
\quad \quad \text{or} \quad \quad
\nabla_\theta F(x|\hat{\theta}) = 0.$$
In this particular case the first condition gives you an explicit solution for the critical points, and the second condition can be solved using standard iterative root-finding methods like Newton-Raphson.  There is no need for any novel iterative method, and it is not clear that your proposed methods would work properly, or outperform existing methods even if it works.

Let's step back from your specific problem and look at general forms of optimisation problems that you might encounter.  In the linked answers to your related question, we find that your problem leads to an optimisation of the form:
$$\text{Maximise } f(\mathbf{x})
\quad \quad \quad \text{for } 0 < x_1 \leqslant \cdots \leqslant x_n < 1.$$
This is an example of a constrained optimisation; there are a number of ways you can solve it.
In one of the answers in the linked question, there is an analytical solution derived that first computes the unconstrained solution (assuming that the required ordering holds in this solution) and then asks what would happen if the ordering does not hold in the solution.  This leads to a solution form where the user finds out that there are certain conditions leading adjacent parameters to be equal, and derives an explicit form for the solution using standard calculus methods.
In another of the answers in the linked question (my answer), an alternative method is deployed, whereby the input parameter for the optimisation is written as a smooth function of an underlying unconstrained parameter vector.  This then allows the optimisation to be rewritten as an unconstrained optimisation, using the chain rule to find relevant derivatives.  The unconstrained optimisation is then solved using ordinary optimisation methods (including numerical methods to iterate towards the solution) and the optima is then converted back to be stated in terms of the constrained parameter.  This latter method is less accurate than an explicit solution, but it is a more general method that can be deployed on a wide range of objective functions.
Comment: Thanks! I may indeed overcomplicate things by having very limited practical experience with such problems. Yet, I am having a problem at hand where solving a $\nabla_\theta = 0$ may not be easy (hence gradient descent comes as a natural way to solve it), or that parameters may be time-varying (same gradient descent may also tackle that case).  That's what the OP about. Would that be correct to assume that you would use different methods in my case?
Comment: I think the key thing to remember here is that this part of statistics is just math --- it is just a constrained or unconstrained optimisation problem, and so you can deploy *any* mathematical technique that is suitable for the relevant optimisation problem.  Statistics does not have any special rules here; it makes use of all the standard optimisation techniques available in all relevant fields of mathematics.
Comment: This is true indeed, but I'm kinda confused by the fact that I don't see GD being described as an online optimization for MLE. Perhaps there are some obvious reasons why one should not try that, or that it does not work, or anything of that kind
Comment: The main reason you don't see GD used much is because in most statistical problems the log-likelihood is twice-differentiable and has a simple (and easily computable) form for this second derivative, which means we can apply Newton's method to get a better iteration that takes account of the curvature of the function.  Newton's method is known to converge more quickly than GD when it is available.
Comment: and what about the case in which parameters may be time-varying? I've actually just implemented GD on time-varying parameters for the problem above and it definitely looks decent


Do there exist space-filling curves that fill the whole plane? If so, can they be visualized?

Question: I know that there are space-filling curves from $[0, 1]$ to the unit square, and this question addresses curves transforming the real line into the entire plane. But what about transforming the unit interval into the whole plane?
And if such curves exist, can their construction somehow be depicted, perhaps by showing a few examples of a sequence of curve that converges to the space-filling curve (as is often done for curves mapping the unit interval to the unit square, see below)?

Image from http://en.wikipedia.org/wiki/Space-filling_curve
Comment: A curve $\gamma$ is continuous. $[0,1]$ is compact. Hence $\gamma([0,1])$ is ...?
Comment: Going further with what Daniel Fischer said, seeing as there are continuous transformations from both $(0, 1)$ and $[0, 1)$ onto the real line, those can be used as a parametrisation to fill the plane.
Answer: Update: Here is a neater construction!

As Daniel Fischer has pointed out this cannot be done with $[0,1]$ as parameter interval. Therefore we shall map the half-open interval $[0,1[\ $ continuously onto ${\mathbb R}^2$. Use the redraw rule shown in the above figure to create a Peano curve
$$\gamma_*: \quad\bigl[0,1]\to R:=[0,\sqrt{3}]\times[0,1]\ .$$
(Sketch of proof: Let $t\mapsto\phi_0(t)\in R$ be the parametrization of the diagonal in the lefthand figure above. The redraw rule, applied recursively in nested triadic subintervals of $[0,1]$, produces a sequence $(\phi_n)_{n\geq0}$ of piecewise linear maps $\phi_n:\>[0,1]\to R$. It is easy to check that $$|\phi_{n+1}(t)-\phi_n(t)|\leq 3^{-n/2}\qquad(0\leq t\leq1)\ ,$$  and this implies that the $\phi_n$ converge uniformly to a continuous map $\gamma_*:\>[0,1]\to R$. Since $\gamma_*(I)$ is closed and dense in $R$ it has to be all of $R$.)
Stretch this $\gamma_*$ horizontally by a factor $\sqrt{2\over3}$, so that we now have a Peano curve
$$\gamma_0:\quad\bigl[0,1]\to[0,\sqrt{2}]\times[0,1]\ ,$$
beginning at $(0,0)$ and ending at $(\sqrt{2},1)$. This $\gamma_0$ is now concatenated with a copy of itself, then with ever larger copies scaled by factors $2^{n/2}$, in a spiraling way, see the following figure which shows only the "diagonal" of each copy:

For the concatenation we allot the time interval $\bigl[0,{1\over2}\bigr]$ for $\gamma_0$, then the subsequent time intervals $$\bigl[1-2^{-n},1-2^{-(n+1)}\bigr]\quad(n\geq1)$$ for the subsequent rectangle filling curves.
Comment: Cool. I don't recall what it takes to prove that the limit of such a sequence of functions exists and is surjective but this seems intuitively to do it.
Comment: @kuzzooroo: See my edit, with sketch of proof.
Answer: We can also use Hilbert type curves to construct a line which fills into the entire plane. I propose a kind of '''Hilbert spiral'''. The basic idea is quite simple - besides the standard downward recursive construction of Hilbert-type curves,
we add an upward process to make a spiral.


Recursive partitioning using rpart() method in R

Question: I am new to R and using rpart for building a regression tree for my data.I wanted to use all the input variables for building the tree, but the rpart method using only a couple of inputs as shown below. As we can see, I have provided 10 inputs, but rpart used only two inputs. Please let me know how can force rpart method to use all the input variables. Thanks.
rm = rpart(uloss ~ tc_b + ublkb + mpa_a + mpa_b +
     sys_a + sys_b + usr_a, data = data81, method="anova")
> princtp(rm)

Regression tree:
rpart(formula = uloss ~ tc_b + ublkb + mpa_a + mpa_b + sys_a +
    sys_b, data = data81, weights = usr_a, method = "anova")

Variables actually used in tree construction:
[1] mpa_a tc_b
Root node error: 647924/81 = 7999
n= 81
       CP nsplit rel error  xerror     xstd
1 0.403169      0   1.00000 1.04470 0.025262
2 0.092390      1   0.59683 0.66102 0.015238
3 0.081084      2   0.50444 0.70702 0.013123
4 0.045304      3   0.42336 0.58683 0.012129
5 0.010000      4   0.37805 0.51930 0.011942

One more question:
I have used rpart.control for minsplit=2, and got the following for another data.
Inorder to avoid overfititng the data, do I need to use splits 3 or splits 7.  Shouldn't I use splits 7? Please let me know.
Variables actually used in tree construction:
[1] ct_a  ct_b  usr_a
Root node error: 23205/60 = 386.75
n= 60
        CP nsplit rel error  xerror     xstd
1 0.615208      0  1.000000 1.05013 0.189409
2 0.181446      1  0.384792 0.54650 0.084423
3 0.044878      2  0.203346 0.31439 0.063681
4 0.027653      3  0.158468 0.27281 0.060605
5 0.025035      4  0.130815 0.30120 0.058992
6 0.022685      5  0.105780 0.29649 0.059138
7 0.013603      6  0.083095 0.21761 0.045295
8 0.010607      7  0.069492 0.21076 0.042196
9 0.010000      8  0.058885 0.21076 0.042196

Answer: Perhaps you misunderstood the message? It is saying that, having built the tree using the control parameters specified, only the variables mpa_a and tc_b have been involved in splits. All the variables were considered, but just these two were needed.
That tree seems quite small; do you have only a small sample of observations? If you want to grow a bigger tree for subsequent pruning back, then you need to alter the minsplit and minbucket control parameters. See ?rpart.control, e.g.:
rm <- rpart(uloss ~ tc_b + ublkb + mpa_a + mpa_b +
            sys_a + sys_b + usr_a, data = data81, method = "anova",
            control = rpart.control(minsplit = 2, minbucket = 1))

would try to fit a full tree --- but it will be hopelessly over-fitted to the data and you must prune it back using prune(). However, that might assure you that rpart() used all the data.
Comment: @kkp the convention is to use the smallest tree within one standard error of the best tree. The best tree is in row 8 (7 splits), but the tree in row 7 (6 splits) does effectively the same job and is simpler, hence the 1 standard error rule would select it. Note Frank's comment in his Answer. Almost certainly you want to be using one of the bagged/boosted trees or random forest algorithms.
Comment: according to the above rpart results, rpart() method used finally two inputs to predict the response variable. That is, according to rpart(), these two inputs are only important and used for classification. Am I right?
Comment: Yes you are right samarasa
Answer: If the number of observations is less than around 20,000 the trees built by rpart do not have a reliable structure.  That is, if you were to use the bootstrap to repeat the process, you will see many different trees that are called 'optimal'.
Comment: Since you qualified your 20,000 observations with "trees built by rpart`, are there any of these single-tree algorithms that don't need upwards of 20,000 observations? Or did you mean any single-tree based methodology (and hence the need to use boosted or bagged trees or random forests?)?
Comment: I don't know of a single tree algorithm that works with non-huge datasets.  That's why random forests, bagging, and boosting are so popular.  But you lose the interpretability of the tree with these.  In general there is a interpretability-reliability tradeoff.  You might as well fit a rich regression model with appropriate attention to number of parameters examined.  Regression models are interpretable and you can make them reliable.  A good start is usually a flexible additive regression model, allowing many of the continuous predictors to have nonlinear effects (using e.g. splines).
Comment: thanks, was just checking - that was my interpretation of single-tree based methods.


Is there a mathematical structure without axioms that is equivalent to topological spaces?

Question: We can sometimes represent a "big structured" object by defining a "smaller unstructured" object. For example, a map $L: V \to W$ that satisfies the axioms of linear maps can be represented as a map $L: B_V \to W$, where $B_V$ is a basis for $V$. So there is a bijection between the space of linear maps $V \to W$ to the space of set-theoretic maps $B_V \to W$.
Is there similarly a family of mathematical structures without axioms, for which there is a bijection with the family of topological spaces?
Comment: This is a vague question, but the answer should be along the lines of "no". Exceptions include special classes such as maps out of discrete spaces, maps into indiscrete spaces or simplicial maps between simplicial complexes.
Answer: I think the only reasonable general interpretation of what you decribe is that of a free object in a category. See also definition of a free object in a category.
In the category of vector spaces over a fixed field each object is free. In fact, each vector space is free on each its bases. In the category of abelian groups not every object is free. The free objects are denoted as free abelian groups.
What about the category $\mathbf{Top}$ of topological spaces and continuous maps? We shall show that the free objects are precisely the discrete spaces. This class of spaces is not very interesting and the answer to your question is "no".
For each space $X$ let $S(X)$ denote its underlying set and for each  continuous map $F : X \to Y$ between spaces $X,Y$ let $S(F) : S(X) \to S(Y)$ denote its underlying function.

Let $X$ be discrete and $Y$ be an arbitrary space. Then each function $f : S(X) \to S(Y)$ is a continuous map $f : X \to Y$; that is, we have a bijection between the set of continuous maps $\mathbf{Top}(X,Y)$ from $X$ to $Y$ and the set of functions $\mathbf{Set}(S(X),S(Y))$ from $S(X)$ to $S(Y)$.

Let $X$ be a space which is free on some set $B$. This means that there exists a function $i : B \to S(X)$ such that for each space $Y$  and each function $f : B \to S(Y)$ there is a unique continuous map $F : X \to Y$ such that $S(F) \circ i = f$.
Let us first verify that $i$ must be surjective. So assume $i(B) \subsetneqq S(X)$. Let $T$ be a two-point space with the trivial topology and $f : B \to S(T)$ be any non-surjective function. Since each function $F : X \to T$ is continuous, we conclude that there must be a unique function $\phi : S(X) \to S(Y)$ such that $\phi \circ i = f$. This is a contradiction because the condition $\phi \circ i = f$ allows that the elements $S(X) \setminus i(B)$ can be mapped arbitrarily into the two-point set $S(T)$, i.e. there exists more than one function satisfying our condition.
Now let $Y$ be the discrete space with underlying set $S = S(X)$ and $f = i : B \to S(Y) = S$. Let $F : X \to Y$ be the unique continuous map such that $S(F) \circ i = i$. Then $S(F)$ is the identity on $S$ because $i$ is surjective. Hence the identity $X \to Y$ is continuous which implies that $X$ is discrete.
Answer: I'm not sure if this is close enough to your question, but it's something vaguely related that came to mind.
An interesting idea in algebraic geometry is that going between algebra and geometry is via opposite categories. (They take this correspondence very literally -- "algebra" is the category of commutative rings $\mathrm{CRing}$, and "geometry" is just $\mathrm{CRing}^{\mathrm{op}}$, objects of which are known as affine schemes.)
We might try to do this in reverse: $\mathrm{Top}^{\mathrm{op}}$ ought to be an "algebraic" description of topological spaces.  I'm not familiar with the full answer (it appears there is a description of this category), but I do know that restricting to certain subcategories of $\mathrm{Top}$ gives some nice answers.  For example, the category of compact totally disconnected Hausdorff spaces (the profinite spaces) is equivalent to the category of boolean algebras. This is an instance of Stone duality.


Checking for the completeness for the M.S of $f(x) = \frac12 \exp(-|x-\theta|)$

Question: The minimum sufficient statistics for $f(x) = \frac12 \exp(-|x-\theta|)$ for $-\infty < \theta < +\infty$ is $ T(X) = \{X_{(1)},X_{(n)} \}$. I want to show that the above is complete.
$f(x) = \frac12 \exp(-|x-\theta|)$ is location family therefore the range is an ancillary statistic which is free of $\theta$
Let $h((T(x))$ be $X_{(n)}-X_{(n)}.$
$$0 = E_\theta [ g(h(T(X))] = \int_{-\infty}^{+\infty} g(h(t)) f(h(t))~dt.$$
$f(h(t))$ is now $$\frac12 \exp(-|(t_{(n)}-\theta) - (t_{(1)}-\theta)|)$$
which reduces to
$$\frac12 \exp(-|(t_{(n)}- t_{(1)}|). $$
When $ \int_{-\infty}^{+\infty} g(h(t)) \frac12 \exp(-|(t_{(n)}- t_{(1)}|)~dt = 0$, then $g(h(t)) = 0~~\forall h(t).$
Now, I want to claim that since $h(T)$ is complete and there is a 1-1 function between $h(T)$ and $T$ therefore $T$ is also complete. Is this approach correct?
Comment: Minimal sufficient statistic is the full set of order statistics $(X_{(1)},X_{(2)},\ldots,X_{(n)})$.
Comment: @StubbornAtom: the set $\{X_1,\ldots,X_n\}$ is equally minimal sufficient.
Comment: The minimal sufficient statistic is _not_ complete in this case. Consider the vector of the pairwise differences, with fixed expectation..
Comment: @Xian, just to follow your suggestion. You would want me to apply a function on T s.t  I have something like $( X_(1)-X_(2),,,X(n-1) - X(n)) as my new t correct?
Answer: Since the double exponential distribution is not part of an exponential family, there cannot exist a sufficient distribution with fixed (in $n$) dimension. The minimal sufficient statistic in this case is $(X_{(1)},\ldots,X_{(n)})$ or, equivalently, $\{X_1,\ldots,X_n\}$. Since $\mathbb{E}[X_i-X_j]=0$, this statistic cannot be complete.


How can i install external pinax projects?

Question: I try to deal with poor documentation of Pinax.
I found this project
https://github.com/pinax/pinax-multiblog-project

what i want is that install it. I normally install a project called account  but here i have to install from git . How can i do that in Pinax
Answer: Edit:
It turns out the new way of using projects is to just copy the folder and rename it.
Usage instructions:
So to use the multiblog project you would do
Copy the multiblog inside the cloned repo to a new location and rename it to the name you would like to use for your project. Then install the requirements via pip and follow the rest of the steps for setting up a django project
OSX/Linux:
cd ~/src
git clone https://github.com/pinax/pinax-multiblog-project
cp -r ~/src/pinax-project-admin ~/Sites/new_project
cd ~/Sites/new_project"
pip install -r requirements.txt
python manage.py syncdb

I too have been trying to accomplish the same thing. So far I found this commit
https://github.com/nrb/pinax/blob/476d2398c48cc444eb2338c12090f0cebad46961/docs/starterprojects.txt
Relevant section on begins on line 160 near the end
External Starter Projects
=========================

The Pinax ``setup_project`` command can also use starter projects built by third     parties.
These can either be plain directory structures, or they may be a git/hg pip editable.

To install a starter project from an external source, simply pass the file path or git/hg
URL to the ``-b`` option::

pinax-admin setup_project -b git+git://github.com/user/project.git#egg=project my_new_project

However all the pinax projects I have come across don't seem to include an egg to use
eg:

https://github.com/pinax/pinax-multiblog-project
https://github.com/pinax/pinax-project-account

I need to use Django 1.4 for my project but the included account base project in both Pinax 0.9a2 and 0.9b1-dev10 use Django 1.3.
I am guessing the external project integration is something we will have to wait for in the Pinax 1.0 release.
Comment: yeap i installed after some trials but directories are downloaded incompletely


Dig from a specific domain shows no answer but normal dig works

Question: I am having an issue with a WHM installation that was done over a week ago. It seems all is good on the WHM side of things but I am having issues with my nameservers I have set up
Whenever I try to change a domains nameservers over to mine it rejects it(ns1.iclixhosting.co.za, ns2.iclixhosting.co.za)
I have called around the different providers and it seems it is ns2 that is giving the problem
When I run a dig command it returns an A record
dig ns2.iclixhosting.co.za

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.el7_9.3 <<>> ns2.iclixhosting.co.za
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8738
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;ns2.iclixhosting.co.za.                IN      A

;; ANSWER SECTION:
ns2.iclixhosting.co.za. 3252    IN      A       18.104.22.168

;; Query time: 304 msec
;; SERVER: 126.96.36.199#53(184.108.40.206)
;; WHEN: Wed Feb 17 15:36:59 SAST 2021
;; MSG SIZE  rcvd: 67

However what they are saying is that they do not pick it up when they try run it through the specific domains we are trying to point to our nameservers
I am not sure what to do further on my side, Thank you for any help in advance
Edited to add more details
I am trying to set up ns1 and ns2 as nameservers that other domains can use. I cant point any domains as they say ns2 is not returning with an answer on their servers below is a dig from 126.96.36.199 as I was asked to do in the comments
dig @22.214.171.124 ns2.iclixhosting.co.za

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.el7_9.3 <<>> @22.214.171.124 ns2.iclixhosting.co.za
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 60456
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;ns2.iclixhosting.co.za.                IN      A

;; ANSWER SECTION:
ns2.iclixhosting.co.za. 3599    IN      A       188.8.131.52

;; Query time: 178 msec
;; SERVER: 220.127.116.11#53(188.8.131.52)
;; WHEN: Wed Feb 17 21:11:17 SAST 2021
;; MSG SIZE  rcvd: 67

As I say I am returning an answer however I cant set ns2 as the nameserver for other domains
Edited to add more details
Alright so thanks to Håkan Lindqvist in the comments I ran the command below and got the following results, This is very strange because if I ping the ns2.iclixhosting.co.za I get a response from the server
dig @ns2.iclixhosting.co.za heavencloud.co.za +norec

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.el7_9.3 <<>> @ns2.iclixhosting.co.za heavencloud.co.za +norec
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

Another Edit
dig results
Comment: Your question seems offtopic here as questions in specific panels are offtopic, however in all cases, it is not very clear, what is "normal dig"? What does "it rejects it" mean? Who rejects what with what error message? You should also always use the `@` option to dig to specify which nameserver your query. Otherwise your results depend on the locally configured recursive nameserver, and as such can vary in space and can not be reproduced by others.
Comment: `dig @ns2.iclixhosting.co.za example.com +norec` would be the kind of query that should work if `ns2.iclixhosting.co.za` has a `example.com` zone. The queries in the question just shows that the name `ns2.iclixhosting.co.za` resolves.
Comment: Hi,

please provide more details about "the problem" ?

---

it seems that your NS are actualy cloudflare.
You can check it with a :
`dig NS ns2.iclixhosting.co.za`
NS records are usualy outside the DNS zone in your ISP web interface.
Comment: Hi @inattendu and Patrick. I have made the edits as requested. Where should this question be placed Patrick?
Comment: Hey @HåkanLindqvist I just added the results of the comment, It does not seem to be responding saying no server could be reached, What could be the issue?
Comment: `ns1.iclixhosting.co.za` seems to work, but `ns2.iclixhosting.co.za` doesn't answer to my lookup requests too, from two completely distinct places in the world (from Russia and Germany). But it answers to ping requests. Are you sure that it really runs a public name service? I think you better ask questions to that server operator, why is it inaccessible.
Comment: Hey @NikitaKipriyanov Thanks for trying your side, Yes I believe it does have a public name service as I don't think ns1 would work if it didn't, I don't 100% know what I should ask them as it appears to be online with no issues due to that ping showing a response. I have updated the question again with another thing I have tried I'm not sure where to start looking for a solution to this.
Answer: It look like the TCP port 53 is firewalled on NS2
nmap -p 53 ns1.iclixhosting.co.za
Starting Nmap 7.91 ( https://nmap.org ) at 2021-02-18 10:50 CET
Nmap scan report for ns1.iclixhosting.co.za (126.96.36.199)
Host is up (0.20s latency).

PORT   STATE SERVICE
53/tcp open  domain

Nmap done: 1 IP address (1 host up) scanned in 0.82 seconds

VS
nmap -p 53 ns2.iclixhosting.co.za  -Pn
Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower.
Starting Nmap 7.91 ( https://nmap.org ) at 2021-02-18 10:51 CET
Nmap scan report for ns2.iclixhosting.co.za (184.108.40.206)
Host is up.

PORT   STATE    SERVICE
53/tcp filtered domain

Nmap done: 1 IP address (1 host up) scanned in 2.11 seconds

could you please list open port on ns2 ?
( ss -ntpl for tcp open port on debian )
Comment: Hi this was 100% the case as it was being blocked by the firewall thank you


Unitary matrices as a function of Hermitian matrices

Question: My books says that a unitary matrix $U$ can be written as:
$ U = A + i B$
where $A$ and $B$ are Hermitian and are related by:
$A^2 + B^2 = I$
where $I$ is the identity matrix.
However, I cannot seem to find any proof of this statement and struggling to understand why that is the case.
Answer: Any square matrix $U$ with complex entries can be written in the form $U=A+iB$ with $A,B$ Hermitian by setting
$$ A=\frac{U+U^*}{2}$$
and
$$ B=\frac{U-U^*}{2i}$$
If also $U$ is unitary, then $U^*U=UU^*=I$, and it follows that
$$ A^2+B^2=\frac{1}{4}(U+U^*)^2-\frac{1}{4}(U-U^*)^2=I$$
To understand the motivation behind the definitions of $A$ and $B$, it might be useful to think of the one dimensional case, when matrices are just complex numbers, Hermitian matrices correspond to real numbers, and unitary matrices to complex numbers with modulus one.
Comment: The notation $M^H$ means the same thing as the $M^*$ which I used in my answer. A matrix is Hermitian if $M^H=M$, not $M^H=M^T$. And also $(A+iB)^H=A^H-iB^H$ since the complex conjugate of $i$ is $-i$.
Comment: Does $U^*$ stand for the complex conjugate or the Hermitian conjugate of $U$?
Comment: $U^*$ is the adjoint, which is given by conjugating every entry of $U$ and then transposing $U$.
Comment: From my understanding if $U = A + iB$, then if I conjugate every entry of $U$ I should obtain $A - iB$. Why is the transposing needed? Wouldn't that modify $A$ and $B$ also?
Comment: Do you know what it means for a matrix to be unitary or hermitian?
Comment: Well to my knowledge a matrix $M$ is Hermitian if its complex conjugate transposed (denoted with $^H$) is equal to its transpose, in other words $M^H = M^T$. A unitary matrix $U$ is one which obeys $U^{-1} = U^H$. What I don't understand from your answer is that according to my knowledge $(A + iB)^H = A^H + iB^H \ne A- iB$.
Comment: Thanks that clarifies it. I had understood the definition completely wrong.


What is the correlation of $X_1 + X_2$ and $X_1 - X_2$?

Question: Suppose $E[X_1] = 2$ and $Var(X_1) = 4$.
Suppose $E[X_2] = 0$ and $Var(X_2) = 1$.
Suppose also that $Cor(X_1,X_2) = \frac13$.
I can calculate that the expected value and variance of $X_1+X_2$ is $2$
and that the variance of $X_1+X_2$ is $6 \frac13$
and that the expected value and variance of $X_1-X_2$ are $2$ and $3 \frac23$ respectively
using $E[(a_1X_1 + a_2X_2)] = a_1E[X_1] + a_2E[X_2]$
and  $Var (a_1X_1 + a_2X_2) = a_1^2Var(X_1) + a_2^2Var(X_2) + 2a_1a_2Cov(X_1,X_2)$
But how do we get the correlation of $X_1+X_2$  and  $X_1-X_2$  ?
the solution should be $0.623$, but I have no idea how to get there?
Answer: Guide:
$$Cor(X_1+X_2, X_1-X_2) = \frac{Cov(X_1+X_2, X_1-X_2)}{\sqrt{Var(X_1+X_2)Var(X_1-X_2)}}\tag{1}$$
\begin{align}Cov(X_1+X_2, X_1-X_2)&=Cov(X_1,X_1)-Cov(X_1,X_2)\\&+Cov(X_2,X_1)-Cov(X_2,X_2)\\
&=  Var(X_1)-Var(X_2)\end{align}
Also, compute $Var(X_1\pm X_2)$ and then substitute inside equation $(1)$ to evaluate the correlation.


Instantiate class variables in constructor of that class

Question: I have a simple class like so:
public class MyClass
{
        public string String1;
        public string String2;

        public MyClass()
        {

        }

        public MyClass(string Json)
        {

        }
}

If the class is instantiated without a parameter, it just brings back an empty object.. However, when I pass a string of JSON to the constructor I would like to set all the properties equal to their value in the JSON.
I have done this outside of the class using JSON.NET by Newtonsoft, like this:
string JsonArray = Base64.Decode(HttpContext.Current.Request.QueryString["songinfo"]);
MyClass tmp = JsonConvert.DeserializeObject<MyClass>(JsonArray);
MyClass InstantiatedClass = tmp;

InstantiatedClass is now a fully populated object.. But, I would like to achieve this within the constructor itself, but I can't figure out a way to do it..
I've tried things like setting this = JsonConvert.DeserializeObject<MyClass>(Json), but of course, this is read-only.
I know I could do it by parsing the Json and setting each variable equal to it's appropriate JSON attribute value, but I'd like to do it this way because it's cleaner.
Comment: Of course, if `MyClass` had been a `struct`, your approach with `this = JsonConvert.DeserializeObject(Json);` would have worked.
Comment: The only way to do it is to create a second instance inside the constructor and then use reflection to clone all the properties. The static factory methods mentioned in the answers are the next best thing compared to what you're asking and a better/cleaner solution even.
Comment: I don't have an answer to your question and it seems that you already have some but I wanted to correct your terminology.  You don't "instantiate variables".  The only thing that you can instantiate is a type, by creating an object of that type.  What you want to do is "initialise" those variables, with an object that is the instantiation of a type.
Answer: You can't do it from the constructor. You might consider a factory method within MyClass like so:
public static MyClass Deserialize(string json)
{
    return JsonConvert.DeserializeObject<MyClass>(json);
}

A constructor doesn't return anything, and as you stated this is read-only. Thus, doing it in the constructor isn't really possible without (as you stated) manually parsing the JSON and initializing the different variables within that instance.
The factory method is probably what you're looking for.
Comment: A note: If you take this approach, you might want to make the constructor `private` so that the object can only be constructed via the factory method.
Answer: You could do sth like this:
public class MyClass
{
    public string String1;
    public string String2;

    public MyClass()
    {

    }

    public static MyClass Instance(string json)
    {
        return new JsonConvert.DeserializeObject<MyClass>(json);
    }
}

But this is just some kind of a workaround on what you want to achieve. There is in fact no possibility to do this via constructor directly.
Answer: public MyClass(string Json)
{
    MyClass tmp = (MyClass) JsonConvert.DeserializeObject<MyClass>(Json);

    this.String1 = tmp.String1;
    this.String2 = tmp.String2;
}

Note, you have access to all private members of the MyClass inside MyClass methods.