text:
Q: DotNet Core Custom Authorize Attribute using Route Params I googled this and nothing was found, so I would like to know from those who use DotNet Core for a longer time than myself.
I am now to DotNet core. I am currently creating an App just for the sake of practicing. I noticed that in most of my Apis' Actions, I am verifying the passed in UserId against claims NameIdentifier (that is the logged in user id).
I am doing like so:
        if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
        {
            return Unauthorized();
        }

But now thinking, it is getting a bit too repetitive. Is there a way of using an Attribute instead?
Something like:
    [AuthorizeUser(UserId = userid)]
    [HttpGet]
    public async Task<IActionResult> GetSomething(int userId)
    {
            //Custom code ...
    }

And then create my Authorize Attribute:
public class AuthorizeUser : AuthorizeAttribute, IAuthorizationFilter
{
    public AuthorizeUser(params string[] args)
    {
        Args = args;
    }

    public string[] Args { get; }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //Custom code ...
    }
}

This way I would check for the user id passed in the "api/user/{userId}" in a single place for all my Actions.
Or there is another way of making my code look nicer and with less copy and paste?
Thank you in advance.

A: I was able to solve my problem by doing the following:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class UserAuthorizationAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // Here I can get userId from my params.
        var userId = context.RouteData.Values["userId"].ToString();

        // It is then being checked against current user claims.
        // The user is only authorized if the userId is equals to ClaimsType.Value and claims Type is equals to NameIdentifier.
        var isUserAuthorized = context.HttpContext.User.Claims.Any(c => c.Type == ClaimTypes.NameIdentifier && c.Value == userId);

        if (!isUserAuthorized)
        {
            context.Result = new UnauthorizedResult();
        }
    }
}


text:
Q: regex quandry with replacing in sublime text I'm finally getting comfortable enough with regex that I use it in my everyday work. It saves me a ton of time, and I get exactly what I type. The problem lies in that sometimes, I have no idea what I typed or why it works that way.
I'm working with using round brackets for grouping, which is incredibly useful when sorting through lists, dumps, yardwork, etc. But I've hit something basic that I don't understand
say i have a simple query that looks for a specific group of characters individually for instance:
([a-z])

this does exactly what I need it to. Now if I need to split up the result into one line per character I'm using:
\1\n

This also works wonders. Simple yet effective. But now comes my quandry. How do I add a one directly after each character?
i.e.
Input:
john

Output:
j1
o1
h1
n1

I've attempted using:
\1 1\n #gives me a space
\11\n  #gives me newlines with a "1" on each line.

And the really interesting one:
(\1)1\n

which outputs:
()1
()1
()1
()1
()1

How do I accomplish this?

A: I think the keyword to search for is "named capturing groups" for backreferences. http://www.regular-expressions.info/named.html
They probably only do \0 thru \9 for the exact use case you're describing.

A: And I answered my own question
\11\n

does give me the desired result. But why? Shouldn't \11 backreference #11?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I implement OpenSSL's EC_POINT_set_compressed_coordinates_GFp in Bouncy Castle? I need a little assistance porting the OpenSSL function  EC_POINT_set_compressed_coordinates_GFp in C# or Java
.
Though I can use Bouncy Castle (preferred), I am open to building it from scratch.
The C++ method signature looks like this:
int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group, EC_POINT *p,
   const BIGNUM *x, int y_bit, BN_CTX *ctx);

From OpenSSL:

Points can also be described in terms of their compressed co-ordinates. For a point (x, y), for any given value for x such that the point is on the curve there will only ever be two possible values for y. Therefore a point can be set using the EC_POINT_set_compressed_coordinates_GFp and EC_POINT_set_compressed_coordinates_GF2m functions where x is the x co-ordinate and y_bit is a value 0 or 1 to identify which of the two possible values for y should be used.

Can anyone assist in the math needed?  I'm having trouble understanding the source and want to make sure I port it over correctly

A: The purpose of this function is to setup a point P using the provided x coordinate and y_bit.  You can look on [x-coordinate,y_bit] as a compressed form of (x-coordinate,y-coordinate); both of them represent point P.
In Weierstrass equation (GFp)
y^2 = x^3 + a*x + b,

suppose y is in its modulo form (0 <= y < p), then y_bit is the LSB of y. As you can see, y is one of the square roots of  x^3 + a*x + b. And it can be proven that each root has different y_bit. This is why you can use y_bit to determine which y (root) should be used.
Take ec_GFp_simple_set_compressed_coordinates in ecp_oct.c(OpenSSL-1.0.1e) for example, here's what it does:

*

*Calculate x^3 + a*x + b

*Calculate y, the square root of x^3 + a*x + b

*Compare y_bit with LSB of y. If different, y = -y (mod p)

*Set affine coordinate (x,y) to point P


text:
Q: Laravel: attach multiple PDFs to email Following is a code to send a PDF with email:
        $pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');

        Mail::send('emails.mail', $data, function($message) use ($data,$pdf){
            $message->from('noreply@...');
            $message->to('...');
            $message->subject('test test');
            //Attach PDF doc
            $message->attachData($pdf->output(),'invoice.pdf');
        });

But my requirement is to send multiple PDFs with email, how can I do this?

A: $attachments = [
    // first attachment
    '/path/to/file1',

    // second attachment
    '/path/to/file2',
    ...
];

    $pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');

    Mail::send('emails.mail', $data, function($message) use ($data,$pdf){
        $message->from('noreply@...');
        $message->to('...');
        $message->subject('test test');
        //Attach PDF doc

        foreach($attachments as $filePath){
              $message->attach($filePath);
        }
    });

A: taibur rahman provides an answer in comment, new PDFs variables must be added in "use", then code will be correct.
Complete Code:
        $pdf = PDF::loadHTML($str_html)->setPaper('a4', 'portrait');

        $pdf2 = PDF::loadHTML($str_html2)->setPaper('a4', 'portrait');

        Mail::send('emails.mail', $data, function($message) use ($data, $pdf, $pdf2){
            $message->from('...@...');
            $message->to(...@...);
            $message->subject('test test');
            $message->attachData($pdf->output(),'test.pdf');
            $message->attachData($pdf2->output(),'test2.pdf');

        });


text:
Q: Adding files to /usr/local/include I recently installed openjtalk on a linux machine, and I want to be able to wrap it in Go. The source files for openjtalk have several subfolders with different sources, which I assume are found by the compiler because of the make files.
Should I copy each of those sub-folders into /usr/local/include? Is that a "correct" way of fixing include dependencies. From what I tested, Go seems to find the included files if I copy them, but I'm not sure if this is the correct, linux way of doing things.

A: It's usually not a good idea to change locations of external libraries. Some libraries automatically put themselves in include paths of compilers but for those that don't, adding their paths to the compilers' include paths is always a better idea.
For example, in gcc, you can gcc -I/your/header/directory to include your directory. Usually people put those info in the Makefile. This way, you can put external libraries' source code in your repository and just tell compiler to also look for the headers there. This way, when setting up a new working environment, all you have to do is pull from the repository.


text:
Q: Can I open and make a popup run javascript on parent/host page? I'm developing some sort of a Javascript SDK that will open a popup of a page of mine. So everyone can call this javascript function and it will open a pop with my page, on my server. So host and popup are on different servers.
When the user do some things on my page (on popup), I need to use functions that are on the SDK on the host.
Is it possible to do this kind of thing? Or is it forbidden by default because it's too dangerous or could be an attack or something like that?

A: I think it may be possible using
easyXDM.


text:
Q: How do I center this logo using CSS? I have a site here: http://donniewalker.com/jen/
That I've been trying to center with CSS, but nothing I've tried seems to work.
Any help would be appreciated.

A: You need to remove float: left; and all margins from .header-v5 #header .logo and add margin: 31px auto;. So it looks like this:
.header-v5 #header .logo {
   margin: 31px auto;
}

A: In your div of class logo get rid of where you have
margin-top: 31px;, margin-right: 0px, margin-bottom: 31px;, margin-left: 0px;

and add
margin: 31px auto 31px;

also, you need to remove the float: left that is applied to .header-v5 #header .logo


text:
Q: Linq - How to put common fields in a base class I am trying to find a way so that I can push some common functionality into a base class for my Linq to SQL processing.  I have two fields (ID and InsertUpdateOperID) that are common to most but not all of my tables.   In my first go around I created a class called BaseEntity that had these fields.  Unfortunately all I accomplished was hiding from the values in the .designer.cs file.   I found an example of how to accomplish what I wanted In order to get around this (http://www.joe-stevens.com/2009/07/01/linq-to-sql-set-inheritance-modifiers-with-sqlmetal/).  As per this article, I modifed the DBML file so that I could add the override modifier to the ID and InsertUpdateOperID properties on the tables that contained these two fields.
The net result of this was that the .designer.cs file added the override qualifier where I wanted it. This enabled me to create my BaseEntity class. Where I defined the ID field and the InsertUpdateOperID field as:
public virtual int ID                 { get; set; }
public virtual int InsertUpdateOperID { get; set; }

Doing this seemed to work fine.
The problem for me is that I hate the idea of modifying generated code.  Can anyone suggest a way for me to put common fields and methods that act on those common fields in a base class so that I could accomplish what I want without modifying the generated .dbml?
Thanks

A: I'm facing the same problem today (wow, it's 1.5 years after your post), and struggled out a solution, so far it's good for me.
in the base class:
    public virtual int __ID
    {
        get
        {
            PropertyInfo pi = this.GetType().GetProperty("ID");
            int id = (int)pi.GetValue(this, new object[] {});
            return id;
        }
        set
        {
            PropertyInfo pi = this.GetType().GetProperty("ID");
            pi.SetValue(this, value, new object[] { });
        }
    }

This looks quite voilent, but it works!
Notice the __ before ID, because there is alread ID and _ID in the auto generated codes. As it's totally a new third way to access ID, no "override" is needed.
And if you need, you can use the __ID in or via your base class.


text:
Q: How to trigger the click event of a Bootgrid command button I'm using Bootgrid with command buttons, and if there is only one row in the grid (I can determine if there's only one row from the data in php) then I want to trigger the command button click event. The command button has a class called "command-view". I've tried the following:
$(".command-view").click();

$("#grid .command-view").click();

