MVC5 EF Entity apparently saving, but is null when retrieved

Question: I have an Account class that holds a list of Payments, which holds a list of Products that are Pending, Sold or Refunded.
When selecting the Products to pay for, I can add them into a Payment object and then save the whole object to an Account.
However, when I retrieve the account in the Pay action, Account.Payments is null.
Here is the AddProduct action:
public ActionResult AddProduct(List<Product> products)
{
    //var acc = Account.FetchAccountFromIdentity(User.Identity.GetUserName());
    var username = User.Identity.GetUserName();
    var acc = db.Accounts.First(u => u.EmailAddress == username);
    var payment = new Payment();

    foreach (var product in products)
    {
        if (product.IsSelected)
        {
            var tempProduct = db.Products.Find(product.ProductID);
            payment.Products.Add(tempProduct);
            payment.PaymentStatus = enPaymentStatus.Pending;
            payment.Gross += tempProduct.Price;
            payment.Vat += tempProduct.Price * 0.2;
            payment.Net += payment.Gross - payment.Vat;
         }
    }
    payment.AccountID = acc;
    if (acc.Payments == null) acc.Payments = new List<Payment>();
    acc.Payments.Add(payment);
    db.SaveChanges();

    return RedirectToAction("Pay", "Products", new {id = acc.AccountID} );
}

acc.Payments is correctly populated with any relevant payments at this point.
And then the Pay action:
    public ActionResult Pay(int? id)
    {
        var acc = db.Accounts.Find(id);
        var data = new AccountPaymentView
        {
            Account =  acc,
            Payment = acc.Payments.First(p => p.PaymentStatus == enPaymentStatus.Pending)
        };

        return View(data);
    }

acc.Payments is now null!?
Any idea as to what I must be doing wrong?
Edit
Now with Account Class:
    public class Account
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AccountID { get; set; }
        [Display(Name = "Title")]
        public string Salutation { get; set; }
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Passwords do not match. Please try again.")]
        [Display(Name = "Confirm Password")]
        public string ConfirmPass { get; set; }
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email Address")]
        public string EmailAddress { get; set; }
        public virtual ICollection<Address> Addresses { get; set; }
        public virtual ICollection<Payment> Payments { get; set; }
        public DateTime CreatedOn { get; set; }
        public virtual  ICollection<DateTime> VistsList { get; set; }
        public bool IsDeleted { get; set; }
        public enAccountType AccountType { get; set; }
}

Edit 2
Here is the OnModelCreating method on the DBContext (Removed unrelated parts). I've got to me missing something glaringly obvious?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Properties<DateTime>()
        .Configure(c => c.HasColumnType("datetime2"));

    modelBuilder.Entity<Account>().HasOptional(x => x.Addresses).WithMany();
    modelBuilder.Entity<Account>().HasOptional(x => x.Payments).WithMany();
    modelBuilder.Entity<Payment>().HasOptional(x => x.Products).WithMany();
    modelBuilder.Entity<Payment>().HasOptional(x => x.AccountID);
    modelBuilder.Entity<Payment>().HasKey(x => x.PaymentID);

}

Edit 3
Checked out the Account.FetchAccountFromIdentity() and it does open a new context. So that has now been removed and I now use a context within the AddProduct method (code updated above).
Now I am getting the following error when saving!!!
An object of type 'System.Collections.Generic.List`1[[PPPv2.Models.Payment, PPPv2,
Version=184.108.40.206, Culture=neutral, PublicKeyToken=null]]'
cannot be set or removed from the Value property of an EntityReference of type 'PPPv2.Models.Payment'.

I've tried forcing the PK relationships in the OnModelCreating method, but it didn't seem to help.
For clarity, here is the Payment class:
public class Payment
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PaymentID { get; set; }
    public virtual Account AccountID { get; set; }
    public virtual ICollection<Product> Products { get; set; }
    public double Gross { get; set; }
    public double Net { get; set; }
    public double Vat { get; set; }
    public string TransactionCode { get; set; }
    public enPaymentStatus PaymentStatus { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime PaidOn { get; set; }

    public Payment()
    {
        Products = new List<Product>();
        Gross = 0.0;
        Net = 0.0;
        Vat = 0.0;
        IsDeleted = false;
        PaidOn = new DateTime(2000, 1, 1, 0, 0,0);
    }

}

Edit 4
As requested, here is the Product model:
public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductID { get; set; }
    public string Name   { get; set; }
    public string Description { get; set; }
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "£{0:#,###0.00}")]
    public double Price { get; set; }
    [DataType(DataType.Currency)]
    [Display(Name = "Total Estimated Legal Cost")]
    [DisplayFormat(DataFormatString = "£{0:#,###0.00}")]
    public double EstimatedTotalLegalCost { get; set; }
    public virtual ICollection<Overview> Overviews { get; set; }
    public virtual ICollection<Process> Processes { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime LastUpdated { get; set; }
    public bool IsSelected { get; set; }
    public bool IsDeleted { get; set; }
}

Comment: What is your Account model?
Comment: OK, the `Payments` are set up with the `virtual` keyword -> lazy loading is enabled. Try accessing the `.Payments` navigation property (`var first = acc.Payments.FirstOrDefault()`) and it should be automagically loaded from the database.
Comment: I put it into the Pay Action as: (var firstPayment = acc.Payments.FirstOrDefault();) but it's still being brought forward as null :(
Comment: I would honestly not use navigation properties to do saving and loading. This can create some really really obscure sql and possibly hammer the database. You need to utilise the database, stored procs and triggers.
Comment: After `db.SaveChanges();` in `AddProduct` are you able to see the data in the database? @No1_Melman That isn't true at all. Stored procs are unnecessary here.
Comment: Interesting, after db.SaveChanges(); the db is empty?! :/
Comment: @Shoe it is unknown to both of us whether they are or aren't necessary here, the way to find out would be to Profile the transaction to see how many calls are being made to the database.
Comment: Does `Account.FetchAccountFromIdentity` use the same context as you are saving against? Maybe post the code from there. Also please use `@name` to tag people so that they know you've responded.
Comment: @Shoe I'll start using the @ name going forward. Account.FetchAccountFromIdentity turned out to be using a seperate instance of the same db context. This has now been removed and now I have a different problem with the db.SaveChanges (added above).
Comment: Remove these lines `if (acc.Payments == null) acc.Payments = new List(); acc.Payments.Add(payment);` and just do `payment.AccountId = acc.AccountId;`
Comment: @Shoe Sorry, tried that just now and neither the Payments table, nor the acc.Payments ends up with any Payment objects in them still :/
Answer: If you look at the tables that the Entity Framework has generated, you'll see there's only three of them. Given your data model, there should be junction tables that map Account and Payment objects to one another (same goes for Payment and Product, and you'll likely need to do the same for the other collections you have).
The exception you are getting regarding being unable to cast a List of Products to a single one is because your data model indicated that Products was a collection, yet the database table was actually storing this as foreign-key (i.e., single entity) relationship between Payment and Product.
If I change the code in the OnModelCreating method to the following, your AddProducts method works as intended.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));

    modelBuilder.Entity<Account>().HasMany(x => x.Addresses)
        .WithMany().Map(t => t.ToTable("AccountAddresses"));
    modelBuilder.Entity<Account>().HasMany(x => x.Payments)
        .WithMany().Map(t => t.ToTable("AccountPayments"));
    modelBuilder.Entity<Payment>().HasMany(x => x.Products)
        .WithMany().Map(t => t.ToTable("PaymentProducts"));
    modelBuilder.Entity<Payment>().HasOptional(x => x.AccountID);
    modelBuilder.Entity<Payment>().HasKey(x => x.PaymentID);
}

The change was going from code like:
modelBuilder.Entity<Payment>().HasOptional(x => x.Products).WithMany();

To:
modelBuilder.Entity<Payment>().HasMany(x => x.Products).WithMany().Map(t => t.ToTable("PaymentProducts"));

Doing so instructs Entity Framework to create the junction tables that allow a Payment to hold a collection of Products.
Comment: YES!!! Thank you! Removing the HasOptional with HasMany.WithMany and them mapping to a junction table did the trick! @nick_w thank you for solving it :)
Answer: When creating your payment you should save it directly to the database. I don't think adding it to your account object would work because it's an entity that isn't being tracked by EF yet.
public ActionResult AddProduct(List<Product> products)
{
//var acc = Account.FetchAccountFromIdentity(User.Identity.GetUserName());
var username = User.Identity.GetUserName();
var acc = db.Accounts.First(u => u.EmailAddress == username);
var payment = new Payment();

foreach (var product in products)
{
    if (product.IsSelected)
    {
        var tempProduct = db.Products.Find(product.ProductID);
        payment.Products.Add(tempProduct);
        payment.PaymentStatus = enPaymentStatus.Pending;
        payment.Gross += tempProduct.Price;
        payment.Vat += tempProduct.Price * 0.2;
        payment.Net += payment.Gross - payment.Vat;
     }
}
payment.AccountID = acc.AccountID;
db.Payments.Add(payment);
db.SaveChanges();

return RedirectToAction("Pay", "Products", new {id = acc.AccountID} );
}

Comment: Whoever down-voted me could you please leave a comment and explain why?
Comment: Closest yet! @Shriike Your solution give the error: Unable to cast object of type 'System.Collections.Generic.List`1[PPPv2.Models.Product]' to type 'PPPv2.Models.Product'. when we reach the line db.Payments.Add(payment)
Comment: The only place that I see a list of products is this line `payment.Products.Add(tempProduct);` could you try commenting that out and see if you still get the same error? Also it might be helpful adding the definition of Product to your message.
Comment: I've now added the Product model to the above. I would comment out payment.Products.Add(tempProduct), but I need it added to the payment before adding it to the account.
Comment: @Dezzamondo I know you need to save the product with the payments, but maybe for debugging purposes you could try taking out that line, using db.Payments.Create() instead of new Payment, taking out the new List in your Payment constructor, just to help narrow down the problem.


Getting IP Address current server

Question: I used symfony 1.4 to create my application.
I'd like to get the IP adress of the current server to put it within soap request
So, how can i get the IP address of the current server?
Comment: It depends if they need to get the IP address using the framework. It is not recommanded to use globals for example
Comment: This is not a Symfony related question, please check this answers about getting the server IP on PHP: http://stackoverflow.com/questions/5800927/how-to-identify-server-ip-address-in-php
Answer: For most situations, using $_SERVER['SERVER_ADDR']; will work.  If that doesn't work you can try $ip = gethostbyname(gethostname());
Answer: Premise of the following method: your domain name has only one IP resolution
Using PHP:
gethostbyname($_SERVER['SERVER_NAME'])

$_SERVER['SERVER_NAME']will generally return your domain name (server_name / ServerName is configured in Nginx / Apache server), and then use gethostbyname().

About $_SERVER['SERVER_ADDR'], it often return a LAN IP address (I only have one server, one domain name, no reverse proxy; cloud server).

