Q:

How to authenticate without prompt to CRM Dynamics Online webservices with ADAL, NetStandard, and Azure AD

I'm currently trying to create a Xamarin App in order to get some info from a Dynamics 365 online instance. The code that authenticate with AD and access the CRM api is deported in a NetStandard (v1.6) Library.
I use the following NuGets :

Microsoft.IdentityModel.Clients.ActiveDirectory (3.13.9)
NETStandard.Library (1.6.1)

I followed the following tutorial in order to link AD with my Dynamics instance : https://nishantrana.me/2016/11/13/register-a-dynamics-365-app-with-azure-active-directory/
Here is my ActiveDirectory helper :
public static class ADHelper
    {

        public async static Task<AuthenticationResult> GetAuthAsync(Uri uri, ClientCredential creditential)
        {
            AuthenticationParameters ap = await AuthenticationParameters.CreateFromResourceUrlAsync(uri);

            String authorityUrl = ap.Authority;
            String resourceUrl = ap.Resource;

            AuthenticationResult result = null;

            AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
            result = await authContext.AcquireTokenAsync(resourceUrl, creditential);
            return result;
        }
    }

And my CRM API Client :
public class CRMClient
{
    private AuthenticationResult Auth { get; set; }
    private Uri baseUri { get; set; }

    public CRMClient(Uri uri, ClientCredential creditential)
    {
        baseUri = uri;
        Auth = ADHelper.GetAuthAsync(uri, creditential).Result;
    }

    public void getObject()
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Auth.AccessToken);
            client.Timeout = new TimeSpan(0, 2, 0);
            client.BaseAddress = baseUri;
            HttpResponseMessage message = client.GetAsync("/accounts").Result;
            String content = message.Content.ReadAsStringAsync().Result;
        }
    }

Parameters used for CRMClient Constructor :

https://[my_crm_instance_Url]/api/data/v8.2/ => the data OData endpoint
ClientCredential(AppId, AppKey) => as credential

Azure AD gives me a token back, but UserInfo, TenantId and idToken are all null (This could be a part of the cause of my problem).
Currently, the returned content is the HTML office 365 login page instead of the data I wanted to get.
Could someone help me?

A:

I create a full blog post here
http://phuocle.net/crm/dynamics-365-online-s2s-authentication-full-explain.aspx


Q:

Using HMAC to secure a "widget"

Let's say I have a web "widget" that a customer could include on their website. They would include the widget by adding an iframe that points to a URL on my site. I want to ensure that my widget can only be used by paying customers so I was thinking of using an HMAC (HMAC-SHA256 specifically) to verify the customer like so:

The URL would contain a customer ID (randomly generated 6 character hexadecimal number), a timestamp (the current time in seconds since UNIX Epoch), and the HMAC "signature". Since the widget is displayed in an iframe, all of these parameters would be sent clear-text (as a GET request).
The "signature" would be computed based on the URL (since there are multiple widgets), the customer ID, and the timestamp, with a (randomly generated) secret key that would be given to the customer.
On the server, the timestamp is checked to ensure that it falls within a specific window (15 minutes, for example) to prevent replays, and then the signature is checked by recomputing the HMAC and comparing.

I patterned my design off Amazon's web services, but Amazon's scheme requires that some of this data is passed via HTTP headers which would be encrypted over SSL. I don't have that luxury, since everything needs to be passed via GET parameters.
Does this sound reasonably secure? A coworker mentioned that it may not be very secure because all of the inputs to the HMAC algorithm are available in clear-text. An attacker would still need to figure out the way in which the URL, customer ID, and timestamp are combined to create an input to the HMAC algorithm, but, if they did, then they'd have both the input and output. My coworker worried that this information could be used to obtain the secret key via brute force or rainbow tables. Everything I've found via searching seems to indicate that our sun would explode before brute force would finish, and rainbow tables don't work on HMAC's, but the wide world of cryptography is very foreign to me. Plus, most of the answers I've found are 2+ years old and much can change... maybe some new vulnerability was found in the last 2 years or something...
So, is this reasonably secure? And, if not, what can I do to improve security?

A:

Yes, this sounds secure to me.  HMAC, like any secure MAC algorithm, is designed to be existentially unforgeable under chosen-plaintext attacks: that is to say, even if the attacker was allowed to request from you the MACs for any set of messages they wanted, they would not be able to compute a valid MAC for any message they didn't request it for.
(Of course, this is only guaranteed to hold if the hash algorithm used to instantiate HMAC meets the security assumptions set out in the HMAC security proof.  In practice, though, secure cryptographic hash algorithms like the SHA-2 family are believed to meet these assumptions — and, in any case, HMAC is a very robust construction and seems to be very tolerant of even rather poor hashes like MD5.)
Of course, I'm assuming that all clients will be getting their own HMAC keys, so that you can revoke keys if they're compromised or simply if the client stops subscribing to your service.


Q:

Perl WSDL11 Can't Make it to Work on two WSDL files

This question is related to the issue I encountered on my Perl Program using XML::Compile::WSD11 Perl Module in which my company Webservice uses multiple WSDL with XML import.
The original post that describe this issue can be found here. From that post, I tried the suggestion of imatveev13 to use the addWSDL API from XML::Compile::WSDL11 and the code snippet is shown below.
The two WSDL files used in the test Perl program are: WSDL0 and WSDL1.
#!/usr/bin/perl

use 5.018;
use strict;
use warnings;

use Data::Dumper qw{Dumper};

use XML::Compile::SOAP11; # XML::Compile::SOAP 2.x
use XML::Compile::WSDL11;
use XML::Compile::Transport::SOAPHTTP;

my $WSDL0 = 'CamstarWebClient0.wsdl';
my $WSDL1 = 'CamstarWebClient1.wsdl';

# Create service proxy for web service
my $wsdlXml0 = XML::LibXML->new->parse_file($WSDL0);
my $wsdlXml1 = XML::LibXML->new->parse_file($WSDL1);

my $SoapSrv = XML::Compile::WSDL11->new();
$SoapSrv->addWSDL($wsdlXml0);
$SoapSrv->addWSDL($wsdlXml1);

print Dumper($SoapSrv);

# Compile all service methods
my (%SoapOps);
foreach my $SoapOp ($SoapSrv->operations)
{
    print Dumper($SoapOp);
    # XML::Compile::SOAP 2.x
    if ($XML::Compile::SOAP::VERSION > 1.99)
    {
        $SoapOps{$SoapOp->name}
            = $SoapSrv->compileClient(operation => $SoapOp->name,
                                      port => "ICamstar");
    }
}

print "\n";
exit;

Running the code gave me an error: cannot find port 'ICamstar', pick from BasicHttpBinding_ICamstar.
I also tried without specifying the port since the service do not implement multiple port but it gave me a different error.
Can't locate object method "_writer_body_rpcenc_hook" via package "XML::Compile::SOAP11::Client" at /usr/local/share/perl5/XML/Compile/SOAP.pm line 155.
Appreciate any help from the community. Thanks.

A:

Make sure to use the module XML::Compile::SOAP11::Encoding on top of your script:
use XML::Compile::SOAP11::Encoding;


Q:

PHP: Alternative to returning a blank file

In my blank.php it currently has following:
<?php
// Blank file...