A: A more conventional approach would be to use the built-in BootGrid click handler (which is essentially row based as you can see below), then deal with the clicks after that.
This is how BootGrid expects you to work, and also means you don't need to put a separate event handler on each row.
  .on('click.rs.jquery.bootgrid', function (e, cols, row, target) {
     if (typeof row != "undefined")    // Only rows, not headers
     {
         // You will get control here when anything in the row is clicked.
         // In your case just filter for your target and you're done.
     }

A: You must do like:
var grid = $("#your_grid").bootgrid({
    formatters: {
        "commands": function(column, row)
         {
            return '<button class="command-select"data-row-id='+ row.id +'></button>';
         }
    }
    }).on("loaded.rs.jquery.bootgrid", function () {
        grid.find(".command-select").on("click", function (e) {
            var id = $(this).data("row-id");
            console.log(e)
            console.log(id);
        });
    });

Pay attention that grid.find refers to the grid variable, created on first line.


text:
Q: Finding distribution of parameter for exponential distribution I came across this question:

Given a sample of 50 values all coming from an exponential distribution where $f(x)=\theta x^{-x/\theta}$, find the MLE for theta. Then, find the 95% confidence interval for $\theta$.

My question is can I assume theta is normally distributed as n>30 so the CLT applies and then how do I find the expected value and variance of theta to then get the standard error of the interval
Thanks!

A: Assuming that you are dealing with the following density
$$f_X(x)=\frac{1}{\theta}e^{-\frac{x}{\theta}}$$
with mean $\mu=\theta$ and variance $\sigma^2=\theta^2$, $x\geq 0$
...easy find that $\hat{\theta}_{ML}=\overline{X}_{50}$ and remembering that the sample mean has the following asympthotic distribution
$$\overline{X}_{50}\dot{\sim} N(\theta;\frac{\theta^2}{50})$$
Thus to find you 95% approx CI you have only to solve in $\theta$ the following double inequality
$$ \bbox[5px,border:2px solid red]
{
-1.96<\frac{\overline{X}_{50}-\theta}{\overline{X}_{50}}\sqrt{50}<1.96
\qquad   (1)
}
$$
... having estimated Sample mean's Standard deviation with $\frac{\overline{X}_{50}}{\sqrt{50}}$

On the contrary, if you are dealing with $f_X(x)=\theta e^{-\theta x}$ follow the same brainstorming modifying the forumlas I showed, accordingly
$$ \bbox[5px,border:2px solid red]
{
-1.96<\frac{\overline{X}_{50}-\frac{1}{\theta}}{\overline{X}_{50}}\sqrt{50}<1.96
\qquad   (2)
}
$$

Personal opinion: even if the sample is large enough, I think it is easier to find the exact Confidence interval, using the $\chi^2$ distribution instead of having a Gaussian approx


text:
Q: bond slave interfaces not getting the same aggregator id on LACP I have a bug on some servers where LACP (802.3ad) is not working.
I have on all servers a bonding device bond0 with two eth slaves and each interface is plugged on a different swich, and both switches configured with LACP.
Everything seems to be ok, but a network engineer detected some MLAG (Arista LACP implementation) was not working while the physical devices were up.
When I looked to /proc/net/bonding/bond0 of affected servers, I found each interface has a different Aggregator ID. On nominal servers the Aggregator ID is the same.
The issue can be reproduced by switching off and on the port on the switch, then we can observe despite physical link is up, MLAG is down. The bug is present on RHEL 6 and 7 (but not all servers are affected).
Configuration
#/etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
MACADDR=14:02:ec:44:e9:80
IPADDR=xxx.xxx.xxx.xxx
NETMASK=xxx.xxx.xxx.xxx
BONDING_OPTS="mode=802.3ad lacp_rate=slow xmit_hash_policy=layer3+4"
BOOTPROTO=none
ONBOOT=yes
USERCTL=no
NM_CONTROLLED=no
PEERDNS=no

# /etc/sysconfig/network-scripts/ifcfg-eno49 (same for other interface)
HWADDR=14:02:ec:44:e9:80
MASTER=bond0
SLAVE=yes
BOOTPROTO=none
ONBOOT=yes
USERCTL=no
NM_CONTROLLED=no
PEERDNS=no

We have a workaround now - set down and up eth interface on server - but this is not ideal.
To check LACP protocol, I did
tcpdump -i eno49 -tt -vv -nnn ether host 01:80:c2:00:00:02

I can see a packet every 30 seconds on one interface but on the other I see a packet every 1 second as is it was trying to establish LACP session.
Do you have a way to troubleshoot and fix that ?
(sorry if I did not use the right term for network I'm not really skilled in LACP)
Thanks

A: After digging into some documentation and some testing, I found out when a server is using bonding you need to force monitor the network links using the miimon parameter from the bonding module.
While looking at /proc/net/bonding/bond0 I should have seen one of the device has the MII status down where actually it was up on the link level.
https://access.redhat.com/articles/172483#Link_Monitoring_Modes states that:

It is critical that a link monitoring mode, either the miimon or arp_interval and arp_ip_target parameters be specified. Configuring a bond without a link monitoring mode is not a valid use of the bonding driver

So to report that in ifcfg-bond0 file you pass that in the BONDING_OPTS options
#/etc/sysconfig/network-scripts/ifcfg-bond0
...
BONDING_OPTS="mode=802.3ad lacp_rate=slow xmit_hash_policy=layer2+2 miimon=100"
...

so it forces to poll the links every 100ms.
Restart the network service to apply the change.


text:
Q: PayPal Permissions API GetAccessToken API call not working Error back from API call is below:
{error(0).message=Internal+Error, error(0).errorId=520002, error(0).subdomain=Application, error(0).category=Application, responseEnvelope.correlationId=46cac792dc1a4, error(0).domain=PLATFORM, responseEnvelope.ack=Failure, error(0).severity=Error}

How do I even debug this? Nothing in the error to help me debug this, everything seems fine code is all against a sandbox and nothing seems suspicious. Any suggestion on debugging this would be great!
Thanks

A: PayPal needs a better documentation.

A: Please post the code, so that it will help me/others to understand where the problem lies..
Make sure you are using the correct URL.
For Sandbox, the GetAccessToken URL is https://svcs.sandbox.paypal.com/Permissions/GetAccessToken
The following parameters need to passed while making the call to 'GetAccessToken' URL

*

*requestEnvelope.errorLanguage

*token (request token)

*verifier(verification code)


text:
Q: Real Analysis Limits Question Currently preparing for a first course in analysis exam and my answer disagrees with the model solutions but I can't see where my logic fails
The question:
Find the limit of:
$$a_n :=\frac{2^{3n}-n3^n}{n^{1729}+8^n}$$
My attempt:
First rewrite $8^n$ as $2^{3n}$
and divide through by $2^{3n}$
This gives us
$$= \frac{1-n\left(\frac{3}{8}\right)^n}{\large \frac{n^{1729}}{2^{3n}}+1}$$
and then divide through by $n$ to give
$$= \frac{\frac{1}{n}-\left(\frac{3}{8}\right)^n}{\large \frac{n^{1728}}{2^{3n}}+\frac{1}{n}}$$
My answer is zero using the following limits:
$\lim_{n\to\infty}\frac{1}{n} = 0$
and since $\frac{3}{8} <1$ $\implies\lim_{n\to\infty}\frac{3}{8}^n = 0$
The model solutions however suggest the limit is $1$, any help would be amazing.

A: The expression $$\frac{\frac{1}{n}-(\frac{3}{8})^n}{\frac{n^{1728}}{2^{3n}}+\frac{1}{n}}$$ cannot immediatelly be used to find the limit. Sure, the numerator tends to $0$, but the denominator does too.
In fact, you should have stopped when you got to $$\frac{1-n(\frac{3}{8})^n}{\frac{n^{1729}}{2^{3n}}+1}$$
where you should notice that both the denominator and the numerator tend to $1$.

A:
and then divide through by $n$ to give
$$= \frac{\frac{1}{n}-(\frac{3}{8})^n}{\frac{n^{1728}}{2^{3n}}+\frac{1}{n}}$$
My answer is zero using the following limits:
$\lim_{n\to\infty}\frac{1}{n} = 0$
and since $\frac{3}{8} <1$ $\implies\lim_{n\to\infty}\frac{3}{8}^n = 0$

But not only the numerator tends to zero, the denominator does too...! That would leave you with an indeterminate form, so you cannot conclude (from this) that the limit is $0$.
Instead, go one step back to the form:

$$= \frac{1-\color{blue}{n(\frac{3}{8})^n}}{\color{red}{\frac{n^{1729}}{2^{3n}}}+1}$$

and try to reason why the blue and red expressions both tend to zero, so?


text:
Q: nHibernate count on unmapped entity Using nHibernate 2.
In our system we have a table that stores records which may point to any of the other tables in the system, as well as some additional fields. e.g.
class PointerTable
{
    public int ID;
    public string ObjectName;
    public int RecordID;
    ... additional fields
}

The ObjectName and RecordID fields point to the name of another table in the system, and the ID of the record in that table that this record points to. There are no relationships between this table and the other tables in the system.
I need to be able to join to this table when I retrieve records from the other tables in the system, as I need to determine if a table has any records in PointerTable that point to it. i.e. get the count of the records in the PointerTable for this record.
I've tried to do this in HQL:
select a.ID, e.Field1, a.Field2, a.Field3,
            count(select *
             from PointerTable p
             where p.ObjectName = "Table1"
               and p.RecordID = a.ID)
from Table1 a
where a.ParentTable.ID = :ID

I've also looked into putting a mapping into the XML configuration files for all the entities in the system which will be pointed to by this table. So I could have a collection of PointerTable records in each of my other entities. Though I'm not sure if this is possible. I can't find how to set the mapping to map on 2 fields rather than the primary key.
Something like:
<bag name="PointerRecords" table="PointerTable" lazy="true" inverse="true">
     <key>
         <column name="ThisEntityID" />
         <column name="ObjectName" />  ?? Hard coded
    </key>
    <one-to-many class="PointerTable" not-found="ignore"/>
</bag>

Is this even possible?
Basically all I'm trying to do is the following SQL query. But ideally we'd like to do this through HQL or mappings.
SQL
select a.ID, e.Field1, a.Field2, a.Field3, Count(d.ID)
from Table1 a
inner join Table2 e on a.ParentID=e.ID
left outer join PointerTable d on d.ObjectName = 'Table1' and d.RecordID = a.ID
where c.ID = @ID
group by a.ID, e.Field1, a.Field2, a.Field3

A: the idea here would be to map this collection with a where clause
using fluentmapping:
public SomeEntityMap(){
    Table("SomeTable");

    HasMany(x => x.PointerRecords)
        .Table("PointerTable")
        .KeyColumn("ThisEntityID")
        .Where("ObjectName = 'SomeTable'")
}

Begin Edit
using xml-mapping
<bag name="PointerRecords" table="PointerTable" lazy="true" inverse="true" where ="ObjectName = 'SomeTable'">
    <key column="ThisEntityID"/>
    <one-to-many class="PointerTable" not-found="ignore"/>
</bag>

End Edit
and query like
object[] results = session.CreateCriteria<SomeEntity>()
    .Add(Restrictions.Eq("Id", id))
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("Field1"))
        ...
        .Add(Projections.Count("PointerRecords")));
    .List()

or
var entities = session.CreateCriteria<SomeEntity>()
    .Add(Restrictions.Eq("Id", id)
    .SetFetchMode("PointerRecords", NHibernate.FetchMode.Eager)
    .List<SomeEntity>();

entities[0].PointerRecords.Count


text:
Q: SAPUI5 sap.m.list in a popover is emtpy when populated using bindElement I have a table (sap.m.table) with different columns. One columns contains a link and when the user clicks on the link a popover fragment opens and shows some details in a list (sap.m.list). The data is coming from an oData Service. One Entity feeds the table and through a navigation property the data for the popover is fetched.
I have a working example for this scenario where I create the the list template in the controller. But I believe that this should also be possible just by xml and a bindElement in the controller. What is the mistake in my second scenario?
First Scenario (which is working fine):
Popover XML:
    <Popover
    showHeader="false"
    contentWidth="320px"
    contentHeight="300px"
    placement="Bottom"
    ariaLabelledBy="master-title">
        <Page
            id="master"
            class="sapUiResponsivePadding--header"
            title="Aktionen">
            <List
                id="AktionList">
            </List>
        </Page>
</Popover>

Calling the Popover in the controller file (sPath is /TableEntity('123456')/AktionSet):
if (!this._oPopover) {
Fragment.load({
    id: "popoverNavCon",
    name: "bernmobil.ZPM_STOERUNG_FDA.view.AktionPopover",
    controller: this
}).then(function(oPopover){
    this._oPopover = oPopover;
    this.getView().addDependent(this._oPopover);

    var oList = Fragment.byId("popoverNavCon", "AktionList");
    var oItemTemplate = this._BuildItemTemplate();
    oList.bindAggregation("items", sPath, oItemTemplate);
    this._oPopover.openBy(oControl);
  }.bind(this));
} else {
    var oList = Fragment.byId("popoverNavCon", "AktionList");
    var oItemTemplate = this._BuildItemTemplate();
        oList.bindAggregation("items", sPath, oItemTemplate);
    this._oPopover.openBy(oControl);
}
_BuildItemTemplate: function(){
        var oItemTemplate = new sap.m.ObjectListItem({
            title:"{AktionsBez}",
            type: "Inactive"
        });

        oItemTemplate.addAttribute(new sap.m.ObjectAttribute({
            text : "{Aktionstext}"
        }));
        oItemTemplate.addAttribute(new sap.m.ObjectAttribute({
            text : "{path: 'ChangedAt', type: 'sap.ui.model.type.DateTime'}"
        }));
        return oItemTemplate;
    }

And this is the idea of the second scenario which is calling the oDataService but not displaying any data:
Instead of having only the List definition in XML also the ObjectListItem is defined in the XML:
<List
    id="AktionList"
    items="{AktionSet}">
    <ObjectListItem
        title="{AktionsBez}"
        type="Active">
        <ObjectAttribute text="{Aktionstext}" />
        <ObjectAttribute text="{ChangedAt}" />
    </ObjectListItem>
</List>

And in the controller instead of building the template and doing the bindAggretation there is just:
var oList = Fragment.byId("popoverNavCon", "AktionList");
oList.bindElement(sPath);

How do I get the second scenario displaying data in the list?

A: Here is how the relevant part of the view should look:
<List
    id="AktionList"
    items="{AktionSet}">
    <dependents>
        <ObjectListItem
            id="oObjectListItem"
            title="{AktionsBez}"
            type="Active">
            <ObjectAttribute text="{Aktionstext}" />
            <ObjectAttribute text="{ChangedAt}" />
        </ObjectListItem>
    </dependents>
</List>

And in the controller:
var oList = sap.ui.core.Fragment.byId(this.getView().createId("popoverNavCon"), "AktionList");
oList.bindItems({
    path: sPath,
    template: sap.ui.core.Fragment.byId(this.getView().createId("popoverNavCon"), "oObjectListItem")
});

Check dependents in sap.m.List aggregation section for details.

A: I would suggest a third solution:
When pressing on your table row, get the binding context of the current row using oContext = oClickedRow.getBindingContext() or something similar. This context should point to /TableEntity('123456').
Apply this context to your Popover using oPopover.setBindingContext(oContext).
Now your Popover has the same context as your table row. The XML should look like in your second scenario.
Using the path is an extra step imo.  I think it also makes more sense to bind the complete Popover and not just the List. Has the neat side effect that you can use a property of your TableEntity as the title for the Popover. It also completely avoids working with controls directly (which is one of the seven deadly sins) and you should be able to remove all those IDs.


text:
Q: Only one line of SimpleHTTPServer output does not appear while running container without '-it' Note: I am not trying to solve any problem in a real project here. This question is intended for merely understanding the reason behind the results I see in the 2nd experiment (Experiment 2) below.
These experiments were performed using Docker version 17.12.0-ce on macOS Terminal version 2.8 on macOS High Sierra 10.13.1.
Experiment 1: docker run SimpleHTTPServer with -it options
Here is my Dockerfile:
FROM python:2.7-slim
CMD ["python", "-m", "SimpleHTTPServer"]

I build it and run it with this command:
docker build -t pyhttp .
docker run -it -p 8000:8000 pyhttp

In another terminal, I test the container with this command:
curl http://localhost:8000/

The curl command produces expected results: a directory listing. In the terminal running docker run, I see this expected output.
$ docker run -it -p 8000:8000 pyhttp
Serving HTTP on 0.0.0.0 port 8000 ...
172.17.0.1 - - [04/Feb/2018 10:07:33] "GET / HTTP/1.1" 200 -

Finally, I stop this docker container by pressing Ctrl + C.
Experiment 2: docker run SimpleHTTPServer without -it options
Now I run the same pyhttp image with this command:
docker run -p 8000:8000 pyhttp

No output appears on the terminal even though the container is running. I don't see the expected Serving HTTP on 0.0.0.0 port 8000 ... message.
Although if I test the container with curl http://localhost:8000/, I see the log for the GET request appearing in the terminal running docker run.
$ docker run -p 8000:8000 pyhttp
172.17.0.1 - - [04/Feb/2018 10:12:41] "GET / HTTP/1.1" 200 -

Question: Why is it that the initial Serving HTTP on 0.0.0.0 port 8000 ... message does not appear but the subsequent logs for HTTP requests appear?
Experiment 3: docker run Flask app without -it options
I build it and run it with this command:
docker build -t flaskapp .
docker run -p 8000:8000 flaskapp

In another terminal, I test the container with this command:
curl http://localhost:8000/

In the terminal running docker run, I see this expected output.
$ docker run -p 8000:8000 flaskapp
 * Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
172.17.0.1 - - [04/Feb/2018 10:22:28] "GET / HTTP/1.1" 200 -

Question: Why only in Experiment 2, the Serving HTTP on 0.0.0.0 port 8000 ... message did not appear?

A: The first line of output from python -m SimpleHTTPServer is getting printed to stdout; the remaining lines are printed to stderr. Consider the difference between these invocations:
njv@organon:~/tmp$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
172.17.2.26 - - [06/Feb/2018 20:55:52] "GET / HTTP/1.1" 200 -

njv@organon:~/tmp$ python -m SimpleHTTPServer  > /dev/null
172.17.2.26 - - [06/Feb/2018 20:56:26] "GET / HTTP/1.1" 200 -

The second doesn't show the "Serving" line because stdout is discarded, but both show the log lines because stderr is not. Flask, on the other hand, writes its "starting" log to stderr (as well as further log lines):
njv@organon:~/tmp$ python flaskapp.py > /dev/null
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Feb/2018 20:58:10] "GET / HTTP/1.1" 200 -

(edited from here) What's happening with your docker invocation of python is that without the -t option, stdout is fully buffered, and with the -t option, it's line-buffered, so it appears immediately after every newline.
$ docker help run|grep -- ' -t'
  -t, --tty                            Allocate a pseudo-TTY

I'm still looking for a definitive source on this (this article looks promising), but it appears that when sys.stdout.isatty() is True, python opens stdout in line-buffered mode, so each line is shown as it's printed, but when it's not, it opens in fully buffered mode, and so output is only printed when the buffer is full.


text:
Q: How do I detect a change in a multi-dimension array in AngularJS If I have the following data structure:
Model: {
    Estimates: [{
        Id: 1, DataItems: [{Id: 1, Amount: 100}, {Id: 2, Amount: 200}] },
        Id: 2, DataItems: [{Id: 3, Amount: 300}, {Id: 4, Amount: 400}] }
    ]}