About gethostname()
In the test, it returns the name of the server (host name, not the domain name you use), and then uses gethostbyname(), will return a LAN IP.

More can be used https://checkip.amazonaws.com/ Get the current IP.
Answer: If you have access to the $request object and it is a sfWebRequest (typical request from a browser) you can use:
$request->getPathInfoArray()['SERVER_ADDR']

Getting IP Address current server


Is there a way to make an indeterminate checkbutton with PyGtk?

Question: I am designing a GUI where I have a list of checkable items that also has a sublist of checkable items. I want to graphically represent in the parent checkbox if only some of the child items are checked. I have been searching Google for hours with this and the only documents explain how to style a possible button. Is there a way in Gtk to do this cleanly?
Answer: Checkbutton's parent ToggleButton has inconsistent property, which is what you are looking for (screenshot)


How do I programmatically update an existing submitted webform submission in Drupal?

Question: I am attempting to use PHP in Drupal rules to update the values in submitted webform submissions. I can access and view the data correctly. When I assign a new value to a field it will even show up correctly if I use print $submission->data[61][0]; But when I navigate to the submission results page the field hasn't been updated.
I have tried using the webform_submission_update() function to push my change but still no luck.
Question: How do I programmatically update an existing submitted webform submission in Drupal?
Code:
$submission = webform_menu_submission_load($nid, $sid);

// Two ways I've tried to update the data
$submission->data[61][0] = "testwork";
$submission->data[61]['value'][0] = 'Declined';

// If I do print $submission->data[61][0]; it will show the new value.

webform_submission_update($nid, $submission);

Answer: Here's how to do that:
// Load the webform submissions file. The webform_get_submission() and
// webform_submission_update() functions are located here.
module_load_include('inc', 'webform', 'includes/webform.submissions');

// Load the node and submission.
$node = node_load(YOUR_NODE_ID);
$submission = webform_get_submission($node->nid, YOUR_SUBMISSION_ID);

// Change submission data.
//
// To see what's available, install Devel and run dpm($submission);
$submission->data[YOUR_FORM_ELEMENT_ID][0] = 'Update';

// Finally, update the submission.
webform_submission_update($node, $submission);

Documentation:

webform_get_submission()
webform_submission_update()


Converting two formats of timestamp with two_datetime

Question: I've got a dataset where timestamps are in two distinct formats...
Tue Oct 30 12:57:49 +0000 2012 and
Tue Mar 11 13: 57: 22 +0000 2014
I would like to parse these into a pd.datetime format.
My approach so far has been to parse one type (with errors='ignore' so that non-matching timestamps aren't touched), then to parse the second time with the other format.
train['timestamp'] = pd.to_datetime(train['timestamp'], format='%a %b %d %H: %M: %S %z %Y', errors='ignore')
train['timestamp'] = pd.to_datetime(train['timestamp'], format='%a %b %d %H:%M:%S %z %Y')

I seem to get an error during the second call for a timestamp I would have expected to be 'picked up' by the first expression:
ValueError: time data 'Tue Mar 11 23: 59: 22 +0000 2014' does not match format '%a %b %d %H:%M:%S %z %Y' (match)
I would have thought Tue Mar 11 23: 59: 22 +0000 2014 would have been matched by %a %b %d %H: %M: %S %z %Y in the first line, so the second line wouldn't be shown this format.
Comment: Not sure about this, but it seems to me a way to solve it would be to just remove all spaces: `pd.to_datetime(train['timestamp'].str.replace(' ',''), format='%a%b%d%H:%M:%S%z%Y')`
Comment: It worked! Thanks a lot. A much nicer solution than that which I was trying to do. :)
Answer: By looking a the output of these two calls we can see that the parsing workes, but that pandas converts the timestamp object back to a string when getting mixed data (timestamp for successful, str for errors)
import pandas as pd
data1 = {
'timestamp':  ['Tue Oct 30 12:57:49 +0000 2012','Tue Mar 11 13: 57: 22 +0000 2014']
}
train = pd.DataFrame.from_dict(data1)

list(map(type, pd.to_datetime(train['timestamp'], format='%a %b %d %H: %M: %S %z %Y', errors='ignore'))) #=> ['str','str']

We can see that the parsing worked fine by running:
pd.to_datetime(train['timestamp'], format='%a %b %d %H: %M: %S %z %Y', errors='coerce')

where one failed and one succeeded (and returned NaT)
The solution is to either convert to same format using:
pd.to_datetime(train['timestamp'].str.replace(' ',''), format='%a%b%d%H:%M:%S%z%Y')

or run two separate parsings and combine:
t1 = pd.to_datetime(train['timestamp'], format='%a %b %d %H: %M: %S %z %Y', errors='coerce')
t2 = pd.to_datetime(train['timestamp'], format='%a %b %d %H:%M:%S %z %Y', errors='coerce')
train['timestamp'] = t1.combine_first(t2)

Comment: Very nice, thanks for explaining why it didn't work properly. I like the combine_first function, I didn't know that existed.


How do conditionally thread in a nodejs application

Question: My website's api works fine and runs fast, except for one route.  Since nodejs is single threaded, we wanted to make the api call DATA be separately threaded so that it doesnt block the rest of the incoming calls, and because it took too long to fork.  Basically the code I want is like this:
router.get(req, res){
    if(MasterThread){
        create a thread to run the DATA functions
    }
    else{
        res.json(getDATA())
    }
}

is this possible at all? All the tutorials I found implied that I either had to use cluster, or my threading had to occur in my main.js, neither of which I want to do.
When I tried to set up the threading across 2 files, the imports for nodejs threading were always null, or my imports never worked.
So again, if this a possible thing?
Comment: You should spawn the secondary thread on the root of you application, outside route definitions, the way you're doing right now is spawning a new thread every time the route is called, this is costly, Node has to load all the modules from a cold-start, if your API is called, let's say, 100 times in a second, this will become an issue. Think the worker thread as another Node API running, it should be started one time and then wait for input.
Comment: Could you post the code for the route that doesn't work properly? Network I/O won't block other code waiting to be executed by the event loop if you're doing async properly.
Comment: Could you please describe which things are performed during the route ?
Based on your answer we can help you better.
Answer: You can use worker_threads for this case I use it for one of my sites and it works perfectly here is minimal example
const { Worker } = require('worker_threads')
const worker_script = path.join(__dirname, "./worker.js")

    router.get('/', function(req, res) {
              const worker = new Worker(worker_script, {
                workerData: JSON.stringify(obj)
              })
              worker.on("error", (err) => console.log(err))
              worker.on("exit", () => console.log("exit"))
              worker.on("message", (data) => {
                console.log(data)
                res.send(data)
              })

    })

and here is the worker
const { parentPort, workerData, isMainThread } = require('worker_threads')

if (!isMainThread) {
     console.log("workerData: ", workerData)
      //do some heavy work with the data
    var parsed = JSON.parse(workerData)

    parentPort.postMessage(parsed)

}

Comment: Thanks.  This makes the most sense!


Question concerning changing order of integration in the following double integral

Question: Can someone check if my solution to the following problem is correct.
(a) Evaluate
$$\int_{0}^{\alpha\sin\beta} \int_{y\cot\beta}^{\sqrt{{a}^{2}-{y}^{2}}} \log({x}^{2}+{y}^{2}) \,dx\,dy$$
(b) Change the order of integration in the integral in (a)
For part (a), I let $x=\alpha cos(\beta)$ and $y=\alpha sin(\beta)$, then applying the change of variable formula
$\int_{0}^{y} \int_{x}^{-x} \alpha\log({\alpha}^{2}) \,d\alpha\,d\beta$
$\int_{x}^{-x} \alpha\log({\alpha}^{2}) \,d\alpha\,d\beta=0$
So $\int_{0}^{y} \int_{x}^{-x} \alpha\log({\alpha}^{2}) \,d\alpha\,d\beta=0$
For part (b), the reverse order of integration becomes
$\int_{0}^{\alpha\cos\beta} \int_{\sqrt{{a}^{2}-{x}^{2}}}^{x\tan\beta} \alpha\log({\alpha}^{2}) \,d\beta\,d\alpha$
thank you in advance
Comment: The problem statement is confusing.  You have x and y as the variables of integration, while $\alpha\ and \ \beta$ are used to describe integration limits.  Then x and y get defined in terms of the other two.  I suggest you use $x=rcos(\theta ) \ and\ y=rsin(\theta)$ when making the switch to polar coordinates.
Comment: @herbsteinberg, what about $\alpha$ and $\beta$, do i change them to $r$ and $\theta$ respectively?  Like this

$$\int_{0}^{r\sin\theta} \int_{r\cot\theta}^{\sqrt{{r}^{2}-{(r\sin(\theta))}^{2}}} \log({x}^{2}+{y}^{2}) \,dx\,dy$$
Comment: @herb steinberg, I meant:

$$\int_{0}^{r\sin\theta} \int_{r\sin\theta\cot\theta}^{\sqrt{{r}^{2}-{(r\sin(\theta))}^{2}}} \log({x}^{2}+{y}^{2}) \,dx\,dy$$
Comment: @mr_e_man, is the way I did it incorrect?
Comment: @mr_e_man, so how would I go about both parts.  I am now stumped how to do it.  Because I thought i can treat $\alpha$ and $\beta$ as $r$ and $\theta$
Comment: @mr_e_man, for the inner integral, the upper and lower limits of integration should be the same, even if i treat $\alpha$ and $\beta$ as constants?  Is that correct?
Comment: Are you sure that the upper limit has $\alpha$ ("alpha") instead of $a$? It would make sense (and I think Piyush assumed in the answer) that the constants in the upper limits for $x$ and $y$ are the same. (It would be the radius of a circle.)
Comment: @mr_e_man, I typed out the question as it appears.  I first though the upper and lower limits of integration should be equal for the inner integral.  I had hard time with which graphs to draw for the two limits of integration in the inner integral.
Comment: The lower limit (actually the left limit, if $x$ represents horizontal position) is simply a straight line ($x$ is proportional to $y$). The upper limit for $x$ (actually the rightward limit) is part of a circle of radius $a$. The upper and lower limits for $y$ are horizontal lines.
Comment: @mr_e_man thank you for clearing that up for me.  :)
Answer: So the region of integration is a sector of a disk $x^2+y^2\le a^2$ with angle $\beta$ at the center. So in polar coordinates the integration becomes $$\int_0^{\beta}\int_0^ar\log r^2 dr d\theta=\beta(\int_0^ar\log r^2 dr)=\beta(\frac{a^2}2(2\log a-1))$$
Change of variables is as follows $$\int_0^{a\cos \beta}\int_0^{x\tan\beta}\log(x^2+y^2)dydx+\int_{a\cos\beta}^a\int_0^{\sqrt{a^2-y^2}}\log(x^2+y^2)dydx$$
Comment: Thank you for helping me to clear up the liimits of integration  Much appreciate it.


Link MySQL with different glibc