I am using this file to replace a particular template in my WordPress like so:
add_filter( 'comments_template', blank_file' );
function blank_file() {
    return PLUGIN_PATH . '/blank.php';
}

However, instead of creating a blank file to return, is it possible to just return a blank value to get the same results? I tried the following which would make sense to me logically, but it didn't work:
function blank_file() {
    $blank = '<?php';
    return $blank;
}

A:

I found a similar question on WordPress Stack Exchange here. However, it looks like the solutions require more coding than what I am currently using which works for me:
add_filter( 'comments_template', 'comments_template', 20, 1 );
 function comments_template() {
    return plugin_dir_path( __FILE__ ) . 'blank.php';
}

Where blank.php has:
<?php
// Blank file...


Q:

What is known about solutions to sparse integer linear programming problems?

If I have a set of linear constraints in which each constraint has at most (say) 4 variables (all nonnegative and with {0,1} coefficients except for one variable that can have a -1 coefficient), what is known about the solution space?  I am less concerned with an efficient solution (although please indicate if one is known) than with knowing how small the minimum of the objective function can be, as a function of the number of variables and number of constraints, and the number of variables per constraint.
More concretely, the program is something like
minimize t
  subject to
for all i, x_i is a positive integer
x1 + x2 + x3 - t < 0
x1 + x4 + x5 - t < 0
...
x3 + x6 - t     ≥ 0
x1 + x2 + x7 - t ≥ 0
...
If a concrete question is needed, then is it the case that the minimum solution obeys t <= O(max{# of variables, # of constraints}), with the constant in the O() depending on the sparseness?  But even if the answer is no, I am more interested in knowing what kind of textbook or paper to study for a discussion of such issues, and if there is an area of study devoted to this kind of thing but I just don't know the terms to search for.  Thank you.
Update: With further reflection (and thinking through the rather simple reduction of 3SAT to ILP, which uses constraints with three variables), I realize that the issue of coefficients is critical (if there is going to be an efficient algorithm).  More precisely, all x_i variables have 0 or 1 coefficients (with at most three 1 coefficients in any one constraint), and all t variables have -1 coefficients, and all comparisons have variables on the left and 0 on the right.  I updated the above example to clarify.

A:

The answer to this (at least to the concrete question about linearly bounding the solution) is no.  This is part of the following paper: http://arxiv.org/abs/1011.3493.  Theorem 5.1 was the motivation for this question.
The counterexample is this:
base case:

a_1'  + b_1'  - t ≥ 0
a_1'' + b_1'' - t ≥ 0
a_1   + b_1'  - t ≤ -1
a_1 ' + b_1'' - t ≤ -1

recursive case:

a_n'  + b_n'  + a_{n-1}   - t ≥ 0
a_n'' + b_n'' + a_{n-1}   - t ≥ 0
a_n   + b_n'  + a_{n-1}'' - t ≤ -1
a_n'  + b_n'  + a_{n-1}'' - t ≤ -1

along with requiring them all to be nonnegative.
You can prove by induction that any real solution must satisfy a_n'' >= a_n + 2^n.  We change the "< 0"-inequalities into "≤ -1" because any integer solution satisfies "≤ -1" if and only if it satisfies "< 0".
So, the moral is that n inequalities of this form can have the property that all integer solutions have at least one integer at least exponential in n, certainly not linearly bounded as we originally suspected.

A:

If the coefficient matrix is totally unimodular, then an efficient solution exists via ordinary linear programming.  This holds for any ILP, not just sparse ones -- though you're more likely to be able to exploit this property for a sparse ILP such as yours.
I suspect you may know this already, so let me try and give you a better answer.  Before thinking about the specifics too deeply, the answer to your concrete question is "yes", a bound exists. The the intersection of n inequalities in m variables defines a polytope.  Because the coefficients are so well-behaved, we can work out an upper bound on the dimension of the coordinates of its vertices with a little arithmetic.  This gives you a very easy upper bound on the dimension of any integer point within the polytope, and thus on a solution to your integer program. Have you tried this already?
Your problem in particular has quite a bit of structure (I'm curious, where does it come from?) so I'm confident that we can be much more precise than this if we discuss it further.
Now, for the more general question about finding information on this topic.  This is the sort of problem that traditionally falls in the theory of linear and integer programming, a subset of mathematical programming.
It's quite an active area of research, but much of the work takes place in operations research departments under the headings of "optimization" and "mathematical programming" instead of computer science.  There are many textbooks available covering the topic.  You might consider the one by Wolsey, which we use at Berkeley.  Here is an underused list of myths and counterexamples by Greenberg, including integer and linear programming, which may give you a sense of what things people consider in analyzing such problems.  Wolsey is dense, but a reasonably good place to start -- there are a bevy of techniques for analyzing ILPs and improving problem formulations to the point of efficiency.
Let me add that if you do pursue the naive approach I suggest, by analyzing the geometry of the polytope, the terms to search for would concern bounding the size of the coordinates of the polytope's vertices. These terms come up more often in the mathematical literature about polytopes.

A:

You may find this account of interest:
http://en.wikipedia.org/wiki/Polyhedral_combinatorics
and in particular the article by G. Ziegler:
Lectures on 0-1 polytopes
in:
Kalai, Gil; Ziegler, Günter M. (2000), Polytopes: Combinatorics and Computation, DMV Seminar, 29, Birkhäuser, ISBN 9783764363512 .


Q:

MvcSiteMapProvider not ready on page render, cache issue?

tl;dr: Menu from MvcSiteMapProvider sometimes fails to render itself after an application comes back online, even though the code runs and the menu renders after a page refresh.
I am using the MvcSiteMapProvider in an ASP.NET MVC 3 project, and occasionally after switching the app from offline to online (by inserting a an App_Offline.htm file into the server's root and removing it) the menu will not render anything until the page is refreshed.
I am using a custom DynamicNodeProvider to query out menu items from a database, and then render the menu. While debugging, I can see that this code is indeed running before the page loads, but no menu is rendered on the page. I have the cache set to several hours, and am using a custom cache key to allow invalidation after certain actions.
Unfortunately I cannot get this error to reproduce consistently. I can however get it to reproduce more frequently if I add a sleep at the top of the DynamicNodeProvider--it will fail about 60-70% of the time with a sleep of 30+ seconds. My best guess so far is that it has to do with the caching mechanism because setting my cache duration to 0 seems to make it so that there is no problem, and the menu always pops up. However, it's difficult to say for sure, as the problem is difficult to pin down. Leaving it at 0 wouldn't be an acceptable solution because of the performance drag.
What could be the root cause of this problem? Has anyone seen this behavior before or have a workaround?

A:

MvcSiteMapProvider is bitten by the ASP.NET SiteMapProvider's threading model from time to time, especially when having larger sitemap definitions. Currently there's no workaround for this behaviour, but I'm planning on doing a rewrite (and ditching the ASP.NET SiteMapProvider dependency) to make it more stable under heavy conditions.


Q:

Can $y''=1/y$ be solved without numerical way?

Is there  any way to solve it without numerical way??
$$ \frac{d^2 y}{d x^2}= \frac{1}{y}$$
thanks in advance!!

A:

Note that $y''y'=y'/y$ hence $(y')^2=c+2\log|y|$ hence $y'=\pm\sqrt{c+2\log|y|}$ and
$$
\int_{y(0)}^{y(x)}\frac{\mathrm dt}{\sqrt{c+2\log|t|}}=\pm x.
$$
The LHS does not seem to be (the inverse of) a usual function of $y(0)$ and $y(x)$. An equivalent formulation is
$$
\mathrm e^{-c/2}\int_{\sqrt{c+2\log|y(0)|}}^{\sqrt{c+2\log|y(x)|}}\mathrm e^{t^2/2}\mathrm dt=\pm x,
$$
and the LHS can be rewritten using the imaginary error function $\mathrm{erfi}$, with no obvious gain.


Q:

target="_blank" in p:menuitem doesn't open new tab

I am using  primefaces 5.1, liferay 6.2.0-ga2 and JSF2. I have a page with button. When I press right-click a context menu with one menuitem is displayed. That menuitem must open a new tab, but it doesn't.
                        <p:commandButton id="viewUnassignedCase"
                            action="application-container" styleClass="icon fa fa-eye">
                            <f:setPropertyActionListener
                                target="#{applicationManagementBean.application}"
                                value="#{unassignedCase}" />

                            <f:setPropertyActionListener
                                target="#{applicationManagementBean.activeIndexTab}" value="0" />
                        </p:commandButton>

                        <p:contextMenu for="viewUnassignedCase" id="tableMenu"
                            widgetVar="tableMenu">
                            <p:menuitem value="#{caseList['caseManagement.case.newtab']}"
                                target="_blank"
                                action="#{applicationManagementBean.openNewTabDetail(unassignedCase)}">
                            </p:menuitem>
                        </p:contextMenu>

and the bean
    public String openNewTabDetail(final FlexibleDomain application)
{
    setApplication(application);
    return "application-container";
}

How can I fix it?

A:

There's an issue tagged as "Won'tFix" on Primefaces's GoogleCode for this behavior (p:menuItem not opening a new window using action).
In your case you would need to adapt your action-based navigation for a url based one.
I can't really figure out how to make it work in your project, but my best bet is trying something like this:
<p:contextMenu for="viewUnassignedCase" id="tableMenu"
                            widgetVar="tableMenu">
                            <p:menuitem value="#{caseList['caseManagement.case.newtab']}"
                                target="_blank"
                                url="www.yoururl.com/yourdesiredpath">
                            </p:menuitem>
                        </p:contextMenu>

In the worst case scenario you should try to override Primefaces's p:menuitem default behavior or maybe try to use another component that support this kind of implementation.
Good luck!


Q:

Displaying the tablix structure for No data values in ssrs?

I am working on a SSRS report in which I have a parameter with a list of names, In which a multiple value can be selected by the user. I gave title of the report using an expression where it shows "Result for SELECTED NAME" and applied page break such that each value is displayed on a new page.
But when i select all the values at a time, the report is only displaying the results for the names only for whom the data is available.
I would like to display the title as "Result for SELECTED NAME"(remember this is for the values with no data along with the values with data, each on new page) and tablix structure with a NoRowmessage.
I am really struggling on this since two days!!
Can any one help me?? Thanks Guys.

A:

I think you should look at your query. Is your query returning a row for each name, or only rows where the names exist? If you can, change the structure of your query to return the names, left joined to your actual query.
Here's some simple code that captures the idea:
SELECT names.Lastname, names,Firstname, data.*
from (select distinct name from name table) as names
left join (previous query) as data on data.nameID = names.nameID


Q:

How to set ICC attribute "fp-model precise" for a single function, to prevent associative optimizations?

I am implementing Kahan summation, in a project that supports compilation with gcc47, gcc48, clang33, icc13, and icc14.
As part of this algorithm, I would like to disable optimizations that take advantage of the associativity of addition of real numbers.  (Floating point operations are not associative.)
I would like to disable those optimizations only in the relevant function.  I have figured out how to do this under gcc, using the ''no-associative-math'' attribute.  How can I do this in icc or clang?  I have searched without luck.
class KahanSummation
{
  // GCC declaration
  void operator()(float observation) __attribute__((__optimize__("no-associative-math")))
  {
    // Kahan summation implementation
  }
};

Other GCC attributes that would imply no-associative-math are no-unsafe-math-optimizations or no-fast-math.
Looking at an Intel presentation (PDF, slide 8) or another or another (PDF, slide 11), I want to set "fp-model precise" in ICC, for only this function.  The compilers I care about are ICC 13 and ICC 14.
class KahanSummation
{
  // ICC or clang declaration
  void operator()(float observation) __attribute__((????))
  {
    // Kahan summation implementation
  }
};

A:

__attribute__ is a GCC extension. Clang also supports that syntax to maintain some GCC compatibility, but the only optimization-related attribute it seems to support is optnone, which turns off all optimizations. ICC has a few optimization pragmas, but nothing that does what you want to do, from what I can tell. appears to support #pragma float_control for VC++ compatibility, although I can't find anything on exactly how that pragma is supposed to be used in ICC's documentation, so you'll have to use VC++'s.
What you can do, though, is to define the function you want in a separate translation unit (i.e., cpp file):
// Your header
class KahanSummation
{
  // Declaration
  void operator()(float observation);
};

// Separate cpp file - implements only this function
void KahanSummation::operator()(float observation)
{
    // Kahan summation implementation
}

You can then compile the separate file using whatever compiler option you need to use, and link the resulting object file to the rest of your program.


Q:

In ref : Linking C compiled static library to C++ Program

Stackoverflow won't let me comment because I am a newbie.
Borrowing the title from the question posted here, the accepted solution says that you have to modify the C header file using #ifdef __cplusplus and extern "C".
I have the exact same question but I have been provided a C library containing over 100 .h C header files and .c C program files and now I have to use a C++ library so my main() will be in C++.
So do I now have to add those modifications to each one of those C header files or is there some other approach? My main() is in a .cpp file which will use functions from this C library.
EDIT
This question has been resolved. I wish for this question to be closed or removed.

A:

You don't have to modify any headers. What is necessary is to wrap all C declarations with extern C {}. You can do this just as well in you cpp file:
extern "C" {
#include "some_c_header.h"
}

int main() {
    std::cout << "This is C++ code\n";
}

It might be useful to create a header file which simply includes C headers with C linkage:
// c_header.hpp
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include "c_header_1.h"
#include "c_header_2.h"

#ifdef __cplusplus
}
#endif

// main.cpp
#include "c_header.hpp" // extern "C" {} already handled for you


Q:

Is there any way to make a shell script to automate creation and preparation of a scratch org wait between steps?

I have the following shell script:
sfdx force:org:create -f ./config/project-scratch-def.json -a ScratchOrg
sfdx force:package:install --package 04t0M000001mF9bQAE -u ScratchOrg
sfdx force:package:install --package 04tG0000000LKgXIAW -u ScratchOrg
sfdx force:package:install --package 04t58000000KnAkAAK -u ScratchOrg
sfdx force:package:install --package 04t1Q000000lpP6QAI -u ScratchOrg
sfdx force:source:push -u ScratchOrg

However this fails because the push happens before the 4 packages have finished installing.
Is there some way I can make this wait?
Or better, include this information in my scratch org configuration?

A:

Use the -w parameter so that each command waits for confirmation, and things proceed in order:
sfdx force:org:create -w 10 -s -f ./config/project-scratch-def.json -a ScratchOrg
sfdx force:package:install -w 10 --package 04t0M000001mF9bQAE
sfdx force:package:install -w 10 --package 04tG0000000LKgXIAW
sfdx force:package:install -w 10 --package 04t58000000KnAkAAK
sfdx force:package:install -w 10 --package 04t1Q000000lpP6QAI
sfdx force:source:push

The 10 here means 10 minutes. If you think you more time, feel free to increase the value. I usually use 99 minutes in my scripts, which should be plenty of time.
Also, note that you can use -s to set the default user name to the scratch org, which simplifies your commands.
I also prefer to use aliases for my packages:
sfdx force:package:install -w 10 --package "package A"
sfdx force:package:install -w 10 --package "package B"
sfdx force:package:install -w 10 --package "package C"
sfdx force:package:install -w 10 --package "package D"

This helps you when you need to update package IDs, as you can centralize the updates to your sfdx-project.json file.


Q:

Why is mass times position not used in physics?

The momentum $\vec{p}=m \vec{v}$ plays a very prominent role in physics.
Why is the same not true for the quantity $\vec{q}=m \vec{r}$?
E.g. one can write angular momentum as $\vec{L} = \vec{r} \times \vec{p}$ but from the rules for the cross product we could equally also write
$$
\vec{L} = \vec{r} \times \vec{p} = \vec{r} \times m\vec{v} = m \vec{r} \times \vec{v} = \vec{q} \times \vec{v}
$$
Similarly in quantum mechanics we have the canonical commutation relation
$$
i\hbar = \left[\hat{r},\hat{p}\right] = \left[\hat{r}, m \hat{v}\right] = \left[m \hat{r}, \hat{v}\right] = \left[\hat{q},\hat{v}\right]
$$
So from these examples one could get the impression that $q$ and $p$ play very symmetric roles in physics. But the quantity $q$ doesn't even have a name, or does it? Why is mass times position not used in physics?

A:

I would call this quantity "first moment of mass" or just "moment of mass". Have a look at this wikipedia article to read about the general concept of moments in physics.
As pointed out in the comments to your question, the first moment of mass is closely related to the center of mass (CoM). For a collection of particles with masses $m_i$ and positions $\vec{r}_i$, the first moment of mass is $\vec{q} = \Sigma m_i \vec{r}_i$ and the position of the CoM is $\vec{r_{com}} = \frac{\Sigma m_i \vec{r}_i}{\Sigma m_i}$. Thus $\vec{r_{com}} = \frac{\vec{q}}{\Sigma m_i}$. This means many statements about $\vec{q}$ can be rephrased in terms of $\vec{r_{com}}$.
The center of mass is a purely geometrical quantity, unlike the moment of mass. It could also be argued that the center of mass is a more intuitive and simple concept. This may explain why the moment of mass is relatively obscure.
One place where I have seen the moment of mass being used and recorded explicitly is in aerospace engineering. I once did a work experience placement with an aircraft manufacturer that kept a database of all components in a particular aircraft. Two of the fields recorded for every component were mass and first moment of mass (relative to some fixed origin, I think it was the nose of the plane). I guess storing information in this way slightly simplified center of mass calculations when components were replaced/removed due to maintenance.


Q:

Does anyone know why all of my elements are being rendered in a single column as if it were a ?

My component  is being rendered in a single column equal to the photo I attached, but it is wrong, it was to be a 5x4 array.
edi1: In an old version of the code I did not have this problem, however  I received some props, and since I have to constantly change the contents of the Component, I thought it was good to use state.

  render() {
    return (

        <Navbar onChange={this.onChange.bind(this)} />

            {<RecipeItem list={this.state.searchString} />}

    );
  }
}

File RecipeItem.js
const RecipeList = ({ searchString }) => {
    return(

{searchString.title}

                Ingredients: {searchString.ingredients}

    )
}

const RecipeItem = (props) => {
    return (

                {props.list && props.list.map((searchString, index) =>
                    <RecipeList searchString={searchString} key={index} />
                )}

    )
}

A:

You're applying col-sm-3 before iterating on each element, you should apply the class on each iteration like this :
const RecipeItem = (props) => {
  return (
     props.list && props.list.map((searchString, index) =>

          <RecipeList searchString={searchString} key={index} />

      )
  )
}


Q:

Suppress C Macro Variable Substitution

I have this bit of code (part of an interpreter for a garbage-collected Forth system, actually):
#define PRIMITIVE(name) \
    do \
    { \
        VocabEntry* entry = (VocabEntry*)gc_alloc(sizeof(VocabEntry)); \
        entry->code = name; \
        entry->name = cstr_to_pstr(#name); \
        entry->prev = latest_vocab_entry; \
        latest_vocab_entry = entry; \
    } \
    while (false)

PRIMITIVE(dup);
PRIMITIVE(drop);
PRIMITIVE(swap);
// and a lot more

but there's a problem: in the line
entry->name = cstr_to_pstr(#name);

the name field is substituted for dup, drop, swap, and the rest. I want the field name to not be substituted.
So, is there any way to solve this, other than simply renaming the macro argument?
For an answer, please explain if there is, in general, a way to suppress the substitution of a macro argument name in the macro body. Don't answer "just do it this way" (please).

A:

You can define a different macro to expand to name, like this:
#define Name name

and change the name field in the PRIMITIVE macro to use the new macro, like this:
#define PRIMITIVE(name) \
    do \
    { \
        VocabEntry* entry = (VocabEntry*)gc_alloc(sizeof(VocabEntry)); \
        entry->code = name; \
        entry->Name = cstr_to_pstr(#name); \
        entry->prev = latest_vocab_entry; \
        latest_vocab_entry = entry; \
    } \
    while (false)

Other than using something different from the parameter name in the macro body or changing the parameter name, there is no other way to do this in the C language. Per C 2011 (N1570) 6.10.3.1 1, when a function-like macro is recognized, parameter names are immediately substituted except when # or ## is present, and there no other exceptions:

After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded.

The # token changes the parameter name to a string, which is no use in this situation. The ## token expands the parameter name and pastes it together with an adjacent token, which is also no use in this situation.

A:

No, there is not.
To see why, you need to consider the way macro expansion actually happens. Expanding a function-like macro requires three main steps:

the arguments to the macro are fully expanded, unless the macro uses the # or ## operators on them (not relevant in the example since they're single tokens)
the entire replacement list is scanned, and any occurrence of a parameter name is replaced by the corresponding argument
after step 2 is complete, the expanded replacement list is itself rescanned, and any macros appearing are expanded at this point

This is outlined in standard section 6.10.3 (C11 and C99).
The upshot of this is that it is impossible to write some kind of macro that can take name and abuse the suppression-rules of '##' or anything like that, because the replacement step in the body of PRIMITIVE must run completely before any of the macros within the body are allowed their turn to be recognised. There is nothing you can do to mark a token within the replacement list for suppression, because any marks you could place upon it will only be examined after the replacement step has already run. Since the order is specified in the standard, any exploit you find that would let you mark a token in this way is a compiler bug.
Best I can suggest if you're really set on not renaming the macro argument is to pass na and me as separate arguments to a concatenation macro; the token name will only be formed after replacement is done and the list is no longer being examined for parameter names.
EDIT wish I typed faster.


Q:

Bootstrapping using Quantlib Python

I want to bootstrap a yield curve in Python using QuantLib library.
I know that when doing bootstrapping using C++, there is a function for bootstrapping called PiecewiseYieldCurve in QuantLiab, but when I am using Python, there is no such function in Python QuantLib.
I wonder that if in Python QuantLib there is an alias of PiecewiseYieldCurve, so I have to call the alias function name in order to use PiecewiseYieldCurve function
Should I creating my own function to bootstrap the yield curve?
Thanks!

A:

PiecewiseYieldCurve is a class template, so it can't be exported to Python as such. By default, we're exporting to Python a particular instantiation of it; it's exported as PiecewiseFlatForward and it correspond to PiecewiseYieldCurve<ForwardRate,BackwardFlat>.
If you need another instantiation, you can edit QuantLib-SWIG/SWIG/piecewiseyieldcurve.i, add it (it you look at the end of the file, you'll find a few examples of how to do it) and regenerate and recompile the Python wrappers.
Finally, an example of bootstrap is available in QuantLib-SWIG/Python/examples/swap.py.


Q:

SQL Server select by grouping

Table 1
csstatus
csid status
122  defaulter
123  regular
124  registery
125  defaulter

table 2
csplotdetials
csid plotsize
122  50
123  25
124  30
125  25

qunery result
Status     totalplotsize

defaulter  75
regular    25
....

how i can do that both tables are not in relationship they are in realtionship with another table

A:

SELECT status, sum(plotsize) as totalplotsize
FROM csstatus cs
INNER JOIN csplotdetials cp ON cs.csid = cp.csid
GROUP BY status


Q:

What kind of Information does the NSA and PRISM collect, and how do they collect it?

Today, It's not uncommon to hear about the NSA and PRISM, and how they've collected information in a controversial manner.
The problem is, that most reports cite abstract "Information on Americans" or, in the case of PRSIM, "Email information" and "Internet Information"
My question is:

What controversial information is the NSA/PRISM known to have collected?
What controversial methods has the NSA/PRISM used to collect this information?
What is the controversy regarding this information/methods?

A:

What controversial information is the NSA/PRISM known to have collected?

It's not the information that's controversial, but the extent of information they have access to--which appears to most communications going through the major internet communications providers (Google, Microsoft, Etc)

What controversial methods has the NSA/PRISM used to collect this information?

I suppose there's lots of controversial aspects depending on who you ask but I think the primary controversy is that the major providers were handing this information over on request and this was not universally known to the public.

What is the controversy regarding this information/methods?

The controversial part of the entire ordeal is that they were likely accessing US Citizen's information sans Warrants. Not necessarily intentionally, but due to the fact that they were only "51% sure" at any given time that the data they were looking at wasn't from a US Citizen (It's illegal to wiretap on an American Citizen without a warrant).
Source: http://en.wikipedia.org/wiki/PRISM_(surveillance_program)#United_States_mass_data_collection_programs


Q:

Does Apple provide disk space that I can back my hard drive up to?

As I understand, with Time Machine I need to provide a drive to back data on to.
Is there also an option to use a server managed by Apple to back up on to?
Either using Time Machine or another program.

A:

The Apple Time Capsule is a network router and network storage server with a 2TB or 3TB hard drive.
When you said, "server" do you mean something you can own and run in your home, or something that exists at a remote location, managed by a storage company, that you access over the Internet?
Internet storage is not suitable for backing up your entire Mac, because moving that many files of that size through your Internet connection is far too slow and inefficient.
You need a local physical hard drive in your home or business to regularly back up your entire Mac using Time Machine. You can supplement this with an Internet storage service like Mozy or Carbonite, but that should only be used for a critical subset of your documents and data, because of the time required to back up the data, and the high cost.

A:

At this point, iCloud only supports backups of iOS devices (though it will keep documents, in those applications which support iCloud document storage). However, other solutions such as Backblaze and Mozy are available (though not free).


Q:

How to read barcodes using Android Phonegap?

I want to scan barcodes using Android Phonegap. How can I do this ?

A:

Check out the PhoneGap barcode tutorial here. It will take you step by step to creating a sample app with zxing via the PhoneGap plugin from purplecabbage.

A:

You would have to build a Phonegap plugin which implements the zxing library.
Or use the pre existing BarcodeScanner plugin which is MUCH easier.


Q:

Check to see if AD Group is empty

I am looking for a way to first check if the AD group is empty and if so, write to the CSV file something like "$GroupName + is empty." I imagine this will be in a IF-THEN construct, but note sure where to place it in my code below or the syntax. Thank you for your help.
#Script will export group members from the imported list of groups
#Import the AD Module necessary for the script to run
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

$resultsarray =@()

foreach ($group in $groups){

    $resultsarray += Get-ADGroupMember -Id $group -Server Server01.domain.com | Get-ADUser -Properties $UserProperties | select (@{n='FirstName';e={$_.GivenName}},
    @{n='LastName';e={$_.Surname}},'Name',@{e={$group};Label="GroupName"})

}
$resultsarray | Export-csv -path C:\temp\Groups_$(get-date -Format yyyy-MM-dd).csv -NTI

A:

After some comments, I think I now understand the question as to when it should be empty or not.
Because the Get-ADGroupMember can return objects of type 'user', 'group' or 'computer', the code needs to handle that and output different results depending on the objectClass of each member.
However, since you want the result as CSV file, you need to take care all objects return the same structured object.
The following should do what you ask for:
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

# loop through the groups and collect group member info in a variable '$result'
$result = foreach ($group in $groups){
    # get all members of the group and force it to be an array
    $groupMembers = @(Get-ADGroupMember -Identity $group -Server 'Server01.domain.com')
    if ($groupMembers.Count) {
        foreach ($member in $groupMembers) {
            switch ($member.objectClass) {
                'user' {
                    # emit an object with the following user properties
                    $member | Get-ADUser -Properties $UserProperties |
                              Select-Object @{Name = 'FirstName'; Expression = {$_.GivenName}},
                                            @{Name = 'LastName'; Expression = {$_.Surname}},
                                            'Name',
                                            @{Name = 'MemberType'; Expression = {$member.objectClass}},
                                            @{Name = 'GroupName'; Expression = {$group}},
                                            @{Name = 'GroupIsEmpty'; Expression = {$false}}
                }
                default {
                    # for other objects like groups or computers, keep the same structure
                    # and only fill in the Name, MemberType and GroupName properties
                    '' | Select-Object 'FirstName','LastName',
                                        @{Name = 'Name'; Expression = {$member.Name}},
                                        @{Name = 'MemberType'; Expression = {$member.objectClass}},
                                        @{Name = 'GroupName'; Expression = {$group}},
                                        @{Name = 'GroupIsEmpty'; Expression = {$false}}
                }
            }
        }
    }
    else {
        # the group is empty. Again: keep the same structure as above
        '' | Select-Object 'FirstName','LastName','Name','MemberType',
                            @{Name = 'GroupName'; Expression = {$group}},
                            @{Name = 'GroupIsEmpty'; Expression = {$true}}
    }
}

$outFile = 'C:\temp\Groups_{0:yyyy-MM-dd}.csv' -f (Get-Date)
$result | Export-csv -path $outFile -NoTypeInformation -Force

Note: in this case you do not even need to use the -Properties parameter on the Get-ADUser cmdlet, since all the properties you want ($UserProperties = 'GivenName', 'Surname', 'Name') are returned by default


Q:

Making android application using pubnub to send GPS information but app crashes and shows no errors

I am making an application that sends  realtime messages through a pubnub server to users that are subscribed to the same channel. I have it working so that I can send strings from device to device, but now I want to send GPS information. The user will input a string "GPS" and that will trigger a method to then send the location info instead of that string. I am having trouble with this part because no errors are shown, but the app crashes when I try to open it. I tried debugging, but I can figure out whats going wrong. The debugger takes me out of my activity and into these other java class files that are embedded in java after I get step over the oncreate method. Any help or feedback would be really appreciated, thanks!

Some errors I found in the logcat:
ADB:
    ddms: null
    java.nio.BufferOverflowException
        at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:182)
        at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
        at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
        at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:698)
        at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
        at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)

Device LogCat:
03-20 15:44:56.780  15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file
03-20 15:44:56.780  15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority [1], There is no sepolicy version file
03-20 15:44:56.780  15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority , loading version is VE=SEPF_SAMSUNG-SGH-I257_4.2.2_0025
03-20 15:44:56.780  15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
java.lang.RuntimeException: Unable to resume activity {com.example.kunalpatel.pubsub/com.example.kunalpatel.pubsub.MainActivity}: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
            at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2835)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2864)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
            at android.app.ActivityThread.access$700(ActivityThread.java:152)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
            at com.example.kunalpatel.pubsub.MainActivity.onResume(MainActivity.java:221)
            at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1202)
            at android.app.Activity.performResume(Activity.java:5404)
            at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2825)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2864)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
            at android.app.ActivityThread.access$700(ActivityThread.java:152)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.pubnub.api.Callback;
import com.pubnub.api.Pubnub;
import com.pubnub.api.PubnubError;
import com.pubnub.api.PubnubException;

public class MainActivity extends ActionBarActivity {

    //Button to subscribe to user specified pubnub channel
    private Button channelSubscribeButton;
    private EditText subscribeChannelEditText;
    private TextView messageLogTextView;

    //Button to send message to other devices subscribed on same channel
    private Button sendMessageButton;
    private EditText sendMessageEditText;

    private LocationManager locationManager;
    private String provider;

    private double lat;
    private double lon;
    private double accuracy;

    private MainActivity activity;

    //-------------------------Access PubNub API-------------------------//

    //pubnub publish and subscribe keys
    Pubnub pubnub = new Pubnub("pub-c-", "sub-c");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Subscribing and sending messages
        channelSubscribeButton = (Button) findViewById(R.id.subscribe_button);
        subscribeChannelEditText = (EditText) findViewById(R.id.channel_name);
        messageLogTextView = (TextView) findViewById(R.id.message_log_text_view);

        sendMessageButton = (Button) findViewById(R.id.send_message_button);
        sendMessageEditText = (EditText) findViewById(R.id.message_edit_text);

        activity = this;

        //Get location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //Define criteria for how to select the location provider --> use default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        //Prints GPS provider if there is or isn't one
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {
            //messageLogTextView.append("GPS Information Not Available");
        }

    }

        @Override
        public boolean onCreateOptionsMenu (Menu menu){
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected (MenuItem item){
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

    public void onChannelButtonClick(View view) {

        //Get the user inputted text in
        String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
        String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";

        Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_SHORT).show();

        try {
            pubnub.subscribe(subscribeChannel, new Callback() {

                        @Override
                        public void connectCallback(String channel, Object message) {
                            Log.d("PUBNUB", "SUBSCRIBE : CONNECT on channel:" + channel
                                    + " : " + message.getClass() + " : "
                                    + message.toString());
                        }

                        @Override
                        public void disconnectCallback(String channel, Object message) {
                            Log.d("PUBNUB", "SUBSCRIBE : DISCONNECT on channel:" + channel
                                    + " : " + message.getClass() + " : "
                                    + message.toString());
                        }

                        public void reconnectCallback(String channel, Object message) {
                            Log.d("PUBNUB", "SUBSCRIBE : RECONNECT on channel:" + channel
                                    + " : " + message.getClass() + " : "
                                    + message.toString());
                        }

                        //Updates textview with message
                        @Override
                        public void successCallback(String channel, Object message) {
                            Log.d("PUBNUB", "SUBSCRIBE : " + channel + " : "
                                    + message.getClass() + " : " + message.toString());
                           updateTextView(message.toString() + "\n");
                        }

                        @Override
                        public void errorCallback(String channel, PubnubError error) {
                            Log.d("PUBNUB", "SUBSCRIBE : ERROR on channel " + channel
                                    + " : " + error.toString());
                        }

                    }
            );
        } catch (PubnubException e) {
            Log.d("PUBNUB", e.toString());
        }

    }

    public void updateTextView(final String message) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try{
                    messageLogTextView.append(message);
                } catch(Exception ex) {

                    Log.d("pubnub", ex.getMessage());
                }
                messageLogTextView.setMovementMethod(new ScrollingMovementMethod());
            }
        });

    }

    public void onSendMessageButtonClick(View view, Location location) {

        String messageToSend = String.valueOf(sendMessageEditText.getText());

        Callback callback = new Callback() {
            public void successCallback(String channel, Object response) {

            }

            public void errorCallback(String channel, PubnubError error) {
                Log.d("PUBNUB", error.toString());
            }
        };

        String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());

        pubnub.publish(subscribeChannel, messageToSend, callback);

        //if the user input string is equal to "GPS" then initialize the onLocationChanged method
        //if not, print to the string to the log textview
        if(messageToSend.equals("GPS")) {

            //Print to the textview log the onLocationChanged
            onLocationChanged(location);

        } else {

            updateTextView("GPS cannot be retrieved");

        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates((LocationListener) this);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        //TODO Auto-generated method stub
    }

    //method to retrieve location information
    public void onLocationChanged(Location location) {

        double lat = (double) (location.getLatitude());
        double lng = (double) (location.getLongitude());
        float accuracy = (float) (location.getAccuracy());
        double alt = (double) (location.getAltitude());
        double speed = (double) (location.getSpeed());
        double heading = (double) (location.getBearing());

        messageLogTextView.append(String.valueOf(lat));
        messageLogTextView.append(String.valueOf(lng));
        messageLogTextView.append(String.valueOf(accuracy));
        messageLogTextView.append(String.valueOf(alt));
        messageLogTextView.append(String.valueOf(speed ));
        messageLogTextView.append(String.valueOf(heading ));

    }

}