How can I set up an Angular $watch to detect when any of the Amount values change?
I tried using
$scope.$watch("budget.Estimates.DataItems", function () {
    console.log("Watch Fired");
});

with no luck.
Also, is there a nice, Angular way to aggregate the sum of all these Amount values?

A: Thanks for the link, tymeJV.  That pointed me in the right direction.
The solution was to do this:
$scope.$watch("budget.Estimates", function () {
    console.log("Watch Fired");
}, true);

The 3rd parameter signals angular to deep compare the values.  Not especially efficient, but it works...


text:
Q: Wordpress taxonomies echo output I am building a site that will feature sellers, kind of like a deal of the day site, on the product page there will be something that will say this:
"Sold by: (Output Custom Taxonomy for company here)" Every product will have a different brand or company name, but I am just trying to output that taxonomy. Currently I am doing it with the "tags" in wordpress like this:
This works for tags: ---->
Sold By: <?php echo $product->get_tags(); ?>

I then tried this: to get the taxonomy rather then the tags, and it isn't working.
<?php echo $taxonomy->name ?>

A: Use wp_get_post_terms() for custom taxonomies -- http://codex.wordpress.org/Function_Reference/wp_get_post_terms
An example code:
// assuming your taxonomy is called "company"
$companies      = wp_get_post_terms( get_the_id(), 'company' );
$companies_list = array();

if ( $companies ):
    foreach ( $companies as $company ):
        $companies_list[] = $company->name;
    endforeach; ?>

    Sold By: <?php echo implode( ', ', $companies_list ); ?>

    <?php
endif;

Note: I'm note sure what $product is in your context, so if you are using get_posts() you might want to change the get_the_id() in the code above to $product->ID

A: So I ended up with this

<?php
  // assuming your taxonomy is called "company"
  $Brands      = wp_get_post_terms( get_the_id(), 'brand' );
  $Brands_list = array();

  if ( $Brands ):
  foreach ( $Brands as $Brands ):
  $Brands_list[] = $brand->name;
  endforeach; ?>

  Sold By: <?php echo implode( ', ', $Brands_list ); ?>

  <?php
  endif;
  ?>

And it ouputs nothing. Within brands I have three terms or brands. Brand1, Brand2 and Brand3. Still not returning anything.


text:
Q: unable to change text color in ion-option when interface="popover" I am using ion-select for selecting an option and i want to change the text color of ion-option. My code is as below...
<ion-item>
    <ion-select interface="popover" [(ngModel)]="selectedGrp" (ionChange)="changeGrp()">
        <ion-option value="" selected disabled>Select</ion-option>
        <ion-option *ngFor="let item of List;let i = index" [value]="item">{{item.name}} </ion-option>
    </ion-select>
</ion-item>

There are no SASS Variables for doing this. I have tried by using css and styles but it's not working. Can any one help me to change the ion-option text color?

A: I was able to change the text color (of all ion-options) by inserting in app.scss
.item-radio.item ion-label {
    color: red; //your color here
}

For the selected option, insert a !important to the color attribute
.item-radio-checked.item ion-label {
    color: blue !important; //your color here for selected option
}


text:
Q: using pandas how do I get the mean of last two rows in a group The code mentioned below seems to work.
Calling tail function on a sorted group is able to give me the last n rows of a group.
Is this the documented behaviour of the tail function for a group.The pandas documentation does not mentioned it and I am worried that in the next version this behaviour may change.
Also is there some other way to do the following. Using the apply function seems to be very slow for large dataset.
The pandas version used in 0.7.3
df1=pds.DataFrame({'A' : ['CU','CU','CU','CU','CU','AU','AU','AU','AU','AU'],'B':[1,2,3,4,5,1,2,3,4,5]}).sort(['A']).reset_index().drop(['index'],axis=1)
df2=df1.groupby(['A'])
df3=df2.tail(2).groupby(['A'])
df3.mean()

A: The documentation does mention head/tail.
And for your code, use pivot_table:
a = pds.DataFrame({'A' : ['CU','CU','CU','CU','CU','AU','AU','AU','AU','AU'],
                   'B':[1,2,3,4,5,1,2,3,4,5]}).sort(['A'])

a.pivot_table(rows='A', values='B', aggfunc=lambda x: x.tail(2).mean())

returns
AU    4.5
CU    4.5