Question: I'm trying to link MySQL with a different glibc that provides e.g. a different pthread implementation and actually thought I got it right a few days ago.
Obviously, I took notes and wanted to reproduce the outcome but I can't get it to link properly, so I must have forgotten a step.
What I did previously was simply to add the flags pointing to my glibc and the default one second to the cmake command.
GLIBC_FLAGS="-Wl,--rpath=/path/to/my/glibc/build/lib:/usr/lib/x86_64-linux-gnu:/lib/x86_64-linux-gnu -Wl,--dynamic-linker=/path/to/my/glibc/build/lib/ld-linux-x86-64.so.2

cmake \
    -DCMAKE_INSTALL_PREFIX=../install \
    .. \
    -DCMAKE_C_FLAGS="$GLIBC_FLAGS" \
    -DCMAKE_CXX_FLAGS="$GLIBC_FLAGS"

These flags work when building a simple a test-program but seem not to work with MySQL as ldd reports the default glibc for mysqld.
$ ldd install/bin/mysqld
    linux-vdso.so.1 =>  (0x00007fff14ffe000)
    libcrypt.so.1 => /lib/x86_64-linux-gnu/libcrypt.so.1 (0x00007f4f1c9bb000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f4f1c7b7000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f4f1c599000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f4f1c295000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f4f1bf91000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f4f1bd7a000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f4f1b9b2000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f4f1cc13000)

I also tried to set the LD_LIBRARY_PATH and changing the linker flags and lib variables in BUILD/scripts/mysql_config but none of these seem to work.
What is necessary to link MySQL against a different glibc?
Comment: You typically have just one `libc` on your system (2 if you count 32/64 bit). Otherwise you're going to run into all kinds of insane problems that can render your entire userspace unusable.
Comment: @JonathonReinhart I need different versions since I test them against each other. I also didn't experience any issues yet as long as the programs are linked properly.
Comment: You're probably going to want to try this at least in a `chroot` jail, or Linux  container.
Comment: Okay but I still need at least two glibcs because the glibc that I'm testing does not provide an implementation of all libc components
Answer:
ldd reports the default glibc for mysqld.

You should not trust ldd -- it uses default loader -- /lib64/ld-linux-x86-64.so.2 which is not the loader you've compiled your musqld to use.
Instead, run your mysqld under GDB and do start followed by info shared. You will likely see that in fact your version of glibc is actually loaded.
Answer: After a Kernel-Update, cmake apparently ignored the DCMAKE_CXX_FLAGS and DCMAKE_C_FLAGS if they contained a colon-separated list of paths (the options were used when they contained only a single path).
I worked around this by setting the colon-separated pathlist directly in the CMakeLists.txt in the MySQL root directory.
Comment: Probably you just have to clear your CMakeCache.txt. That can never happen with a Kernel update!

Link MySQL with different glibc


issue retrieve json data in swift iOS

Question: I have issue that I can't retrieving json data in swift, I kept getting error message

var url = NSURL(string: getDataURL)!
    var data = NSData(contentsOf: url as URL)
    do {
        jsonArray = try JSONSerialization.jsonObject(withData: data, options: .allowFragments)!
    }
    catch let error {
    }

I was working with Objective C but I want to switch to Swift language
Comment: The Information **Swift 3** is crucial to get the right signature. I edited the tags.
Comment: let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
Comment: @MikeAlter I have tried this before and still not working
Comment: Your app will certainly crash if an error occurs in the `do - catch` block. You cannot simply continue after the catch part.
Comment: @vadian I'm getting error before the app crush, I have tried many codes but still not working for me at all
Comment: You should make clear that you are talking about Swift 3.
Comment: @vadian I know that but I want first receive data from my json file then thinking about that issue
Comment: Have you tried : let jsonArray = try? JSONSerialization.jsonObject(with: data, options: [])
Comment: @CRDave yes but still getting error :(
Comment: Same error or different?
Comment: @CRDave Of course different error ;-)
Answer: Folks, please use the code completion feature to find the proper syntax
When you type JSONSerialization. you will see

The appropriate method is
JSONSerialization.jsonObject(with:data, options: .allowFragments)

Or press ⇧⌘0 (zero not O) and look up the method in the documentation by typing or pasting the class. Every developer must be able to read the documentation.
Aside from that you have to cast the result of the deserialization to the expected type
jsonArray = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [[String:Any]]

Comment: Write `let data = try Data(contentsOf: url)!` and put it in the `do` block
Comment: yes I have tried it before and still not working at all
Comment: Basically this code works. You will get other errors. I updated the answer to resolve one.
Comment: I'm getting "Ambigouus reference member 'jsonObject(with:options)' error
Comment: `data` is an optional. You need to unwrap it. By the way you should use the new native types: `let url = URL(string: getDataURL)!` `let data = Data(contentsOf: url)!` But you are strongly discouraged from using synchronous methods like `Data(contentsOf:` because they block the thread.
Answer: Try this code send request and get data.
 if let jsonResult = try NSJSONSerialization.JSONObjectWithData(fooData!, options: []) as? NSDictionary
 {
        print(jsonResult)
  }else{
         return failure(NSError)
 }

Comment: @YousefAbuSallamah in fooData pass your Data
Comment: This is Swift 2, the question is about Swift 3.
Comment: @HimanshuMoradiya It seem like you and OP are on different Swift version.
Comment: @vadian xcode will replace code from swift 2 to swift 3
Comment: @HimanshuMoradiya I'm getting error swift compiler now after adding your code

issue retrieve json data in swift iOS


Requisição AJAX no Bootstrap

Question: Olá
Eu estou precisando abrir uma pagina externa por meio de uma requisição AJAX na minha ROW no Bootstrap, mas não estou tendo sucesso, eu estou seguindo o tutorial do link abaixo, mas não esta abrindo a minha pagina na ROW do Bootstrap, como eu posso fazer ? Tem alguma função nativa do Bootstrap para isso ?
http://tedk.com.br/blog/html/carregar-uma-pagina-dentro-de-uma-div-com-ajax/
Código:
    <!doctype html>

    <meta charset="utf-8">
    <title>load demo</title>

    Projects:

Obrigado
Answer: Use isto:

$( "#new-projects" ).html('<object data="https://pt.stackoverflow.com"/>');
  body {
    font-size: 12px;
    font-family: Arial;
  }
<!doctype html>

  <meta charset="utf-8">
  <title>load demo</title>

Projects:

Comment: Que legal. Agora deu certo. Obrigado.
Comment: Eu sei o seu código, mas não esta rodando, porque ?
Comment: Veja se está carregando o jQuery. Uma pergunta, a página é externa, outro domínio?
Comment: Então, Esta aparecendo isso no meu console ( Refused to display 'https://pt.stackoverflow.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
pt.stackoverflow.com/ Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE
/favicon.ico Failed to load resource: the server responded with a status of 404 (Not Found) )
Comment: E eu botei seu script acima em um host online. Mas não funciona.
Comment: O motivo é o domínio. Ex: se estou em www.meusite.com eu posso chamar www.meusite.com/outrapagina, mas se chamar www.google.com por segurança não permite.

Requisição AJAX no Bootstrap


exercise autocovariance function

Question: I don't know how to obtain the autocovariance function of the following process, having a multiplication makes it difficult for me.
$X_t = Z_t + \theta Z_tZ_{t-1}$
with $Z_i \sim N(0, \sigma^2)$ (white noise)
pd:
the answer is:
$\gamma_X(k) = \sigma^2(1+\theta\sigma^2), \hspace{1cm} k = 0$
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us what you understand thus far, what
you've tried & where you're stuck. We'll provide hints to
help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you
is grounds for closing.
Comment: That answer cannot possibly be correct, because for $\theta \lt -1/\sigma^2$ and $\sigma \ne 0$ it is negative.  I believe you need $\theta^2$ in the formula in place of $\theta.$  As far as the calculation goes, do you know how to compute [variances of products of independent variables?](https://stats.stackexchange.com/questions/52646)
Answer: Given that $\mathbb{E}[X_t]=0$, we have
$$\gamma_X(k)=\mathbb{E}[(Z_t+\theta Z_tZ_{t-1})(Z_{t+k}+\theta Z_{t+k}Z_{t+k-1})]$$
If $h=0$, then
$$\gamma_X(k)=\mathbb{E}[Z_tZ_t + \theta Z_tZ_tZ_{t-1} + \theta Z_tZ_{t-1}Z_t + \theta^2Z_tZ_{t-1}Z_tZ_{t-1}]
\\=\mathbb{E}[Z_tZ_t] + \mathbb{E}[\theta Z_tZ_tZ_{t-1}] + \mathbb{E}[\theta Z_tZ_{t-1}Z_t] + \mathbb{E}[\theta^2Z_tZ_{t-1}Z_tZ_{t-1}]$$
The trick is that in effect
$$\mathbb{E}[Z_sZ_tZ_u]=\mathbb{E}[Z_s]\mathbb{E}[Z_tZ_u]$$ and $$\mathbb{E}[Z_sZ_tZ_uZ_v]=\mathbb{E}[Z_sZ_t]\mathbb{E}[Z_uZ_v]$$
So
$$\gamma_X(k)=\sigma^2+\theta^2\sigma^4=\sigma^2(1+\theta^2\sigma^2)$$

exercise autocovariance function


Existence of stationary process with a given ACF

Question: Consider the sequence
$$\gamma(\tau) = \begin{cases}
1 & \text{if } |\tau| ≤ K \\
0 & \text{if }|\tau| > K
\end{cases}$$
where $K$ is a positive integer. Is $\gamma(\tau)$ an auto covariance sequence for some discrete parameter stationary process $Y_t$ ?
The answer is no but I don't see any valid argument. This would correspond to a process with a Toepliz matrix with ones on the diagonal and the $K$ sub diagonals near it and I can arrange myself to define a process with such a matrix.
Does this mean that if a process is stationary then it has a Toeplitz covariance matrix but the converse is not true ?
Comment: Consider what it means for $\gamma(1)=1$ in a stationary process: you must have $Y_{t+1}=\alpha+\beta Y_t$ for all $t$ (and $\beta\ne 0$). What does that imply about $\gamma(n)$ for any $n$?  (The role of a "discrete parameter ... process" is obscure and seems to be irrelevant.  Maybe you intend that $\tau$ be limited to a lattice? If so, wlg you can take $\tau\in\mathbb Z.$) Another way to analyze this is to consider the eigenvalues of your Toeplitz matrix: at least one will be *negative.*
Comment: @Zhanxiong Thank you.  It's also standard terminology to use "parameter" for the variables determining a family of distributions or processes.  Given the reference to an *integral* $K,$ the use of "parameter" to refer to $t$ otherwise looked superfluous; and the evident collection of examples supporting a "no" answer made me wonder whether there were some special unstated parametric assumptions in effect, whence my request for clarification.
Comment: @whuber "Discrete parameter" means that the time index $t \in \mathbb{Z}$ (as opposed to $t \in \mathbb{R}$, the continuous case).  It is a quite standard terminology in stochastic process.
Answer: To show that such a stationary process does not exist, it suffices to show that $\gamma$ is not non-negative definite (see Definition 1.5.1 and Theorem 1.5.1 of Time Series: Theory and Methods by Brockwell and Davis), which can be shown by demonstrating the covariance matrix $\Gamma$ of $(Y_1, Y_2, Y_{K + 2})$ is not non-negative definite. By assumption, the order $3$ matrix $\Gamma$ equals to
\begin{align}
\begin{bmatrix}
1 & 1 & 0 \\
1 & 1 & 1 \\
0 & 1 & 1
\end{bmatrix}.
\end{align}
It is easy to verify that the determinant of this matrix is $-1$, hence it cannot be non-negative definite (here we used the fact that if a matrix is PSD, then its determinant must be non-negative).
To put in a more comprehensible way, consider the linear combination $X = Y_1 - Y_2 + Y_{K + 2}$. Under the assumption, the variance of $X$ is $1 + 1 + 1 - 2 - 2 = -1 < 0$, which is absurd.


Alter login form in block by id

Question: I have a small problem on D7, I need to alter the login form inside block (add class to inputs, placeholder and submit button text, custom pass reset and login links) im using hook_form_FORM_ID_alter. I don't need to use custom module.
block id = block-user-login, form id = user_login_block
My theme.php code
function themename_form_user_login_block_alter(&$form, &$form_state) {

    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );

   // custom register link
    $form['actions']['signup'] = array(
        '#markup' => l(t('Register'), 'user/register', array(
            'attributes' => array(
                'class' => 'top-user-block-link register',
                'title' => t('Create a new user account.')
            )
        )),
    );

    // custom reset password link
    $form['actions']['request_password'] = array(
        '#markup' => l(t('Forgot my password'), 'user/password', array(
            'attributes' => array(
                'class' => 'top-user-block-link new-password',
                'title' => t('Request new password.'),
            )
        )),
    );
}