A:

Your error is this (in the middle of the stack trace you provided):
Caused by: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
  at com.example.kunalpatel.pubsub.MainActivity.onResume(MainActivity.java:221)

Examining MainActivity.onResume, it turns out that you're casting your MainActivity to LocationListener. You'll need to implement LocationListener if you want to be able to pass MainActivity to locationManager.requestLocationUpdates.
To do this, first check the documentation for LocationListener. There are four abstract methods, you've implemented two of them so far - onStatusChanged, and onLocationChanged. You need to implement onProviderEnabled, and onProviderDisabled. Then, change your class declaration to:
public class MainActivity extends ActionBarActivity implements LocationListener


Q:

find() for std::set

I have a question on how the objects stored in set are compared.
class A
{
public:
char * name;
};

I am storing objects of A in a set. I am provide a comparator class which provides implementation of operator() ( A &ob1, A & ob2 ). Here I compare ob1.name & ob2.name and return true when ob1.name is lesser than ob2.name.
Will I be able to search for an object using the find() of set ? I have provided implementation only for operator(). Will this be sufficient ? Could someone explain how find() works in this case ?
Thanks in advance

A:

Will I be able to search for an object using the find() of set ? I have provided implementation only for operator(). Will this be sufficient ?

Yes, it will be sufficient to provide only comparator class with implementation for operator ()(A&,A&) only. See default comparator std::less<>.