text:
Q: $\sum\limits_{n=1}^{\infty} \frac{1}{n\sqrt[n]{n}}$ converge? Does the series $\sum\limits_{n=1}^{\infty}\frac{1}{n\sqrt[n]{n}}$ converge?

A: For $n>0$, $n < 2^n$. So, $\sqrt[n]{n} < 2$, and $\frac{1}{\sqrt[n]{n}} > \frac{1}{2}$.
Thus, $\frac{1}{n \sqrt[n]{n}} > \frac{1}{2n}$, so
$$ \sum_{n=1}^{k} \frac{1}{n \sqrt[n]{n}} > \sum_{n=1}^{k} \frac{1}{2n}$$ and since the right side diverges to infinity, so does the left.

A: Limit Comparison Test:
Suppose that we have two series $\displaystyle\sum a_n $ and $\displaystyle\sum b_n$ with $a_n\geq0$,$b_n>0 $ $\forall n$. Define, $$ c = \displaystyle\lim_{n\to \infty} \frac{a_n}{b_n} $$ if $c$ is positive (i.e. $c>0$) and is finite (i.e. $c<\infty$) then either both series converge or both series diverge.
Take $a_n=\sum_{n=1}^{\infty} \frac{1}{n}$ and $b_n=\sum_{n=1}^{\infty} \frac{1}{n \sqrt[n]{n}}$
$$\lim_{n\to \infty} \frac{a_n}{b_n}=\frac{n \sqrt[n]{n}}{n}=\lim_{n\to\infty}\sqrt[n]{n}=1$$
Proof: Proof that $\lim_{n\rightarrow \infty} \sqrt[n]{n}=1$
Therefore the series in the question diverges.


text:
Q: algorithm: move bars on a grid to minimize interactions I have to model a chemical phenomenon. To do that, I decided to use a square grid, where I put "bars":

(The bars are represented in green). The grid and the bars can have variable dimensions. The bars can be horizontal or vertical, and the grid is periodic, i.e the first square of the first line is considered just next to the last square of the first line. Also, the number of bars is variable (really variable, I would say from 20 to 200).
My goal is to mimic some "minimization of interactions". Basically, each bar needs to be as far as possible from the others. More precisely, the distance between the green squares needs to be maximal. I need a way to find the best positioning.
But I have no idea how to do that. If the bars were single squares, I guess I would use some kind of brute force, and I would calculate the distance between all the squares for each possibility. But I'm not sure it is the good way, and it's not applicable here, for sure.
Would you have any idea about how to do that ?


text:
Q: Confirmed regression in behavior of reloadRowsAtIndexPaths on iOS 9.1 only? I have an app that supports iOS 7.1 and higher.  When an user selects a cell and makes a field change on a detail view the tableView row will be reloaded to reflect the change upon navigating back.   There are several autolayout constraints on this cell in its storyboard.  The cell contains only 9 UILabels but with varying point sizes of non-default fonts.
Row updating is verified working correctly on devices running iOS 7.1.2, 8.4.1, and 9.0.2.  In addition I have tested it working in the simulator for 8.1, 8.2, and 8.3.   But if fails on 9.1 with users reporting this since the iOS update came out. It fails for both device and simulator.
The failure is a loss of storyboard autolayout constraints for the entire cell.  All of the cell labels overwrite each other in a jumble after calling reloadRowsAtIndexPaths for only the updated row.  The problem with the one cell persists until reloading the entire table again from core data (pull to refresh).  At which point it will have the updated value the user did.
To work around this I have done the following to the call:
// work around cell layout bug introduced with iOS 9.1
  if (SYSTEM_VERSION_LESS_THAN(@"9.0.3"))
      [self.tableView reloadRowsAtIndexPaths:@[selectedRowIndexPath] withRowAnimation:UITableViewRowAnimationNone];

Which is just a version check macro.  This code is called within viewWillAppear of the tableView after the user navigates back from the detail view having made their value change.  This workaround avoids the problem.
To insure we can do this reload before we lose the value, the beginning of viewWillAppear has also always had these lines:
// we need to save this before the super clears it
NSIndexPath *selectedRowIndexPath = [self.tableView indexPathForSelectedRow];
[super viewWillAppear: animated];

The app is built with Xcode 7.1 using storyboard and size classes. The problem remains with Xcode 7.1.1 as well.  Usage is within a UITableViewController.
Just me or anyone else seen this change in behavior?


text:
Q: ldaseqmodel runtimewarning Invalid value in double_scalars I am currently trying to use dynamic topic modeling on some news crawled from the web.
Unfortunately, I receive a warning in the logs:
INFO : using serial LDA version on this node
path/to/gensim/models/ldaseqmodel.py:1472: RuntimeWarning: invalid value encountered in double_scalars converged = np.fabs((lhood_old - lhood) / (lhood_old * total))

After using google to find out more about this issue, I learned that this numpy error is often produced by NaNs or null values. So with regards to dynamic topic modeling this probably refers to an empty document? but I dont have any empty documents in my dataframe

A: Because of the lack of reputation, I am unable to comment which is why I am writing my suggestion here. So you may have done some pre-processing before running the ldaseqmodel of gensim. First, check that after all the pre-processing you have done is there any empty document in your corpus. To check that if it is in the list of lists format(generally it is in the list of lists format) you can do this:
for i in range(len(bow_corpus)): #bow_corpus is the corpus
    if len(bow_corpus[i])==0: #check for empty document
        print(i) #if there is any empty document then print the index of that document

By running the above you will get all the indices of the empty documents. Then you can simply remove the corresponding documents.


text:
Q: How can I count to get by quarter in sql server? this is my code below. I am populating country to ship out their items. The shipping month is always showing 12 months in a year (Jan-Dec). I'm using dynamic pivot to make the shipping month on columns. I manage to populate as below. How can I add in to count by Quarter? Expected result as below.
create table #temp
(
    country varchar(20),
    ship varchar(3),
    amount money
)

insert into #temp values ('German', 'Jan', 1000.00)
insert into #temp values ('USA', 'Feb', 500.00)
insert into #temp values ('AUS', 'Feb', 800.00)
insert into #temp values ('AUS', 'Mar', 700.00)
insert into #temp values ('German', 'Apr', 1100.00)
insert into #temp values ('UK', 'May', 1100.00)
insert into #temp values ('Africa', 'Jun', 1100.00)

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    ,@cols2 AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(ship)
            FROM #temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @cols2 =STUFF(( select distinct ',IsNull(['+ship+'],0) as ['+ship+']' from #temp
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

--select @cols,@cols2

set @query = 'SELECT country, ' + @cols2 + '  from
            (
                select country
                    , amount
                    , ship
                from #temp
           ) x
            pivot
            (
                 max(amount)
                for ship in (' + @cols + ')
            ) p '

execute(@query)

A: I'm not sure why you're using a dynamic pivot here, the months of the year are fixed and aren't subject to change. Code your pivot literally and adding quarters into it is trivial.
SELECT Country,
       SUM(CASE ship WHEN 'Jan' THEN amount END) AS Jan,
       SUM(CASE ship WHEN 'Feb' THEN amount END) AS Feb,
       SUM(CASE ship WHEN 'Mar' THEN amount END) AS Mar,
       SUM(CASE WHEN ship IN ('Jan','Feb','Mar') THEN amount END) AS Q1,
       ...
       SUM(CASE ship WHEN 'Dec' THEN amount END) AS Dec,
       SUM(CASE WHEN ship IN ('Oct','Nov','Dec') THEN amount END) AS Q4
FROM YourTable
GROUP BY Country;


text:
Q: use indexing to speed up reading from mongodb database I have a collection of documents that is very very large (hundreds of million documents)
each document is as such

*

*date in YYYY/MM/DD format

*name

*type1

*type2

*value

There are ~50 different names, ~60 different type1, ~20 different type2
I need to read from this database, usually it is either:

*

*a unique set of (name,type1,type2), but with all dates

*a few dates for all type1

*List item

Currently I am reading without any indexing and it is very slow! Much slower than having a few flat sql tables...
How can I use index to speed up this database?
thanks

A:
date in YYYY/MM/DD format

There's MongoDB datetime format. Use it. It uses less memory than the string and it doesn't need additional conventions. Your format is sane in the sense that it's lexicographical ordering is equivalent to chronological ordering for dates between 0001-01-01 and 9999-12-31, but the built-in datatype is definitely preferable for range queries.

There are ~50 different names, ~60 different type1, ~20 different type2

Your keys have very low selectivity, so individual indexes are probably pointless

I need to read from this database, usually it is either:

*

*a unique set of (name,type1,type2), but with all dates

Use a compound index for {name, type1, type2}. If you also need chronological ordering, you might want to add date for sorting or use a monotic primary key like ObjectId and rely on natural ordering.
db.collection.ensureIndex({'name' : 1, 'type1' : 1, 'type2' : 1, 'date' : 1});

*

*a few dates for all type1
What is 'a few dates'? I assume you mean something like "all dates in a given date range"? Use an index for date. date should naturally have a much better selectivity, so individual keys make sense.
db.collection.ensureIndex({'date' : 1});

*

*List item

List all items? Any ordering? You need something more specific. Keep in mind that skip/take is expensive.


text:
Q: Show Lightbox on form submit I want to sbmit show a page in a lightbox like in this link:
http://www.smkhutankampong.co.cc/infopendidikan.php
I have seen this post : Lightbox on form submit
but I have not understand how I can use the example in the right way.
Please help !

A: in the given link they are using Jquery facebook plugin to show the lightbox.
You can do in a similar way, ie in the form submission after successful form submission show the lightbox
jQuery.facebox({ div: '#div1' });  div1 contains the contents to be shown in popup.
You can find javascript code they have done by taking the page source.

A: Regarding to the used facebox:
You may open onsubmit a facebox with an on-the-fly-created iframe, which may be the target of the form.
Provide the markup of the iframe as argument to jQuery.facebox() and set the form's target-attribute and the iframes name-attribute to the same value.
Example: http://jsfiddle.net/doktormolle/RD88Z/


text:
Q: Getting the body of a Reddit submission? I am trying to search for some data by scraping Reddit. I want to get the self-text of the posts in the subreddit, not the title/url. How can I do this? Here's my code that I am using to get the titles, but how can I get the text written in the posts with this title?
reddit = praw.Reddit(client_id=cid,
                     client_secret=secret, password=pass_word,
                     user_agent='mmm', username=user_name)

subreddit = reddit.subreddit('python')
subreddit_hot=subreddit.hot(limit=5)
for submission in subreddit_hot:
    if not submission.stickied:
        print(submission.title)

A: Replace print(submission.title) with print(submission.selftext).
To see other attributes of a Submission object, take a look at the PRAW docs, which has a table of common attributes for the model. PRAW's documentation also features a guide for discovering attributes on any model.


text:
Q: Velocity showing in GPS-Navigation Systems How exact is the velocity that is showing in a GPS Navigation System like Navigon or TomTom?

A: This depends upon a large number of variables that are imposed by the GPS navigation system in use and by the processing of the data by the SAT-NAV following the determination of the position fix.  These include

*

*The interval between position fix solutions.  This is normally 1 second.

*The position accuracy of each of the positions used to determine the velocity.  This depends upon the quality of the sky view and, to a certain extent, the length of time that the GPS has had a sky view.

*The number of positions used to calculate the velocity

*The acceleration of the unit

*Filtering algorithm used to smooth the velocity value