Links for password reset and login links renders fine, but i can't make the placeholders or class add to work.
i've tried to use
function theme_form_alter(&$form, &$form_state, $form_id){
  if ($form_id === 'user_login_block') {
$form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
}

but i works only on /login page.
Answer: If I recall correctly, you need $form['account']['name']['#attributes'].
Answer: $form['name']['#attributes']['placeholder'] = t( 'Username' );
$form['pass']['#attributes']['placeholder'] = t( 'Password' );

Both the code are working. If you can't see your changes or placeholder.
Please try with var_dump($form). You will find $form_id and all other fields of the form. just check your debug (array) ordering and make sure that order is same as in your form_alter() function.
Comment: var_dump($form) do the job, it was some custom login form generated form module. Simply i was calling bad id.
Comment: Now, Working? Or need help ?
Comment: Yes, work perfect ! :) thx !

Alter login form in block by id


Component do angular é renderizado várias em vez, porém só foi solicitado fazer isso uma vez

Question: Estou começando no angular e estou tendo um pequeno problema.
Estava seguindo um tutorial, e nele estava construindo uma applicação angular bem simples.
Nele temos basicamente 3 componentes, o app-root(principal) ,app-server e app-servers.
Nesse eu construi o html do  app-server , praticamente não fiz nada no .ts, ele tá praticamente no padrão de quando você cria um componente, só que olha só que estranho:
Clique na imagem para visualiza-la em seu tamanho original
O meu app-server é renderizado infinitas vezes sendo que eu só referenciei ele uma vez no app-components.
Se alguém tiver dúvida como fiz segue meu código.
Sever.component.html:

    <title>title</title>

asd.

server.component.ts:
import { Component } from '@angular/core';

@Component({
            selector: 'app-server',
            templateUrl: './server.component.html'

})

export class ServerComponent {

}

app.component.html:

I'm in the AppComponent

<app-servers></app-servers>

app.component.ts:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   name = 'lucas';
}

app.modules.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { ServerComponent } from './server/server.component';
import { ServersComponent } from './servers/servers.component';

@NgModule({
  declarations: [
    AppComponent,
    ServerComponent,
    ServersComponent
  ],
  imports: [
    BrowserModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

servers.component.ts:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-servers',
  template: `<app-server></app-server><app-servers><app-server>`,
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

Alguém poderia me dizer porque isso está acontecendo?? Aonde foi que eu errei? Eu revi o código alguma vezes e parece esta tudo certo.
Comment: porque tem uma tag html e body no seu componente?
Comment: porque, até onde eu sei,  é assim que docs html são estruturados. tag html  para indicar que inciou um doc html e body para configurar  os componentes  visiveis. Mas, Eu fiz um teste e tirei eles, parece que não é preciso usar esses tacs no angular, sem eles ele renderiza da mesma forma.
Comment: essa informações ficam no index.hmtl, no seu componente deixa somente o html referente a ele
Comment: eu dei uma debugada aqui, e achei o problema  ta em servers.component.ts: `template:`. Não sei pq , mais esse código ta gerando um loop infinito].
Comment: pq vc ta fazendo isso?
Comment: Não fiz isso propositalmente, provavelmete foi um erro de digitação. Eu tinha escrito esse código há algum tempo e voltei nele hoje pq voltei a fazer o curso, por isso tava muito confuso do pq tava acontecendo aquela parafernalha.
Answer: Você colocou <app-servers>, que é o selector do componente ServersComponent, dentro do seu próprio template.
Isso cria uma recursão infinita, pois toda vez que app-servers for renderizado, ele acaba criando uma nova instância dele mesmo, que em seguida criam mais outra instância e assim por diante.
O template correto neste caso seria esse:
template: `<app-server></app-server>`,

Esse template vai apenas imprimir o conteúdo do componente ServerComponent uma única vez.
Comment: excelente explicação faz todo  sentido. Agora eu entedi o problema. Obrigado.
Answer: Eu não entendi muito bem o que você esta tentando fazer, mas tente trocar
template: <app-server></app-server><app-servers><app-server>
por
template: <app-server></app-server><app-servers></app-server>
ou
template: <app-server></app-server>
Comment: apenas estava seguindo um tutorial de um curso udemy, para começar no angular. Vc sabe explicar o pq estava acontecendo o loop?


Configurar site no IIS no Windows 8

Question: Tenho o Windows 8 instalado em minha casa. Fiz um site em ASP.Net e  C# e agora fui colocá-lo no ar. Em minha casa, são dois computadores e em apenas um (desktop) eu configurei o IIS, o outro é para testar mesmo. Esses foram os passos:

1) Instalei o IIS em meu computador.
  2) No painel esquerdo do IIS,
  fui em site, direito e Configurar Novo Site.
  3) Escolhi um nome para
  o Site e um nome de host (www.agendamento.com.br)
  4) Copiei os
  arquivos publicados para uma pasta e escolhi essa pasta como a pasta
  de trabalho do IIS.
  5) Startei o site.
  6) Abri o navegador (Chrome) e
  digitei: www.agendamento.com.br.
  7) O IP coloquei todos não
  atribuídos e a posta deixei a padrão dele (80).