Could someone explain how find() works in this case ?

Very simple speaking: std::set<T,comparator>::find(k) returns iterator it if and only if both comparison fails:

false == comparator(k,*it)
false == comparator(*it, k)

Otherwise it returns std::set<>::end()...

Speaking in mathematical sense - std::set define equality by its weak ordering by this formula:
  a == b  <==>  !(a < b) && !(b < a)

A:

The function that will be used in std::set::find() is an instance of the Comparator class that you declared as a template parameter of your set.
template < class Key, class Compare = less<Key>,
           class Allocator = allocator<Key> > class set;

Concretely, the comparator instance will be passed to Key objects and should return true if the first is located before the second. So yes, your implementation is fine.
Now, to dig further: if you want to convince yourself, you can dig into the source code of gcc’s implementation of the standard library, and you’ll find:
  template<typename _Key, typename _Val, typename _KeyOfValue,
           typename _Compare, typename _Alloc>
    typename _Rb_tree<_Key, _Val, _KeyOfValue,
              _Compare, _Alloc>::iterator
    _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::
    find(const _Key& __k)
    {
      iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k);
      return (__j == end()
          || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j;
    }

You can see that _M_key_compare (which is an instance of the _Compare class you provided), is called with __k as a first parameter (one of your Key) and the return value of _S_key(...) which is a key. The return value of _M_key_compare is used in a ternary expression, so it should be a boolean.