The velocity value from the GPS receiver is calculated from the difference between position fixes.  As these are typically generated at a 1Hz rate you are measuring a distance travelled in 1 second.  The position fixes can have an error of a number of metres, with successive positions wandering from the true position, sometimes by a metre or more for a static unit.  I have had static units using high end GPS chipsets that have apparently had a velocity of up to 2 m/s while fixed to my office building.
Some units may filter the velocity value or use more than 2 position fixes to calculate the antenna velocity.  This will add a lag to the velocity value shown as the antenna accelerates.
Providing a definitive answer is not possible in just the same way that defining position accuracy has to be bounded by many caveats around the sky view and number of satellites visible.

A: With no filter at all the most error you should ever see is 30 meters/second, but this will only last for 1 sample. In my past experiences, you should expect to see an error more around less than 1 meter a second, but with 0 mean. This equates to about +/- 2.25 miles per hour. However, for consumer GPS modules you will never see an error like this. There are several reasons for this, but it all comes down to filtering.
GPS systems like the Garmin and Tom Tom employ filtering algorithms to give you the most accurate position it can. One of the things that these systems do is they assume you stay on the road until they are very sure that you didn't. With the filtering on the position, it forces the velocity calculations to already be much more accurate then using the raw data. Then with the filtering on the velocity calculations you get a very accurate measurement.
NOTE: I should probably quantify what I mean by "very accurate". I thinking about the situation of you having a GPS in a car and comparing its accuracy to what the car says it is at.


text:
Q: How the get the whole source html code of a webpage that is generated by Javascript using Java / Webdriver? I am a newbie in programming and I have a task here I need to solve. I am trying to get the html source code of a webpage using Java / Webdriver method getPageSource(). Problem is, that page is somehow generated, probably by javascript, so the result I get is html code containing just page skeleton - a table that is empty, not filled by data. But, there is tag like <script type="text/javascript" src="/x/js/main.c0e805a3.js"></script> in the very bottom of that html code.
The question is, how can I force Webdriver to run that Javascript and give me the result - the whole source html with data. I already tried to use this (js.executeScript("window.location = '/x/js/main.c0e805a3.js'");) before calling getPageSource() but not successful.
Any help will be appreciated, thanks!