Quando digito o URL não vem nada.
O que mais devo fazer?
Comment: Você está querendo apenas publicar o seu site no iis, ou está querendo colocar um endereço de dns (www.agendamento.com.br) junto?
Comment: @Randrade até então não estava entendendo que eu precisava de um servidor DNS para poder acessar pelo nome do Host. Agora percebi que eu não posso fazer sem ele. Pelo IP também não consigo. Qual a finalidade disso? Eu preciso aprender, pois eu tenho um cliente que deseja que sua aplicação rode em seu ambiente de rede apenas, ou seja, todas as 6 máquinas deverão acessar o aplicativo e por isso estou testando em casa, em meu ambiente, para ao chegar lá, não ficar dando bandeira.
Comment: Seu site está em que? Web Forms? Asp.NET MVC? Asp Classico, ou alguma outra? Para eu elaborar uma resposta.
Comment: web forms. É sóum teste que eu estou fazendo aqui, para aprender a configurar o IIS
Answer: Você não pode usar um domínio qualquer. Você precisa usar um domínio que esteja configurado em um servidor de DNS. Você pode configurar um servidor de DNS próprio e configurar o domínio que deseja nele. Claro que só os computadores que estão "olhando" para este servidor de DNS conseguirão enxergar este domínio configurado nele.
Se você deseja que isto seja acessível pela internet, você deverá registrar este domínio em um órgão oficial para estar disponível em DNS público em toda a internet. OS domínios com final .br são registrados no Registro.br. Mas este domínio especificamente está bloqueado para registro e só pode ser usado internamente (na verdade não aconselho usar um domínio que deveria ser público de forma privada.
Se você tiver um domínio registrado, pode apontar para sua rede se tiver um IP fixo. Ou pode usar um serviço que substitua o IP fixo como o No-IP.
Mas acho que você só quer algo interno, então basta configurar um servidor de DNS para ter um domínio seu. Aconselho usar algo como meusite.teste ao invés de domínios válidos na internet.
Definitivamente eu faria isto em um Windows Server que tem um servidor DNS. Mas se quer insistir da maneira como está usando, instale o MaraDNS. Isto tem a vantagem de poder acessar em outro computador desde que o cliente de DNS do outro computador esteja apontando para este servidor.
Outra possibilidade mambembe seria mudar o arquivo de hosts. Ele fica em:
C:\Windows\System32\drivers\etc\hosts

Lá você adiciona (não vai apagar o que já existe):
127.0.0.1       meusite.teste

Ou se fizer questão:
127.0.0.1       www.agendamento.com.br

Claro que você também pode acessar pelo IP, ou mesmo localhost, se está na mesma máquina. Eu faria isto neste caso precário.
Se for acessar em outro computador, basta mudar o IP para este computador (vamos supor que o IIS está no computador de IP 192.168.0.103):
192.168.0.103       meusite.teste

Claro que você também pode estar com problemas de firewall, se for isto, libere a porta do IIS na máquina onde ele está instalado.
Coloquei no GitHub para referência futura.

Configurar site no IIS no Windows 8


Changing the From Address with the Printer, email, and PDF versions module

Question: I'm using the Printer, email, and PDF versions module. On all my 'resource' nodes (resource content type) I have a link now that says 'Send by Email'. Great. But when it sends the email it's sending it with a'from' address as MY email (the site admin). I'd rather it be the email of the person who's sending the resource. There is an email field on that form they have to fill out to send the resource to someone else.
Anyone know how to make the email they use for THEIR email in the form be the 'from' email to whomever they are sending this resource?
Answer: It's in Administration » Configuration » User interface » Printer, email and PDF versions, as the Use Reply-To Header option.
Comment: Thanks, but I had that checked already. The problem is that I want to enable this feature for anonymous users, not just logged in users.
Comment: Have you granted anons permission to **Access the Send by email functionality**?
Comment: yes, I have. They can send the email fine, it just always shows as coming from me, the drupal admin. I'm wondering if maybe there's a way to alter it programmatically with a hook or something.
Comment: Hmm, are you on shared hosting or some environment where outgoing email might be restricted? The toggling Reply-To... allows me to send out emails as email@example.com.
Comment: Yes, I am on shared hosting. You can just specify an email right there in the config page? Hmmm...any idea how to fix that with shared hosting? I would think the option would still appear though...Drupal doesn't know I have shared hosting. Am I totally wrong for thinking that?
Comment: Correct. Drupal is going to set the correct headers and pass it along to whatever MTA PHP is configured for. I'm not 100% sure that's the problem, I'm just trying reason why we see different behavior. If you have the core contact module enabled, you can test that form out to see if it sends out email as firstname.lastname@example.com when you fill it in the form.
Comment: Ok, so I enabled that and set the recipient to my work email and then filled out the form as an anonymous user (after config permissions of course) and set my name to my name to bubba fett and his email, I then clicked send I received the message in my work email as expected coming from bubba fett. So I don't think it's my hosting provider.


Module for comment validation

Question: I'm learning how to create a new module for the first time, so please bare with me. I'm trying to add a validation on the comment form from scratch; it's just not validating at all, meaning that my form successfully submits when I intentionally don't fill out the subject field.
Here is my code:
/*
 *  Implementation of hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == "comment_form") {
    $form['#validate'][] =  'my_module_comment_validate';
  }
}

/**
  * Validate routine to prevent keywords from being used within comments.
  */
function my_module_comment_validate($form, &$form_state){

if ($form_state['values']['subject'] == '') {
 form_set_error('', t('Error!'));
 }
}

Comment: Have you reset the cache?
Comment: Thanks for the reply. I have reset the cache and no luck.
Comment: have you tried debugging by adding a ```dpm``` inside the validate function ? what is the output?
Answer: In your form_set_error() call, you haven't set a specific field name on which to set an error. It's possible that without a form_set_error() call identifying a real form element no error is happening.
form_set_error('subject', t('Error!'));

Also, check to make sure your validation function is being called with a drupal_set_message()
Answer: change your form id...that should be
function MYMODULE_form_comment_form_alter(&$form, &$form_state, &$form_id){
}

and clear your cache..it should work for you

Module for comment validation


Blank search should show all results

Question: I remember that, in previous versions of the Search API and Search API Solr, by default not entering any search term would return the entire list of items.
I have tried with new empty Drupal 8.5.1 using Search API and Search API Solr, using the default configuration, with MariaDB and Postgresql, using the default view pages /search/content and /solr-search/content, but it shows an empty list and the message Please enter some keywords to search. message.
Does somebody know how to change it to the previous behavior to get again the whole list of elements when no search terms are used?
Comment: Remove the "required" status on the exposed filter?
Comment: I have the same issue,I removed the required status of the exposed filter,but still I get no results.Any help on this?
Answer: After trying everything that I could figure out, I have uninstalled the module, deleting all the views and installing it again and it works. No idea about what was happening sorry, but it work.

Finally thanks for some help I could understand what was happening :D The Filter Criteria Fulltext search was a Required, if you remove the checkbox then you will get the full list of items by default.

Blank search should show all results


Angular 2 URL Re-Writing

Question: I am new in Angular 2. I am working on project where i have a requirement like ' https://www.zomato.com/ ' for url re-writing. means in zomato when we select city it will show city in url like ' https://www.zomato.com/indore ' and when we select any restaurant the url will be like 'https://www.zomato.com/indore/square-sayaji-hotel-vijay-nagar' (url contains hotel name + address with dash). and in my site i am currently doing this ' http://fw.proaspire.com/restaurant-details?id=1 '
i need How can i implement it ?
Thanks in advance
Comment: And your question is?
Comment: I want to know how can i implement this ?
Comment: url rewriting has nothing to do with angular....
Answer: You need to write url rewrites in .htaccess if you are using apache.
Comment: i am using IIS web server. so will i need to write in web.config ?

Angular 2 URL Re-Writing


SELinux: Replacing selinux-default-policy (/etc/selinux/default/policy/policy.24) in Debian 6?

Question: I am using Debian 6 with SELinux enabled.
On first time setup, I have installed selinux-default-policy package. So, policy at location /etc/selinux/default/policy/policy.24 is used by SELinux.
Now, I want to build my own policy and make Debian to use my new policy instead of old policy (/etc/selinux/default/policy/policy.24).
To do this, I have downloaded the refpolicy from github.com and compiled using make policy. I have succeed at this point. After that, I have installed the same policy using make install. Now I could see that files are copied into location /usr/share/selinux/policy/.
I couldn't see any files like policy.24 in /usr/share/selinux/policy. Please guide me to replace my selinux-default-policy with new one.
Comment: Your question is unrelated to programming and off-topic.
Comment: IMO this question is not unrelated to programming and off-topic. These SELinux policy files are programmable. If /etc/security/selinux/src/policy is present then replace it with newly compiled polcy file.
Comment: @anil, Thank you for your support! I have a directory like "/etc/selinux/refpolicy/src/" and it contains source only. And I have *.pp files in location "/usr/share/selinux/refpolicy". I couldn't find any file like policy.24, which is available in location /etc/selinux/default/policy/policy.24.
Answer: Just do:
make clean; make install; make load

Now you can see: contexts, modules, seusers, policy directories. Copy them and paste it into /etc/selinux/default. Then:
touch /.autorelabel ; reboot

You are done!


HTML - Remove iframe Display

Question: I created an HTML page (main page) with an iframe so when I click the button the iframe will display covering the whole page. But I am having a problem on how to remove it whenever I click the back button from the iframe to the main page.
Here is my code:

function displayIframe() {
  document.getElementById("iframeDisplay").innerHTML = "";
}

<button onclick="displayIframe()">Display Iframe</button>

Can you help me on how can I achieve closing the iframe via javascript or jquery
Answer: You could wrap the iframe in a div and add the back button and the iframe in that div.
Add the click listener to the back button and remove the Iframe on button click.
Example:

function back() {
    document.getElementById("iframe").remove();
}
.back-button {
            position: absolute;
            right: 2px;
        }

    <button class="back-button" onclick="back()">Back</button>

Comment: But the problem is, the back button is found in my iframe html file
Comment: You cannot interact from iframe to outside environment .
Answer: Since the source of your frame is on the same domain (even site) as the containing page, you should be able to reach from frame's code into the parent.
window.parent.document.querySelector('iframe').style.display = 'none';

Comment: Thanks, Igor, for the answer. Can you add a little bit more details so that it helps Euph better understand the solution?

HTML - Remove iframe Display


DE: Orthogonal trajectories to an elipse

Question: Find orthogonal trajectories to the family of elipses:
$$\frac{x^2}{a^2}+y^2=1$$ where $a>0$
The idea is to remove the parameter $a$ from the equation via clever integration so it drops out.
-> rearrange to get $y'=f(x,y)$
-> we go into the exuation of orthogonal trajectories.
$$y'=\frac {-1}{f(x,y)}$$
-> solve this new DE to get the family of equations that give you orthogonal trajectories to the primary elipse.
BUT
I calcualted 3 times with 3 seperate solutions and at that point I decided that I better just ask someone.
Comment: You basically just need to differentiate the given equation of ellipse with respect to $x$ and rearrange to get an expression for $y'=\frac{dy}{dx}$. This might help: https://en.wikipedia.org/wiki/Orthogonal_trajectory
Answer: $$ x^2/a^2 + y^2 =1  \tag1 $$
Differentiate wrt x
$$  x/a^2 + y y^\prime = 0  \tag2 $$
From 1) and 2) eliminate $1/a^2 $, simplify
$$ \frac{1-y^2}{x} = \frac{-y y^\prime}{1} \tag3 $$
which is the DE of all ellipses with unit semi minor axis
To get at orthogonal trajectory DE,  $ y^\prime \rightarrow -1/ y^\prime $
$$ \frac{y^\prime }{y} = \frac{x}{1-y^2} \tag4 $$
Variable separable DE
$$ (1/y - y)dy = x\, dx \tag 5 $$
Integrate and simplify
$$ 2 log y = x^2+y^2 + c_1 \tag 6 $$
Simplify again to get $x=f(y)$ a relation or an implicit relation with arbitrary constants,
$$ x= \sqrt{ 2 \, log ( c_1\, y) - y^2 }, \quad y/e^ {\sqrt{ x^2+y^2}} = c_2 \tag7  $$
An plot for approximate loci indication
Please tell if any step is not clear, shall explain it.
EDIT1:
<code>g1=ContourPlot[ y/ Exp[Sqrt[x^2+y^2]], {x,-4,4},{y,-1.1,1.1},AspectRatio-> .2]
g2=ContourPlot[ (1-y^2)/ x^2 , {x,-4,4},{y,-1.1,1.1},AspectRatio-> .2]
Show[{g1,g2}, PlotRange->All]
g5=ParametricPlot[ (1-y^2)/ x^2  , {x,-4,4},{y,-1.1,1.1},AspectRatio-> .5]
</code>
Comment: Plotting better than ContourPlot is possible.Mathematica code is  pasted in EDIT1
Comment: This makes perfect sense. But honestly I doupt I would have figured it out anytime soon as my thoughts went in completely the wrong direction before.

Also thanks for the \tag# checked your source how you make those in markdown.

Do wonder where you managed to do the plot so quickly.
Cheers


Minha sessão não está sendo destruída -PHP-

Question: Eu tenho o seguinte código numa página de usuraiosessao:
  public static function destruirSessao() {
     if (isset($_SESSION)) {
        session_start();
        unset($_SESSION["codigo"]);
        unset($_SESSION["nome"]);
        session_destroy();
       }

  }

na pagina da index.php:
if (!thread::getUsuarioAtivo()) {
 header("location: login.php");
 } else {
 ?>
   Código HTML/ conteúdo da página
 <?php } ?>

Mesmo definindo o Session_destroy, a mesma ainda permanece,e, então eu sou capaz de digitar o url: index.php e entrar na sessão da ultima pessoa, como posso resolver? há algum erro de lógica no código?
O link de Logout é esta na pagina index:

que chama uma outra pagina que faz o logout, essa pagina de logout tem o código
      $verif = $_GET['act'];
        if ($verif == "logout") {
        thread::destruirSessao();
        header('Location: login.php');
      }

Comment: Era exatamente isso, dei um session_start(); na função destruirSessao(); e deu certo :D, Obrigado! Gabriel Carvalho! e ao outro Gabriel Falieri também! :D
Comment: Uai, onde você está chamando a destruir sessão?
Comment: Ah sim, tem um botão na página Index que chama uma pagina php que é de logout, e tem o codigo thread::destruirSessao();
Comment: Coloque o código desse botão por favor?
Comment: Edita sua pergunta, assim fica mais fácil
Answer: Temos um erro de lógica aí. Veja que primeiro você verifica se a sessão existe para depois inicializá-la. Como você não a iniciou, ela nunca vai entrar no IF para ser destruída. Coloque o session_start() fora do IF e poste o resultado, por favor.
public static function destruirSessao() {
   session_start();
   if (isset($_SESSION)) {
       unset($_SESSION["codigo"]);
       unset($_SESSION["nome"]);
       session_destroy();
   }
}