Q:

How to enable bottom menu button in android 4.0 ICS

I want to enable bottom menu button and Which theme will be use for this menu button.I try many theme but did not work for me by the any theme.How can I achieve this?. Thanks in Advance.

A:

set android:targetSdkVersion="8"  in manifest.xml ,
Image is taken from Samsung galaxy nexus
Example
<uses-sdk
    android:minSdkVersion="8"
    android:maxSdkVersion="17"
    android:targetSdkVersion="8" />


Q:

TF51005 Query columns other than workitem properties listed?

I'm trying to run this query and it keeps throwing a TF51005 The query references a field that does not exist. Caused by the [Microsoft.VSTS.Common.Severity], I don't know how i'm suppose to pull the severity
select [System.Id], [System.WorkItemType],[Microsoft.VSTS.Common.Severity]
from WorkItems

I'm using a console application with this code
 foreach (WorkItem workItem in queryResults)
            {
                Console.WriteLine("ID: {0}", workItem.Id);
                Console.WriteLine("Title: {0}", workItem.Title);
                Console.WriteLine("State: {0}", workItem.State);
                Console.WriteLine("Reason: {0}", workItem.Reason);

            }

And I realized even if i can pull the column Severity isn't listed as a workitem property. Is it not possible to pull this data?

A:

The query is probably failing because that field is only present some work item types. Specifically, it's present on the Bug, Issue, and Risk work items, depending on your process template selection.
Restrict your query accordingly and it should be fine.
Work items can contain any number of fields, as defined by the process template. The work item object in the TFS API has properties that correspond to the fields that absolutely exist on every work item.
You can access the actual fields by inspecting the Fields property on the work item object.


Q:

Is it possible to create an Android application directly on the HTC Evo phone?

As a means of simplifying development, I'd like to be able to create and test an application right on my handset.
Is it possible to build an application directly on the HTC Evo phone?

A:

No, sorry. With the Android Scripting Environment, you can write small scripts that run on the device. But the build tools require a fair bit more memory and computing power than an Android phone offers.


Q:

php array_diff with sql query and $REQUEST

I want to use array_diff with the result of an mysql query and the result of an $REQUEST here is what I tried:
while($resultarray3 = mysql_fetch_array($result3))
{
$Bestand = $resultarray3['Bestand']
}
$Ergebnis = array_diff($_REQUEST['Menge'], $Bestand);

I got this error by using it: Warning: array_diff(): Argument #2 is not an array in /var/www/html/lager_management/warenkorb.php on line 143
Example for the array $Bestand:
Array ( [0] => 20 [1] => 250 [2] => 90 )

Example for the array $Menge:
Array ([0] => 10 [1] => 45 [3] => 80 )

A:

You are replacing the varible each time in loop.
Try this
$Bestand =array();
while($resultarray3 = mysql_fetch_array($result3))
{
$Bestand[] = $resultarray3['Bestand']
}
$Ergebnis = array_diff($_REQUEST['Menge'], $Bestand);
Need to change/Modify
$Bestand=array()

and
$Bestand[] = $resultarray3['Bestand']


Q:

Hide TextView after some time in Android

I want to hide TextView after some time interval say 3 seconds. I googled and found some code and I tried code as shown below but It is not working.
Please tell me what is the wrong with this ?
tvRQPoint.setText("+0");
tvRQPoint.postDelayed(new Runnable() {
    public void run() {
        tvRQPoint.setText("+0");
    }
}, 3000);

One more thing, how to remove timeout ? As I am using this on click event of ListView, If user clicks on one option and then clicks on second option, then as 3 seconds got over (after clicked on first option), It does not show second option for 3 seconds.

A:

try View INVISIBLE or GONE like:
tvRQPoint.postDelayed(new Runnable() {
public void run() {
    tvRQPoint.setVisibility(View.INVISIBLE);
}
}, 3000);

Set View visibility  with view.setVisibility(View.INVISIBLE|View.VISIBLE|View.GONE);

A:

How about hiding your text view with some animation?
  int delayMillis = 3000;
  Handler handler = new Handler();
  final View v = tvRQPoint; // your view
  handler.postDelayed(new Runnable() {
    @Override
    public void run() {
       TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);
       animate.setDuration(500);
       animate.setFillAfter(true);
       v.startAnimation(animate);
       v.setVisibility(View.GONE);

    }, delayMillis);

A:

What you are trying to do is ok but after three seconds you want to hide the textview so use  setVisibility
tvRQPoint.setText("+0");
    tvRQPoint.postDelayed(new Runnable() {
        public void run() {
            tvRQPoint.setVisibility(View.INVISIBLE);
        }
    }, 3000);


Q:

WPF DevComponents Dock Control will not fill screen