A: There are quite a few setups, now, that can run the Java-Script on a web-page.  The most well known, I think, is likely Selenium since I think it has been around for a while.   Others include karate, Puppeteer, and even an old tool called Rhino.  Puppeteer is a Google, Inc. project that uses Java-Script (server-side Java-Script, called Node.js.  They don't like us comparing, contrasting libraries here.
I haven't had the time to engage Selenium, yet, but I write HTML parser, search and update code all the time.  If your only goal is to load a page whose contents are dynamically "filled in by AJAX calls" - and what I mean by that, you only want the contents of an HTML that would normally see when you visit the sites web-page, and you are not concerned with button presses then the one I have been using for that is called Splash  This tool does have the ability to let you invoke Java-Script, but if all you want to do is see the JS on a page dynamically load the table, then, literally, all you have to do is start-the tool, and add one line to your program.
On Google Cloud Platform, these 2 lines will start a Splash Proxy Server.  If you are writing your code on AWS (Amazon) or Azure (Microsoft), it would likely be similar.  If you are running your code in an office on the local machine, you would have to research how to start it.

Install Docker. Make sure Docker version >= 17 is installed.
Pull the image:
 $ sudo docker pull scrapinghub/splash

Start the container:
$ sudo docker run -it -p 8050:8050 --rm scrapinghub/splash

Then, in your code, all you have to do is the following:
// If your original code looked like this:
URL url = new URL("https://en.wikipedia.org/wiki/Christopher_Columbus");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
return new BufferedReader(new InputStreamReader(con.getInputStream()));

Change the first line of code in this example to this, and (theoretically), and dynamically loaded HTML tables that are completed with the onload page events will be automatically loaded before returning the HTML page.
// Add this line to your methods
String splashProxy = "http://localhost:8050/render.html?url=";
URL url = new URL(splashProxy + "https://en.wikipedia.org/wiki/Christopher_Columbus");

For most web-sites, any initial tables that are filled by JS/jQuery/AJAX will be filled in.  If you are willing to learn teh Lua Programming Language, you can also start invoking the methods there.  It has been pretty convenient for my purposes, since I am not writing web-page testing code (code that simulates user button presses).  If that is what you are doing, Selenium is likely worth spending time learning / studying the A.P.I.


text:
Q: PHP codeigniter : I want to make an output product detail but the output shows only one productID and other productID can not output I want to make an output product detail but the output shows only one productID and other productID can not output!
Is there a mistake on my controller, model, and view ??
View
<?php foreach ($categories as $key=>$value) { ?>

<?php echo $categories[$key]->categoriesName; ?>

         <?php if(count($categories[$key]->subs)>0) { ?>
             <?php foreach ($categories[$key]->subs as $k=>$v)  { ?>

<a href="<?php echo base_url();?>member/detail/"><?php echo $v->productName; ?>

             <?php } ?>
             <?php } ?>

  <?php } ?>

    <?php if(count($details)>0){ ?>

<img src="<?php echo base_url('upload/'.$details->photo);?>"
         alt="" class="img-responsive">div>

<?php echo $details->productName;?>

                <?php echo $details->price;?>

    <?php } ?>

Controller
public function detail($product_id=''){
     $data=array('title'   =>'Pasar Online | Detail Produk',
           'username'      => $this->session->userdata('username'),
           'categories'    => $this->categories_model->get_categories(),
           'details'       => $this->categories_model->get_details($product_id=''),
           'isi'           =>'member/detail');
     $this->load->view('template_home/wrapper',$data);
 }

Model
public function get_details($product_id)
{
    $this->db->where("productID",$product_id);
    $query = $this->db->query("SELECT * FROM product");
    $row = $query->row();
    return $row;
}

print_r($details)
stdClass Object ( [productID] => P0001 [categoriesID] => 1 [productName] => AAA ) 1

Where is my mistake? Thank you

A: In your model use
For object output $row = $query->result();
For array output $row = $query->result_array();
So change the function to
public function get_details($product_id) { $this->db->where("productID",$product_id); $query = $this->db->query("SELECT * FROM product"); $row = $query->result(); return $row; }


text:
Q: MAGENTO: How to display waringns like errors? My errors/local.xml content:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <skin>default</skin>
    <report>
        <action>print</action>
        <subject>Store Debug Information</subject>
        <email_address></email_address>
        <trash>trash</trash>
    </report>
</config>

Is it possible to display warning in browser?
PS:
I can see errors in browser when they are.
But I would like to see warnings also, not just in log file.

A: Enable developer mode. In Magento > 1.3 you need only set an environment variable (MAGE_IS_DEVELOPER_MODE) as this is evaluated in index.php.

A: You can uncomment errors settings in index.php


text:
Q: How to find the parent ID in a return table I have following table:
ID     ParentID
1         NULL
2          1
3          2
4          NULL
5          4
6          5
7          3

I want to find the first  ID of a specific child ID.
Example: ID=7 and the result is 1
ID=6     and the result is  4
How to do it?

A: You need to do a bit of recursive CTE magic to solve this one.
Given the data in a table variable thusly:
declare @data table(id int, parentid int)
insert into @data
  select 1, null
  union select 2,1
  union select 3,2
  union select 4, null
  union select 5,4
  union select 6,5
  union select 7,3

The following should do the trick:
;with recursiveTable as
(
    select d.id, d.parentId, 0 as depth
    from @data d
    where d.id=6 -- Parameterize this
    union all

    select d.id, d.parentid, r.depth-1
    from @data d
    inner join recursiveTable r
    on d.id = r.parentId
)
select top 1 id
from recursiveTable
order by depth

Plugging 6 in as above returns 4. Changing this to 7 returns 1 as requested.

A: Try this:
 CREATE TABLE childpar(ID int,ParentID int)
    INSERT INTO childpar
    values(1,NULL),
    (2, 1),
    (3, 2),
    (4, NULL),
    (5, 4),
    (6, 5),
    (7, 3)

DECLARE @inpyID int
SET @inpyID=7

;WITH CTE1 as (
select * from childpar where id=@inpyID
union all
select c2.* from CTE1 c1 inner join childpar c2 on c1.ParentID = c2.ID
)

select top 1 id from CTE1 order by id asc


text:
Q: How to acces a Service from the Service host in WCF Communication I have a number of clients, communicating using WCF wsDualHttpBinding, that are accessing a host, asking for information.
This information has be to searched, this means that the answer is can not be given back in the same thread.
The problem looks the same as in:
How to communicate between WCF service and host application?
Only I can not use the Singleton constructor but have to use the Typeof(..) contructor of the host because I can have more clients.
But how can the service host access the client to send the correct answer?
Regards,
Rob

A: Is there a reason that the out-of-the box WCF duplex communication can not work?
Here's a definition and example:
http://msdn.microsoft.com/en-us/library/ms731064.aspx


text:
Q: Mongo, Mongoid join data from different models in Ruby on Rails I'm adapting a Ruby on Rails application to work with MongoDB instead of PostgreSQL. I have this 2 class:
module Cms
  class Content
    include Mongoid::Document
    include Mongoid::Orderable

    field :title, type: String
    field :position, type: String
    field :text_body, type: String
    field :expiration_date, type: Date
    field :active, type: Boolean, default: false

    validates :title, :text_body, presence: true

    orderable base: 0

    belongs_to :cms_content_category, class_name: 'Cms::ContentCategory'

    scope :ordered, ->() { order(position: :asc) }
    scope :not_expired, ->() { any_of({ expiration_date: nil }, { :expiration_date.gte => Date.today }) }
  end
end

module Cms
  class Submenu
    include Mongoid::Document
    include Mongoid::Orderable

    field :title, type: String
    field :position, type: String
    field :external_url, type: String
    field :open_as, type: String, default: '_self'
    field :active, type: Boolean, default: false

    delegate :url_helpers, to: :'Rails.application.routes'

    validates :title, presence: true

    validates :external_url, presence: true, if: Proc.new { |obj| obj.cms_content_id.nil? }
    validates :cms_content_id, presence: true, if: Proc.new { |obj| obj.external_url.blank? }

    orderable base: 0

    belongs_to :cms_content, class_name: 'Cms::Content'
    belongs_to :cms_menu, class_name: 'Cms::Menu'

    scope :ordered, ->() { order(position: :asc) }

    def url
      self.external_url.present? ? self.external_url : url_helpers.content_show_path(self.cms_content_id)
    end
  end
end

The problem is that I don't know how to adapt the following SQL query to work with MongoDB.
scope :active, joins("FULL JOIN contents ON contents.id = cms_submenus.content_id")
               .where("cms_submenus.active IS TRUE AND (
                        (cms_submenus.content_id IS NOT NULL AND ((contents.expiration_date >= :today OR expiration_date IS NULL) AND contents.archived IS NOT TRUE)) OR
                        (cms_submenus.external_url IS NOT NULL AND cms_submenus.external_url <> '')
                      )", today: Date.today)

This scope has to be called from Submenu model.
Someone has an idea on how to solve this problem?
I'm using Rails 4.2.0 with Ruby 2.2.0 and Mongoid 4.0.2 with MongoDB 2.6.8.
thank you


text:
Q: C# call SOAP webservice from console application This seems very trivial, but it is not working for me at all. I am attempting to call a soap web service from within my c# console application. The app is built for .net 4.5.  Here's what I did:

*

*Added the service reference to the project in visual studio 2013 by pointing it to the wsdl. It finds the Service and it's operations fine.

*Attempt to create an instance of that service by doing the following:

            ServiceReference1 s = new ServiceReference1();

I get the following error code:
Project1.ServiceReference1 is a 'namespace' but is used like a 'type'

Any ideas? I've searched for this for a while and can't come across someone having the same problem with a real solution. I will provide any more info needed.

A: If you already added the service reference to the project you see the reference. In this case you left a default name 'ServiceReference1'.
Now you want to call the web service's methods, for this you have to instantiate a SOAPClient.
    ServiceReference1.YourWebserviceNameSoapClient client = new  ServiceReference1.YourWebserviceNameSoapClient();
    client.HelloWorld(); // call of webmethod

now you access the webmethods under the 'client' object.

A: When you create a service reference, Visual Studio 2013 will generate a proxy class you can use to transparently call into the service. The default proxy namespace is your_project_name.ServiceReference1. The type is the name of your service.
For an example service http://localhost/YourService.svc.
You generate the Service Reference ServiceReference1 from your console project ConsoleApp. The generated files have the namespace ConsoleApp.ServiceReference1. The type is YourService.
var service = new ServiceReference1.YourService();

will return an instance of the proxy generated by Visual Studio. Then you will be able to call any of the service methods.


text:
Q: Batch Create folder by file names with the same name and extension I have a lot of jpg files to be moved in a folder with the same name. here my example
ABCD, DEFG (1).jpg
ABCD, DEFG (2).jpg
ABCD, DEFG (3).jpg

and the files with the same name should be moved in one folder like this.
\ABCD, DEFG\ABCD, DEFG (1).jpg
\ABCD, DEFG\ABCD, DEFG (2).jpg
\ABCD, DEFG\ABCD, DEFG (3).jpg

is this possible just by using a command prompt?

A: It's possible.
Once you recognize a set of files you want to build a directory for and move, use
md "ABCD, DEFG"
move "ABCD, DEFG (?).jpg" "ABCD, DEFG"

Now, just guessing: You wanted more automation than I built in there. What more?
By the way, the MS documentation for the command prompt commands is very useful. Try
md /?
move /?

There are lots of sites that'll teach you the various batch file commands. Between those and the documentation, you can figure it out. It's not the greatest programming environment, but it works. And it's everywhere!


text:
Q: Output not right on Descending Selection Sort I am working on an assignment and I am really struggling to figure out what I am doing wrong. I am new to Python, and honestly, I barely understand the code I have cobbled together so far.
What I have currently is:
array=[int(n) for n in input().split()]

for i in range(len(array)):
    max_index = i
    for j in range(i+1, len(array)):
        if int(array[j]) > int(array[max_index]):
            max_index = j
    array[i],array[max_index] = array[max_index],array[i]

    print(array)

With the input of
50 40 20 10 30

I get:
[50, 40, 20, 10, 30]
[50, 40, 20, 10, 30]
[50, 40, 30, 10, 20]
[50, 40, 30, 20, 10]
[50, 40, 30, 20, 10]

What I need is:
[50, 40, 20, 10, 30]
[50, 40, 20, 10, 30]
[50, 40, 30, 10, 20]
[50, 40, 30, 20, 10]

A: See the below code, here checking that array is sorted using a flag and stop processing for loop after sorted, it will improve time complexity of algorithm.
array=[int(n) for n in input().split()]

for i in range(len(array)):
    max_index = i
    is_sorted = True
    for j in range(i + 1, len(array)):
        if int(array[j]) > int(array[max_index]):
            max_index = j
            is_sorted = False

    if (is_sorted == True):
        break
    array[i],array[max_index] = array[max_index],array[i]
    print(array)

Input: 50 40 30 20 10   (i.e. sorted array and it prints None as its sorted)
Output:
Input: 10 20 30 40 50    (i.e. unsorted array and it prints till it sorted & break)
Output:
[50, 20, 30, 40, 10]
[50, 40, 30, 20, 10]

A: The only difference between the actual and expected output is that it outputs the sorted array an additional time. If you're looking to stop sorting whenever the array is sorted, you can add a break statement to terminate the loop early:
def is_sorted_descending(array):
    for i in range(len(array) - 1):
        if array[i] < array[i + 1]:
            return False
    return True

for i in range(len(array)):
    max_index = i
    for j in range(i+1, len(array)):
        if int(array[j]) > int(array[max_index]):
            max_index = j
    array[i],array[max_index] = array[max_index],array[i]

    print(array)

    if is_sorted_descending(array):
        break


text:
Q: Jmeter engine & threads query What is Jmeter Engine ? Is it same as Jmeter instance we have on our machine ? .. I want to understand difference between Jmeter instance and Jmeter engine , also how can we setup multiple engines on same machine so that I can put more load on application through difference engines..
I read somewhere, where one of the Jmeter expert mentioned that we can use 300 vusers at a given time , is that correct ? I dont see any limit on vusers I use in Jmeter thread group.. I can enter any number.. please clarify

A: Yes, Jmeter engine and jmeter instance is related terminology. One Jmeter engine can generate one instance of jmeter.
Set-up for configuring two Jmeter engines on same machine:
Pre-requisite:
Jmeter should be installed on both machines
Steps:
1.Set-up master machine -
Add machine2 ip (slave machine ip) in jmeter.properties file of machine1 (master machine)
2.Set-up slave machine - Run Jmeter-server.bat from machine2. This will make machine2 as slave
3.Launch Jmeter from machine1. You will be able to see slave engine ip in remote start

4.You can use remote start option, this will run Jmeter test cases from both the machines


text:
Q: feasible method is stucked in infinite loop I have run the following simplex method which is written in C++ .The code is as follows :
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;

#define maxm 500
#define maxn 500
double inf = 1e100;
double eps = 1e-13;

int row,col;
double A[maxm][maxn];
double B[maxn];
///////////////////////////////////////////////////////////////////////////////////////////
// Simon Lo's
// Simplex algorithm on augmented matrix a of dimension (m+1)x(n+1)
// returns 1 if feasible, 0 if not feasible, -1 if unbounded
// returns solution in b[] in original var order, max(f) in ret
// form: maximize sum_j(a_mj*x_j)-a_mn s.t. sum_j(a_ij*x_j)<=a_in
// in standard form.
// To convert into standard form:
// 1. if exists equality constraint, then replace by both >= and <=
// 2. if variable x doesn't have nonnegativity constraint, then replace by
// difference of 2 variables like x1-x2, where x1>=0, x2>=0
// 3. for a>=b constraints, convert to -a<=-b
// note: watch out for -0.0 in the solution, algorithm may cycle
// eps = 1e-7 may give wrong answer, 1e-10 is better

void pivot(int m, int n, double a[maxm][maxn], int B[maxm], int N[maxn], int r, int c) {
        int i, j;
        swap(N[c], B[r]);
        a[r][c]=1/a[r][c];
        for (j=0; j<=n; j++)if (j!=c) a[r][j]*=a[r][c];
        for (i=0; i<=m; i++)if (i!=r) {
                for (j=0; j<=n; j++)if (j!=c)
                        a[i][j]-=a[i][c]*a[r][j];
                a[i][c] = -a[i][c]*a[r][c];
        }
}
int feasible(int m, int n, double a[maxm][maxn], int B[maxm], int N[maxn]) {
        int r, c, i; double p, v;
        while (1) {
                for (p=inf, i=0; i<m; i++) if (a[i][n]<p) p=a[r=i][n];
                if (p>-eps) return 1;
                for (p=0, i=0; i<n; i++) if (a[r][i]<p) p=a[r][c=i];
                if (p>-eps) return 0;
                cout<<"Sultan"<<endl;
                p = a[r][n]/a[r][c];
                for (i=r+1; i<m; i++) if (a[i][c]>eps) {
                        v = a[i][n]/a[i][c];
                        if (v<p) r=i, p=v;
                }
                pivot(m, n, a, B, N, r, c);
        }
}
int simplex(int m, int n, double a[maxm][maxn], double b[maxn], double& ret)
 {
        int B[maxm], N[maxn], r, c, i; double p, v;
        for (i=0; i<n; i++) N[i]=i;
        for (i=0; i<m; i++) B[i]=n+i;
        if (!feasible(m, n, a, B, N)) return 0;
        while (1) {
                for (p=0, i=0; i<n; i++) if (a[m][i]>p)
                        p=a[m][c=i];
                if (p<eps) {
                        for (i=0; i<n; i++) if (N[i]<n)
                                b[N[i]]=0;
                        for (i=0; i<m; i++) if (B[i]<n)
                                b[B[i]]=a[i][n];
                        ret = -a[m][n];
                        return 1;
                }
                for (p=inf, i=0; i<m; i++) if (a[i][c]>eps) {
                        v = a[i][n]/a[i][c];
                        if (v<p) p=v, r=i;
                }
                if (p==inf) return -1;
                pivot(m, n, a, B, N, r, c);
        }
}
//////////////////////////////////////////////////////////////////////////////////////////////

void read_file()
{
    freopen("Dimen.txt","r",stdin);

    scanf("%d",&row);
    scanf("%d",&col);

    row = 30 ;
    col = 100;

    cout << row << " "<<col<<endl;

    freopen("A1.txt","r",stdin);
    for(int i=0;i<row;i++)
       for(int j=0;j<col;j++)
         scanf("%lf",&A[i][j]);
    cout<"Completed A";

    freopen("B1.txt","r",stdin);
    for(int i=0;i<row;i++){
       scanf("%lf",&A[i][col]);
    }
    cout<"Completed B";

    freopen("F1.txt","r",stdin);
    for(int j=0;j<col;j++){
        scanf("%lf",&A[row][j]);
        //B[i]=-B[i];
    }
    cout<"Completed F";

}

int main()
{
    read_file();
    double value,opt=0;
    int flag = simplex(row,col, A,B, value);
    freopen("opt.txt","r",stdin);
    scanf("%lf",&opt);
    if(flag != -1)
    {
        cout<<"The result is "<<(value+opt);
    }
    else
    {
        cout<<"The result is infeasible";
    }

    return 0;
}

But this code runs in infinite loop . The feasible method stucks in infinite loop . How can I solve this error ? Please help me .

A: Lets start by fixing the unclear bits of the code:
#include<bits/stdc++.h>

You should not use any includes that starts with bits/ include the standard header that will include it.
#include<cstdio>
using namespace std;

Using std is bad practice, it might confuse the compiler in large projects and select a function/template/whatever that you did not mean to.
#define maxm 500
#define maxn 500

As minimum change these to
#define maxm (500)
#define maxn (500)

So macro substitution doesn't get confused. Better use c++11 and use
constexpr int maxm = 500;
constexpr int maxn = 500;

double inf = 1e100;
double eps = 1e-13;

There are standard ways of finding the correct values for inf and eps
double inf = std::numeric_limits<double>::max();

From you code I presume you really meant max double.
For eps I wonder if you need
double eps = std::numeric_limits<double>::epsilon();

or
double eps = std::numeric_limits<double>::round_error();


text:
Q: Flash/XML breaklines & hidden characters I got this problem, when edit my xml everything on a next line renders two breaklines
<![CDATA[Line one
Line two
Line three
]]>

Renders in flash as

Line One

Line Two

Line Three

Now I researched this before and it had something to do with hidden breakline characters, Im using Flexbuilder and or Aptana to edit the xml, but how do I avoid having two breaklines when I want one.

A: Flash interprets both \r and \n as new line characters. If your input contains windows line endings (\r\n), then you see a blank line in the output.
To solve your problem, use the following regex to replace two consecutive occurrences of \r and \n with one before you output your data.
var newline:RegExp = /\r\n|\n\r/g;
var input:String = "your XML CDATA input";
var output:String = input.replace(newline, "\n");

Actually it is unlikely that \n\r ever occurs, but since we are already replacing, we can fix these invalid line endings as well.

A: Perhaps you're inserting the wrong end-of-line characters.  Usually your choices are: cr-lf, cr, and lf.  The first works well on windows, the second on Mac, the third on most flavors of Unix.  Try setting your editor to use lf (\n).


text:
Q: How can an arrow cross under an entry in xymatrix? I know how can an arrow cross under another arrow in xymatrix (i.e. using |\hole). But how can it cross under an entry (e.g. wide textual entry). One solution would be to fill the box under the entry with white color. However it seems that only black color works in pdflatex, which seems weird. I don't really need colors, just white color so that the arrow doesn't intersect with the text. Minimal example follows.
\def \objectstyle {\hbox}
\xymatrix{
    short & short \ar@/_/[lddd] \\
    short & short \\
    long long long & short \\
    short
}

A: The idea of using a white background is good:
\documentclass{article}
\usepackage[all,cmtip]{xy}
\usepackage{color}
\begin{document}
\def \objectstyle {\hbox}
\xymatrix{
    short & short \ar@/_/[lddd] \\
    short & short \\
    \colorbox{white}{long long long} & short \\
    short
}
\end{document}

With "native" methods it would be something like
\documentclass{article}
\usepackage[all,cmtip]{xy}
\usepackage{color}
\begin{document}
\def \objectstyle {\hbox}
\xymatrix{
    short & short \ar@/_/[lddd] \\
    short & short \\
    *++[F*:white]{long long long} & short \\
    short
}
\end{document}

In both cases one has to pay attention to what object is drawn first; if the box is processed before the arrow, the white background will not make any difference.


text:
Q: rails 3.1 auto-completion and realtime update in rails Can anyone tell me how to easily implement auto-complete in rails 3.1?thanks. p.s. What's the best solution for simple_form to do this??
Besides, I also want to know how to implement meetup's RSVP instant push in rails?
I have the following form, but it didn't work, please advise.
%table
= simple_form_for(@book) do |f|
%th book name
%th
= f.input :name, label: false, placeholder: "add a name", :wrapper_html => { :id => 'autocomplete' }
= f.input :object, autofocus: true, label: false
%th
= f.button :submit, "Yes!"

A: I built a simple Rails 3.1 app using the jQueryUI autocompletion feature here. You simply add the jQueryUI library to your assets, add a css class or id to the actual text field that shall be autocompleted and put some javascript logic in your application, like:
$(function() {
  $('#autocomplete').autocomplete({
    source: '/movies/autocomplete'
  });
});

with #autocomplete the css id of the text field. '/movies/autocomplete' is the actual route that will HTTp requested with the data that's put into the text field. In the movies#autocomplete action you then use that param to search for data for the autocompletion. Depending in what kind of jQueryUI autocompletion you use, you simply return an array like [{:label => 'FOO', :value => 'foo'}, ...] as JSON. label is the text you get autocompleted, value is the text that is put into the text field when clicking the label. I think and hope the code from the repo is quite understandable. Also, have a look at the JQueryUI library.
Though there shouldn't be a problem with simple_form, since it's just the text field that gets touched.
Best regards
Tobias


text:
Q: How to change background opacity correctly So I have a div which includes a form with many input fields.
If I click on a button all the input fields are getting disabled and the opacity of these input fields should change to around 0.2.
Also an image kinda pops up, (it style.display was set to none, and now onclick to block) So while the opacity of the elements gets perfectly disabled and are made transparent, the onclick from the image that pops up doesn't work, if there is an input field in the background.
Is there a way to not complicity vanish the input fields but still being able to press the image at every pixel?

<input id="c" onclick="dis()" type=button value="hey"><input id="f" type=text >

Test

 <button id="button">Button</button>


text:
Q: Error: Attribute audio_url not allowed on element li at this point I have created an audio playlist. It's an unordered list with several list items. The
 element defines the list items that are part of the unordered list. Each list item consists of an audio url and an image url.

     Intro

     Castaway

     Robert Smith

     Stolen Youth

     Red Vines

     On the Attack

     South Migration

The code works great with no issues, but as I understand it, these are not valid attributes allowed with list items. List items can have valid attributes of type, and value, as well as global and event attributes. Consequently, the attributes I have included lead to validation errors. I have tried many fixes- such aswrapping the audio and img urls as
 or as <audio> but without any success.
When I check it on the W3C validator, I get the error message:

Error: Attribute audio_url not allowed on element li at this point.

I am not sure how to fix it.  Any suggestions?

A: If you want to keep your markup like that, you could add data- as prefix to your invented attributes:

Castaway

But it would typically be better to use semantic markup. For example, something like this:

  <button type="button" data-audio_url="music/Castaway.mp3">

    Castaway
  </button>

(assuming that a click adds the track to the playlist)


text:
Q: Looking for Explanation of pointer initializing to const int and int I was working through exercises in C++ Primer and found online solutions for Exercise 2.32.
I understood that the following code was illegal because initializing can't convert from int to int*:
int null = 0, *p = null;
However, two of the solutions that were mentioned, that I did not come up with were:
    const int null3 = 0, *p3 = null3;

    constexpr int null4 = 0, *p4 = null4;

How come it allows these during compile without error? I was still expecting the initialize of p3 and p4 to require the & to denote address (&null3, &null4).
Here is the code I have from my notepad file:

#include <iostream>

int main()
{

//  int null = 0, *p = null; // it is not legal; depending on intent there are two ways to fix (that I can think off atm)

    {
    int null = 0, *p = &null; // if the goal is to point to 'null'
    }
    {
    int null2 = 0, *p2 = 0; // if the goal is to create a nullptr
    }
    {
    const int null3 = 0, *p3 = null3; // if the goal is to create a nullptr
    }
    {
    constexpr int null4 = 0, *p4 = null4; // if the goal is to create a nullptr
    }

return 0;
}

When I run via Microsoft Visual Studio CMDPrompt it allows me to 'cl "Exercise 2.32.cpp"' without error.

A: 0 is one way of denoting a null pointer constant. (It's an integer type that evaluates to zero.) In other words it is a special case and you are allowed to assign a pointer type to it.
A standards compliant compiler should issue a diagnostic for the assignments of a pointer type to null3 and null4. (It should also issue a diagnostic for int *p = +0;.) If yours doesn't then check appropriate compiler flags are set.
Using nullptr is far better though:
int *p = nullptr;


text:
Q: Adding multiple annotations on WKInterfaceMap I am trying to add multiple annotations to my map but the watch is only showing one. This is what I am doing.
for (RestaurantObject *restaurant in nearbyMapArray) {
     CLLocationCoordinate2D mapLocation = CLLocationCoordinate2DMake([restaurant.latitude doubleValue], [restaurant.longitude doubleValue]);
    [self.map addAnnotation:mapLocation withPinColor: WKInterfaceMapPinColorRed];
    MKCoordinateSpan coordinateSpan = MKCoordinateSpanMake(0.1, 0.1);
    [self.map setRegion:(MKCoordinateRegionMake(mapLocation, coordinateSpan))];
  }

A: I think the problem is that you are setting the region at each annotation location. Try setting it once.
regionCoordinate = ?
MKCoordinateSpan coordinateSpan = MKCoordinateSpanMake(0.1, 0.1);
[self.map setRegion:(MKCoordinateRegionMake(regionCoordinate, coordinateSpan))];

for (RestaurantObject *restaurant in nearbyMapArray) {
    CLLocationCoordinate2D mapLocation = CLLocationCoordinate2DMake([restaurant.latitude doubleValue], [restaurant.longitude doubleValue]);
    [self.map addAnnotation:mapLocation withPinColor: WKInterfaceMapPinColorRed];
}

You may need to play around with the coordinateSpan value and the region coordinate to show them all. I am wondering if there is a maximum of 5 annotations allowed though.


text:
Q: Are empty for loops even executed in C++? I was wondering if the condition inside for loop is always executed if it's a mathematical operation like:
int margin = 100;

for(int i=0; i<margin/2;i++);//is margin divided by two at every cycle?

so I have written the following program:
long margin = 1000000000, halfOfMargin = margin/2;
clock_t begin_time;
clock_t stop_time;

for(long j=0;j<10;++j)
{
    begin_time = clock();
    for(long i=0;i<margin/2;i++);
    stop_time = clock ();

    cout <<"With margin/2 :"<< float( stop_time - begin_time ) /  CLOCKS_PER_SEC<<"\n";
}
for(long j=0;j<10;++j)
{
    begin_time = clock();
    for(long i=0;i<halfOfMargin;i++);
    stop_time = clock ();
    cout <<"With halfOfMargin :"<< float( stop_time - begin_time ) /  CLOCKS_PER_SEC<<"\n";
}

to test the two methods separately, (sorry for the messy code).
I have concluded that in Debug configuration the divide version is even faster than the second aproach. What surprised me was that when I switched to Release, I got the output of 0 for each of the versions every time, which would have been imposible if the for instructions were actually executed (in Debug configuration the time of each output was about a second and a half).
My question is that if it is possible to be skiped instructions by the compiler if it finds them unnecesary, and if not why the times were so different for those two cases?
Note: I am using Visual Studio 2012 express as an IDE with the default compiler.

A: The C++ standard describes the behavior of an abstract machine.
Certain parts of its behavior are externally observable.
Any behavior whose effects are not observable can be skipped under what is known as the "as-if" rule.
That means the compiler is free to skip useless code.  In some situations, it can even skip an infinite loop by proving that it changes nothing anyone could spot, set the state to be what would permit the loop to exit, and exit the loop.
In "debug", compilers tend to optimize far less.

A: As the 'margin' variable is local and not modified, the compiler can see that it never changes and will only do the test once.
If you call a function and are testing the result then it probably can't.
Try adding volatile to the variable definition and running it again. Then the compiler will think that the variable could be modified from another thread and perform the test every loop.

A: Yes the compiler do this. This falls under the as-if rule - the code may be reorganized as long as the observable behaviour doesn't change. Since the change to i in your loop cannot be observed by anything (i.e. a function the compiler can't see the body of or a IO function), it can be sped up.
If you look at the code generated by clang or gcc, it'll also be optimized out:
void foo(int n)
{
  int i;
  for(i = 0; i < n/2; ++i);
  sink(i);
}

clang:
foo(int):                                # @foo(int)
# BB#0:
        #DEBUG_VALUE: foo:n <- %EDI
        #DEBUG_VALUE: foo:i <- 0
        mov     eax, edi
        shr     eax, 31
        add     eax, edi
        xor     ecx, ecx
        sar     eax
        cmovs   eax, ecx
        mov     edi, eax
        jmp     sink(int)                # TAILCALL

gcc:
foo(int):
        mov     eax, edi
        shr     eax, 31
        add     eax, edi
        xor     edi, edi
        sar     eax
        test    eax, eax
        jle     .L2
.L3:
        add     edi, 1
        cmp     edi, eax
        jne     .L3
.L2:
        jmp     sink(int)


text:
Q: extrack string from rectangular brackets in tcl i want to latch a string between brackets and i wondered what is the best way
what do i mean
i got some line in file
[307b..3fff] : 00000000000000000;

i need to latch 307b , 3fff and 00000000000000000
i try to latch it using regexp , to find the brackets and latch the string inside
regexp -nocase -lineanchor -- {^\[\s*\]} $line match
puts $match

how can i latch the value in the brackets , 307b..3fff ?
itamar

A: While there are solutions using regular expressions, they're not the only way to parse that string. The scan command is useful too… especially you're after the value as a number and not as hex digit string per se.
set inputString {[307b..3fff] : 00000000000000000;}

scan $inputString {[%x..%x] : %lx;} v1 v2 v3

puts "$v1->$v2 => $v3"
# Output: 12411->16383 => 0

A: Use the following solution, num1, num2 and num3 will hold the values you need:
set line {[307b..3fff] : 00000000000000000;}
regexp {\[([^][]*)\.\.([^][]*)]\s*:\s*(\d+)} $line - num1 num2 num3
puts "Number1: $num1\nNumber2: $num2\nNumber3: $num3"

See the Tcl online demo
The regex matches:

*

*\[ - a [

*([^][]*) - Group 1 ("num1"): any 0+ chars other than ] and [

*\.\. - two dots

*([^][]*) - Group 2 ("num2"): any 0+ chars other than ] and [

*] - a  ]

*\s*:\s* - a colon enclosed with 0+ whitespaces

*(\d+) - Group 3 ("num3"): 1 or more digits

See the regex demo.

A: I would go with Donal's answer, but
set inputString {[307b..3fff] : 00000000000000000;}
lassign [regexp -inline -all {[[:xdigit:]]+} $inputString] v1 v2 v3

works too (fwiw, it also preserves hexadecimaliality).

A: You can use:
\[([0-9a-z]+\.\.[0-9a-z]+)\] * : *([0-9])+;

Demo


text:
Q: How to get current page id in Lightning controller? I am using force:hasRecordId and   <aura:attribute name="recordId" type="Id" />..to get the ID to Controller.
Component:
<aura:component controller="dcontroller" implements='force:hasRecordId'>

    <link href="assets/styles/salesforce-lightning-design-system-vf.css" rel="stylesheet"/>
  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="recordId" type="Id" />

    <ui:inputSelect class="slds-col slds-media slds-media--center" aura:id="InputSelectDynamic"/>
</aura:component>

Controller
public class dcontroller {

    @AuraEnabled
    public static List<String> getpickval(ID accId) {
        List<String> options = new List<String>();

        List<Contact> contactResult = [Select Name from Contact where AccountID =:accId];
        options.add('Contact ('+ contactResult.size() + ')');
        for (Contact f: contactResult) {
            options.add(f.Name);
        }
        return options;
    }
}

Helper.js
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getpickval");
action.setParams({
            "accId": component.get("v.recordId")
        });
        var inputsel = component.find("InputSelectDynamic");
        var opts=[];
        action.setCallback(this, function(a) {
            for(var i=0;i< a.getReturnValue().length;i++){
                opts.push({"class": "optionClass", label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
            }
            inputsel.set("v.options", opts);

        });
        $A.enqueueAction(action);
        }
})