Comment: Sim, exatamente isso, preciso inciá-la antes, deu certo aqui, era realmente isso! Muitíssimo obrigado!


Improving accuracy of a binary classification when the target is unbalanced

Question: I am working on the BRFSS dataset with the goal of predicting Diabetes. The dataset has 500,000 rows and 405 columns. It is a 0/1 classification problem, the ratio of 0 to 1 is 90:10. I tried using decision trees, logistic regression an ensemble of decision trees and logistic regression and my misclassification rate is almost 14% in all of these methods.

What should I do to increase the accuracy?

I saw an earlier post which says subsampling or assigning different weights helps. But I am not sure about the ratio.

What would be the best ratio to start off with?
I am working using SAS. Is there a way to do subsampling in SAS?
I am also interested in trying out the weighted approach. Is there a way to implement this in SAS?

EDIT (28 Apr 2011)
I tried subsampling and my misclassification rate goes up from 14% to 23%. The ratio I used was 50:50 for classes 0 and 1. The original ratio in the data was 90:10 and using the data as it is gave 14% error. So I believe subsampling doesn't work for my data. Would you suggest any other  way to improve accuracy?
Comment: I can obtain a misclassification rate of just 10% with these data, sight unseen, by always predicting 0!  Surely *any* method you try will improve on this, right?  Perhaps some more information about the quality of your results would help us understand the situation better.
Comment: By "quality" I meant more details about the misclassification rate.  For instance, there are two kinds of misclassification: predicting the 0's as 1's and predicting the 1's as 0's.  Also, how are you doing the classifying?  With such an imbalance of 0's and 1's it's unlikely that setting the classification threshold to a logit of 0 is best: you will need a different threshold.
Comment: @whuber: Yes, we can always predict 0 and get misclassification rate(MIR) of < 10%. But, the models that I am using make prediction by reducing error, they do not look at the proportion of the classes (i.e.) 90:10. The dataset I am working on is BRFSS 2009 dataset which is available here in [csv format](http://www.hofroe.net/stat579/brfss%2009/brfss-2009-clean.csv). The target variable is DIABETE2.
http://stats.stackexchange.com/posts/10049/edit. I am not sure about what you mean on information about the quality of my results.
Comment: @whuber I have provided the confusion matrix [here](https://docs.google.com/document/d/1ud3bif91BIE2YLEs1jtl_UhUbjIjjWIkoxwyJCMSkK4/edit?hl=en&authkey=CPCGnKIC#) Could you suggest a way of improving the accuracy based on this?
Comment: Have you considered using a negative threshold?
Answer: The problem is more with the choice of the accuracy scoring rule.  Make sure that the ultimate goal is classification as opposed to prediction.  The proportion classified correctly is a discontinuous improper scoring rule.  An improper scoring rule is one that is optimized by a bogus model.  With an improper scoring rule such things as addition of a highly important predictor making the model less accurate can happen.  The use of log likelihood (or deviance) or the Brier quadratic scoring rule will help.  The concordance index C (which happens to equal the ROC area, making ROCs appear more useful than they really are) is a useful measure of predictive discrimination once the model is finalized.
Comment: Could you explain a bit more on the ROC/concordance relationship??
Comment: https://www.sciencedirect.com/science/article/abs/pii/0022249675900012
Answer: Regarding decision trees, I would suggest the following. Assume that you have 10 training examples from class $C_1$ and 90 training examples from class $C_2$. You can use an ensemble of $N$ decision trees, where each tree is trained on 10 examples from $C_1$ and 10 randomly chosen examples from $C_2$. The decision of the ensemble may be the majority vote. You can play with different $N$ to see how it works.
Comment: @User3897:  Whatever you do, definitely save some of your half million cases as a holdover sample for crossvalidation...I'm perplexed by your inability to find a better-predicting decision tree.  Have you fully explored SAS's options, e.g., on your inputted rules for node size requirements for when a parent node can be split, or when a child can be formed?  For the statistical significance of such splits?  For the program's ability to group the values of continuous predictors into effective subsets?
Comment: @rolando2 I have provided my SAS Enterprise Miner output [here](https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B_a7XsRmdVaENWM2NWQyMzUtZGI1Ni00NDBjLWI3ZDctMTUwZWQ2MWViNDZh&hl=en&authkey=CO3ij40B). This contains the tree settings that I used. Could you suggest what I need to improve upon.
Answer: Based on the output you shared, Maximum # of branches from a node is set at 2.  It's possible that raising that limit would give you more options for branches, especially if SAS can take continuous variables and break them up into categories.  It's data dredgy, but that's the game we're in, and as long as you crossvalidate you're on solid moral ground :-)
Comment: Yes, rigorous cross-validation or bootstrapping will tell you how arbitrary the intervals are.  It is not reasonable to expect the world to operate discontinuously however.  Smooth fits are undoubtedly more realistic and will predict better at the margins.  I'm not clear on why tree-based methods are as popular as they are.  With absolutely huge databases the issues are less important.
Comment: What I meant in the last sentence is that tree methods suffer less in terms of predictive accuracy when the sample size is exceedingly large.  Methods based on a single tree can not improve upon continuous modeling for any sample size, however.  And binning the data often results in gaming of the system at the margins.
Answer: If you are using tree-based methods, you can play around with the splitting criterion. For example, at each step, choose the split that gives the highest weighted accuracy (the average of the two classes' accuracies).
This can be used as the basis for a random forest too, which should give you a good classifier.
I once used a similar process to boost precision while sacrificing recall. It worked very well (better than thresholding the scores from the classification algorithm which were very noisy anyway).


Redirect Port 80 request to 443 for site

Question: I managed to redirect my requests from port 80 to 443 using the redirect permanent.
However, there is a problem. On my page there is a link to /forum/. When one clicks the link it tries to go to https://futureretrogaming.comforum with no slashes.
What can be done about this?
<VirtualHost *:80>
    ServerAdmin email@example.com
    DocumentRoot "/var/www/frg"
    ServerName www.futureretrogaming.com
    ServerAlias futureretrogaming.com
    ServerAlias futureretrogaming.net
    ServerAlias www.futureretrogaming.net
    ErrorLog "/var/www/frg/log/error.log"
    CustomLog "/var/www/frg/log/access.log" common
    <Directory /var/www/frg>
                DirectoryIndex index.html index.php
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
    </Directory>
    Redirect permanent / https://futureretrogaming.com/
</VirtualHost>

Answer: Try using mod_rewrite instead of a simple Redirect. First, make sure your Apache setup has mod_write enabled by running this command; this works for Ubuntu/Debian:
sudo a2enmod rewrite

Then restart Apache; again this works for Ubuntu/Debian:
sudo service apache2 restart

And your server should now be able to handle mod_write instructions. So adjust your virtual host config like so:
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    DocumentRoot "/var/www/frg"
    ServerName www.futureretrogaming.com

    ServerAlias futureretrogaming.com
    ServerAlias futureretrogaming.net
    ServerAlias www.futureretrogaming.net

    ErrorLog "/var/www/frg/log/error.log"
    CustomLog "/var/www/frg/log/access.log" common

    <Directory /var/www/frg>
        DirectoryIndex index.html index.php
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    // Redirect permanent / https://futureretrogaming.com/
    RewriteEngine on
    ReWriteCond %{SERVER_PORT} !^443$
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

</VirtualHost>

If you notice I commented out the Redirect you had in place & added some spacing for readability. And you can check this from the command line using curl -I like this:
curl -I http://futureretrogaming.com/forum

And the results I see right now show this working:
HTTP/1.1 302 Found
Date: Fri, 30 May 2014 02:03:46 GMT
Server: Apache/2.2.22 (Ubuntu)
Location: https://futureretrogaming.com/forum
Vary: Accept-Encoding
Content-Type: text/html; charset=iso-8859-1

Somewhat unrelated but since I am noticing it, you can also make your life a bit easier by consolidating & simplifying some of the ServerAlias stuff:
ServerAlias futureretrogaming.com
ServerAlias futureretrogaming.net
ServerAlias www.futureretrogaming.net

Instead of 3 lines that could be all consolidated into one line:
ServerAlias futureretrogaming.* www.futureretrogaming.*

The wildcard covers all top level domains such as .com, .net & even .org as well as others.
Comment: It says RewriteEngine is an invalid command
Comment: @Kyle Your server probably needs to have `mod_rewrite` enabled. Will update.
Comment: Thanks for the update, how do I enable mod_rewrite is that just a apt-get install deal?
Comment: @Kyle Nope. No need to run `apt-get unstall`. Please read my recent edit near the top of the answer. If you are on Ubuntu/Debian then simply run `sudo a2enmod rewrite` then run `sudo service apache2 restart` & you should be set for this configuration to work.
Comment: https://futureretrogaming.comforum/ is still what is happening
Comment: @Kyle This should work. Be sure you are not caching a browser response. Also, check from the terminal using: `curl -I http://futureretrogaming.com/forum`. I see it as working. Check my edit to see the output of `curl -I` as I am seeing it.
Comment: Naturally I don't have curl. Okay after clearing cache it does work. Wish I get my browser to stop doing that. Thanks for the help.
Comment: @Kyle Hey, all good. If you login to your Ubuntu server (I assume) you can run that `curl -I` from the command line as well to confirm. But glad it's all fixed now.


Interpolation method that gives the least arc lenght of the curve.

Question: this question may be a bit sloppy on my part but I will make it anyway, I recently have been fascinated by the idea that the surface of a soap bubble film restricted to a boundary will be so as to minimize surface area, and I have been thinking if there is no such equivalent thing for a curve in $\mathbb{R}^2$, by that i mean something like given a finite set of points, that will work as if they were the boundary of the tridimensional case, to find a curve that will minimize the arc length of the path.
I do realize that given that the smallest distance between two points is a straight line and because the curve has to pass trough a set of points, comparing the length of the sections of the possible curves in between two points and continuing two by two points until the last one, each time the straight line will win in least length, and so a linear interpolation will be the curve with least arc length, but given that linear interpolation will in the majority of cases produce a path that is non-differentiable on a given set of points, I then thought of limiting this curves by only differentiable ones, but I suspect that only differentiability is not enough to guarantee the existence of such a curve, for i can take the linear interpolation curve, let's call it $f(x)$ and pass it trough a "differentiability filter" such as :
$$\frac{1}{2\varepsilon}\int^{x+\varepsilon}_{x-\varepsilon}f(t)dt = g_{\varepsilon}(x)$$
and the function $g_\varepsilon(x)$ will be equal to the function $f(x)$ outside of open balls of radii $\varepsilon$ from the points of non-differentiability and as $\varepsilon$ can be made as small as wanted it probably means there is no lower bound inside the set of differentiable functions.
So instead of only requiring differentiability and a minimum arc length if it was request that the function be of class $C^\infty$ and have minimum arc length, would there exist a solution ? and if so, is there some type of interpolation that accomplishes just that ? or at least is there some type of interpolation that shares some type of link with the soap bubble film in tree dimensions so aforementioned, something like least curvature or other properties? because it feels as if it should exist!
Comment: You've made a very nice analysis of the differentiable case. Now notice that your filter is equivalent to convolving $f(x)$ with a box function $h(x)$ which is $1/(2\epsilon)$ when $|x|\le\epsilon$ and $0$ otherwise. If you replace $h$ with a Gaussian function of standard deviation $\epsilon$, then the filtered version of $f$ will be $C^\infty$.
Comment: Splines under tension might be relevant.
Answer: There are $C^{\infty}$ functions that approximate piecewise linear functions arbitrarily closely. For example,
$$\lim_{n\rightarrow\infty}\frac{\log(\exp(n x)+1)}{n}=\frac{x+|x|}{2}$$
Given a piecewise linear interpolation of your set of points (which has minimum arc length), it is thus possible to construct a $C^{\infty}$ function that approximates this piecewise linear interpolation arbitrarily closely, with corresponding arc length arbitrarily close to the minimum.
Answer: Perhaps what you are looking for is mean curvature flow (https://en.wikipedia.org/wiki/Mean_curvature_flow), which you can think of as a nonlinear filter for smoothing out curves. You can take your initial piecewise linear optimal path and evolve it under mean curvature flow for an arbitrarily short period of time $t>0$ and you will get a $C^\infty$ curve that is as close as you like (by making $t$ small) to the original curve, and necessarily has shorter length! This is also nice because the 3D version of mean curvature flow describes how a soap bubble moves into its equilibrium position.


Understanding Functions With Recurrence

Question: I'm having a heck of a time understanding what is being asked of me and every time I check my answer, I'm being told it's wrong but not understanding where and why.
Suppose f: N 7→ N satisfies the recurrence f(n + 1) = f(n) + 3. For each of the initial conditions below, find the value of f(5).

a) f(0) = 0
b) f(0) = 1
c) f(0) = 2
d) f(0) = 100