I am using the DevComponents third-party control to create a screen with multiple docking components organized in three rows, the last row having three columns. I have been successful in creating this layout, however I cannot figure out how to expand the height of the DockSite to the borders of the screen.
I have posted the XAML below:
<UserControl x:Class="Docking_UC"
xmlns:my="clr-namespace:DevComponents.WpfDock;assembly=DevComponents.WpfDock"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="714" Width="1057">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" MinHeight="83"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid HorizontalAlignment="Stretch" Margin="0" Name="bodyGrid" Width="Auto" Grid.Row="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="71" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <WrapPanel>
            Dock Test #
            1
        </WrapPanel>
        <Rectangle Height="12" Name="menuRectangle" Stroke="Black" VerticalAlignment="Bottom" Fill="SteelBlue" Opacity="0.25" Grid.Row="1" />
    </Grid>
    <my:DockSite Background="Transparent" Name="dashDockSiteAll" Grid.Row="1">
        <my:DockSite.SplitPanels>
            <my:SplitPanel Orientation="Vertical" my:DockSite.Dock="Top" my:DockSite.DockSize="714">
                <my:SplitPanel Orientation="Vertical">
                    <my:DockWindowGroup my:SplitPanel.RelativeSize="50,135">
                        <my:DockWindow Header="Top" Name="dockWindowTop">
                            2
                        </my:DockWindow>
                    </my:DockWindowGroup>
                    <my:DockWindowGroup my:SplitPanel.RelativeSize="50,220">
                        <my:DockWindow Header="MidWindowTab1" Name="dockWindowMid1">
                            3
                        </my:DockWindow>
                        <my:DockWindow Header="MidWindowTab2" Name="dockWindowMid2">
                            4
                        </my:DockWindow>
                    </my:DockWindowGroup>
                    <my:DockWindowGroup my:SplitPanel.RelativeSize="50,150">
                        <my:DockWindow Header="Bottom" Name="dockWindowBottom">
                            <my:SplitPanel Orientation="Horizontal" my:SplitPanel.RelativeSize="50,150">
                                <my:DockWindowGroup>
                                    <my:DockWindow Header="BottomLeft">
                                        5
                                    </my:DockWindow>
                                </my:DockWindowGroup>
                                <my:DockWindowGroup>
                                    <my:DockWindow Header="BottomMid">
                                        6
                                    </my:DockWindow>
                                </my:DockWindowGroup>
                                <my:DockWindowGroup>
                                    <my:DockWindow Header="BottomRight">
                                        7
                                    </my:DockWindow>
                                </my:DockWindowGroup>
                            </my:SplitPanel>
                        </my:DockWindow>
                    </my:DockWindowGroup>
                </my:SplitPanel>
            </my:SplitPanel>
        </my:DockSite.SplitPanels>
    </my:DockSite>
</Grid>

I have tried removing the DockSite.Site property but then the DockSite defaults to a Left Docked. Also, upon docking one window to the Bottom site there still remains an empty area about the height of the cursor that I cannot remove.

A:

OK, so after another day of troubleshooting/messing around with the control I finally discovered what I have been trying to accomplish. I have added a my:SplitPanel to the DockSite outside of the  tag and apparently this SplitPanel will automatically dock to the remaining white space.
The corrected code is below and the additions are obscenely tabbed over:
<UserControl x:Class="Docking_UC" xmlns:my="clr-namespace:DevComponents.WpfDock assembly=DevComponents.WpfDock" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="714" Width="1057">
<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="Auto" MinHeight="83"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid HorizontalAlignment="Stretch" Margin="0" Name="bodyGrid" Width="Auto" Grid.Row="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="71" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <WrapPanel>
        Dock Test #
        1
    </WrapPanel>
    <Rectangle Height="12" Name="menuRectangle" Stroke="Black" VerticalAlignment="Bottom" Fill="SteelBlue" Opacity="0.25" Grid.Row="1" />
</Grid>
<my:DockSite Background="Transparent" Name="dashDockSiteAll" Grid.Row="1">
    <my:DockSite.SplitPanels>
        <my:SplitPanel Orientation="Vertical" my:DockSite.Dock="Top" my:DockSite.DockSize="714">
            <my:SplitPanel Orientation="Vertical">
                <my:DockWindowGroup my:SplitPanel.RelativeSize="50,135">
                    <my:DockWindow Header="Top" Name="dockWindowTop">
                        2
                    </my:DockWindow>
                </my:DockWindowGroup>
                <my:DockWindowGroup my:SplitPanel.RelativeSize="50,220">
                    <my:DockWindow Header="MidWindowTab1" Name="dockWindowMid1">
                        3
                    </my:DockWindow>
                    <my:DockWindow Header="MidWindowTab2" Name="dockWindowMid2">
                        4
                    </my:DockWindow>
                </my:DockWindowGroup>
            </my:SplitPanel>
        </my:SplitPanel>
    </my:DockSite.SplitPanels>
                 <my:SplitPanel Orientation="Horizontal" my:DockSite.DockSize="100">
                       <my:SplitPanel Orientation="Horizontal" my:SplitPanel.RelativeSize="50,100">
                            <my:DockWindowGroup>
                                <my:DockWindow Header="BottomLeft">
                                    5
                                </my:DockWindow>
                            </my:DockWindowGroup>
                            <my:DockWindowGroup>
                                <my:DockWindow Header="BottomMid">
                                    6
                                </my:DockWindow>
                            </my:DockWindowGroup>
                            <my:DockWindowGroup>
                                <my:DockWindow Header="BottomRight">
                                    7
                                </my:DockWindow>
                            </my:DockWindowGroup>
                        </my:SplitPanel>
                     </my:SplitPanel>
</my:DockSite>
</Grid>

Hope this helps anyone else having the same issue.
Also, if anyone with enough reputation reads this, would you please add a DevComponents tag?


Q:

Add captions to my HTML slider

How can I add a title or caption that displays a short description unique to each slide on my carousel. Here is my code:

Incredibly Basic Slider

  >>
  <

SLIDE 1

SLIDE 2

SLIDE3

SLIDE4

A:

My idea of adding captions would be using HTML and CSS:

ul {margin: 0; padding: 0; text-align: center;}
li {position: relative; width: 150px; height: 150px; list-style: none; display: inline-block; padding: 10px; border: 1px solid #999; line-height: 150px; margin-bottom: 0.25em;}
li .caption {position: absolute; bottom: 0; left: 0; right: 0; background: rgba(0,0,0,0.25); line-height: 3em;}

Incredibly Basic Slider

  >
  <

      SLIDE 1

Caption 1

      SLIDE 2

Caption 2

      SLIDE 3

Caption 3

      SLIDE 4

Caption 4


Q:

Struggling to interpret exam past paper question, calculus and vectors involved.

I hate to do this but there are no solutions and I am really struggling to interpret what it means.
$f:\mathbb{R}^3\to\mathbb{R}$,
$f(X)=\|X \|^2$ ($X=$ the vector $(x,y,z)$)
and
$P:\mathbb{R}^3\to\mathbb{R}^3$
$P(X) = A\times X$ where $A$ is the vector $(a_1,a_2,a_3)$ (constant)
a)
Calculate gradient $\nabla f(X)$
I got $(2x,2y,2z)$ which I am pretty sure is fine (I'd love a "yeah it is"), this makes sense, because $\| X\|^2$ is "radius squared" and this vector is in the direction "pointing away from" the origin in the direction $x,y,z$.
It passes the "sanity check" basically.
b)
calculate the 3x3 matrix $DP(X)$
well $A\times X$ is:
\begin{pmatrix}
    a_2 z - a_3 y\\
    a_1 z - a_3 x\\
    a_1 y - a_2 x\\
\end{pmatrix}
so a row in the matrix is the change in the row in $P(X)$ wrt x, y and z.
This gives:
\begin{pmatrix}0 & -a_3 & a_2 \\ -a_3 & 0 & a_1 \\-a_2 & a_1 & 0\end{pmatrix}
(I'd love a "that's right" here too)
so I'm fine with that.... here's the question
c)
using the chain rule or otherwise, show that $\nabla (f\circ P)(X) = 2\|A\|^2 X - 2(A\cdot X)A$
where T is the upside down triangle. the @ sign denotes composition
DOES IT MEAN: "gradient of (f(P(x)))"
"Tf(P(X))" we worked out Tf in part a (2x,2y,2z) = 2(x,y,z) so 2P(X)....
Why the chain rule? Where does differentiation come into play?
I've probably missed something simple, but yes, quite unsure of this part c.

A:

a) It's ok. No need for sanity checks, as
$\nabla f(X)=\begin{pmatrix}\partial_x f\\\partial_y f\\\partial_z f \end{pmatrix}=\begin{pmatrix}\partial_x (x^2+y^2+z^2)\\\partial_y (x^2+y^2+z^2)\\\partial_z (x^2+y^2+z^2) \end{pmatrix}=\begin{pmatrix}2x\\2y\\2z \end{pmatrix}$.
b) Here you should obtain a different result. There is an "intuition" rule:
$\displaystyle A\times X = \det\begin{pmatrix}\vec e_x&\vec e_y&\vec e_z\\a_1&a_2&a_3\\x&y&z\end{pmatrix} =\vec e_x(za_2-ya_3)+\vec e_y(xa_3-za_1)+\vec e_z(ya_1-xa_2)=\begin{pmatrix}za_2-ya_3\\xa_3-za_1\\ya_1-xa_2\end{pmatrix}.$
Hence your $DP(X)$ gradient is
\begin{pmatrix}0&-a_3&a_2\\a_3&0&-a_1\\-a_2&a_1&0\end{pmatrix}
c) Here you can either write the expression explicitly:
$\nabla(f\circ P)(X) = \nabla ((za_2-ya_3)^2+(xa_3-za_1)^2+(ya_1-xa_2)^2)$
$=\begin{pmatrix}2xa_3^2-2a_1a_3z+2xa_2^2-2ya_1a_2\\
2ya_3^2+2ya_1^2-2xa_1a_2-2za_2a_3\\ 2za_2^2+2za_1^2-2xa_3a_1-2ya_2a_3\end{pmatrix}=2\|A\|^2X - 2\begin{pmatrix}   a_1a_1x+ a_1a_3z+  ya_1a_2\\
  ya_2a_2 +xa_1a_2+za_2a_3\\   za_3a_3xa_3a_1+ya_2a_3\end{pmatrix} $
