Does Perl6 (a.k.a Raku) support something equivalent to Perl5's __DATA__ and __END__ sections?

Question: Does perl6/Rakudo have something equivalent to perl5's __DATA__ or __END__ sections?
Answer: Quote S26:

Named Perldoc blocks whose typename is
  DATA are the Perl 6 equivalent of the
  Perl 5 __DATA__ section. The
  difference is that =DATA blocks are
  just regular Pod blocks and may appear
  anywhere within a source file, and as
  many times as required. Synopsis 2
  describes the new Perl 6 interface for
  inline data.

In theory you should be able to do something like this (somebody please fix the syntax if it's off):
use v6;

=begin DATA
Foo
=end DATA

say @=DATA;

In practice it seems that Rakudo does not support that, yet.
Comment: Unfortunately Rakudo doesn't implement them yet.
Answer: To carefully selectively quote the current S02 design document:

There is no longer any special DATA stream--any Pod block in the
  current file can be accessed via a Pod object ...
You have to split [Pod block] contents into lines yourself.
[Speculative] It may also be possible to treat a Pod object as an
  IO::Handle, to read the Pod information line-by-line (like the DATA
  filehandle in Perl 5, but for any Pod block).

So, instead of the single DATA section per file which you access by reading a filehandle, you define any number of Pod blocks in your script file; they're stored in the $=pod variable at compile time; you read from that variable; and the ones called 'data' are the equivalents of Perl 5's DATA.
This works today. I'll show that in a moment. But first I need to talk about stuff that does not work today.
The quoting above was highly selective. The elided text talked about P6 automatically creating a variable with a name of the form $=foo corresponding to Pod blocks with the name 'foo'. This is a general still unimplemented feature of Pod blocks, not just data blocks.
The "data block" section of the Pod design doc S26 talks about data blocks doing some fancier stuff than plain old Pod blocks. This has not yet been implemented either.
So, now let's move on to what can be done today:
=foo This is a Pod block. A single line one. This Pod block's name is 'foo'.

=begin qux
This is another syntax for defining a Pod block.
It allows for multi line content.
This block's name is 'qux'.
=end qux

=data A data block -- a Pod block with the name 'data'.

# Data blocks are P6's version of P5's __DATA__.
# But you can have multiple data blocks:

=begin data
Another data block.
This time a multi line one.
=end data

$=pod.grep(*.name eq 'data').map(*.contents[0].contents.say);

This prints:
A data block -- a Pod block with the name 'data'.
Another data block. This time a multi line one.

So, it sorta works. But it clearly needs a lot more sugar.
By the way, if the last FP style line didn't make sense, here's an imperative equivalent:
for @$=pod {
  if .name eq 'data' {
    say .contents[0].contents
  }
};

Answer: As a work-around until this gets fully implemented, you can use heredocs.
for data().lines -> $line {
    put $line;
}

sub data {
    return q:to/END/;
           Foo, bar, baz
           1, 2, 3
           END
}

Outputs

Foo, bar, baz
1, 2, 3

Answer: To get an array of data, while putting the data at the bottom of the program to help with readability, here is an variation of @Christopher Bottoms answer:
my @txts = data();
dd @txts;
# this works too
my %stuff = hashdata();
dd %stuff;

# a lot of lines

sub data() {
    return ( q:to/LINE1/,
        Phasellus dictum, nunc id vestibulum rhoncus, mauris massa tempus nibh,
        nec tincidunt nisi tellus et arcu. Phasellus vulputate consectetur
        vulputate. Quisque viverra commodo velit ac tincidunt. Nulla et est sem.
        Mauris gravida, nulla rutrum pharetra dapibus, eros velit feugiat nibh,
        nec iaculis purus urna ut diam. Praesent molestie felis a turpis gravida
        placerat. Duis sagittis pulvinar risus non aliquet. Nunc quis purus
        tempor, mattis nunc eu, porta ligula. Suspendisse dictum sit amet urna
        dapibus suscipit.
        LINE1
        q:to/LINE2/,
        Praesent molestie felis a turpis gravida
        placerat. Duis sagittis pulvinar risus non aliquet. Nunc quis purus
        tempor, mattis nunc eu, porta ligula. Suspendisse dictum sit amet urna
        dapibus suscipit.
        LINE2
        q:to/LINE3/);
        Quisque viverra commodo velit ac tincidunt. Nulla et est sem.
        Mauris gravida, nulla rutrum pharetra dapibus, eros velit feugiat nibh,
        nec iaculis purus urna ut diam. Praesent molestie felis a turpis gravida
        placerat.
        LINE3
}

sub hashdata() { # a hash works too.
      return ( 'p' => q:to/PDATA/,
        Some multiline data
        in some lines
        PDATA

        'q' => q:to/QDATA/,
           More data in
           multiple lines
           QDATA

         'r' => q:to/RDATA/
              Note that indentation depends on the position of the
              ending token.
              Also, the punctuation following the regex is the punctuation
              following the expression. So a comma after each of the
              p and q, but not needed after the r
              RDATA
         )
}

Comment: Three heredocs in one array. Nice! Thanks for bringing this up. It reminds me of something similar I've done with hashes (trying to emulate [Data::Section](https://metacpan.org/pod/Data::Section) from Perl 5).
Answer: YES.
According to this 2023 perl6.users email conversation, you end your program/document with:
=finish
Then: "Anything after =finish is put in string that can be pulled into a Raku program with $=finish (also undocumented)."
So you can reference the string (within the body of your program) using:
$=finish

That link further elaborates:

"=finish was introduced instead of Perl's __DATA__."

"=finish is an undocumented part of the POD6 specification ... . It will be documented soon."

https://www.nntp.perl.org/group/perl.perl6.users/2023/06/msg10997.html


how to calculate checksum as per AIS 140 standard

Question: I want to send a message to the server as per the AIS 140 standard. Please explain how to calculate the checksum. Find below the sample message format.
$Header,iTriangle,KA01I2000,861693034634154,1_37T02B0164MAIS,AIS140,12.976545,N,77.5497 59,E*50

Answer: As per AIS140 Standard Checksum is calculated by performing xor to all bytes received from packet.
Note: You have to remove '$'.
Caution: Use data from device to verify this code (Example provided from doc doesnt have valid checksum)
This Javascript code will help your job done.
function checksum(packet) {
  const charArray = packet.split('');
  let xor = 0;
  const n = charArray.length;
  for (let i = 1; i < n - 3; i++) {
    xor = xor ^ charArray[i].charCodeAt(0);
  }
  const cs = parseInt("0x" + charArray[n - 2] + charArray[n - 1]);
  return xor === cs;
}
checksum('$Header,iTriangle,KA01I2000,861693034634154,1_37T02B0164MAIS,AIS140,12.976545,N,77.549759,E*50')


Emacs/Common Lisp: Quote variable's value

Question: I need the quoted value of a variable.
For example, let's say we have the variables qwe and asd:
(setq qwe '(1 2 3)) ;; qwe is set to (1 2 3)
(setq asd ''(1 2 3)) ;; asd is set to '(1 2 3)

My question is: how do I achieve the same value for asd by using qwe?
I did it this way:
(setq asd `(quote ,qwe))
;; Now asd is '(1 2 3)

But it looks ugly and bad to me. I'll be surprised if there isn't a better way.
Comment: FWIW the code you've written does precisely what you want, and looks neither ugly nor bad to me. Quite to the contrary, it *very clearly* reads as quoting the evaluated value of `qwe`. What is it that you don't like about it?
Comment: @phils, well, I always try to escape quasiquotes as they appear to be harder to read. I like what Vatine proposed: `(list 'quote qwe)`, which, by me, looks better and is more understandable.
Answer: You are looking for
(setq asd `',qwe)

which is, in fact, equivalent to
(setq asd `(quote ,qwe))

Comment: Or indeed `(setq asd (list 'quote qwe))`.
Comment: Thank you, Vatine, your answer is what I was looking for! :)


Where do I install my hairpin legs on this 8 foot long butcher block for my new workstation desk?

Question: So this is my first DYI wood project for my new workstation desk. I purchased this Baltic birch butcher block and finished it myself. Not bad for my first go! It's 8 feet wide, 25" deep and 1.75 (1" 3/4) thick. It's a heavy boy.
For my legs I purchased these 28 inch ones. They're solid but the 1 inch dry wall screws that arrived with them are poor quality so I'm going to pick up some wood screws.
Questions:

Where should I install the legs from the edges? It says 2 inches from the edge. Will that be enough for an 8 foot wide heavy butcher block? I don't see a problem with bowing in the center. Is there a rule of thumb for installing legs? I'm worried I'm gonna mess it up.

The holes in the leg plates are 1/4" in diameter. The desk is 1.75 (1" 3/4) thick. What kind wood screw size will do? Also, do you recommend I drill a pilot holes for birch wood?

Apologies for the super newb questions. Thanks a bunch!
Comment: I'd be more concerned about it being wobbly on those legs than about any sort of sag. It will _look_ nice (if you're into that style leg, I'm not so much), but it gives me the overall impression of being rickety. You've got a _long_, _heavy_ desk top on some very spindly supports - if you bump into the 25" end, the whole thing may well wobble along the 96" length, knocking over things on the desktop.
Comment: Do a search for similar desks and see where / how the legs are positioned, then consider any local issues to you.
Comment: Yes to pilot holes. #10 or #12 pan head, 1-1/2" long. Subtleties in leg positioning aren't going to matter. If, as @FreeMan suggests, the desk has wobble problems, you could put two struts on the back legs that form triangles. Or you could tie it to a wall with a bracket if you had a wall handy.
Comment: Thanks for the tip! you were right about the legs. I ended up going 3 inches in from the sides and 2 inches up. The legs are heavy metal and the desk feels incredibly solid. No wobble with sheer force.
Comment: @AloysiusDefenestrate maybe make that an answer so the OP can accept it and this question can be closed out.
Answer: Yes to pilot holes. #10 or #12 pan head screws, 1-1/2" long.
Subtleties in leg positioning aren't going to matter. If, as @FreeMan suggests, the desk has wobble problems, you could put two struts on the back legs that form triangles. Or you could tie it to a wall with a bracket if you had a wall handy.
For anyone facing the same questions about sag, the Sagulator, http://www.woodbin.com/calcs/sagulator/ is a great resource to see if a given piece of wood or wood product will sag under a particular design load. If the OP had a flimsier piece of wood, that might have guided the positioning of the legs or changed the design.


Herstein exercise: A subgroup of a finite group G such that $|G| \nmid i_G(H)!$ must contain a non-trivial normal subgroup.

Question: This is a 'Harder' problem 40 from Abstract Algebra(1996) by Herstein. I'm just not able to figure out how to do this. even though I found a very similar post. Following is a verbatim statement of the question.

If $G$ is a finite group, $H$ a subgroup of $G$ such that $n \nmid i_G(H)!$, where $n=|G|$, prove that there is a normal subgroup $N \neq (e)$ of $G$ contained in $H$.

P.S. I've been stuck on this for about a week, and now I'm throwing in the towel, so I'd really appreciate a solution, but I humbly implore you to give me hints instead so that I can kill this problem (sort of) on my own, although frankly, I've given up hope.
Comment: What is $i_G(H)$? My guess from the rest of the question: the index of $H$ in $G$. In which case I have a solution. If it's something else, I'm not so sure.
Comment: I'm missing something maybe. Isn't a proof of what you need in the similar post you mention?
Answer: Suppose that $H$ has index $n$ in $G$. The action on the (right, say) cosets of $H$ induces a homomorphism $\phi:G\to S_n$, and the kernel of this map, the core of $H$ in $G$, is the largest normal subgroup of $G$ contained in $H$. Thus the core is non-trivial if and only if the subgroup $N$ you require exists, so let $N$ denote this core. Since $G/N$ is isomorphic to a subgroup of $S_n$, $|G/N|\mid n!$. But $|G|\nmid n!$, and therefore $|N|>1$.
Comment: @codesPliff It's best to assume that $N=1$ and derive a contradiction, if you don't have isomorphism theorems. Then the action of $G$ on the right cosets of $H$ is faithful, i.e., no element of $G$ acts trivially on the cosets of $H$. Thus it forms a subgroup of $A(S)$. This has order $n!$, so Lagrange gives you $|G|\mid n!$. This is a standard argument in group theory, then if $G$ has a subgroup of index $n$, then it has a normal subgroup of index at most $n!$.
Comment: The presence of a factorial suggests that this is the way to do it...
Comment: I've now looked in Herstein, and Problem 38 is what I am using. It's just that his notation is all over the place. So $i_G(H)$ is normally written $|G:H|$, and $A(S)$ is usually written $\mathrm{Sym}(S)$. I just noted that $\mathrm{Sym}(S)$ is naturally isomorphic to $S_n$. And you don't need isomorphism theorems. If $N=1$ then $G$ is a subgroup of $A(S)$, and that's all you are trying to prove.
Comment: Alright, I understand most of the proof now, and it'squite clever, I still don't get how you arrived at it. Just one thing though, how do we know $G/N$ is isomorphic to a subgroup of $S_n$ ? by Cayley's theorem ?


SOLID: Same-class constructor call allowed?

Question: An important property of really SOLID code is the fact that constructor calls do not often happen within the actual application code but primarily in the composition root and factory methods where necessary.
This makes a lot of sense to me, and I adhere to this wherever I can.
I have created a simple class where it seems to me it is not only allowed, but actually correct to deviate from the above rule.
This abstracts some simple Registry queries to facilitate unit testing of some other code:
public class RegistryKeyProxy : IRegistryKey
{
    private RegistryKey registrykey;

    public RegistryKeyProxy(RegistryKey registrykey)
    {
        this.registrykey = registrykey;
    }

    public IRegistryKey OpenSubKey(string subKeyName)
    {
        var subkey = this.registrykey.OpenSubKey(subKeyName);

        return (null == subkey ? null : new RegistryKeyProxy(subkey));
    }

    public IEnumerable<string> GetSubKeyNames()
    {
        return this.registrykey.GetSubKeyNames();
    }

    public object GetValue(string valueName)
    {
        return this.registrykey.GetValue(valueName);
    }
}

The OpenSubKey() method actually creates an instance of this same class without using a factory, but because of the closed concept that the Registry presents, it actually seems desirable to me not to return anything that looks like a Registry key, but really something that works exactly the same way as the current object.
I know that in the end it's up to me just how SOLID I want to work, but I'd like to know if this generally is a feasible path to go because of the nature of the underlying concept, or if this is not an exception to the rule but actually a SOLID violation.
Comment: "One of the most important properties of really SOLID code is the fact that constructors (save for basic framework classes that can't be replaced anyway without breaking the code's function) are never called within the actual application code" - citation needed.
Comment: A class calling its own constructor is a private implementation detail and it's perfectly reasonable for code within a class to be tightly coupled in its private implementation details.  There is no new dependency being introduced here.
Comment: IMO that principle only applies to Services and similar constructions. And not to ValueObjects, Entities,...
Comment: @DonRoby: I admit the wording is a bit too absolute, but from my understanding that is one of the main things that make SOLID work. I also remember reading something pretty close to that from Mark Seemann the other day (though I don't remember where).
Comment: I guess I really went a bit overboard there, going with too strict an interpretation of DIP. And after thinking about it again, that Seemann post was not about constructors but a DI container; so it was related to constructors but sufficiently different. I'll modify my question to make that initial statement more correct.
Answer: You are talking about the Dependency Inversion principle. This principle doesn't say that you should never new up objects at all, but it differentiates between two types of objects. Objects that implement behavior (services), and objects that contain data (DTOs, Value Types, Entities).
It would be rather silly in not newing up DTOs, since there is no behavior to be abstracted. They just contain data. (Just as would be silly to add an IPerson interface to a Person DTO).
Miško Hevery calls them injectables and newables, which is an nice terminolgoy.
For more information, see this Stackoverflow question: Why not use an IoC container to resolve dependencies for entities/business objects?
Comment: Thanks for this concise clarification; that makes perfect sense. Injectables and newables are indeed an accessible approach of thinking about it.


Extjs-Store is not loaded when clicking on the button

Question: I need to do search operation.I have added a textfield and button for search.I have done this by passing the search entry which will get from text box through extraParam.When i did not search anything in the grid that has to display everything.Now my problem is that grid doesnt load the data
my js looks like this
Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.form.*',
    'Ext.util.*',

    ]);

Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'id_job',
        mapping: 'id_job',
        type: 'int'
    }, {
        name: 'job_name',
        mapping: 'job_name',
        type: 'string'
    }, {
        name: 'error_message',
        mapping: 'error_message',
        type: 'string'
    },
    {
        name: 'status',
        mapping: 'status',
        type: 'string'
    },
    {
        name: 'starttime',
        mapping: 'starttime',
        type: 'string'
    },
    {
        name: 'endtime',
        mapping: 'endtime',
        type: 'string'
    },
      {
        name: 'last_updated_time',
        mapping: 'last_updated_time',
        type: 'string'
    },

]
});
Ext.onReady(function(){
    // Ext.QuickTips.init();
    var store = new Ext.data.JsonStore({
        model: MyModel,

        proxy: new Ext.data.HttpProxy({
            url: 'job_audit.php',
            // method: 'GET',
            type: 'ajax',
            extraParams:{
             JobName:'test'
           },
        reader:new Ext.data.JsonReader({
            type:'json',
            root:'jobdisplay',
            totalProperty:'Count'

        })
   }) ,
        autoLoad:false,
        idProperty: 'id'
    });
  var formPanel=Ext.create('Ext.form.Panel', {
    title: 'Search',
    width:300,
    bodyPadding: 10,
     submitOnAction: true,
      activeItem: 1,
   //renderTo: Ext.getBody(),
    items: [{
        xtype: 'textfield',
        name: 'JobName',
        id:'JobName',
        fieldLabel: 'JobName',
        allowBlank: false,
         anchor:'95%'// requires a non-empty value
    }, {
        xtype: 'button',
        name: 'search',
        fieldLabel: 'Search',
         text: 'Search',
        width:100,
       listeners:{
           click:function(){
            //var textValue=formPanel.items.get('JobName').getValue();
            var text=Ext.getCmp('JobName').getValue();
               store.proxy.extraParams={JobName : text};

          store.load();
        }
       }
    }]

});
formPanel.render('paging-grid');
    // baseParams:{task: "LISTING"}

    var grid=new Ext.grid.GridPanel({

        store: store,

        columns: [

        {
            header: 'id_job',
            width: 50,
            hidden:true,
             filterable:true,
            sortable: true,
            dataIndex: 'id_job'

        },

        {
            header: 'JobName',
            width: 150,
            sortable: true,
            dataIndex: 'job_name',
             renderer:function(myValue, myDontKnow, myRecord) {
                           var id=myRecord.get('id_job');
                            return '' + myValue + ' ';
                        }

        },
          {
            header: 'Start Time',
            width: 150,
            sortable: true,
            dataIndex: 'starttime'
        },
         {
            header: 'End Time',
            width: 150,
            sortable: true,
            dataIndex: 'endtime'
        },
         {
            header: 'tatus',
            width: 200,
            sortable: true,
            dataIndex: 'status'
        },
        {
            header: 'Error_Message',
            width: 150,
            sortable: true,
            dataIndex: 'error_message'
        },
        {
            header: 'Last_Updated_Time',
            width: 150,
            sortable: true,
            dataIndex: 'last_updated_time'
        },

        ],
          autoExpandable:true,
        stripeRows: true,

        height:600,

        width:950,

        title:'JobDetails',

        bbar: new Ext.PagingToolbar({

          pageSize:25,

            store: store,

            displayInfo: true,

            displayMsg: 'Displaying topics {0} - {1} of {2}',

            emptyMsg: "No topics to display"

        })

    });
  store.load();

    grid.render('paging-grid');

});