Page
<apex:page standardController="Lead">
    <apex:includeScript value="/lightning/lightning.out.js" />

</apex:page>

A: The value of the 'recordId' attribute is not being set anywhere in the process. You might want pass the value of 'record Id' from the script part of visual force page

Please confirm if this worked

A: Try using this:
<apex:includeLightning />

instead of:
 <apex:includeScript value="/lightning/lightning.out.js" />

See Use Lightning Components in Visualforce Pages:
<apex:page>
    <apex:includeLightning />

</apex:page>


text:
Q: Codeigniter in localhost WAMP Windows I try to use Codeigniter in localhost with WAMP.
Problem is, that I can open just basic function in basic controller, and when I tried to use root like site/controller/function, its do not work. Result is that it put me back to wamp start page, or text that page not found.
Mostly I found solutions about makingthe .htaccess file, and many variations what to put in it.
To uncomment rewrtie mod in wamp .conf file. And in my web page to leave index_page empty.
But It do not work for me.
My controller:
class Home extends CI_Controller {

    function index() {

            $this->load->view('index');
            }

    function slide() {

            $this->load->view('slider');
            }
 }

And my web page is in: www/mysite/....

A: Try this .htaccess
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond $1 !^(index\.php|indexcp\.php?|resources|robots\.txt)
RewriteRule ^([A-Za-z0-9_/.-]+)$ index.php?$1