Now I think my issue is that my understanidng of functions is coming more from an algebra/calculus understanding so I'm thinking that inputs should match outputs. But this is wrong.
Here is the work I tried to understand recurrence.
a) F(0) = 0

 F(0 + 1) = f(1) + 3 = 4
   F(1+ 1) = f(2) + 3 = 5
   F( 2 + 1) = f(3) + 3 = 6
    F( 3 + 1) = f(4) + 3 = 7
    F( 4 + 1) = f(5) + 3 = 8

    b)  F(0) = 1

    F(1 + 1) = F(2) + 3
    F(2 + 3) = F(5) + 3
    F(5 + 3) = F(8) + 3
    F(8 + 3) = F(11) + 3
    F(11+3) = F(14) + 3

    c)  F(0) = 2
    F(2 + 1)  = F (3) + 3
    F(6 + 1) = F ( 7) + 3
    F( 10 + 1) = F(11) + 3
    F(14 + 1) = F(15) + 3
    F(18 + 1) = F(18) + 3

    d)  F(0) = 100
    F(100 + 1) = f(101) + 3 = 104
    F(104 + 1) = f(104) + 3 = 107
    F(107 + 1) = f(108) + 3 = 111
    F(111 + 1) = f(112) + 3  = 115
    F(115 + 1) = f(115) + 3 = 118

My answer is wrong but I'm not understanding or misinterpreting the problem.
Answer: You've made a notation error when you write, for example, $f(0+1) = f(1) + 3$. The recursion statement $f(n + 1) = f(n) + 3$ means that for any fixed value of $n$, the evaluation of $f$ at $n+1$ is equal to the evaluation of $f$ at $n$, plus 3 - that is, you should be replacing $n$ with the same thing on both sides, which looks something like this:
$\begin{array}{lrcl}
n = 0: & f(0 + 1) & = & f(0) + 3 \\
& f(1) & = & 0 + 3 \\
& & = & 3 \\
n = 1: & f(1 + 1) & = & f(1) + 3 \\
& f(2) & = & 3 + 3 \\
& & = & 6 \\
n = m + 1: & f(m + 1 + 1) & = & f(m + 1) + 3 \\
& f(m + 2) & = & (f(m) + 3) + 3 \\
& & = & f(m) + 6\end{array}$
They're still functions - there's still an input and an output, but we're describing the output at one value in terms of the output of another. Compare that to, for example, $f(x + 2\pi) = f(x)$, which is a recurrence relation that holds true for $f(x) = \sin x$, among other functions, and which you can check the truth of by looking at various values of $x$ (e.g. $\sin 2\pi = \sin 0$, $\sin (2 \pi + \frac{1}{2}) = \sin \frac{1}{2}$).

Understanding Functions With Recurrence


How to properly build a SGDClassifier with both text and numerical data using FeatureUnion and Pipeline?

Question: I have a features DF that looks like

text
number

text1
0

text2
1

...
...

where the number column is binary and the text column contains texts with ~2k characters in each row. The targets DF contains three classes.
def get_numeric_data(x):
    return [x.number.values]
def get_text_data(x):
    return [record for record in x.text.values]
transfomer_numeric = FunctionTransformer(get_numeric_data)
transformer_text = FunctionTransformer(get_text_data)

and when trying to fit, code below, I get the error File "C:\fakepath\scipy\sparse\construct.py", line 588, in bmat raise ValueError(msg) ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 98, expected 1.. I tried to build functions get_text_data and get_numerical_data in different ways but none helped.
combined_clf = Pipeline([
    ('features', FeatureUnion([
        ('numeric_features', Pipeline([
            ('selector', transfomer_numeric)
        ])),
        ('text_features', Pipeline([
            ('selector', transformer_text),
            ('vect', vect),
            ('tfidf', tfidf),
            ('scaler', scl),
        ]))
    ])),
    ('clf', SGDClassifier(random_state=42,
                          max_iter=int(10 ** 6 / len(X_train)), shuffle=True))
])
gs_clf = GridSearchCV(combined_clf, parameters, cv=5,n_jobs=-1)
gs_clf.fit(X_train, y_train)

Comment: `ColumnTransformer` is probably the better approach here.  If you want to debug the `FeatureUnion`, please provide the full error traceback.
Answer: The main problem is the way you are returning the numeric values. x.number.values will return an array of shape (n_samples,) which the FeatureUnion object will try to combine with the result of the transformation of the text features later on. In your case, the dimension of the transformed text features is (n_samples, 98) which cannot be combined with the vector you get for the numeric features.
An easy fix would be to reshape the vector into a 2d array with dimensions (n_samples, 1) like the following:
def get_numeric_data(x):
    return x.number.values.reshape(-1, 1)

Note that I removed the brackets surrounding the expression, as they unnecessarily wrapped the result in a list.

While the above will make your code run, there are still a couple of things about your code that are not quite efficient and can be improved.
First is the expression [record for record in x.text.values] which is redundant, as x.text.values would already be enough. The only difference is that the former is a list object, whereas the latter is a numpy ndarray which is usually preferred.
Second is what Ben Reiniger already stated in his comment. FeatureUnion is meant to perform several transformations on the same data and combine the results into a single object. However, it appears that you simply want to transform the text features separately from your numeric ones. In this case, the ColumnTransformer offers a much simpler and canonical way:
combined_clf = Pipeline([
    ('transformer', ColumnTransformer([
        ('vectorizer', Pipeline([
            ('vect', vect),
            ('tfidf', tfidf),
            ('scaler', scl)
        ]), 'text')
    ], remainder='passthrough')),
    ('clf', SGDClassifier(random_state=42, max_iter=int(10 ** 6 / len(X_train)), shuffle=True))
])

What happens above is that ColumnTransformer only selects the text column and passes it to the pipeline of transformations, and will eventually merge it with the numeric column that was just passed through. Note that it becomes obsolete to define your own selectors as ColumnTransformer will take care of that by specifying the columns to be transformed by each transformer. See the documentation for more information.
Comment: Not sure which scenario 'similar fashion' is referring to. But in general, if you just want to apply different transformations to each column, you should go for `ColumnTransformer`. `FeatureUnion` is used if you want to concatenate results of multiple transformer objects on the same columns or data. An example for the latter is if you have a numeric feature `x1` in your original dataset and you want to have two new features in your final dataset, `scaled_x1` and `squared_x1`. They are based on the same feature but are now two separate results which you want to keep both.
Comment: Wow, thanks! Just for to understand more, if I were to do some transformations on `number` column I should use `FeatureUnion` in a similar fashion?


PHP - Problems creating an image containg text

Question: I'm trying to create an image containing text.
I've tried several examples I've found on the web, among them are:
http://php.net/manual/en/function.imagettftext.php
http://www.daftlogic.com/projects-text-to-image.htm
http://www.phpro.org/examples/Text-to-Image-with-GD.html
but I've tried others.
Let's take the one from daftlogic.com - http://www.daftlogic.com/projects-text-to-image.htm
I'm not using the large, main example on that page, but rather the short test shown, about 1/3 of the way down the page, after the line of text that reads:
"(1) Please test this example to ensure imagecreate works on your server..."
Search for that text and you'll find the code I'm testing.
I have tried the main example and it has failed with almost the same results.
I added the GD support test, just to see if it was really there. The error is not triggered - and phpinfo() run on the server shows GD support.
The PHP code: is
<?php
error_reporting(E_ALL);
// check for GD support if(!function_exists('ImageCreate')) {
fatal_error('Error: Server does not support PHP image generation') ;
}
header("Content-type: image/png");
$im = @imagecreate(110, 20)
   or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

I have that code in a file named daftlogic.php in a directory named PHP which is right off my testing root on my server. I tried this on the copy of Abyss server I have installed on my system for PHP and other testing but the GD library is not included in the PHP installed for Abyss and if I ever get this working on the server (which does have GD) I'll go figure out how to include GD support on my system.
Okay -
Here's the directory structure:
\testing -
      \phpmodules
      \rootfolder

"testing" is a directory below the root directory for my real world site on this sever.
Basically I've emulating the structure of the actual web site directories and "testing" takes the place of the "httpdoc" directory which is not real world accessible.
"phpmodules" contains the files containing PHP code, no HTML, just PHP.
"rootfolder" is where the "pages" are, the HTML pages with extensions like HTML, SHTML, and PHP.
In my actual web site, there is a comparable directory which is the "root" directory and nothing above that, such as the directory in which I put the PHP code, is visible to the world.
daftlogic.php is in \testing\PHP
A file named "testinanotherone.php" is in \testing\rootfolder
The contents of that file are:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Try yet another sample</title>

<?php include("../phpmodules/daftlogic.php"); php?>

BY THE WAY - the directory structure is as I have shown you but the directory names have been changed to protect the .. well, I don't want any links to my actual test directories escaping the lab - that is, I don't want there to be links to my test directories.
If I use Firefox (3.6.24) to view the file testinanotherone.php, all that is displayed is an error message from Firefox which reads:

The image "http://bobnovell.com/testing/rootfolder/testanotherone.php'
  can't be displayed because it contains errors.