I am getting the param values in php side , retrieve the records also but that was not loading in the grid .Where I want to load store correctly in order to get load
Answer: I solved the problem.Json encodes all the "echo"(in php).I have given some echo's for testing purpose.I have removed all and my problem was solved.


looking to know how to convert non-Python expressions into Python expressions

Question: How do i Convert each of the following (non-Python) expressions into Python expressions
3x
3x + y
x is evenly divisible by 12
x plus 7 is more than 100 or else x is less than fifty
Answer: You can model them with lambda (anonymous functions) expressions or actual function definitions.
Example: 3x is a statement that for every x returns 3 times it's value:
x_times_three = lambda x: x * 3
x_times_three(9) # 27

Using a function that would be:
def x_times_three(x):
    return x * 3

The others using lambdas:
# 3x + y
lambda x,y: 3*x + y

# x is evenly divisible by 12
lambda x: x % 12 == 0

# x plus 7 is more than 100 or else x is less than fifty
lambda x: (x + 7) > 100 or (x < 50)

Answer: Convert the (non-Python) expressions into Python expressions:
x plus 7 is less than 100, else x is smaller than fifty
Comment: please can you add example.


UITableViewCell separator lines are missing

Question: The separator lines on my table view are absent from the view. Need suggestions on what may be the cause. I have checked my storyboard and everything seems to check out. The separator and separator color are both set to default.

As for my code:
<code>- (void)viewDidLoad {

[super viewDidLoad];

}

- (void)viewWillAppear:(BOOL)animated {

[super viewWillAppear:YES];

[self loadObjects];

self->restaurants = [NSArray array];
[self performSelector: @selector(retreiveFromParse)];

[_restaurantTable reloadData];

}