$= 2\|A\|^2X - 2(A\cdot X)A$.
or you can use the chain rule $\nabla (f\circ P)(X) = \nabla f (P(X))\circ DP(X) = 2P(X)\circ DP$ to arrive to the same result as Ros suggested.
It's up to you to  decide which way is faster/safer for you.
EDIT
On the chain rule: (I can see why there could be some difficulties here, I'll try to stay simple).
Let's say, we note $P_i$ - the elements of the vector $P(X)$ and $\vec e_i$ - unitary basis, so $P(X) = \sum_{i=1}^3 P_i \vec e_i$. Additionaly, we will note our coordinates as $x_i$; it might be useful for future, when the dimension becomes arbitrary and/or you study tensors. Then $f(P(X)) = \sum_{i=1}^3 P_i^2$.
The gradient of an arbitrary function writes $\nabla g(X) = \sum_i \partial_{x_i}g(X)\cdot \vec e_i$, so in our case
$\nabla (f (P(X)) =\sum_{i=1}^3\partial_{x_j}(f(P(X)))\vec e_j = \sum_{i=1}^3\sum_{j=1}^3\partial_{P_i}(f(P ))\partial_{x_j}P_i(X)\vec e_j$
$=\displaystyle \sum_{i=1}^3\sum_{j=1}^3 2P_i\partial_{x_j} P_i \cdot \vec e_j $
On the other hand, the elements of the matrix $(DP)_{ij}$ are found as $\partial _{x_j}P_i$, so it's now easy to interpet the required gradient as
$\nabla f(P(X)) DP(X) = 2P(X) DP(X)$, where the first factor is seen as a row-vector and the second one - a square matrix.
Another simplification closely related to the nature of vector product is that $\forall X \, A\times X = DP\cdot X$ (the last one is a product of a square matrix and a vector), and $DP^T=-DP$. It allows to say that
$  (2P(X) DP(X))^T = -2DP(X) P(X) \text{(last term seen as a column vector)} = -2A\times (A\times X)$. By a so-called "vector triple product rule" (cf. wikipedia), it simplifies into $2((A\cdot A)X-(A\cdot X)A)$, which is exactly the desired result.


Q:

Gradle build fails if trying to implement interface

I have my gradle project building fine unless I try to implement specific interface: It imports some unresolved package. However, if the interface is used do describe types (method arguments. etc.), everything compiles fine.
How should I fix the build to be able to implement that interface?

A:

If you extend a class or implement an interface, you also need their dependencies in the compile classpath. If you just use the class or interface in fields, parameters, annotations and so on, you only need the class or interface itself in the compile classpath.
This is not Gradle specific but also true for plain commandline Java compiler.


Q:

MVC C# crear archivo y guardarlo

Amigos estoy tratando de crear un txt y guardarlo en mi proyecto, pero tengo algunos problemas, hize algo similar hace unos días con la diferencia de que le pasa ya un archivo a mi método, en este apenas lo estoy creando pero tengo problemas para guardalo alguien me puede ayudar.

    if (abono != null && cargo != null && saldo != null && refer != null)
            {

                Random rnd = new Random();
                int rndx = rnd.Next(0, 1000);

                var folder = Server.MapPath("~/Facturas/" + banco + "_" + rndx);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);

                       StreamWriter File = new StreamWriter("~/Facturas/" + banco + "_" + rndx + ".txt");
                File.Write(DateTime.Now + ", " + refer + ", " + cargo + ", " + abono + ", " + saldo);

                using (StreamWriter writer = File.CreateText(folder))
                {
                    writer.WriteLineAsync("First line of example");
                    writer.WriteLineAsync("and second line");
                }

                File.Close();
                }

            }

Aquí mi error

A:

lo que necesitas es instanciar tu StreamWriter de la siguiente forma (la clase TextWriter es abstracta por lo que no puedes instanciarla directamente.
    if (abono != null && cargo != null && saldo != null && refer != null)
            {

                Random rnd = new Random();
                int rndx = rnd.Next(0, 1000);

                var folder = Server.MapPath("~/Facturas/" + banco + "_" + rndx);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);

                     string filePath = System.IO.Path.Combine(folder, "fichero.txt") ;

                using (StreamWriter writer = File.CreateText(filePath))
                {
                    writer.WriteLine(DateTime.Now + ", " + refer + ", " + cargo + ", " + abono + ", " + saldo");

                }
}


Q:

How to get a simple array of DB names with Laravel DB facade?

When I do this:
$databases = DB::select("SELECT `schema_name` FROM information_schema.schemata");

dd($databases);

I get this:
array:1 [
  0 => {#1304
    +"schema_name": "database_name"
  }
]

and I want this:
array:1 [
  0 => "database_name"
]

How can I get a simple array with only DB names, or the more important question WHY is that not giving a simple array?

A:

You can simply do this:
return DB::table('information_schema.schemata')->pluck('schema_name');


Q:

Global variable reset to 0 between classes in Android

There are a few questions related to this, but I couldn't find any that helped me. My code is below. Basically touchX is set in OnTouch. Once we get to OnDraw(), it is reset to 0.
public class NonmultiplierSixView extends View implements View.OnTouchListener{
int touchX;
int touchY;
public NonmultiplierSixView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    int touchX = (int)event.getX();
    int touchY = (int)event.getY();
    Log.i("STATE", Integer.toString(touchX));
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.i("STATE", Integer.toString(touchX));
}

}

How do I stop it from resetting the value of touchX and touchY to 0?

A:

You have created 2 copies of touchX and touchY.
These two,
public class NonmultiplierSixView extends View implements View.OnTouchListener {
int touchX;
int touchY;

are the instance variables (i.e. they belong to the object of class NonmultiplierSixView)
Whereas, the ones defined in the function onTouch are local copies.
public boolean onTouch(View v, MotionEvent event) {
    int touchX = (int)event.getX();
    int touchY = (int)event.getY();

In the function onDraw, you are actually accessing the instance variable touchX and not the local variable. As instance int variables have default value of 0, you are getting 0 in the onDraw function.
=============================================
Solution:
Try this
public boolean onTouch(View v, MotionEvent event) {
    this.touchX = (int)event.getX();
    this.touchY = (int)event.getY();
    Log.i("STATE", Integer.toString(this.touchX));
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.i("STATE", Integer.toString(this.touchX));
}


Q:

Product of a multi-dimensional array (or tensor) and vectors

I would like to ask for a fast way to perform the following operations, either in native Matlab, C++, or using toolboxes/libraries, whichever would give the fastest solutions.
Let M be a tensor of D dimensions: n1 x n2 x... x nD, and let v1, v2,..., vD be D vectors whose dimensions are respectively n1, n2,..., nD.

Compute the product M*vi (1 <= i <= D). The result is a multi-dimensional array of (D-1) dimensions.
Compute the product of M with all vectors, except vi.

For example, with D = 3:

The product of M and v1 is a tensor N of 2 dimensions (i.e. a matrix) where

N[i2][i3] = Sum_over_i1 of M[i1][i2][i3]*v1[i1]

The product of M and v2 is a matrix N where

N[i1][i3] = Sum_over_i2 of M[i1][i2][i3]*v2[i2]

The product of M and v2 and v3 is a vector v where

v[i1] = Sum_over_i2 of (Sum_over_i3 of M[i1][i2][i3]*v2[i2]*v3[i3])
A further question: the above but for sparse tensors.
An example of Matlab code is given below.
Thank you very much in advance for your help!!
n1 = 3;
n2 = 5;
n3 = 4;

M = randn(n1,n2,n3);
v1 = randn(n1,1);
v2 = randn(n2,1);
v3 = randn(n3,1);

%% N = M*v2
N = zeros(n1,n3);
for i1=1:n1
    for i3=1:n3
        for i2=1:n2
            N(i1,i3) = N(i1,i3) + M(i1,i2,i3)*v2(i2);
        end
    end
end

%% v = M*v2*v3
v = zeros(n1,1);
for i1=1:n1
    for i2=1:n2
        for i3=1:n3
            v(i1) = v(i1) + M(i1,i2,i3)*v2(i2)*v3(i3);
        end
    end
end

A:

I've noticed that operation you are describing takes (D - 1) dimensional slices of M and scales them by the corresponding entry of vi subsequently summing the result over the indices of vi. This code seems to work for getting N in your example:
N2 = squeeze(sum(M.*(v2)', 2));

To get v in your code, all you need to do is multiply N by v3:
v2 = N2*v3;

EDIT
On older versions of MatLab the element-wise operator .* doesn't work the way I've used it above. One alternative is bsxfun:
N2 = squeeze(sum(bsxfun(@times, M, v2'), 2));

Just checked: In terms of performance, the bsxfun way seems as fast as the .* way for large arrays, at least on R2016b.


Q:

How can I move an object from one object's array to another object's array with the fewest dependencies?

I have two objects with container arrays (Station and Carriage) and I want to move a third object (Passenger) from a station to a carriage.
I'm using the following method within my Carriage class (passengers is just an empty array), but whilst this does board the passengers on the carriage, they still remain in the station meaning I'm just cloning them rather than moving them.
def board(passenger)
  passengers << passenger
end

I could fix this by passing another argument to the board method (station) and then delete the passenger from the station's own array all from this one method as below but this seems like bad practice.
def board(passenger, station)
  passengers << passenger
  station.passengers.delete(passenger)
end

I've been reading about Object Oriented Design and am aware that I should minimise any dependencies between classes... and this code above seems to flout a lot of the guidelines of good OOD because:

My Carriage class is reaching into the Station class
My board method depends upon two arguments being passed in the
correct order

Is there a better way for me to achieve this with fewer class dependencies?

A:

If you think in term of messages, things will get easier to figure out.At first the passengers belongs to Station. So when the Carriage wants a passenger to get onto it, it has to send the message to the Station asking it to send a passenger in. So I think a better way to implement this is:
class Station
  # First version
  # get any passenger
  def get_passenger
     # this will return the first one and remove it from the array
     passengers.shift
  end

  # Second version
  # Get a specific passenger
  # in this case the board method of Carriage
  # will normally depend on the passenger as
  # well as the station
  def get_passenger(passenger)
     if(passengers.include?(passenger))
       passengers.delete(passenger)
     else
       raise "Passenger not found!"
     end
  end
end

in the Carriage class's board method you will only need to dependency inject the station from where passengers will board.
class Carriage
  # board any passenger from the station
  def board(station)
    passengers << station.get_passenger
  end
  # Board a specific passenger from the station
  def board(passenger, station)
    passengers << station.get_passenger(passenger)
  end
end

and if you want to be free from injecting the arguments in this order, and you're using Ruby >= 2.1, you can use Ruby keyword arguments instead.
Another approach I think of is to make the messages flow between passenger and station, and passenger and carriage.
class Passenger
  # the passenger can be in one station or
  # one carriage at the same time
  attr_accessor :station, :carriage

  def board(carriage)
    carriage.board(self)
    station.remove_passenger(self)
  end
end

class Station
  attr_accessor :passengers
  def remove_passenger(passenger)
    passengers.delete(passenger)
  end
end

class Carriage
  attr_accessor :passengers
  def board(passenger)
    passengers << passenger
  end
end

Now you just make a passenger board, by just providing to which carriage to board.
passenger.board(carriage)


Q:

jquery mobile multiple html files vs multiple page

In my phonegap/jquery mobile app, the multi page model is been used.
index.html have all the pages of my app, so far 6 pages .
If this app would grow too much and it turned to be 19 pages in a single html file, would it be bad?
I created other app to test and used one html file to each page. But looks like every time the page is changed, the whole DOM is loaded again, is that right?
Please tell me which structure is better for a big app

A:

When working with jQuery Mobile first thing to think about is what kind of page template should I use. I have already talk a little bit about this topic in one of my previous ARTICLES and now I have a need to clarify this part of a story a little bit more.
To make a story short (I am not going to talk about page architecture, everything you need to know can be found in a previous link). This answer can also be found on THIS location, to be transparent it is my personal blog.
Multi HTML page template:
This is a template where one jQuery Mobile page is placed inside a single HTML page.
Good

Smaller and lighter, each data-role="page" is inside a separate HTML file and page structure is much more modular.
Can become even smaller if every subsequent HTML page is stripped from HEAD content, or anything that isn't data-role="pšage" div. Unfortunately in this case fallback if JavaScript is not supported is out of question.
DOM size is relatively small, only first page is permanently loaded into the DOM,  any other page will also be loaded into the DOM but at the same time it will also be removed when not used actively, basically each time you move from it.
Better fallback if JavaScript is not supported. Works great in desktop browsers after a page refresh, mainly because every HTML page has an existing HEAD content. This also allows your app to behave like normal web app mainly because AJAX can be turned off.

 ...vs the bad

Consumes more bandwidth as each page navigation generates a new request. When moved from every page will be permanently removed from the DOM, unless cashing is turned on.
Navigating back to a previously loaded page will again generate a fresh request.
Initial page load is fast but subsequent page loads are slower then in multipage template. This can cause problems during page transitions, more so on mobile devices. Desktop browsers don't have this problem.
Much more suitable for desktop browsers then mobile browsers. Also suitable for larger applications, again this is problem for mobile devices.
Pageinit event will be triggered each time page is visited (for those who don't know this an event that replaces document ready in jQuery Mobile and thus it should run only once), which consequently causes problems with multiple event binding.
Can't use more then one data-role="page" inside any subsequent HTML page, only initial one can have more then one page.

Multipage template
This is a template where one or more jQuery Mobile pages are part of a single HTML file.
Good

Since all pages are already loaded, no additional requests are generated for navigating between pages.
First load is slower as the file size is larger, but subsequent page navigation is fast, thus making transitions much more smooth. Almost native like smooth, emphasize on almost.
Suitable for relatively smaller applications and situations where you know the capabilities of your target platforms including presence of JavaScript support, thus making it a great solution for a hybrid app. It works much much better as a Phonegap app then multi HTML template.
The "page" data-role element is required.

 ...vs the bad

Heavier. All the pages are in a single html file. Large applications with many pages will increase the DOM size.
Needs JavaScript support as Ajax Navigation is used.
Multiple page containers are present, and only the first one is shown when page loads.
Using data-ajax="false" for internal pages ignores the data-transition attribute, by default slide is used
Heavily styled pages can become sluggish on mobile devices.

In the end, the secret of a good jQuery Mobile page architecture is somewhere in the middle.

A:

Your code will be easier to maintain and update if you break each page into its own html file.
Sometimes you want to animate between every page, or have an input form that has the illusion of being multiple pages but is in fact multiple divs on the same page.  In these and many other cases, using one page has distinct advantages.  If you have no real need for that kind of functionality, though, break apart your site.


Q:

Stop NSFileManager process

I am copying some data using NSFileManager:
success = [manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:[dirToCopyTo stringByAppendingPathComponent:file] error:&copyError];

NSFileManager seems to provide no way of stopping this process however. Is there a way?
Thanks

A:

Not with NSFileManager, no.  You have to drop to the lower level FSCopyObjectAsync function.
For an example on how to use this function, check out this question.
As for how to cancel the copy, the first parameter you're going to get to your copy callback is an FSFileOperationRef.  Passing that parameter as the argument to FSFileOperationCancel() should cancel the copy. (See this CocoaBuilder.com thread for more info)


Q:

How to sync Mails from Server to Backup with only the latest Mails remaining on the Server

At the moment i do a simple Mail-Backup:
On the server there is a Maildir, and i use rsync to sync the Maildir from server to backup.
So i delete on the Server every file which is older than i.e. one month. So i have only the latest mails on the server and the rest in the Backup only. So i do not use much space on the server, and if somebody hacks me, he will get only a month of mails instead of the whole archive.
the commands i use are:
rsync -avz Maildir/ backupserver:backup/Mails/
cd Maildir
touch -d 2011-07-30 dummy
find -type f \! -newer dummy -delete

That is working pretty good, but when i move a mail, which is already in the backup, i will have two copies of the mail in the backup. One copy from the old backup job, one from the new one. Or i may even decide to delete the mail and it will not be deleted in the backup.
I could use rsync with --delete, but then i need to have the full archive on the server, because otherwise it will delete the old mails in the backup, too.
So now my question is: How can i sync the Mails in a way, that preserves moves and deletions?

A:

Okay, i think i have found a solution:
Using Syncmaildir, i keep my E-Mails from the local maildir in sync with the remote maildir. When i want to delete old mails from the server, but not from the backup, i first sync a last time, which syncs added/deleted/moved mails, then i remove the mail-db from the local and the remote .smd/ folder and delete the old mails.
Steps in Detail:

sync mails with smd-pull
when removing old mails from the server:

sync a last time with smd-pull
delete the old mails with the find-cmdline.
delete .smd/profilename__Mail.db.txt* files locally/remotely
sync again, so the db gets rebuild for the remaining files, so moves/deletions can be detected.

sync mails as always


Q:

Passing a string value will fail to find the file

I write a shell which will try to collect a file from the file path into current directory if it exists:
collect_file() {
  fpath=$1
  echo $fpath
  if [ -e $fpath ]; then

    fname=`basename $fpath`
    `cp $1 $fname`
    retval=$?
    if [ $retval == 0 ]; then
      echo "Collect file '$fpath'"
    else
      echo "Error: fail to copy file '$fpath'"
    fi

  else
    echo "Error: file '$fpath' not found"
  fi
}

Now, if I pass a bare value ~/.gitconfig, it will succeed, but when I pass a string value "~/.gitconfig", it will fail.
collect_file ~/.gitconfig        # will succeed to copy the file
collect_file "~/.gitconfig"      # will fail

Shows:
# results for bare value
/Users/Xaree/.gitconfig
Collect file '/Users/Xaree/.gitconfig'

# results for string value
~/.gitconfig
Error: file '~/.gitconfig' not found

Why and how can I fix it?

A:

The following refers to a file in the user's home directory:
~/.gitconfig

By contrast, the following refers to a file in a directory named ~:
"~/.gitconfig"

~/ is interpreted as the home directory when the shell performs tilde expansion.  The shell only perform tilde expansion when the ! is unquoted.  If the string is quoted, then ~ just means ~ and nothing else.
Examples
Observe that tilde expansion is performed for only one of the following three statements:
$ echo "~/.bashrc"
~/.bashrc
$ echo ~"/.bashrc"
~/.bashrc
$ echo ~/".bashrc"
/home/john1024/.bashrc

Forcing a tilde expansion
Tilde expansion, as implemented by the shell, offers many features with many special cases.  We could force a general tilde expansion using eval but that would introduce many security issues.  For just the basic case, however, we can safely replace ~/ in a variable with $HOME/ as follows:
fpath="${fpath/~\//$HOME\/}"

A problem with the above is that it will do the replace the first occurrence of ~/ even if the string does not start with ~/.  To avoid that, we can use:
[ "${fpath#\~/}" != "$fpath" ] && fpath="${fpath/~\//$HOME\/}"

This tests to be sure that the string starts with ~/ before it makes the substitution.


Q:

How do you get speech dictated without adding it to a grammar list?

I'm new to Speech Recognition, and I'm working on a project that will receive a command from a recognizable list.
For example, I would say "Play song". The computer would ask the song title, and I can say it. It will then compare my answer to my music library and find it.
I know how to add recognizable grammar to the SpeechRecognizer object, how to make the computer speak, and how to play a song in iTunes. I cannot, however, figure out how to get it to dictate or listen and interpret something that isn't in the grammar list. Is there a method I'm missing? Or not yet been simplified by Microsoft? I have no code to show for this, as I am not even sure how to search for this particular idea.
Of course, I could have the program read my entire library, but that's not an optimal solution considering I have tens of thousands of songs. Thanks in advance!

A:

Speech recognition works by comparing the signal to grammars, so there really isn't a good way to get a result without a grammar.  Why not use the music library to generate the grammar list?  I'm sure the result will be much more satisfactory.  A really general grammar won't enable you to tell whether the user said "Madonna," "My Donna," or "Mad on a" with any sort of reliability.  You might want to narrow the grammars further by letting the user choose to say an artist, title or album before they say it.


Q:

error : can't read .... no such variable in TCL script using "after"

I am working in a TCL automation environent at my workplace.
I'm trying to run a delayed command in my script using "after".
The problem i encounter is that when i try to specify commands with variables inside a code block under an "after" , the vars are not recognized and i get an error message.
I'll quote the relevant parts of the code.
proc test_script1 {{bh0 0} ...more vars....} {
.
.
.
after [expr 20000]   {
   set some_value[ ns1::probe_TCP_connections $bh0 $main_duration 1  15]    }

puts "the value i got is $some_value"
}

And i seem to get an error:
can't read "some_value": no such variable
Can anyone suggets what is the problem , and how to oversome it?
thx

A:

You can capture the values of local variables with the help of apply (and it's advisable to use list to build callbacks when they get even slightly non-trivial). Since the body of an apply is a lambda expression with its own scope — a little nameless procedure — you have to use global in it to access state that will persist, and in any case after callbacks are called from the global namespace always (since the mechanism doesn't know how to keep arbitrary stack frames around for the duration of the asynchronous operation).
after 20000 [list apply {{bh0 main_duration} {
    global some_value
    set some_value [ns1::probe_TCP_connections $bh0 $main_duration 1 15]
}} $bh0 $main_duration]

global some_value
vwait some_value
puts "The value was changed to $some_value"

It's possible to get even more sophisticated, especially in Tcl 8.6 which has a coroutine system that can be used to hide the complexity of using continuation passing style programming.