RewriteRule ^(CSI) index.php?/CSI
AddType text/x-component .htc

EDIT
Add the above code here

Don't change any thing in CI system..
Once check this repo


text:
Q: NumberFormatException when trying to convert the contents of a String Array into an Integer to be stored in an ArrayList This is my current code:
    ArrayList<String> arrayCurrency = new ArrayList<String>();
    ArrayList<Integer> arrayRate = new ArrayList<Integer>();
    ArrayList<String> arraySymbol = new ArrayList<String>();

public void loadFile() {

    File file = new File("C://Users//me//Documents//TestingAssignment//Assignment 2 Part 2//src/currency2.txt");

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));

        String line = in.readLine().trim();

        while (line != null) {

            String[] parts = line.split(",");

            line = in.readLine();

            String currency = parts[0].trim();
            String rate = parts[1].trim();
            String symbol = parts[2].trim();

            int rateConverted = Integer.parseInt(rate);

            //int thisRate = rateConverted2;

            arrayCurrency.add(currency);
            arrayRate.add(rateConverted);
            arraySymbol.add(symbol);

        }

        for(String name:arrayCurrency) {
            System.out.println(name);
        }

        for(int name:arrayRate) {
            System.out.println(name);
        }

        for(String name:arraySymbol) {
            System.out.println(name);
        }

        in.close();

    } catch (Exception e) {

        String msg = e.getMessage();

        JOptionPane.showMessageDialog(null, msg);
    }

}

I have gone through the code with a debugger. It happens when it attempts to convert the first number in the text file.
An example of how the .txt file is set out:
US Dollars, 1.60, $
I want to split this up into 3 different arrays. However, I am having a problem trying to convert parts[1].trim(); into an Integer so that it can be stored in ArrayList<Integer> arrayRate = new ArrayList<Integer>();.
The error message shown is: "For Input String:" 1.60".
Any help is appreciated. Thanks.

A: you can do like this if you want integer part only
String s = parts[1].trim();
double d = Double.parseDouble(s);
int i = (int) d;

and if you want both part separately then do like below:
String s =parts[1].trim();
double d = Double.parseDouble(s);
int i = (int) d;
double j=d-i;

A: Amounts like "1.60" should be better represented as doubles, rather than integers.
I'd suggest you change your amount arrayList to ArrayList<Double> and parse the rate like below :
 double rateConverted = Double.parseDouble(rate);

A: 1.6 is not an Integer. You will need to store it in a Double List and convert to double using methods of Double class.
ArrayList<Double> arrayRate = new ArrayList<>();
Double dnum = Double.parseDouble(str);

Use this link for reference - https://beginnersbook.com/2013/12/how-to-convert-string-to-double-in-java/


text:
Q: How to show x and y are equal? I'm working on a proof to show that f: $\mathbb{R} \to \mathbb{R}$ for an $f$ defined as $f(x) = x^3 - 6x^2 + 12x - 7$ is injective. Here is the general outline of the proof as I have it right now:
Proof: For a function to be injective, whenever $x,y \in A$ and $x\neq y$, then $f(x) \neq f(y)$, i.e., where $A$, $B$ are finite sets, every two elements of $A$ must have distinct images in $B$, which also implies that there must be at least as many elements in $B$ as in $A$ such that the cardinality of $A$ is less than or equals the cardinality of $B$.
We shall prove the contra-positive: If $\exists$ $f(x) = f(y)$, then $x=y.$
Let $x^3 - 6x^2 + 12x - 7 = y^3 - 6y^2 + 12y - 7$.
Then by addition and some algebra, we get $x(x^2 - 6x + 12) = y(y^2 - 6y + 12)$

This feels dumb to ask but how do I continue to finally get the result that $x = y$?

A: A differentiable function with everywhere positive derivative is injective. The derivative of $f$ is $f'(x)=3x^2-12x+12=3(x^2-4x+4)=3(x-2)^2$. This is positive for $x\ne2$. To see that the zero derivative at $x=2$ doesn't destroy injectivity, integrate this to find $f(x)=(x-2)^3+C$ (with $C=1$). Thus $f$ is a shifted version of $x^3$, which is injective.

A: Hint $\rm\,\ 0 = f(x)\!-\!f(y) = (\color{#C00}{x\!-\!y})\,\left(\left(\color{blue}{y\!-\!2}\ +\dfrac{\color{#0A0}{x\!-\!2}}2\right)^2\! + 3\,\left(\dfrac{\color{#0A0}{x\!-\!2}}{2}\right)^2\right)\iff \begin{eqnarray}\rm \color{#C00}{x=y}\quad \ or\\\rm\  \color{#0A0}{x=2}\ \ and\ \ \color{blue}{y = 2}\end{eqnarray}$
Remark $\ $ This approach doesn't require noticing that $\rm\:f(x) = (x-2)^3\!+1.\:$ Rather, we use only  $\rm\:x\!-\!y\:|\:f(x)\!-f(y)\:$ (Factor Theorem), and we complete the square in the quadratic cofactor.

A: Note that $w^3-6w^2+12w-8=(w-2)^3$.  So $w^3-6w^2+12w-7=(w-2)^3+1$.
So we want to show that if $(x-2)^3+1=(y-2)^3+1$ then $x=y$.
Equivalently, we want to show that if $(x-2)^3=(y-2)^3$ then $x=y$. This is easy, the cube function is increasing.
Remark: We can use the basic algebra of ordered fields to show that if $s^3=t^3$ then $s=t$. For $s^3-t^3=(s-t)(s^2+st+t^2)$. But
$$2(s^2+st+t^2)=(s+t)^2+s^2+t^2,$$
so $s^2+st+t^2$ can only be $0$ when $s=t=s+t=0$.


text:
Q: NODEJS parse cell value get from google sheets I get value from cell range from google sheets using REST api, this is my response from google sheets
{
  "range": "RECORD!A2:J2",
  "majorDimension": "ROWS",
  "values": [
    [
      "07/11/2016",
      "21:20:10",
      "3",
      "MAIN",
      "Nam",
      "1",
      "xxxxxxxxxxx",
      "xxxxxxxxxxx",
      "xxxxxxxxxxx",
      "xxxxxxxxxxx"
    ]
  ]
}

I try to use JSON.parse() method. Here my code
var data = JSON.parse(response);              //reponse store presponse from google sheets
var data_values = resposne.values[0];

How I get data from values[0]? like:
var DAY = values[0][0];
var TIME = values[0][1];
var NO = values[0][2];
var OBJECT = values[0][3];
var NAME = values[0][4];
.........

A: for(var i=0;i<response.values.length;i++){
  for(var j=0;j<response.values[i].length;i++){
          var DAY = values[i][j];
          var TIME = values[i][j];
          var NO = values[i][j];
          var OBJECT = values[i][j];
          var NAME = values[i][j];
  }
}