- (void)retreiveFromParse {

PFQuery *retrieveRestaurants = [PFQuery queryWithClassName:@"Restaurants"];

[retrieveRestaurants findObjectsInBackgroundWithBlock:^(NSArray *objects,     NSError *error) {

    if (!error) {
        restaurants = [[NSArray alloc] initWithArray:objects];
        NSLog(@"successful");

    }
}];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:  (NSInteger)section {

return [self->restaurants count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  (NSIndexPath *)indexPath object:(PFObject*)object
{
static NSString *CellIdentifier = @"Cell";

  UITableViewCell *cell = (UITableViewCell *)[tableView   dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){

    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:CellIdentifier];
}

  UILabel *title = (UILabel*) [cell viewWithTag:1];
title.text = [object objectForKey:@"title"];

  return cell;

}
</code>
Update: I solved it by simply deleting the [self loadObjects]; line my viewDidLoad method. The separator lines now show in my view !
Answer: The problem might be of separator color itself .By default it is White
so try changing it to another color either in storyboard or by code itself.
<code>[self.tableView setSeparatorColor:[UIColor blackColor]];
</code>
Answer: When the UITableView is selected in the storyboard, the Separator dropdown should be set to: "Default" or "Single Line"
Comment: Hmmm. Might want to clean and rebuild, and reset Simulator. Note that you don't need to check for nil after dequeueReusableCellWithIdentifier if you are using a Storyboard. Also, make sure the Indentation is set to default: Level=0, Width=10
Comment: The indentation was set to a width of 0, however when even when I changed it to 10 it did not solve the issue.
Answer: I have the same issue on simulator for xcode6.1 but it works fine for the device. Have you tried running it on the device?


Convert URI to path

Question: I am working on a Windows C++ App, where I get a URI similar to file:///C:/test 1/file.foo. Now I want to e.g. open that URI with ifstream.
Is there any C/C++ API available on Windows to convert such a path?
My Google Foo seems to be weak today.
Comment: Just remove the `"file:///"` part? Or get a substring of the rest? And if the URI doesn't start with `"file:///"` then it's not something that should be opened as a file anyway.
Comment: There are lots of libraries and functions around that will decode URIs. I cannot believe that you can't find one. Question must have been asked here loads of times. Search harder.
Comment: one possibility: https://msdn.microsoft.com/en-us/library/bb773581(v=vs.85).aspx
Comment: And then there is `%` escaping and perhaps existence check. It is not as easy as you think it is.
Comment: Possibly relevant: http://stackoverflow.com/questions/2616011/easy-way-to-parse-a-url-in-c-cross-platform
Comment: This link [http://stackoverflow.com/questions/2616011/easy-way-to-parse-a-url-in-c-cross-platform](http://stackoverflow.com/questions/2616011/easy-way-to-parse-a-url-in-c-cross-platform) was in a comment, and I found it helpful.
Comment: adding helpful comment as an answer seems difficult.
Answer: There is PathCreateFromUrl() :
https://msdn.microsoft.com/en-us/library/bb773581(v=vs.85).aspx
Answer: There are multiple file URI "versions" so you should not parse it yourself, some of the APIs are broken as well.
If you just want a Windows style path, call PathCreateFromUrl.
If you don't want to convert the path then you must use CreateURLMonikerEx or SHParseDisplayName (with a bind context) but then you end up with a Windows IStream instead.

Convert URI to path


Difference between jquery bind

Question: Friends, are there any differences between the following snippet codes?
  $('.has-child > a').on("click", function() {
                $(this).parent().find("ul").slideToggle('fast');
                var classname = $(this).find("i").attr('class');
                $(this).find("i").toggleClass("fa fa-minus-square").toggleClass("fa fa-plus-square");
            });

and
 $('.nav-tree').on('click', '.has-child > a', function() {
                $(this).parent().find("ul").slideToggle('fast');
                var classname = $(this).find("i").attr('class');
                $(this).find("i").toggleClass("fa fa-minus-square").toggleClass("fa fa-plus-square");
            });

what's the differences? Appreciate if you could help me out. thanks.

$('.has-child > a').on("click", function()

and

$('.nav-tree').on('click', '.has-child > a', function()
Comment: @guradio thanks. you means the click is happened on .nav-tree, however for the 1st way, the click is happened on .has-child->a, am i right?
Comment: The second one has means the given selector in the second parameter needs to be contained in `.nav-tree`.
Comment: second one click is delegated to `'.nav-tree'` `Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.`
Comment: Besides, the father-child relationships, any other difference, thanks.
Comment: @Guradio, thanks a lot for your wonderful answer.
Comment: The first only binds to `.has-child > a` elements that are in the DOM when you call `.on()`. The second will fire on elements that are added dynamically later.
Answer: The first selector tells you that in the complete DOM, find all the direct children of class has-child which are of type a and bind the click handler on them.
The second selector tells you the the same as above. But instead of searching the complete DOM, it only searches inside the DOM elements marked with nav-tree class.
Also, binding such a handler to the parent allows events to be attached to elements which are still not mounted in the DOM.

Difference between jquery bind


Sprites with partially transparent edges in OpenGL

Question: Many sprites/textures with a high resolution have partially transparent pixels arounds their edge to make their edges smoother (antialiasing basically). When rendering these it seems to me that you have to do the same as with any other sprites containing partially transparent pixel, which is to render them from back to front. That is if you want proper blending, of course.
But is there really no way to render these sprites with these tiny edges of partially transparency with some order independent method?
I'm attempting to do this, because I want to store a large number of static sprites in a seperate buffer from my dynamic sprites, such that I don't have to reupload the data every frame. However, with these partially transparent static sprites, I have to sort them together with all my other dynamic transparent sprites every frame. Of course, this is only a problem if my static sprites can be in between my dynamic sprites depth wise, but that is unfortunately what I want.
Comment: Since you are using sprites, I am assuming that you are implementing a 2D game or using 2D sprites to simulate a 3D effect in a 2D world. In either case, depth sorting shouldn't be the problem.
Comment: Indeed, I am implementing a 2D game :-) I suppose you mean that the depth sorting is not a performance problem? I think you are probably right. But I am also asking this question because I expected there to be a simpler way around this which I had just missed.
Answer: There is unfortunately no way of getting around depth sorting. Consider the case where there is a completely solid pixel behind a partially-transparent one. You have to to draw the transparent one last, otherwise you lose all the information from it.
Now consider how the situation changes as the completely solid pixel becomes very slightly transparent. It doesn't really change things; the solid pixel would still blow away information if written over the partially-transparent one. You could do some sort of calculation to apply an opacity and color tint to the solid pixel to allow you to draw it after the fact, but the calculation is equivalent to just drawing all the pixels in depth order.
So you really have to draw everything in depth order.
If the sort every frame is a problem, maybe you could optimize things by breaking stuff down into "background" and "foreground" layers? (or even three or more layers). Draw the background dynamics on top of the background statics and then draw the foreground.
Or perhaps you could keep all your sprites sorted using a heap?
Comment: It looks like OIT is the equivalent to the hypothetical "calculation" -- it's still sorting, but just offloaded somewhere else. The approximation stuff sounds interesting though.
Comment: What about [Order-independent transparency](https://en.wikipedia.org/wiki/Order-independent_transparency).
Comment: There are algorithms that work without sorting. The color channels are weighted according to the depth and alpha channel. I think the following paper describes such an algorithm: [Moment-Based Order-Independent Transparency](https://momentsingraphics.de/I3D2018.html).
Comment: I have been fiddling with OIT previously for another project, and I found it complicated enough to seek another solution for this project.
However, I have just stumpled upon [Alpha to coverage](https://stackoverflow.com/questions/23280692/opengl-es2-alpha-test-problems) as mentioned in this post, and I think this may be perfect.


How to prove that the product of two divergent limits is divergent.

Question: I'm trying to prove that, if $a_n\rightarrow\infty$ and if $b_n\rightarrow\infty$, then $a_nb_n\rightarrow \infty$.
Here's my proof:

But what happens when $0<K<1,$ in which case $K>K^2$?
Thanks
Comment: Well, I guess it's a matter of why you're writing this proof. If it is some form of coursework then I'd write out the details fully (as I always have with any coursework!), but otherwise some form of explanation as why it won't matter would be enough, if the reader could see the detail for themselves from it.
Comment: It doesn't matter. The definition means that if you happen to be given $K<1$ then it will be covered by say, the case $K=1$. Just give it a think; an $N$ that works for some $K$ also works for every $K' < K$.
Comment: Sorry, I don't quite follow.
Comment: Given some $K$, you can find an $N$ such that $a_n>K$ whenever $n>N$. Now if you wanted $a_n>L$ where $LN$ will still work; we'll have $a_n>K>L$. The same will apply to the product, just with some slightly fiddly details to write.
Comment: Got it. Thanks. Should I explain the last bit in the proof or can I just say that it's trivially true for $K<1$?
Answer: Once you prove the statement for large K it is automatically proven for any smaller K:  We know eventually the product is bigger than 10000000 so of course it is eventually bigger than 1/2.
If you're writing out a neat proof, for K between 0 and 1, just take N to be whatever it would be for K=1.


Flatpickr - Limit the amount of dates that can be selected

Question: I am using 'flatpickr' as a datetime picker on my app. This date picker allows for multiple dates to be selected but after reading the docs I can't find any way to limit the maximum amount of selected dates.
Jquery:
$('#gig_date_multi').flatpickr({
  "mode": "multiple",
  "locale": "<%= I18n.locale %>",
  minDate: new Date(),
  enableTime: true,
  time_24hr: true,
  minuteIncrement: 15,

    onChange: function(selectedDates, dateStr, instance) {

      var array = selectedDates;
      if (array.length >= 3) {
        console.log("YOU HAVE REACHED YOUR LIMIT")
      } else {
        console.log("YOU CAN STILL SELECT MORE DATES")
      }

      var newHTML = [];
      $.each(array, function(index, value) {
        var formatted = moment(value).format("HH:mm - dddd Do MMMM YYYY");
        newHTML.push('' + formatted + '');
      });

      $(".multi-dates").html(newHTML.join(""));

    }
});

Here when 3 dates are selected the console outputs "YOU HAVE REACHED YOUR LIMIT" and I was thinking maybe I could disable all dates (apart from previously selected ones) when this occurs.
Flatpickr has a disable and enable function but I am unsure how I can integrate this into the code... I am a jquery beginner.
The docs show these two methods;
{
    "disable": [
        function(date) {
            // return true to disable
            return (date.getDay() === 5 || date.getDay() === 6);

        }
    ],
    "locale": {
        "firstDayOfWeek": 1 // start week on Monday
    }
}

and
{
    enable: ["2017-03-30", "2017-05-21", "2017-06-08", new Date(2017, 8, 9) ]
}

Comment: Are these a range of dates  or individual dates that can be selected?
Comment: @Cue These are individual dates that can be selected.
Answer: You can use:

set(option, value): Sets a config option optionto value, redrawing the calendar and updating the current view, if necessary

In order to disable all dates except the 3 selected you can write:
instance.set('enable', selectedDates);

and, in order to reset you can:
instance.set('enable', []);

A different approach can be based on Enabling dates by a function:
instance.set('enable', [function(date) {
    if (selectedDates.length >= 3) {
        var currDateStr = FlatpickrInstance.prototype.formatDate(date, "d/m/Y")
        var x = selectedDatesStr.indexOf(currDateStr);
        return x != -1;
    } else {
        return true;
    }
}]);

The snippet:

$('#gig_date_multi').flatpickr({
    "mode": "multiple",
    "locale": 'en',
    minDate: new Date(),
    enableTime: true,
    time_24hr: true,
    minuteIncrement: 15,
    onChange: function(selectedDates, dateStr, instance) {
        var selectedDatesStr = selectedDates.reduce(function(acc, ele) {
            var str = instance.formatDate(ele, "d/m/Y");
            acc = (acc == '') ? str : acc + ';' + str;
            return acc;
        }, '');
        instance.set('enable', [function(date) {
            if (selectedDates.length >= 3) {
                var currDateStr = instance.formatDate(date, "d/m/Y")
                var x = selectedDatesStr.indexOf(currDateStr);
                return x != -1;
            } else {
                return true;
            }
        }]);
    }
});
input[type="text"] {
    width: 100%;
    box-sizing: border-box;
    -webkit-box-sizing:border-box;
    -moz-box-sizing: border-box;
}

<link rel="stylesheet" href="https://unpkg.com/flatpickr/dist/flatpickr.min.css">

<input type="text" id="gig_date_multi">
Comment: While this seems to be almost working, there does appear to be a bug with the code. If I select 3 dates, then deselect one, all the times change to 00:00.
Comment: @RobHughes You are right. Sorry for the delay. Snippet updated. Let me know. Thanks
Comment: Many thanks for this, this does work now. The 'enable' or 'disable' functions appeared to remove all time data. I had previously changed the code to hide and show dates using css selectors which seemed to work ok, but I prefer your code, although I don't understand all of it.
Comment: @RobHughes Thanks so much.
Answer: On a side note, if anyone wants to disable past date as well as time selection in Flatpickr, use Date().getTime() like this:
 $("input.picker-datetime").flatpickr({
        enableTime: true,
        dateFormat: "Y-m-d H:i",
        time_24hr: true,
        minDate: new Date().getTime()
    });


Number of sequences which follow a given pattern

Question: How to find the number of sequences of length K with elements from {0, 1,2 ... N} which follow a particular pattern?
If the pattern is strictly increasing or decreasing then its N choose K. What if the pattern is mixed?
Comment: what kind of pattern?
Comment: Say a pattern like -IIDDI, Where in positions 2,3,6 the number increases, and in positions 4,5 they decrease
Answer: Any pattern:
$$_NP_K$$
Only decreasing:
$$_NC_K$$
Only increasing:
$$_NC_K$$
Mixed pattern:
$$_NP_K-2\cdot _NC_K=(K!-2)\cdot _NC_K$$
Comment: Not sure. In {0,1,2} if the required pattern is -DI, where D is decreasing and I is increasing. Then the following are the valid permutations: {1,0,2}, {2,0,1}. The above formula doesn't fit in?!?
Comment: Maybe I didn't understand what you meant by "mixed pattern". Did you mean DI and ID ?
Comment: By mixed pattern I meant both increasing and decreasing in a given pattern.
Comment: Okay, I modified my answer.
Comment: Can you explain what kind of mixed pattern is this expression for??
Comment: The only cases that are not mixed are only decreasing and only increasing.
Comment: Well, my interpretation was: DIDIDIDI is also a mixed pattern.
Comment: Can you please justify your reasoning(especially for the mixed pattern)
Comment: Mixed = mix of D and I (e.g., DI, ID, DID, IDI, DIDI, IDID, DIDID, DIDIDIDIDID...), Not-mixed = D, I (only 2 cases). Do I need to justify more??
Comment: Ok so this formula is for all mixed patterns. This doesn't give the number of sequences for a given pattern like IDIIID.
Comment: There is nothing like IDIIID. It's just IDID
Comment: Well it's a matter of different way of expression. In your expression, I included everything - IIIIIIID, IIIIDID, DDIDDIID, ..., except only two - IIIIIIII, DDDDDDDD


Prove the undecidability of a formula

Question: I'm studying natural deduction for classical propositional logic, and I'm struggling with a point I cannot understand: when the book listed all the rules for natural deduction, it simply said that we have a list of objects in this logic: $\top, \bot, \land, \lor, \lnot, \implies $ (the symbols denotes respectively a true statement, a false statement, the "and" connective, the "or", the "not" and the "implies" connectives) and, based on the semantic function (sometimes called the interpretation function), we build up the rules for natural deduction.
Then, at a point, it says that only with the introduction and elimination rules for those symbols and connectives, we cannot prove some statements (for instance $A \lor \lnot A$, or $\lnot \lnot A \!\implies\! A$), so we need to add another rule called the Reductio ad Absurdum (RAA).
The point I cannot grasp is the lack of a proof that such wfs (well formed formulas) are undecidable without RAA or the excluded middle (tertium non datur, EM).
From that point I ask myself: in the intuitionistic logic (therefore a logic where the RAA or the EM does not hold), is there a way to show that a formula is undecidable? I'm not asking if there is a way to conclude that a formula is false (because the converse is true), I'm asking if there is a way to prove that neither $A$ nor $\lnot A$ are provable.
Comment: Let us clarify the terminology: you confuse "unprovable" with "undecidable". See [here](https://math.stackexchange.com/questions/1104299/whats-the-difference-between-unprovable-and-undecidable) for a clarification.
Comment: @Taroccoesbrocco: It is clear enough that they are not _disprovable_, since they are classical tautologies and everything intuitionistic logic proves is classically valid.
Comment: $A \to \lnot \lnot A$ is provable also in intuitionistic logic. $\lnot\lnot A \to A$ is not provable in intuitionistic logic because its proofs needs RAA (or an equivalent inference rule).
Comment: @HenningMakholm - Good point, thank you! I included it in the edit of my answer.
Comment: Mmhh... so as far as I've understood, $F$ is unprovable if $\lnot F$ is provable, whereas $F$ is undecidable if neither $F$ nor $\lnot F$ are provable (and therefore they're both unprovable). So $2+2=5$ is unprovable because I can prove that $\lnot(2+2=5)$, whereas the existence of a cardinal between $\aleph_0$ and $\aleph_1$ in ZFC is undecidable. And, as far as I have understood, in intuitionistic logic, the proposition $A \lor \lnot A$ (or $\lnot \lnot A \implies A$) is undecidable, right? Thanks for the clarifications
Comment: @Taroccoesbrocco Thanks for the clarification between "unprovable" and "undecidable". I've updated my question!
Answer: In intuitionistic and classical logic there is a standard way to show that a formula $A$ is unprovable or undecidable (i.e. both $A$ and $\lnot A$ are unprovable), it is based on the completeness theorem.
Completeness theorem says that a formula $A$ is provable (in intuitionistic natural deduction or equivalent system) if and only if $A$ is valid in all the structures (in intutionistic logic these structures are intuitionistic Kripke models).
So:

To prove that $A$ is unprovable in intuitionistic logic, it is sufficient to show that $A$ is not valid in some Kripke model (this entails that $A$ is not provable in intutionistic natural deduction by the completeness theorem).
To prove that $A$ is undecidable in intuitionistic logic, it is sufficient to apply point 1. to both $A$ and $\lnot A$; i.e. to show that $A$ is not valid in some Kripke model (this entails that $A$ is not provable in intutionistic natural deduction by the completeness theorem), and $\lnot A$ is not valid in some Kripke model (this entails that $\lnot A$ is not provable in intutionistic natural deduction by the completeness theorem).

As correctly remarked by Henning Makholm in his comment, if a formula $B$ is provable in classical logic, then $\lnot B$ is unprovable in intuitionistic logic (since all intuitionistically provable formulas are classically provable). Therefore, a classically provable formula $B$ is intuitionistically undecidable (take for instance $A \lor \lnot A$, or $\lnot\lnot A \to A$) if and only if $B$ is intuitionistically unprovable.

Let us show that $A \lor \lnot A$ and $\lnot \lnot A \to A$ are unprovable (and then undecidable, since they are classically provable) in intuitionistic logic using the completeness theorem. Assume $A$ is a propositional variable. Consider the following Kripke model for propositional logic: $\mathcal{K} = (\{0,1\},\leq, \Vdash)$ where $\leq$ is the (total) order relation over $\{0,1\}$ defined by
\begin{align}
0 \leq 0 && 0 \leq 1 && 1 \leq 1,
\end{align}
and $\Vdash$ is a binary relation from $\{0,1\}$ to the set of propositional variables such that $0 \not\Vdash A$ and $1 \Vdash A$. According to the definition of intuitionistic Kripke model for propositional logic, it is easy to check that $0 \not\Vdash A \lor \lnot A$ and $0 \not \Vdash \lnot\lnot A \to A$, which means that neither $A \lor \lnot A$ nor $\lnot\lnot A \to A$ are valid in $\mathcal{K}$. Thus, both  $A \lor \lnot A$ and $\lnot \lnot A \to A$ are unprovable (and hence undecidable) in intuitionistic logic.

There is also a completeness theorem for classical logic: in the formulation given above, replace intutionistic natural deduction with classical natural deduction (or equivalent system), and Kripke models with truth tables (in the propositional case). Therefore, also in classical logic the completeness theorem (for classical logic) can be used to show that a formula is unprovable or undecidable.
Comment: "1. [...] (this entails that  is not provable in intutionistic natural deduction by the completeness theorem)" Shouldn't this be by the soundness theorem?
Comment: @lemontree - Sure. It depends on what you call as completeness. In a more informative definition, _completeness_ means that all valid formulas are provable, and conversely, _soundness_ means that all provable formulas are valid. With these definitions, here we use soundness, not completeness. However, is quite common to call _completeness_ the whole equivalence between validity and provability. I used this second definition of completeness because, in my opinion, the distinction between soundness and completeness is not the focus of the question (the OP confuses provability and decidability).
Comment: @lemontree - Anyway, thank you for your comment. If you think that the distinction between completeness and soundness is relevant here, I can modify my answer (or you can do it by yourself).
Comment: Oh right, I forgot about that colloquial use of the term. That's fine then.
Answer: One possible way to see this is to provide a model of "truth values" such that intuitionistic logical proofs translate to statements which are true in that model, but $A \to \lnot \lnot A$ is not true in this model.
One such model is to take truth values to be open subsets of $\mathbb{R}$, with $\top := \mathbb{R}$, $\bot := \emptyset$, $U \wedge V := U \cap V$, $U \vee V := U \cup V$, $\lnot U := \operatorname{int}(U^c)$, $U \rightarrow V := \operatorname{int}(U^c \cup V)$.  Then it is possible to prove by structural induction on the proof that whenever $p_1, \ldots, p_n \vdash q$ in natural deduction without reductio ad absurdum ($ND - RAA$), then for any assignment $\mathfrak{U}$ of open subsets of $\mathbb{R}$ to atomic variables, we have $p_1(\mathfrak{U}) \cap \cdots \cap p_n(\mathfrak{U}) \subseteq q(\mathfrak{U})$.  On the other hand, if you choose an assignment where an atomic variable $A$ gets mapped to $\mathbb{R} \setminus \{ 0 \}$, then $\lnot A \mapsto \emptyset$, $\lnot \lnot A \mapsto \mathbb{R}$, $(\lnot \lnot A \rightarrow A) \mapsto \mathbb{R} \setminus \{ 0 \}$.  Since $\mathbb{R} \not\subseteq \mathbb{R} \setminus \{ 0 \}$, this implies that $\not\vdash (\lnot \lnot A \rightarrow A)$ in $ND - RAA$.
You can look up the theory of Heyting algebras for more on this interpretation of intuitionstic logic.  Another example of a Heyting algebra which is not a Boolean algebra is the lattice $\{ 0, \frac{1}{2}, 1 \}$ with an appropriate choice of $\rightarrow$ operation; this example has the advantage that it doesn't depend heavily on set-theoretic or topological constructions as the other one, but I personally find it less intuitive to work with.  Other examples that are easy to prove using this formulation: $\not\vdash (A \vee \lnot A)$, and $\not\vdash (\lnot(A \wedge B) \rightarrow \lnot A \vee \lnot B)$.

Another completely different approach is through the theory of sequent calculus.  Essentially, the idea here is that any proof in $ND - RAA$ can be "simplified" to a "normal form" in which there isn't any redundancy or "cleverness" left in the proof.  Here "cleverness" mostly refers to the use of the cut rule:
\begin{align*}
\Gamma & \vdash P \\
P, \Gamma & \vdash Q \\ \hline
\Gamma & \vdash Q
\end{align*}
where $P$ is a cleverly chosen intermediate step that clarifies the proof.  So, in the end, you get a proof with severely restricted possibilities, and from these restrictions you can conclude that certain things can't be proved at all.
Moreover, there are variants of the sequent calculus which lend themselves to a totally automated proof search, which give the result that there is a mechanical decision procedure which decides for each formulas $p_1, \ldots, p_n, q$ whether or not $p_1, \ldots, p_n \vdash q$ in $ND - RAA$.
Another interesting application is that it makes it easy to prove: if $p \vee q$ is a tautology in $ND - RAA$, then either $p$ or $q$ is a tautology in $ND - RAA$.  Which is a surprising result at first, given that $A \vee \lnot A$ is a tautology in $ND + RAA$ whereas obviously neither $A$ nor $\lnot A$ is a tautology in $ND + RAA$.
Comment: ... with the caveat that the "totally automated proof search" works only for _propositional_ (classical or intuitionistic) logic. If we extend to _predicate_ logic we need to be clever again.
Comment: Well, both intuitionistic and classical validity of first-order formulas, even without equality, are algorithmically undecidable as soon as there is a binary predicate symbol in the language, so I think you must be misremembering.
Comment: Actually, I thought I'd seen a version of sequent calculus which worked for predicate calculus, as long as it was *without* an equality symbol and substitution rule (aka equality-elimination).  But I could be wrong as my knowledge in this area is mostly from self-study...
Comment: Another caveat is that the automated proof search could take exponential time in the worst case.  (Which is unsurprising since it would be possible to use it to solve the NP-complete SAT problem, so it's at least as hard as an NP-complete problem.)  In most practical cases, though, the proof search is reasonably fast.
Comment: @HenningMakholm Ah, OK, I guess I see how allowing a general binary predicate symbol would cause the same sort of problems.  Luckily there's still the slightly generalized approach to #1 of trying to come up with a topos model which doesn't satisfy the statement...
Comment: Thanks for your answer! I did not know about Heyting algebras. I accepted the other solution just because I was more familiar with Kripke models. If I could, I'd have accepted both.

Prove the undecidability of a formula


The system freezes sometimes/randomly, when I browse a HTML5/CSS3 website in Chrome

Question: My laptop has Intel B960 (2.2GHz x 2) with 4 GB RAM. OS is Ubuntu 12.04 with all updates to current date.
I am getting a peculiar issue since about 2 weeks - when I browse a HTML5/CSS3 website in Chrome, sometimes (randomly) the system freezes - mouse, keyboard nothing seems to work. Ctrl-Alt-Del wouldn't work. The mouse pointer moves but clicking doesn't do anything. There is no such issue in Firefox. Only Chrome on Ubuntu has the problem.
Answer: As nothing seemed to work, I was doing a cold restart (power switch).
Then, today I referred to this troubleshooting wiki: What should I do when Ubuntu freezes? and pressed Ctrl-Alt-F1, which worked to get the TTY1 session. Logged in as root and checked memory usage with top. Noticed that one instance of Chrome was using over 700 MB and another instance of Chrome was randomly coming up with usage of over 900 MB.
I pressed Ctrl-Alt-F7 to check the graphical desktop and surprisingly the graphical session is working now. I am writing this in that same graphical session that froze earlier.
Have written this Q&A specifically for folks who get this "Chrome freeze on Ubuntu".


Simple browserify test only runs when built with --debug

Question: I have a simple hello world script main.js:
window.addEventListener('load', function() {
    "use strict";
    document.getElementById('output').textContent = "Hello, browser.";
});

If I build bundle.js with:
browserify -r ./main.js > bundle.js

It doesn't run in the browser. No errors, just doesn't execute. If I use:
browserify -r --debug ./main.js > bundle.js

It runs fine. Why doesn't the non-debug one run?
Answer: -r means require. -> -r file.js means, that you will put it into a seperate scope to require it in an other bundle, but it don't will execute.
Your "solution" -r --debug (or short -r -d) works, because the require attribute has no parameter/file, so it will be ignored by browserify.

Just removing -r --debug should solve your problem.

This...
browserify -r --debug ./main.js -o ./bundle.js

...is the same as this:
browserify -d ./main.js -o ./bundle.js

Comment: Thanks. Yes, I figured that out... I originally added -r because I was having trouble with `require` being undefined. Not sure how that happened because now it works.


How can i convert a factor column that contains decimal numbers to numeric?

Question: I have a csv file and when i use this command
SOLK<-read.table('Book1.csv',header=TRUE,sep=';')

I get this output
> SOLK
          Time Close Volume
1   10:27:03,6  0,99   1000
2   10:32:58,4  0,98    100
3   10:34:16,9  0,98    600
4   10:35:46,0  0,97    500
5   10:35:50,6  0,96     50
6   10:35:50,6  0,96   1000
7   10:36:10,3  0,95     40
8   10:36:10,3  0,95    100
9   10:36:10,4  0,95    500
10  10:36:10,4  0,95    100
.      .         .       .
.      .         .       .
.      .         .       .
285 17:09:44,0  0,96    404

the str(SOLK) outcomes this
    'data.frame':   285 obs. of  3 variables:
 $ Time  : Factor w/ 174 levels "10:27:03,6","10:32:58,4",..: 1 2 3 4 5 5 6 6 7 7 ...
 $ Close : Factor w/ 8 levels "0,92","0,93",..: 8 7 7 6 5 5 4 4 4 4 ...
 $ Volume: int  1000 100 600 500 50 1000 40 100 500 100 ...

and and dput(SOLK[1:10,]) this
structure(list(Time = structure(c(1L, 2L, 3L, 4L, 5L, 5L, 6L,
6L, 7L, 7L), .Label = c("10:27:03,6", "10:32:58,4", "10:34:16,9",
"10:35:46,0", "10:35:50,6", "10:36:10,3", "10:36:10,4", "10:36:30,8",
"10:37:23,3", "10:37:38,2", "10:37:39,3", "10:37:45,9", "10:39:07,5",
"10:39:07,6", "10:39:46,6", "10:41:21,8", "10:43:20,6", "10:43:36,4",
"10:43:48,8", "10:43:48,9", "10:43:54,6", "10:44:01,5", "10:44:08,4",
"10:45:47,2", "10:46:16,7", "10:47:03,6", "10:47:48,6", "10:47:55,0",
"10:48:09,9", "10:48:30,6", "10:49:20,6", "10:50:31,9", "10:50:34,6",
"10:50:38,1", "10:51:02,8", "10:51:11,5", "10:55:57,7", "10:57:57,2",
"10:59:06,9", "10:59:33,5", "11:00:31,0", "11:00:31,1", "11:04:46,4",
"11:04:53,4", "11:04:54,6", "11:04:56,1", "11:04:58,9", "11:05:02,0",
"11:05:02,6", "11:05:24,7", "11:05:56,7", "11:06:15,8", "11:13:24,1",
"11:13:24,2", "11:13:32,1", "11:13:36,2", "11:13:37,2", "11:13:44,5",
"11:13:46,8", "11:14:12,7", "11:14:19,4", "11:14:19,8", "11:14:21,2",
"11:14:38,7", "11:14:44,0", "11:14:44,5", "11:15:10,5", "11:15:10,6",
"11:15:12,9", "11:15:16,6", "11:15:23,3", "11:15:31,4", "11:15:36,4",
"11:15:37,4", "11:15:49,5", "11:16:01,4", "11:16:06,0", "11:17:56,2",
"11:19:08,1", "11:20:17,2", "11:26:39,4", "11:26:53,2", "11:27:39,5",
"11:28:33,0", "11:30:42,3", "11:31:00,7", "11:33:44,2", "11:39:56,1",
"11:40:07,3", "11:41:02,1", "11:41:30,1", "11:45:07,0", "11:45:26,6",
"11:49:50,8", "11:59:58,1", "12:03:49,9", "12:04:12,6", "12:06:05,8",
"12:06:49,2", "12:07:56,0", "12:09:37,7", "12:14:25,5", "12:14:32,1",
"12:15:42,1", "12:15:55,2", "12:16:36,9", "12:16:44,2", "12:18:00,3",
"12:18:12,8", "12:28:17,8", "12:28:17,9", "12:28:23,7", "12:28:51,1",
"12:36:33,2", "12:37:45,0", "12:39:22,2", "12:40:19,5", "12:42:22,1",
"12:58:46,3", "13:06:05,8", "13:06:05,9", "13:07:17,6", "13:07:17,7",
"13:09:01,3", "13:09:01,4", "13:09:11,3", "13:09:31,0", "13:10:07,8",
"13:35:43,8", "13:38:27,7", "14:11:16,0", "14:17:31,5", "14:26:13,9",
"14:36:11,8", "14:38:43,7", "14:38:47,8", "14:38:51,8", "14:48:26,7",
"14:52:07,4", "14:52:13,8", "15:09:24,7", "15:10:25,8", "15:29:12,1",
"15:31:55,9", "15:34:04,1", "15:44:10,8", "15:45:07,1", "15:57:04,9",
"15:57:13,9", "16:16:27,9", "16:21:41,7", "16:36:01,5", "16:36:13,2",
"16:46:10,5", "16:46:10,6", "16:47:37,3", "16:50:52,4", "16:50:52,5",
"16:51:44,5", "16:55:11,5", "16:56:21,8", "16:56:37,5", "16:57:37,9",
"16:58:18,6", "16:58:44,5", "17:00:39,1", "17:01:50,7", "17:03:13,2",
"17:03:28,3", "17:03:46,7", "17:03:47,0", "17:04:30,4", "17:08:41,8",
"17:09:44,0"), class = "factor"), Close = structure(c(8L, 7L,
7L, 6L, 5L, 5L, 4L, 4L, 4L, 4L), .Label = c("0,92", "0,93", "0,94",
"0,95", "0,96", "0,97", "0,98", "0,99"), class = "factor"), Volume = c(1000L,
100L, 600L, 500L, 50L, 1000L, 40L, 100L, 500L, 100L)), .Names = c("Time",
"Close", "Volume"), row.names = c(NA, 10L), class = "data.frame")

How can i convert the SOLK$Close column from factor to numeric?
Comment: possible duplicate of [How can i convert a dataframe with a factor column to a xts object?](http://stackoverflow.com/questions/7288045/how-can-i-convert-a-dataframe-with-a-factor-column-to-a-xts-object)
Answer: as.numeric(as.character(sub("," , ".", SOLK$Close)))

I noticed (after you posted a better example) that you may need to do some conversion on the "Time" values as well:
> SOLK$Close.n <- as.numeric(sub("," , ".", SOLK$Close))
> head(SOLK)
        Time Close Volume Close.n
1 10:27:03,6  0,99   1000    0.99
2 10:32:58,4  0,98    100    0.98
3 10:34:16,9  0,98    600    0.98
4 10:35:46,0  0,97    500    0.97
5 10:35:50,6  0,96     50    0.96
6 10:35:50,6  0,96   1000    0.96

Since that is also a factor, you will gain generality if you finish the conversions. Perhaps:
SOLK$Time.n <- as.POSIXct(sub("," , ".", SOLK$Time), format="%H:%M:%S")

Comment: Is that `as.character` on `sub` needed? `sub` returns character
Comment: This solution does not fix potential thousands separators `"."` to `","`
Comment: No, it doesn't. That was not the question that was asked. I do have another answer that shows how to to that at the input stage.
Answer: as.numeric(as.character(SOLK$Close))

This is in the R-FAQ,  7.10 .
Comment: Karl B's answer below applies -- you need to convert "," to "." unless your R setup is in Euro mode, whichfrom your error message appears not to be the case.
Comment: `[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA......
[276] NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion`
Comment: here is the output of `as.numeric(as.character(SOLK$Close))
`
Answer: I think your numbers have commas rather than periods, so you might call read.table with dec=",".
Answer: SOLK<-read.table('Book1.csv',header=TRUE,sep=';', colClasses = "character")
SOLK[, position] <- as.numeric(SOLK[, position])


Height of div adjusting to resolution

Question: I am wondering if it is possible to make div adjust to height of screen view. What I want to achieve, is to make the first div always adapt to resolution and push everything beneath off screen. That greyish part should be off screen for any resolution. I know height is a bit tricky, but is this possible ?
Comment: you can use : `div {height:100vh;}`  see https://www.w3.org/TR/css3-values/#viewport-relative-lengths
Comment: Possible that you have paddings or margins (or collapsing-margin effects) . Without html and CSS that reproduce you issue. We can only try guesses. TJis might be a new question)
Comment: It worked like a charm. Thank you !
Comment: Also, it leaves me with a question. I managed to set height to 86vh, it fits my needs the best. If I got it right, then it means only 86% of view port, but it takes the whole view port for me. Is there something I missed ?
Answer: you can use : div {height:100vh;}
see https://www.w3.org/TR/css3-values/#viewport-relative-lengths

vw unit
Equal to 1% of the width of the initial containing block.
In the example below, if the width of the viewport is 200mm, the font size of h1 elements will be 16mm (i.e. (8×200mm)/100).
   `h1 { font-size: 8vw }`

vh unit
   Equal to 1% of the height of the initial containing block.

vmin unit
    Equal to the smaller of vw or vh.

vmax unit
    Equal to the larger of vw or vh.

See also http://caniuse.com/#feat=viewport-units for browsers support
Answer: CSS has viewport units. Try this:
height: 100vh
Documentation
Explanation:
Viewport units are based on percentages of viewport.
1vh: 1/100th of the height of the viewport.
1vw: 1/100th of the width of the viewport.
Answer: CSS Has Viewport and viewheight units(namely vw and vh)
Add This in your CSS:
div {
  height: 100vh;
}

Answer: You can use
div { width: 100%; height: 100%; min-width: 1000px; min-height: 1000px; }

That way div can't be smaller then 1000px, but its not good for mobile browsers.

Height of div adjusting to resolution


Missile turret placement

Question: Whenever I scout a build that has potential for airborne harassment (e.g. Banshee, Muta, Oracle) my reaction is to build missile turrets to defend the mineral line, however all too often my opponent manages to find a spot where they can still get free shots at my workers. (I generally place my turrets beind the mineral line)
How should I place missile turrets to properly defend against airborne harassment?
Comment: See the update EDIT please :)
Answer: I will always recommend placing the Turret inside your mineral line - for several reasons.

It covers the entire mineral line. There is no "sweet-spot" for whatever early harass your opponent might throw at you.
Easy to repair placement. The Turret can get a complete suround by your SCVs, repairing the Turret instantly. By this, they dont need to move around the minerals, only to have 2-4 SCVs repairing and possibly fail the repair.
It comes at a minor mineral loss, due to a "block", you probably won't notice any difference by having a Turret in your line of minerals.
You can manage early harass easily and cheaply by only building 1 Turret in your mineral line.

EDIT:
There is usually a gap between your minerals somewhere in the middle. That is where you would want to place your turret, as it would still protect the entire mineral line and it does not obstruct the workers that much.

EDIT: I added two pitctures from WCS EU showing players placing turrets inside thier mine lines. Like explained, it is the best position.
Comment: I hope you dont mind but i added an image for you with the description.
Comment: Hey Marco. Thanks! Execelent screendump! It is the right spot as displayed on the picture. The Turret should be in the center of the line. I would recomment having "Build Grid" active all the time.
Comment: Solid advice for TvZ, but far less than ideal in TvT. Banshee range is enough to pick you apart.
Comment: I still find it solid for all match-ups since the Turret keeps your SCVs clear. In 90% of all builds (correct me if I'm wrong) you have the marines to deal with a banshee.
Comment: @Decency, :) - to back up the theory of placing the Turrets inside the mineral line. If you watch GSL, MLG and so on, you will see that most Terran´s place the Turret inside the mineral line as well, to defend from Oracles and so on. I am not judging, but I think they place it there, be cause it is the logical location, and you only need 1 = 100 minerals, and not 2 = 200 minerals.
Comment: Where abouts exactly?  If you get a chance could you post a screenshot?
Comment: @AtlasEU Try to reply to a user with the @, it sends them a notification that way. You definitely have the Marines, but dancing in and out with them while the Banshee picks off free workers is a huge issue, and you can just auto-lose a game if he does it well. If I see cloak researching, I drop 2 Turrets per base almost always- it's much less an investment than he's made. Against no cloak, you don't really need any unless you want to push out, and then you'll again need 2.
Comment: The facts as stated should sum up the effectiveness of having 1 Turret and not 2 or 3.
Comment: @AtlasEU TvP is again different, as Oracles also have low range and are a low-cost investment. Banshees with cloak are neither.
Answer: On the Team Liquid forum, there was some research done about this. The research was done in 2010 for Wings of Liberty, but should still be mostly valid.
User Fork posted some replays with math in this thread, and came to these conclusions:

It is better to place turrets next to the CC, not by the minerals.
Placing turrets in your mineral line may lower income by ~6% (50 minerals/minute out of 700-800; this is equivalent to the loss of one worker)
Surprisingly, scooting your CC back 1 space and then building the turrets diminishes the income penalty (However, the income loss from lifting off and re-landing was not accounted for).

Also, here is another thread (also from 2010) which backs up point #1: Even up to 3 buildings placed next to a Nexus had minimal effect on gathering rate (!50 minerals/minute, about the cost of one worker).
Comment: @AtlasEU I'm not sure of your point. The research simply shows that 1-3 turrets placed next to your CC had a smaller impact on income than other locations. I know it is from 2010, but I don't recall any worker pathing changes since then.
Comment: You can also place 4-6 Turrets all around your base, and it will by no doubt be more effective. Problem is the mineral costs. 1½ Turret  = 1 Barrack or 3 marines. Getting one Turret in the line = Easy repair, only 100 minerals spent and an all over more cost effective play. With all due respect, the links are from oct. 2010, a few months after the release.

Missile turret placement


A minimal polynomial problem that's bothering me

Question: Let $F$ be a field and $P$ an irreducible polynomial in $F[x]$. If I find a root of $P$ in an extention of $F$, does that make $P$ a minimal polynomial?
Answer: Yes, if it is normed and has minimal degree and the root is algebraic.
Comment: I knew it! Thank you so much!
Answer: If $E$ is an extension of $F$ in which an irreducible polynomial $P(x) \in F[x]$ has a root $\alpha$, then $P(x)$ is indeed a polynomial of least degree such that
$P(\alpha) = 0; \tag 1$
furthermore, we may without loss of generality assume $P(x)$ is monic, that is, the leading coefficient of
$P(x) = \displaystyle \sum_0^{\deg P} p_k x^k, \; p_k \in F, \; 0 \le k \le n, \tag 2$
$p_{\deg P} = 1$; certainly this assumption will not effect the validity of (1), since it may be effected by simply dividing $P(x)$ through by $p_{\deg P} \ne 0$; under such circumstance we indeed term $P(x)$ the minimal polynomial of $\alpha \in E$.
We may see that $\deg P(x)$ is least amongst all polynomials $Q(x) \in F[x]$ such that $Q(\alpha) = 0$ by assuming to the contrary that there exists some such $Q(x) \in F[x]$ with $\deg Q(x) < \deg P(x)$; then by the Euclidean division algorithm for polynomials, we may write
$P(x) = q(x) Q(x) + r(x); \; q(x), r(x) \in F[x], \tag 3$
where either $r(x) = 0$ or
$0 \le \deg r(x) < \deg Q(x); \tag 4$
if $r(x) \ne 0$ we may thus write
$r(x) = P(x) - q(x) Q(x), \tag 5$
which yields
$r(\alpha) = P(\alpha) - q(\alpha) Q(\alpha) = 0 - q(\alpha) \cdot 0 = 0; \tag 6$
but by (4) this contradicts our selection of $Q(x)$ as having least degree in $F[x]$ with $Q(\alpha) = 0$; thus $r(x) = 0$ and
$P(x) = q(x) Q(x); \tag 7$
but now since $\deg Q(x) < \deg P(x)$, this equation asserts that $P(x)$ is reducible in $F[x]$, contrary to hypothesis.  Therefore there is no such $Q(x) \in F[x]$ and thus $P(x)$ is indeed a minimal polynomial for $\alpha \in E$.
Comment: Thank you very much for taking time to prove it! ^^


Can't turn my smelters on

Question: I bought a couple of smelters in Iron Will mode and left them running as meteors came in to build up my iron. However, they have somehow shut themselves off and won't turn back on. When I click the [+] to enable one it blinks green and turns right back off.
I have both wood and minerals and I have 100 iron left before I'm maxed out, so why would my smelters refuse to run?
Comment: That's weird... in normal mode, even when you run out of wood or minerals, they stay turned on and just don't produce any iron until you have enough wood and minerals.  Or so I recall, the game is blocked from here (I'm at work).
Answer: In Iron Will mode, smelters automatically cut off when you reach 95% of the cap, in order to preserve resources. If your current iron cap is 2000, then this fits exactly with stopping 100 before the cap.
Source: buildings.js, line 448-453:
<code>//safe switch for IW to save precious resources, as per players request
if (game.ironWill && iron.value > iron.maxValue * 0.95){
    self.enabled = false;
    self.on = 0;
    return;
}
</code>
Comment: nice feature and good to know. I'm trying to avoid reading the source code so I don't spoil any surprises so thanks for doing it for me :)

Can't turn my smelters on


Does a proper map have to be continuous?

Question: In Pollack's differential topology, the proper map is defined by the preimage of every compact set is compact. Here it doesn't require the map to be continuous. However, in his following claim, to a compact manifold $X$, every map f:$X$ $\rightarrow$$Y$ is proper. Here I think if f is not continuous, we can not get the claim. So I am confused if the proper map has to be continuous.
Comment: Likely every time they use the word 'map' they mean 'continuous map', for now and the rest of the book.
Comment: Yes, continuity should be part of the definition of a proper map, or at least it should be part of the hypothesis of any application of proper maps.
Comment: @LeeMosher, thank you very much!
Comment: @MikeMiller Thank you very much!
Answer: Whether to include continuity in the definition of proper maps is to some extent a matter of taste. I think the most common convention is that proper maps are not, by definition, continuous. Wikipedia follows this convention, and I follow it in my books.
The issue in the statement you quoted, "Every map from a compact manifold to another manifold is proper," is the definition of map. I don't have Guillemin & Pollack handy, but the only way this sentence can possibly be true is if the authors adopt the convention that every "map" between manifolds is automatically assumed to be continuous, or maybe even smooth. Personally, I don't like this convention, because it leads to exactly the kind of confusion that tripped up the OP.
In any case, what is true is that every continuous map from a compact space to a Hausdorff space (and hence from a compact manifold to any manifold) is proper.
Comment: Thank you, that's very helpful
Comment: Dear @Jack Lee One more question, do you assume every manifold is Hausdorff? I also saw some body talked about non-Hausdorff manifold. I am a little confused
Comment: @Joseph: yes, part of my definition of a manifold is that it's Hausdorff and second countable. Many of the basic theorems about manifolds fail without those assumptions.
Answer: As Lee and Mike said, yes proper map is continuous!
Comment: Could you restate what you are referring to when you say, "yes it is"? so that the answer is self-contained, otherwise I am not sure this is too helpful because it isn't grammatically an answer to the question in the title. Do you mean, "yes it does have to be continuous"?


Uncountable number of disjoint open balls in $\mathbb{R}$

Question: I came up with a construction of an uncountable set of open balls in $[0,1]\subseteq \mathbb{R}$.
I realize this is wrong (since every open ball contains some $x\in\mathbb{Q}$), but I'd like to know why my argument breaks down? (I will not accept answers which do not address my question)

In a construction of the Cantor Set, we iteratively remove open intervals. In ternary numeral system:
\begin{align}
C_1&:=[0,1]\setminus (0.1,0.2)\\
C_2&:=C_1\setminus (0.01,0.02)\setminus (0.21,0.22)\\
\vdots\\
C&=\lim_{n\to\infty}C_n
\end{align}
What if at each stage we split the removed intervals in two and took two open intervals. Then for each element $c\in C$, there is some open interval. E.g. For $0.1\in C$, let $(0.1,0.\overline{1})$ be the open interval, or, $0.022\in C$ gives $(0.2\overline{1},0.22)$ is an open interval.
And the Cantor set is uncountable, so there are an uncountable number of intervals?
Comment: To show that for each $c\in C$ you get an interval cannot be done by just listing two examples
Comment: What interval would correspond with $0.02002000200002\cdots$ which is in $C$ but since it's not a finite base 3 expansion does not go with any specific endpoint?
Comment: @coffeemath Thanks, so the issue is with the $C\setminus\mathbb{Q}$.
Comment: Szmagpie-- If by $C \setminus \mathbb{Q}$ you mean the result of removing the "endpoints" of the removed intervals, then your last comment is right, that's the issue. I put an answer which doesn't depend on what notation one uses for the points in the cantor set which get associated with removed intervals.
Answer: With your description, $C_1$ has $1$ removed interval, $C_2$ has $2$, $C_3$ has $4$ removed, and so on, in general $C_k$ has $2^{k-1}$ removed intervals. If at each stage you split the removed intervals each into two parts, then what this does is to double the number of removed intervals at each stage, so that at stage $k$ you now have $2^k$ removed intervals.
Note that for this, as in the usual construction of the cantor set, there are only a countable number of removed intervals. So if in some way one associates an element of the Cantor set with each removed interval, one has only associated countably many elements of the Cantor set with the removed intervals. However since the Cantor set is uncountable, there remain (uncountably many) elements of the Cantor set which have not been associated with any of the removed intervals. In short there isn't a contradiction.


SBT multiproject can't locate logback extension

Question: I have a multi project SBT build where the common project contains a logback related extension, while logback.xml is placed in a global resource folder.
I have a structure as below, but when running the application (App) it is not applying LogbackCompositeConverterEx.
How do I get the logback CompositeConverter to affect depending projects at runtime?
build.sbt

|- Common
|-- src
|--- main
|---- scala
|----- LogbackCompositeConverterEx.scala // Does not seem to be applied
|---- resources

|- Feature
|-- src
|--- main
|---- scala
|---- resources

|- App
|-- src
|--- main
|---- scala
|---- resources
|----- logback.xml // Can this be in common?

Answer: To answer your question, yes, you can move the logback.xml in the common, resources folder. But I'm not sure that will fix the issue. Is there a way to share the project privately, or at least the build.sbt, to be able to check how you have defined the dependencies and aggregation of submodules?


.conf files comment

Question: I am quite new to Ubuntu and I think this might be a stupid question to ask. But I wanted to confirm if # meant comments in Ubuntu .conf files. For instance in the code below:
<code> #send dhcp-client-identifier 1:0:a0:24:ab:fb:9c;
 #send dhcp-lease-time 3600;
 #supersede domain-name "fugue.com home.vix.com";
</code>
Are all these lines commented out by the .conf file? I ask this because all the lines in the .conf file have a # preceding them. So I am confused if all the lines were meant to be commented.
Any help would be appreciated! :)
Comment: It depends on what is the conf file. In most cases `#` is a comment.
Answer: A hashmark in a .conf file is always either an explanatory comment or, in the example you gave, a parameter that may be invoked if it is uncommented.
Many processes run perfectly well with the default settings built in. You may, however, change some settings to better suit your needs by examining the .conf file and invoking the parameter by uncommenting.

.conf files comment


What's size of upgrading from desktop? in update manager app?

Question: I'm using Ubuntu 11.10 and wanna to update to 12.04 LTS.
I want to know the size of upgrade from my desktop PC.
Please, tell me that
Thanks
Answer: It will depend what or how much files you need to Upgrade. Suppose you have Open Office and you have never Upgraded it to the latest version, then On Ubuntu 12.04 LTS Upgrade, it will add an extra burden of Upgrading Open Office.
Comment: Go for a fresh install of 12.04 if possible.
Comment: I want to upgrade with only bases detail Ubuntu 32bit OS,my open office is old too


CMake not working with C++11 on OSX

Question: I've just upgraded to Mountain Lion so I can use some of the C++11 features on the new version of Clang that comes with xcode. I'm using cmake 2.8.9 from Homebrew.
I've made a very simple CMake project which adds the compiler flags for C++11:
# CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
add_executable(test test.cxx)
add_definitions(-std=c++0x -stdlib=libc++)

where the C++ code in test.cxx is the following:
#include <iostream>

int main()
{
  std::cout << "Howdy" << std::endl;
  return 0;
}

When running cmake and make, the file compiles just fine but then the linker outputs the following errors:
Linking CXX executable test
Undefined symbols for architecture x86_64:
  "std::__1::locale::use_facet(std::__1::locale::id&) const", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in test.cxx.o
  "std::__1::ios_base::getloc() const", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in test.cxx.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::put(char)", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in test.cxx.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::flush()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in test.cxx.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::sentry(std::__1::basic_ostream<char, std::__1::char_traits<char> >&)", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<<<std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*) in test.cxx.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::~sentry()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<<<std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*) in test.cxx.o
  "std::__1::cout", referenced from:
      _main in test.cxx.o
  "std::__1::ctype<char>::id", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in test.cxx.o
  "std::__1::locale::~locale()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in test.cxx.o
  "std::__1::ios_base::__set_badbit_and_consider_rethrow()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<<<std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*) in test.cxx.o
  "std::__1::ios_base::clear(unsigned int)", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<<<std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*) in test.cxx.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [test] Error 1
make[1]: *** [CMakeFiles/test.dir/all] Error 2
make: *** [all] Error 2

I get no errors if I comment out the add_definitions line in the CMakeLists.txt file, and I can also avoid errors if I remove the std::cout line in test.cxx. Perhaps the weirdest part of all is that if I simply run
clang++ -std=c++0x -stdlib=libc++ test.cxx

it compiles just fine! So, following a commentor's advice, I checked the actual commands cmake is running for compiling and linking.
Compile:
/usr/bin/c++    -std=c++0x -stdlib=libc++ -o CMakeFiles/test.dir/test.cxx.o -c /Users/luis/test.cxx

Link:
/usr/bin/c++    -Wl,-search_paths_first -Wl,-headerpad_max_install_names   CMakeFiles/test.dir/test.cxx.o  -o test

The main issue now seems to be that the linker is not supplying the proper C++11 flags. Is there a better way to supply these flags so that both the compiler and the linker will use them?
Comment: Can you ask cmake to print out the commands it's running?
Answer: I'm not sure that ADD_DEFINITIONS is the right tool for this particular job.
Perhaps a better option is to set the value of CMAKE_CXX_FLAGS directly:
cmake_minimum_required(VERSION 2.8)
set (CMAKE_CXX_FLAGS "-std=c++0x -stdlib=libc++ -g3 -Wall -O0")
add_executable(test test.cxx)

Comment: Yup, that was it. Thanks for the help!
Comment: I have an analogue problem here
http://stackoverflow.com/questions/38802547/googletest-undefined-symbols-for-architecture-x86-64-error
but wasn't able to solve it using your hint.
Answer: I saw this error when running gcc rather than g++. If I use g++, things compile correctly. Perhaps your Makefile is using the wrong compiler front end.
Answer: Go to your project targets->Apple LLVM compiler 4.1 - Language->select c++library to
libc__(LLVM C++ stadard library with c++ 11 support);

Answer: After getting this error recently (using Clang) the problem was in not passing -std=c++11 -stdlib=libc++ as linker flags too.
So they have to be passed both as compiler flags and as linker flags.
For GCC the first flag is -std=c++0x, instead of -std=c++11.
Answer: For me the answer was simply using clang++ instead of clang.

CMake not working with C++11 on OSX


Fundamental group of the $S^2$ with the labeling scheme

Question: I know that the labeling scheme of $S^2$ is $aa^{-1}$ which should imply the following representation of the fundamental group:
$$\langle a | aa^{-1}=1\rangle$$
but this is not trivial unlike the fundamental group. How do I square this?
Comment: It's probably worth noting that for every element $g$ in any group, it's always true that $gg^{-1}=1$. So your presentation is really just $\langle a \rangle$; i.e., there are no relations in the group you wrote down. Anyway, I'm not quite sure what you mean by your labeling scheme being given by $aa^{-1}$, can you be a bit more precise?
Comment: @kamills yes, the representation I wrote is just $\mathbb{Z}$. I am basically talking about how we obtain $S^2$ from the disc by identifying the boundary. There's a labeling scheme (I don't know how to draw on latex) which describes how the identification is made. Basically, identify two opposite points on the boundary of the disc and then the identification is that you go from on point to the other in both sides (like magnetic fields).
Comment: Gotcha, okay. Well, two things: first, the space I think you're talking about in this comment (taking the disc and identifying antipodal points) actually produces $\mathbb{R}P^2$, the real projective plane. Second, the way to obtain $S^2$ from a disc is to identify all points on the boundary to a single point; this is written $D^2/S^1$.
Comment: If you mean identifying non-antipodal points (i.e. if we consider the disc centered at the origin in $\mathbb{R}^2$ and then we're identifying points on the boundary with the same x-coordinates, like identifying points that would touch if we folded in half along the x-axis), then that does produce $S^2$. But I'm not sure how to write a labeling scheme for this; potentially the labeling scheme is just $1$ since the map $S^1 \to S^1$ that traces $S^1$ on the first half of the domain and then traces $S^1$ backwards on the second half of the domain is nullhomotopic...?
Comment: @kamills I wish I knew how to draw on latex. What you described for the identification of the projective space is when you have the $aa$ labeling scheme. Notice that you get $\mathbb{Z}_2$ as the representation of the fundamental group. The identification which I describe is the one that preserves orientation. Your identification to the point works and so does mine.
Comment: @kamills yes I think we are now talking about the same identification. So the labeling scheme I am talking about is that  if you go counterclockwise on the boundary, you will have to go in $a$ (parallel to the orientation) until you reach the antipodal point and $a^{-1}$  (opposite the orientation) until you get to where you started. So you get $aa^{-1}$ labeling scheme. You will get $aa$ for the projective plane if you try this.
Comment: I follow now. So this labeling scheme is indeed correct. I think the issue in your question comes from misunderstanding how van Kampen's theorem applies to computing fundamental groups from a labeling scheme in this particular case. If you follow the "normal" van Kampen's argument that would compute the fundamental group of, say, the torus, but instead using a disc (using the disc as our 2-sided polygon), you'll get an amalgamated free product of $\mathbb{Z}$ with $0$ over $\mathbb{Z}$, where both copies of $\mathbb{Z}$ are $\langle a \rangle$. This is $0$.
Comment: @kamills I don't understand. Could you elaborate in the answer? Could you also explain why this approach works for the projective plane and not for the sphere?
Answer: Note that for a surface $X$ given by a given labeling scheme $a_1^{\epsilon_1}\cdots a_n^{\epsilon_n}$ where each $\epsilon_i = \pm 1$ (not necessarily all presented in order; e.g., $a_1 a_2 a_1^{-1} a_2^{-1}$ is allowed), this is equivalent to obtaining $X$ via the following construction.
Take a wedge of $n$ circles labeled $a_1, \ldots, a_n$, and call this space $X^1$. Then attach $D^2$ to $X^1$ via the map $S^1 \to X^1$ defined as follows: Divide the domain $S^1$ into a number of parts equal to the number of symbols in the labeling scheme, and then for each chunk of the domain $S^1$ we trace the named circle in $X^1$ either forwards or backwards according to the labeling scheme. Call the result $X$.
This wording is complicated, so here are some examples:
For the labeling scheme $a_1 a_2 a_1^{-1} a_2^{-1}$, $X^1$ is a wedge of $2$ circles labeled $a_1$ and $a_2$. We think of the domain $S^1$ as four quarter-circles, and the attaching map says that on the first quarter-circle we trace $a_1$ forwards, then on the second quarter-circle we trace $a_2$ forwards, on the third quarter-circle we trace $a_1$ backwards, and on the fourth quarter-circle we trace $a_2$ backwards. This gives $X$ as the torus.
For the labeling scheme $aa$, $X^1$ is a single circle. The domain $S^1$ is two half-circles, and the attaching map traces $a$ on the first half-circle and then $a$ on the second half-circle, forwards both times. This gives $X$ as $\mathbb{R}P^2$.
To see that this results in a surface equivalent to what you'd expect from the labeling scheme, the point is that the wedge-of-circles is equivalent to drawing a (non-filled-in) polygon where each vertex will be identified, and the "filling in the polygon then gluing the edges according to the labeling scheme" is the same thing as "attaching a disc where the boundary circle traces the labeling scheme's rules." (Also, my notation is suggestive of CW complexes and that's exactly what I'm describing here--the CW decomposition of surfaces.)
For a surface $X$ constructed this way, van Kampen's theorem shows that the fundamental group of $X$ is the group whose generators are the circles $a_1, \ldots, a_n$ and relation given by the labeling scheme. This result you are familiar with since it's what your question is about.
So what's going on with $S^2$? Remember that labeling schemes only give surfaces when they satisfy certain properties, and one of the rules for a labeling scheme such that the above consequence of van Kampen's theorem is true is that it's a fully reduced word in the letters $a_1,\ldots,a_n$ (there are more rules about what orders the letters can come up in, how many times each letter shows up, etc., and perhaps these are part of what a 'labeling scheme' is defined as). So $S^2$'s labeling scheme really should be $1$ if we want to use the result, which would then say that the fundamental group is trivial.
Further, $aa^{-1}$ does not in fact produce $S^2$. Otherwise, this would give $S^2$ as a CW complex with a single 0-cell, a single 1-cell, and a single 2-cell. This has Euler characteristic $1$, but the Euler characteristic of $S^2$ is $2$. This is one example of why your labeling scheme needs to be a reduced word.
This raises an important question, which is "can we write $S^2$ as the result of the above process where we start with a wedge of 0 circles?" After all, my description should work if $n=0$ and if it's going to work for all surfaces, and if the labeling scheme for $S^2$ would be something like "$1$"; i.e., start with no circles. The answer is yes: a wedge of zero circles is a single point (because a wedge sum of circles is the same thing as taking the one-point space and then adding copies of $D^1$ according to the constant attaching map $S^0 \to \{ * \}$), so $X^1$ is the one-point space, and then attach $D^2$ to this via the constant map $S^1 \to \{ * \}$; this gives $S^2$.
The other consideration worth mentioning is that if you do start with $X^1 = S^1$ and attach via $aa^{-1}$, we see that this attaching map is nullhomotopic ($a$ can be thought of as a generator for the fundamental group of $X^1$, and $aa^{-1}$ is the group identity in $\pi_1(X^1)$). And it's a fact of adjunction spaces that the homotopy type of the attaching map is all that matters. So, what do you get if you attach a $2$-cell to $S^1$ via a constant map? This is the space $S^1 \vee S^2$.
Comment: Thank you for this detailed answer. I think I should read more about van Kampen's application on CW complexes.
Comment: Sorry to bother you again, but could you refer to me where I can read more about the rules on the labeling schemes? I understand the description you gave with CW complexes and they are the exact same thing that I am describing but I don't remember seeing anything like it.

The general result that I have been using is that if I have a space $X$ and the I attach a 2-cell to it to get $Y$, then the inclusion $\iota: X \rightarrow Y $ induces surjection on the fundamental group with the kernel generated by the "attaching maps."
Comment: @asktksa - I fixed some errors. Actually, the issue is that this construction doesn't work for the labeling scheme $aa^{-1}$--if it does, it would imply the Euler characteristic of $S^2$ is $1$. The "rules" for labeling schemes producing surfaces are essentially what prevent this from happening -- a labeling scheme fitting the rules is a space that can be obtained by attaching a single 2-cell to a wedge of circles. (If $S^2$ is to have a single circle as its 1-skeleton, it requires 2 2-cells attached.) As for the rules...
Comment: I don't know of a reference where to find them, but I learned them during the classification of compact connected surfaces. Some of the rules are: words must be fully reduced, every letter you use must appear exactly twice, either as a "twisted pair" ($a$ appearing twice in the word) or an "oriented pair" ($a$ appearing once, $a^{-1}$ appearing once), oriented pairs are interlaced with other oriented pairs (e.g. like the torus). I think these are the only relevant rules for labeling schemes; the other "rules" are more like constructions that occur during the classification theorem.


What's the measure of the $\angle PBN$ in the question below?

Question: For reference (exact copy of question): In the acute triangle $ABC$, the heights AH and BN are plotted. Extended H intersects the circumcircle at $P$.
Calculate $\angle PBN$ if $\angle AON=30^\circ.$ $O$ is the orthocenter of triangle $ABC$.
(answer $120^\circ$)
My progress: Here is the picture I made and the relationships found. I drew some auxiliary lines...

$D$ is circumcenter
$ABPC$ is cyclic $\implies \angle PAB = \angle PCB\\
\angle BDA = \angle NAP=60^o=\angle NBC$
Comment: $\angle OAN=60^{\circ}.$ So $ABC$ cannot be equilateral.
Comment: @SathvikAcharya..thanks for alert...
Answer: $$\angle HBO=90^{\circ}-\angle BOH=90^{\circ}-\angle AON=60^{\circ}$$
Since $ABPC$ is cyclic,
$$\angle PBC=\angle PAC=90^{\circ}-\angle AON=60^{\circ}$$
Therefore,
$$\angle PBN=\angle PBC+\angle CBN=\boxed{120^{\circ}}$$


How do I get Pillager Patrols to spawn?

Question: I can't find a Pillager Outpost anywhere near my house, and so I've been trying to AFK far away from my house (it has a village and patrols don't spawn near villages). But there seem to be none spawning. Anything I might be doing wrong?
I'm playing Minecraft Java Edition 1.18.
Answer: Maybe not the actual answer to your question, but you can easily locate a Pillager Outpost using this Pillager Outpost finder site. The only thing you need is your world seed.
As far as I know Pillager patrols are spawned randomly, there's no reliable way to get one outside of their outpost.
From Minecraft wikia:

Patrols spawn naturally after the world age reaches 100 minutes (5 in-game days), then after a delay between 10–11 minutes an attempt is made to spawn a patrol with 20% chance of success. After an attempt is made, the delay is reset.

You also need to check that:

In Java Edition, patrols never spawn if <code>/gamerule doPatrolSpawning</code> is set to false.
Answer: According to the Minecraft Wiki,

Patrols can spawn during the day on blocks with a block light level of 8 or lower. If a player is within 5 by 5 by 5 sub-chunk cube around a village, patrols do not spawn.

The game picks a random location 24–48 blocks along each of the X and Z axis away from the player to try to spawn the patrol's captain. If a pillager cannot spawn at the chosen position, it gives up and does not spawn anything. If the captain can spawn, the game tries to spawn 1 + localDifficulty [verify](rounded up) more pillagers, with each pillager spawning within a 4-block radius square around the previous pillager.

So, if you find a large open area and wait for long enough, a pillager patrol will spawn.
Please note, that Pillager Patrols only spawn when your world reaches 100 minutes or 5 in-game days. The game will attempt to spawn a pillager patrol every 10 ish minutes with a success rate of 20%.
So in theory, if you find a large open area, you should be able to find a pillager patrol in 10 minutes if you're lucky, or up to 50 minutes if you aren't.
Comment: "up to 50 minutes if you aren't", if you mean that 5x 20% makes 100%, that's not how probability works
Answer: The patrols are based on certain factors: time, amount of villagers outside of a village nearby(so like make your own village at your base) and a few other factors. Get at least 10 villagers in your fake village (doesn't have to look like a village).
Answer: Pretty sure, off of odds, that around every 50 minutes you would have around a 67% chance to get one, then increasing from there. Not sure though, this was after a lot of searches and an at least once rule, so correct me if I'm wrong.
The amount of time it would take for pretty much perfect odds 1%>a is 3 and a half hours.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How do I get Pillager Patrols to spawn?