Now, the interesting thing is that there is no page source - if I right click on the page, and the "View Page Source" menu item grayed out.
If I right click on the message, the contextual menu I get is that for an image file. If I then select "View Image Info" I get:
Under "General"
testanotherone.php (PNG Image):
Address:   http://www.bobnovell.com/testing/rootfolder/testanotherone.php (again, I've modified that to conceal the real directory names)
Type:  image/png
Render Mode: Quirks mode
Encoding: ISO-8859-1
Size: 0.42 KB (433 bytes)
Modified: Monday, April 02, 2012 10:35:17 PM
Under "Media"
Location: http://www.bobnovell.com/testing/rootfolder/testanotherone.php (again, I've modified that to conceal the real directory names)
Type: Image
Size: 0.42 KB (433 bytes
Dimensions: 0px × 0px (scaled to 740px × 19px)
I'll skip "Permissions" and "Security"

This what I.E. shows when I view the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

‰PNG

IHDRnV,šPLTEé[an÷fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0—
œi
<n+²
Já-8Û4˜B8ÕAŠ»ñp¼Q'Uγ…v@¯×Ò¥kAIEND®B`'

The "View Source" menu item IS available and the source is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

PNG

Now - since Firefox was reporting errors in the image, I decided to comment out the header statement in daftlogic.php and see what I could see.
In Firefox I get:
‰PNG  ��� IHDR���n������V,š���PLTE���é[an÷���fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0— œi

In I.E. I get:
‰PNG  IHDRnV,šPLTEé[an÷fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0— œi

The source in Firefox (with the header statement commented out in the code) is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

‰PNG

���
IHDR���n������V,š���PLTE���é[an÷���fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0—
œi

The source in I.E. (without the header statement) is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

PNG

Which is, as far as I can tell, the same source shown when the header statemnt is in the code.
Does anyone have any idea how to make this work?
The only thing I'm wondering about is that I've see references to a package name FreeImage that is used in some of the samples I've found.
I don't think it comes into play with the code I'm trying but hey, you never know.
I began this trip through Wonderland because I want to add some math tests to pages instead of CAPTCHAs (as the OCR software gets better, the CAPTCHAs are being made harder and harder and I find I have trouble with them myself and I don't want to lose user input because the CAPTCHA stumps them) and I wanted to show the equation using an image.
I'm about ready to drop back and punt and manually make up a bunch of small images containing single digits and then "paste" them together to make the equation I want the user to solve.
I've wasted enough time spinning my wheels on this that I could have had single digit images (and plus, minus, division, and multiplication signs) finished by now and probably most of the code to stitch them together.
Any one have any suggestions to get this code (or any such example) to actually work for me.
Any assistance will be GREATLY appreciated.
Bob
_______________ Edited 2012-04-03 2334 CST
It does not matter whether I have a header statement, to define the type of the contents, or not - The image is displayed.
Here's the code I'm now using:
<?php

if(!function_exists('imagettftext')) {
    fatal_error('Error: Server does not support PHP image generation') ;
}
// from php.net/manual/en/function.imagejpeg.php
// Create a blank image and add some text and send to browser
$im = imagecreatetruecolor(200, 60);
//$text_color = imagecolorallocate($im, 233, 14, 91);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 200, 60, $white);
imagestring($im, 5, 5, 5,  'A Simple Text String without header', $black);

// Set the content type header - in this case image/jpeg
//header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);
?>

Here is the HTML which invokes it:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Test Create JPG</title>

Here's the source displayed by Firefox:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Test Create JPG</title>

If I un-comment the header statement, I get the same output as when it is commented out:
Here's the source with the header un-commented and the text changed:
<?php

if(!function_exists('imagettftext')) {
    fatal_error('Error: Server does not support PHP image generation') ;
}
// from php.net/manual/en/function.imagejpeg.php
// Create a blank image and add some text and send to browser
$im = imagecreatetruecolor(200, 60);
//$text_color = imagecolorallocate($im, 233, 14, 91);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 200, 60, $white);
imagestring($im, 5, 5, 5,  'A Simple Text String with header', $black);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);

I use the same HTML file to invoke and the source is the same.
I get the same results with I.E. 8
I have double and triple, quadrupole checked - actually I've lost count of how many times I've tested with and without the header statement - the results are the same.
The image is displayed regardless of whether not I have a header statement or not.
Any thoughts on this?
Answer: daftlogic.php directly outputs png image. So you need to put this in an img tag.

Here /web/path/to/daftlogic.php means the browser accessible path of daftlogic.php.
Note:

Width and height is necessary to prevent the browser from rendering the page again after loading the image to fix the image layout.
Always use meaningful alt tag. This tag is mandatoryspec

It does not matter whether I have a header statement, to define the type of the contents, or not - The image is displayed.

For the update part of your question
As long as you are putting the source in an image tag, no matter what the Content-type it sends browser will try to render it as an image. If you put a html file as src in an image tag, browser will treat it as a damaged image. It also preserves the space but doesn't display it.

But image content type has advantage. If you directly load an image browser will obey the content type. Load daftlogic.php in browser. If you used content-type browser will show according to to content type. Otherwise browser will show it as text/html which is default content type of PHP.
Comment: @BobN please mark this as accepted by clicking the tick mark.  This will help people who come here in the future to take it as a solved problem.
Comment: Ah - shiplu, your suggestion gets the image displayed but I just ran into something that is a bit strange. If I take the header statement out of the PHP code , the results are the same as having it  present. This makes me think that there is perhaps another way to "skin this cat."
Comment: I see the image regardless of whether the header statement is present or not.
Comment: Go look at my posting, I'll edit it to put in more detail for you about this header "thing."
Comment: Got it - thanks. Far better to explicitly state things that to assume a browser, or any other software - including compilers - will do what you think they will do. Whenever the option exists, particularly in languages, I always turn on the explicit required option. Saves a lot of headaches. I've been at this for 34+ years and have done quite a bit of teaching on programming languages and proper philosophies of programming. Again, thanks for the help. Should you ever find yourself in need of advice on treating a diabetic cat - don't hesitate to holler :-) see - wwww.sugarcatsimon.com
Comment: I'm sorry, I don't know what the "tick mark" is - what and where is it? Do you meant the upward pointing arrow which shows the left when I hover of the comment?
Comment: I did a bit more testing using a header statement and not using one. Found that without a header, "View Image" in the browser right click menu does not display an image - it displays the file as though it was text. With a header, "View Image" shows you the image - that goes with what you said about browsers trying to determine the type of file according to where it is referenced. An image without a header referenced in an <img tag will be display as an image but if you tell the browser to display it "stand alone" it has to have a header to work properly.


How to remove one extension by asterisk CLI

Question: How to remove one extension by asterisk CLI?
I try the command:
remove extension 300809@from-internal

return
failed to remove extension 300809@from-internal

The extension existed , I could use the command to show it :
sip show user   300809

return
* Name       : 300809

Secret       : <Set>
  MD5Secret    : <Not set>
  Context      : from-internal
  Language     :
  AMA flags    : Unknown
  CallingPres  : Presentation Allowed, Not Screened
  Call limit   : 0
  Callgroup    :
  Pickupgroup  :
  Callerid     : "device" <300809>
  ACL          : No
  Codec Order  : (ulaw|alaw)

Answer: 300809@from-internal is not an extension. most likely it is the user id.
At least in asterisk terminology an extension would be in the dialplan it would look like this [some_extension]. the filename is:
/etc/asterisk/extensions.conf

Comment: Thanks ,I could not find the 300809 in /etc/asterisk/extensions.conf. The '300809' is added in http://X.X.X.X/admin/config.php?type=setup&display=extensions and select  Generic sip  Device to create the extension. Now I only want to delete the extension. Do you know how to remove it?
Comment: there is no such commands, just edit the config file directly


Difference between "Redirect permanent" vs. mod_rewrite RewriteRule

Question: This is an Apache httpd 2.2 server.
We require that access to this webserver be encrypted by HTTPS.
When web clients visit my site at http://www.example.org/$foo (port 80), I want to redirect their request to the HTTPS encrypted website at https://www.example.org/$foo .
There seem to be two common ways to do this:
First method uses the 'Redirect' directive from mod_alias:
<VirtualHost *:80>
    Redirect permanent / https://www.example.org/
</VirtualHost>

Second method uses mod_rewrite:
<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

What is the difference between a "Redirect permanent" and the mod_rewrite stanza. Is one better then the other?
Answer: By default mod_rewrite does "302 Found" redirects, which are temporary. Assuming everything else is equal, Redirect permanent is equivalent to RewriteRule <blah> [R=permanent].
Comment: Actually no, `Redirect` directive handles redirect from http to https better. See Stefan's comment below and check this section of Apache documentation: http://httpd.apache.org/docs/current/rewrite/avoid.html#redirect
Answer:
Is one better then the other?

Apache now recommends the use of Redirect from mod_alias instead of using RewriteRule from mod_rewrite. See https://httpd.apache.org/docs/current/rewrite/avoid.html#redirect , which says:

mod_rewrite should be considered a last resort, when other alternatives are found wanting. Using it when there are simpler alternatives leads to configurations which are confusing, fragile, and hard to maintain.
Answer: Search engines will see a permanent redirect and update their indexes accordingly.
Comment: > Is one better then the other?


Append string in another string

Question: I have a string a="
i'm working in C#
 abcdefghjiklmnopqr ii oo yy uu hh gg rr", and b="Finish
". I need string a as
  a="
i'm working in C#
 Finish
 abcdefghjiklmnopqr ii oo yy uu hh gg rr".

How do we append string in string like above? I asked a same question earlier which was wrong.
Here will have to find for first ">" character and append b in a.
Comment: _"have to find for first > and append b"_ But your desired result appended b at ` ` so after the second `>`. Apart from that, use `HtmlAgilityPack` to parse or create html dynamically.
Comment: Use indexOf() and insert() methods (http://msdn.microsoft.com/en-us/library/k8b1470s.aspx, http://msdn.microsoft.com/en-us/library/system.string.insert.aspx).
Comment: "insert", not "append".
Answer: int i = 0;
while(i ",i)) != -1){
   a = a.Insert(i+2,b);
   i += b.Length;
}

Comment: This just mimics `a.Replace("/>", "/>" + b)`. Why is this being done manually?
Comment: @MikePrecup I miss the while loop, in fact this question is so trivial
Answer: I suppose you could do this with indexOf and substrings
var a="
i'm working in C#
abcdefghjiklmnopqr ii oo yy uu hh gg rr";
var b="Finish
";

var insertPoint = a.IndexOf("
")+5;
var c = a.Substring(0,insertPoint) + b + a.Substring(insertPoint);

But really if you're trying to do html generation with string concatenation, this will be a nightmare. Try using Razor, or any other templating language.
Answer: use insert to append a string at a specific location.
String findText = @"
";
String a = @"
i'm working in C#
 abcdefghjiklmnopqr ii oo yy uu hh gg rr";
String b = @"Finish
";
int appendLocation = a.IndexOf(findText) + findText.Length;
String c = a.Insert(appendLocation, b);
MessageBox.Show(c);

Append string in another string