text:
Q: LINQ: Having trouble navigating across multiple jeft join What I'm trying to do in SQL looks like this:
SELECT
    ....
    ct.FirstName + ' ' + ct.LastName
    ....
FROM
    Leads l
    LEFT JOIN LeadContacts lc ON lc.LeadID = l.LeadID
    LEFT JOIN Contacts ct on ct.ContactID = lc.ContactID

In the Lead model:
public class Lead
{
    ....
    public virtual ICollection<LeadContact> LeadContacts { get; set; }
    ....
}

And in the LeadContact model:
public class LeadContact
{
    ....
    [ForeignKey(nameof(LeadID))]
    public virtual Lead Lead { get; set; }

    [ForeignKey(nameof(ContactID))]
    public virtual Contact Contact { get; set; }
    ....
}

And now, I'm trying to build an object from an instance of:
leads = IQueryable<Lead>...

And for the life of me, I can't figure out how to navigate to the Contacts table.
var results = leads.Select(l => new QuoteSearchItem
{
    ....
    SomeProperty = l.SomeProperty,
    LeadSales = l.LeadContacts. ?????
    SomeOtherProperty = l.SomeOtherProperty
    ....
 });

QuoteSearchItem.LeadSales is a string.  It needs to be:
Contacts.FirstName + " " + Contacts.LastName

Because of the relationship type, l.LeadContacts.Contacts is not an option.
What do I need to do so that this is possible?

A: You could do something like:
l.LeadContacts.SelectMany(x => x.Contacts)
But, your Contact property is not a list inside your LeadContact class. So either make it a list or you could access it like:
l.LeadContacts.Select(x => x.Contact)

A: You can do that easily if you use comprehension syntax (which use SelectMany when there are multiple froms):
var query = from l in Leads
            from lc in l.LeadContacts.DefaultIfEmpty()
            from ct in lc.Contacts.DefaultIfEmpty()
            select new
            {
               //....
               ContactName = ct.FirstName + ' ' + ct.LastName
               //....
            };

And if you wish, running this in LinqPad, you can get the lambda version + if that is Linq To SQL the SQL itself.
EDIT: Your class is implying that there is a single Contact per LeadContact, then you can shorten this:
var query = from l in Leads
            from lc in l.LeadContacts.DefaultIfEmpty()
            select new
            {
                //....
                ContactName = lc.Contact.FirstName + ' ' + lc.Contact.LastName
                //....
            };

It almost maps to this sample which use the Northwind sample database:
var data = from c in Customers
               from o in c.Orders.DefaultIfEmpty()
               select new {
                 CustomerId = c.CustomerID,
                 OrderId = (int?)o.OrderID,
                 Employee = o.Employee.FirstName + ' ' + o.Employee.LastName
               };

which yields this SQL:
-- Region Parameters
DECLARE @p0 NChar(1) = ' '
-- EndRegion
SELECT [t0].[CustomerID] AS [CustomerId], [t1].[OrderID] AS [OrderId], ([t2].[FirstName] + @p0) + [t2].[LastName] AS [Employee]
FROM [Customers] AS [t0]
LEFT OUTER JOIN [Orders] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
LEFT OUTER JOIN [Employees] AS [t2] ON [t2].[EmployeeID] = [t1].[EmployeeID]

EDIT: What I was saying, instead of:
var results = leads.Select(l => new QuoteSearchItem
{
    ....
    LeadSales = l.LeadContacts. ?????
    ....
});

Do it like:
var results = from l in leads
              from lc in l.LeadContacts.DefaultIfEmpty()
              select new  QuoteSearchItem
              {
                ....
                LeadSales = lc.Contact.FirstName + " " + lc.Contact.LastName
               ....
              };

Either in (method) lambda form or comprehension syntax, end result is same. When selectMany is needed I find comprehension syntax to be easier. And as I said, if you are dying for method syntax, try running it in LinqPad and it will give you lambda counterpart, something like:
var result = leads
   .SelectMany (
      l => l.LeadContacts.DefaultIfEmpty (),
      (l, lc) =>
         new QuoteSearchItem
         {
            //...
            LeadSales = lc.Contact.FirstName + " " + lc.Contact.LastName
         }
   );

A: First of all, you need a Foreign Key in your LeadContact table. I will assume your Lead table has a LeadId field:
//Foreign key for Standard
public int LeadId { get; set; }

[ForeignKey("LeadId")]
public Lead Lead { get; set; }

That represents the relationship between Lead and Lead Contact and it will limit the records to the ones you want. LeadContact is a cross reference so I am sure it already has a "LeadId" field (or some other name) that maps to the Lead Id field in the Lead table so indicate that relationship as shown above.
Assuming LeadSales is of type IEnumerable<string>, you can then do:
var results = leads.Select(l => new QuoteSearchItem
{
    ....
    LeadSales = l.LeadContacts.Select(lc => lc.Contact.FirstName + " " + lc.Contact.LastName);
    ....
});

A: Are you using contexts ?
var result = await context.SearchLead.AsNoTracking()
.Where(l => l.LeadContacts.Any(lc => lc.Contact == QuoteSearchItem))
.ToListAsync();


text:
Q: How to inherit background in a custom canvas in reveal.js slides? I am trying to replicate what was done on this blog http://vda-lab.github.io/2016/07/interactive-visualizations-in-revealjs-markdown# in terms of using a custom JavaScript file inside reveal.js slides for interactive slides. How can we make the script below inherit the background colour of the reveal.js slides?
var viz_function = function(p) {
   p.setup = function() {
   var myCanvas = p.createCanvas(800,600)
   myCanvas.parent('viz2')
   p.noStroke()
   p.noLoop()
   }

   p.draw = function() {
      p.background(255,255,255) //Setting this manually will work; but it will not be a generic solution
      p.fill(0,255,0)
      p.ellipse(p.mouseX,p.mouseY,20,20)
    }

   p.mouseMoved = function() {
       p.redraw()
   }
 }
var viz = new p5(viz_function)

One obvious solution is to manually set the background colour. However, that approach will fail if one were to change the theme of reveal.js. What is a more generic way to inherit the background colour from the slide or the theme of reveal.js?

A: Use the clear() function to clear out old frames without drawing a background with a specific color.
function setup() {
  createCanvas(400, 400);
}

function draw() {
  clear();
  ellipse(mouseX, mouseY, 20, 20);
}

More info can be found in the reference.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tomcat/Seam Seam component Instantiation Exception What could be the reason for the below exception? I have my persistence.xml and components.xml look ok. Environment: Tomcat6, Seam2 framework.
Oct 17, 2013 10:37:46 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.jboss.seam.servlet.SeamListener
org.jboss.seam.InstantiationException: Could not instantiate Seam component: someComponent
    at org.jboss.seam.Component.newInstance(Component.java:2170)
    at org.jboss.seam.Component.getInstance(Component.java:2024)
    at org.jboss.seam.Component.getInstance(Component.java:1986)
    at org.jboss.seam.core.Events.raiseEvent(Events.java:77)
    at org.jboss.seam.contexts.ServletLifecycle.endInitialization(ServletLifecycle.java:145)
    at org.jboss.seam.init.Initialization.init(Initialization.java:744)
    at org.jboss.seam.servlet.SeamListener.contextInitialized(SeamListener.java:36)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.RuntimeException: exception invoking: getTransaction
    at org.jboss.seam.util.Reflections.invokeAndWrap(Reflections.java:154)
    at org.jboss.seam.Component.callComponentMethod(Component.java:2275)
    at org.jboss.seam.Component.unwrap(Component.java:2301)
    at org.jboss.seam.Component.getInstance(Component.java:2044)
    at org.jboss.seam.Component.getInstance(Component.java:2003)
    at org.jboss.seam.Component.getInstance(Component.java:1997)
    at org.jboss.seam.Component.getInstance(Component.java:1970)
    at org.jboss.seam.Component.getInstance(Component.java:1965)
    at org.jboss.seam.transaction.Transaction.instance(Transaction.java:39)
    at org.jboss.seam.persistence.ManagedPersistenceContext.joinTransaction(ManagedPersistenceContext.java:120)
    at org.jboss.seam.persistence.ManagedPersistenceContext.getEntityManager(ManagedPersistenceContext.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.util.Reflections.invokeAndWrap(Reflections.java:144)
    at org.jboss.seam.Component.callComponentMethod(Component.java:2275)
    at org.jboss.seam.Component.unwrap(Component.java:2301)
    at org.jboss.seam.Component.getInstance(Component.java:2044)
    at org.jboss.seam.Component.getInstance(Component.java:1986)
    at org.jboss.seam.Component.getInstance(Component.java:1980)
    at org.jboss.seam.Component.getInstanceInAllNamespaces(Component.java:2375)
    at org.jboss.seam.Component.getValueToInject(Component.java:2327)
    at org.jboss.seam.Component.injectAttributes(Component.java:1739)
    at org.jboss.seam.Component.inject(Component.java:1557)
    at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:61)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
    at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
    at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
    at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
    at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
    at pg.exess.manager.ExessBusinessUnitManager_$$_javassist_seam_2.create(ExessBusinessUnitManager_$$_javassist_seam_2.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.util.Reflections.invokeAndWrap(Reflections.java:144)
    at org.jboss.seam.Component.callComponentMethod(Component.java:2275)
    at org.jboss.seam.Component.callCreateMethod(Component.java:2198)
    at org.jboss.seam.Component.newInstance(Component.java:2158)
    ... 21 more
Caused by: javax.naming.NamingException: Cannot create resource instance
    at org.apache.naming.factory.TransactionFactory.getObjectInstance(TransactionFactory.java:113)
    at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:793)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
    at org.apache.naming.SelectorContext.lookup(SelectorContext.java:137)
    at javax.naming.InitialContext.lookup(InitialContext.java:392)
    at org.jboss.seam.transaction.Transaction.getUserTransaction(Transaction.java:82)
    at org.jboss.seam.transaction.Transaction.createUTTransaction(Transaction.java:74)
    at org.jboss.seam.transaction.Transaction.getTransaction(Transaction.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
    at org.jboss.seam.util.Reflections.invokeAndWrap(Reflections.java:144)
    ... 63 more
Oct 17, 2013 10:37:46 AM org.apache.catalina.core.StandardContext start
SEVERE: Error listenerStart
Oct 17, 2013 10:37:46 AM org.apache.catalina.core.StandardContext start
SEVERE: Context [/project] startup failed due to previous errors

Thanks for your help!

A: This issue is resolved after removing "name" attribute from entity transaction in components.xml.
<transaction:entity-transaction name="someName "entity-manager="#{em}" />
To
<transaction:entity-transaction entity-manager="#{em}" />


text:
Q: If I find a public web API am I allowed to use it in my application? If I find a public web API (by public I mean that isn't protected by any type of authentication) what do I need to do so that I am allowed to use it in my own application?
Is it enough to read and follow the terms of service, or do I need to do something over and above that?
Is it true that this is as legal as using a web scraper and that all search engines get away with that?

A: I am not a lawyer and you aren't even saying which jurisdiction applies to you, so no legal advise from me.
But from a purely practical standpoint, building a product based on an undocumented API is a very bad idea. You have no way to tell if the API will still be there tomorrow. The one who made it can destroy your whole work with a single change to their API.
They might do this intentionally because they want to keep you out. After all, you are only consuming their resources without giving them anything in return. Or they might do it just because their own requirements changed and they don't even know that others also use their API. The only way to have any chance to get a warning in advance is to ask them if you may use it. When you are serious about your project and their API is essential for it, you could ask them to make a deal that they guarantee availability and stability of their API in exchange for money.


text:
Q: What shape does a piece of paper make when it is pushed from the edges? When I push a piece of (A4) paper oriented landscape to me from the shorter edges, it makes a pretty shape, resembling a bell-curve. I seem to remember these sort of situations being a motivation for or concrete instance of some theorems in differential geometry, but apart from that I have no idea how to determine what the true shape of the paper in this situation.
Not a great example (as I'm pushing with one hand to take the photo) but similar to what I'm after. (Hey, if you can generalize to a one-sided push I might just award the checkmark!)

A: It is the Elastica. For small wave heights, the equation is like $\sin^2 k x$ , where $k$ depends on bending rigidity $EI$, applied force $P$. More accurately described in terms of Elliptic functions.
The differential equation is simply: $\text{curvature}  = -k\, y$


text:
Q: 8 men and 8 women in a circle There are 8 men and 8 women sitting in a circle. Prove that there are 8 adjacent people, so that 4 of them are men and 4 are women. (This is obvious, but how do I prove it?)

A: Label each vertex with the number of men less the number of women in the eight people starting at that vertex. Confirm that this will be an even number between $-8$ and $8$ and that labels on adjacent vertices differ by either $0$ or $2$.
Pick a vertex. If its label is $0$ you are done. If the label $L$ is not $0$ confirm that the opposite vertex has label $-L$.
Now moving clockwise from the chosen vertex to the opposite vertex, the label changes sign. It can't change sign without becoming zero somewhere. This is a discrete version of the intermediate value theorem.

A: Hint: Treat the problem as a discrete version of the Intermediate Value Theorem.  Take a block of $8$ consecutive people, compute the excess or shortage of men, and then start moving the block, say clockwise, until you get to the complementary block of $8$.

A: Arrange the 16 people as specified in a circle;  make the spacing uniform.
Draw a diameter that runs from space  to space (no one on the dividing line)
Assume that There are more men in the part of the semicircle to the left.  Call this the area of interest.
Then the semi-circle to the right has more women.
Then rotate the dividing line clockwise 180 degrees.  The formerly "man-rich" area of interest has become the "woman-rich" area.  It must do this by passing through a balanced state...
Edit:  late by less than a minute!...


text:
Q: How to use Twitter Streaming API wih PHP? I was successfully able to retrieve my user timeline for display on my website using
$tweets = simplexml_load_file("http://twitter.com/statuses/user_timeline/" . $userID . ".rss");

for quite some time. However, having had more and more page views lately, I am finding now that I am getting the dreaded HTTP 400 error due to rate limiting.
I have been trying to get my head around the Twitter streaming API with litte/no luck (I have no experience with OAuth/JSON so it's completely alien to me).
I've looked at the code for TwitStream which provides access to the Search API using AJAX/JQuery. Unfortunately, I don't post enough to provide consistent search results so this is not an option.
I haven't found the documentation from Twitter very useful (I'm sure it is if JSON etc isn't very new to you) and I haven't found any simple end-to-end examples of using the Streaming API to fetch the last x posts from a user (i.e. me) from a PHP webpage. There are plenty of examples using command line utilities (e.g. curl) to open a stream but this may not be possible on some webservers (I may not have command line access).
I would be massively grateful if someone could provide me with code for a simple PHP/AJAX/JQuery but NOT Ruby/Python webpage that fetches the last 10 tweets from a users timeline. I don't care if it polls or anything for the time being, just a simple fetch of the tweets on the page load would be great!
So to clarify, I am after a simple example (e.g. don't bother with CSS/making the JSON response human readable etc) similar to to TwitStream but for fetching user timelines and displaying them on a webpage.

A: are you looking for something like this?
`<?php
$username = "TwitterUsername"; // Your twitter username.
$limit = "5"; // Number of tweets to pull in.

/* These prefixes and suffixes will display before and after the entire block of tweets. */
$prefix = ""; // Prefix - some text you want displayed before all your tweets.
$suffix = ""; // Suffix - some text you want displayed after all your tweets.
$tweetprefix = ""; // Tweet Prefix - some text you want displayed before each tweet.
$tweetsuffix = "<br>"; // Tweet Suffix - some text you want displayed after each tweet.

$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $limit;

function parse_feed($feed, $prefix, $tweetprefix, $tweetsuffix, $suffix) {

$feed = str_replace("<", "<", $feed);
$feed = str_replace(">", ">", $feed);
$clean = explode("<content type=\"html\">", $feed);

$amount = count($clean) - 1;

echo $prefix;

for ($i = 1; $i <= $amount; $i++) {
$cleaner = explode("</content>", $clean[$i]);
echo $tweetprefix;
echo $cleaner[0];
echo $tweetsuffix;
}

echo $suffix;
}

$twitterFeed = file_get_contents($feed);
parse_feed($twitterFeed, $prefix, $tweetprefix, $tweetsuffix, $suffix);
?>`

I found this at: http://www.instantshift.com/2009/05/25/10-twitter-hacks-for-your-wordpress-blog/

A: Try using this class
https://github.com/KartikTalwar/Twitter-Class
Comes with excellent simple examples and you can display tonnes of details with just a couple of lines of code

A: You cannot get around rate limiting when pulling the tweets from your server without doing one of two things:
1) Pull down the tweets at a time interval and cache them on your site
2) Have users authenticate themselves and using their tokens to pull the tweets
Of course there is a much simpler way to do this. Request the timeline in javascript on the page itself. These timeline requests will count against the user's IP that views the page rather than your server.
Here is a site that has some javascript samples for this: http://www.mivamerchant.com/blog/how-to-make-custom-twitter-feed-for-your-website


text:
Q: ViewPager not showing correct View I'm using the V4 compatibility JAR.  I have a ViewPager that shows information about some bands.  When I create the PagerAdapter, I pass it an ArrayList of Band objects.
In the emulator, it always shows shows the 2nd band in the ArrayList's information first.  When I flip to the last view, the view always has no data.  When I flip back and forth, the data then gets really buggy.
BandsActivity
private ViewPager mBandsPager;
private BandsPagerAdapter mBandsPagerAdapter;
private static final String TAG = "Paging";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.awesomepager);

    // Build a couple bands;
    ArrayList<Band> bands = new ArrayList<Band>();
    bands.add(new Band(1, "Led Zeppelin"));
    bands.add(new Band(37, "Brand New"));
    bands.add(new Band(49, "Jay-Z"));

    mBandsPagerAdapter = new BandsPagerAdapter(this, bands);

    mBandsPager = (ViewPager) findViewById(R.id.awesomepager);
    mBandsPager.setAdapter(mBandsPagerAdapter);

}

BandsPagerAdapter
private Context mCtx;
private ArrayList<Band> mBands;

public BandsPagerAdapter(Context ctx, ArrayList<Band> bands) {
    mCtx = ctx;
    mBands = bands;
}

@Override
public int getCount() {
    return mBands.size();
}

@Override
public Object instantiateItem(View collection, int position) {

    // Inflate and create the view
    LayoutInflater layoutInflater = (LayoutInflater)mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.featured_bands_layout, null);

    // Build UI
    TextView name = (TextView)collection.findViewById(R.id.featured_band_name);

    // Populate UI with band data
    Band band = mBands.get(position);
    if(name != null) {
        name.setText("Name: " + band.getName() + ", Pos: " + position);
    }

    // Add View to the ViewPager collection
    ((ViewPager)collection).addView(view,0);

    return view;
}

@Override
public void destroyItem(View collection, int position, Object view) {

    ((ViewGroup) collection).removeView((View)view);
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view==((View)object);
}

@Override
public void finishUpdate(View arg0) {}

@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}

@Override
public Parcelable saveState() {
    return null;
}

@Override
public void startUpdate(View arg0) {}

Any suggestions?  I saw a mention of implementing ViewPager.SimpleOnPageChangeListener, but didn't see how it could be used properly.

A: Your BandsPagerAdapter seems to be the problem. Here's how I would implement it. See if it makes a difference!
public class BandsPagerAdapter extends PageAdaptor{

    private ArrayList<Band> mBands;

    public BandsPagerAdapter(ArrayList<Band> bands) {
        mBands = bands;
    }

    @Override
    public int getCount() {
        return mBands.size();
    }

    @Override
    public Object instantiateItem(View collection, int position) {

        // Inflate and create the view
        LayoutInflater layoutInflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.featured_bands_layout, null);

        // Build UI
        TextView name = (TextView) view.findViewById(R.id.featured_band_name);

        // Populate UI with band data
        Band band = mBands.get(position);
        if(name != null) {
            name.setText("Name: " + band.getName() + ", Pos: " + position);
        }

        // Add View to the ViewPager collection
        ((ViewPager) collection).addView(view,0);

        return view;
    }

    @Override
    public void destroyItem(View collection, int position, Object view)
        ((ViewPager) collection).removeView((View) view);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View) object);
    }

    @Override
    public void finishUpdate(View arg0) {}

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {}

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void startUpdate(View arg0) {}
}


text:
Q: Tensorflow: multiple one-hot outputs with one input? Is there a way to feed a Feed Forward tensorflow model with the labels containing multiple one hot encoding in one input?
For example:
x[0]: [15, 32, 3], y[0]: [[0,0,1], [0,1,0], [1,0,0]]
x[1]: [23, 2, 7], y[1]: [[1,0,0], [0,0,1], [0,1,0]]
The shape of x will be (1,3) while y will have (3, 3)
Is there a way to train a data like this in a simple feed forward neural network?

A: You could do that with a custom training loop and a model subclassed from Keras.Model. You can then have 3 output with 3 losses (potentially even a mix of categorical and continuous).
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras import Model
from functools import partial
import numpy as np

X = np.random.randint(0, 100, (100, 3)).astype(np.float32)
w = np.random.randint(0, 3, 100)
y = np.random.randint(0, 3, 100)
z = np.random.randint(0, 3, 100)

onehot = partial(tf.one_hot, depth=3)

dataset = tf.data.Dataset.from_tensor_slices((X, w, y, z)).\
    shuffle(100).\
    batch(4).\
    map(lambda a, b, c, d: (a, onehot(b), onehot(c), onehot(d)))

print(next(iter(dataset)))

class MyModel(Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.d0 = Dense(16, activation='relu')
        self.d1 = Dense(32, activation='relu')
        self.d2 = Dense(3)
        self.d3 = Dense(3)
        self.d4 = Dense(3)

    def call(self, x, training=None, **kwargs):
        x = self.d0(x)
        x = self.d1(x)
        out1 = self.d2(x)
        out2 = self.d3(x)
        out3 = self.d4(x)
        return out1, out2, out3

model = MyModel()

loss_object = tf.losses.categorical_crossentropy

def compute_loss(model, x, w, y, z, training):
  out1, out2, out3 = model(inputs=x, training=training)
  loss1 = loss_object(y_true=w, y_pred=out1, from_logits=True)
  loss2 = loss_object(y_true=y, y_pred=out2, from_logits=True)
  loss3 = loss_object(y_true=z, y_pred=out3, from_logits=True)
  return loss1, loss2, loss3

def get_grad(model, x, w, y, z):
    with tf.GradientTape() as tape:
        loss1, loss2, loss3 = compute_loss(model, x, w, y, z, training=False)
    gradients = tape.gradient([loss1, loss2, loss3], model.trainable_variables)
    return (loss1, loss2, loss3), gradients

optimizer = tf.optimizers.Adam()

verbose = "Epoch {:2d} Loss1: {:.3f} Loss2: {:.3f} Loss3: {:.3f}"

for epoch in range(1, 10 + 1):
    loss1 = tf.metrics.Mean()
    loss2 = tf.metrics.Mean()
    loss3 = tf.metrics.Mean()

    for X, w, y, z in dataset:
        losses, grads = get_grad(model, X, w, y, z)
        optimizer.apply_gradients(zip(grads, model.trainable_variables))

        for current_loss, running_loss in zip(losses, [loss1, loss2, loss3]):
            running_loss.update_state(current_loss)

    print(verbose.format(epoch,
                         loss1.result(),
                         loss2.result(),
                         loss3.result()))

Input:
(<tf.Tensor: shape=(4, 3), dtype=float32, numpy=
array([[45., 35., 46.],
       [64., 95., 55.],
       [90., 41., 12.],
       [98., 17., 81.]], dtype=float32)>, <tf.Tensor: shape=(4, 3), dtype=float32, numpy=
array([[0., 0., 1.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.]], dtype=float32)>, <tf.Tensor: shape=(4, 3), dtype=float32, numpy=
array([[0., 0., 1.],
       [0., 1., 0.],
       [0., 0., 1.],
       [0., 1., 0.]], dtype=float32)>, <tf.Tensor: shape=(4, 3), dtype=float32, numpy=
array([[0., 1., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.]], dtype=float32)>)

Output:
Epoch  1 Loss1: 0.980 Loss2: 1.051 Loss3: 1.035
Epoch  2 Loss1: 0.886 Loss2: 0.961 Loss3: 0.934
Epoch  3 Loss1: 0.814 Loss2: 0.872 Loss3: 0.847
Epoch  4 Loss1: 0.762 Loss2: 0.804 Loss3: 0.786
Epoch  5 Loss1: 0.732 Loss2: 0.755 Loss3: 0.747
Epoch  6 Loss1: 0.718 Loss2: 0.731 Loss3: 0.723
Epoch  7 Loss1: 0.709 Loss2: 0.715 Loss3: 0.714
Epoch  8 Loss1: 0.700 Loss2: 0.708 Loss3: 0.705
Epoch  9 Loss1: 0.699 Loss2: 0.697 Loss3: 0.701
Epoch 10 Loss1: 0.703 Loss2: 0.702 Loss3: 0.698


text:
Q: several plots (scatter plot of a specific variable vs other variables) in R How can I modify this code to have all plots together and on one page(loop function)? In my real data set, I want to have the scatter plot between the dependent variable and 10 independent variables. The scatter plot between the dependent variable and each IV separately.
plot(rock$area, rock$peri)
plot(rock$area, rock$shape)
plot(rock$area, rock$perm)

A: Since you tagged your question with ggplot2, I'll assume that you are interested in a ggplot2 solution.
rock <- data.frame(area  = sample(1:100, 10, replace = TRUE),
                   peri  = sample(1:100, 10, replace = TRUE),
                   shape = sample(1:100, 10, replace = TRUE),
                   perm  = sample(1:100, 10, replace = TRUE))

Now we can make the data tidy (a column for y variable names, another column for y variable values) and use facets to create separate plots per y variable.
library(tidyr)
library(ggplot2)
rock %>%
  gather(yvar, val, -area) %>%
  ggplot(aes(area, val)) +
    geom_point() +
    facet_grid(yvar ~ .)


text:
Q: Metric of the doubling i.e circular billard table Let $D^2=B_1(0) \cup_{\partial B_1(0)} B_1(0)$ denote the doubling in $\mathbb{R}^2$ i.e. the metric space which one gets after gluing two closed balls of radius $1$ with their induced metric coming from $\mathbb{R}^2$ along their boundary.
The distance between two points $p_1,p_2$ is just the euclidean distance if they are lying in the same ball. If two points $p_1,p_2$ lie in distinct balls, then their distance is given by the path a particle would travel in a circular billiard from $p_1$ to $p_2'$. Where $p_2'$ is the corresponding point of $p_2$ in the first ball.
Since elliptic billiards are a well studied subject, does there exist an explicit formula for the distance between two points $p_1,p_2$?


text:
Q: Make EditText gain focus using dpad I have a simple interface in my app - a button on the top of the screen, an EditText in the screen center and 2 more buttons at the bottom.
Now I would like to use dpad to navigate thru the app's elements, everything works fine besides the EditText - basically i can browse thru the items fine, buttons get highlighted on focus, but not the EditText - it seems unresponsive even when I click the dpad center button (so the keyboard doesn't show up). For example when I have the very top element highlighted and I press down on the dpad, the top button looses focus, none of the 2 buttons at the bottom get the focus, so it looks like it's the EditText that gets the focus, but it doesn't highlight in any way, nor show the keyboard. When I click it with the coursor (or touch on the device) it's all ok.
I've tried adding the OnKeyListener to check but doesn't seem to fire off - like the EditText didn't really get the focus and the KeyEvent isn't fired on the EditText:
editKanal.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
                if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
                    Toast.makeText(getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
                    return true;
                }

            return false;
        }
    });

Can anyone tell me what I am doing wrong? How do I make an EditText show the keyboard on DPAD_CENTER pressed?

A: Try to put this line after click:
editKanal.requestFocus();

If this is not working, can you post your XMl layout?

A: Hello had this problem before
most likely causes are
1-not adding focus down
2-the items not being in the same layout
please make sure both are true


text:
Q: Why is int[] a = new int[0]; allowed? Is there a reason why
int[] myArray = new int[0];

compiles?
Is there any use of such an expression?
myArray[0] = 1;

gives java.lang.ArrayIndexOutOfBoundsException.
if (myArray == null) {
    System.out.println("myArray is null.");
} else {
    System.out.println("myArray is not null.");
}

gives myArray is not null..
So I can't see a reason why int[] myArray = new int[0] should be preferred over myArray = null;.

A: Yes there is eg main method execution w/o command line parameters. It gives you a 0-sized array instead of null.

A:  int[] myArray = new int[0];

Arrays in java are regular objects. So above code says that array size is zero. This is particularly useful for protection against Null pointer exception.
Similar to this even Collections API have a way to initialize to an empty place holder.
 List<String> list = Collections.EMPTY_LIST;

A: public int[] getData()
{
    if (iGotNothinForYa)
    {
        return new int[0];
    }

    int[] data = buildUpArray();
    return data;
}

It's often easier, in code consuming the data returned by a method like this, to not have to do a null check. Particularly when iterating over the array.
int[] data = getData();
for (int i : data) // yay! no null check!
{
    doSomethingWith(i);
}

A: It's just for reducing null checks.
You can iterate on empty array but can not iterate on null.
Consider the code:
for (Integer i: myArray) {
   System.out.println(i);
}

On empty array it prints nothing, on null it causes NullPointerException.

A: Why not?
You can get an array with the list of .exe files in a directory. And that directory can have no .exe files.
Forcing to use null for this case complicated the logic both creating and handling the array and helps to nothing.
UPDATE: More the point, the array size in Java is decided at compile time. It is true that new int[0] can be detected at compile time, but new int[System.currentTimeMillis % 10] cannot. So checking the 0 case at compile time does not ensure that you don't get empty arrays.

A: For example:
public void getArraySum(int[] array) {
    int sum = 0;

    for (int i = 0; i < array.length; i++)
        sum += array[i];

    return sum;
}

This will work with an empty array, but won't with null reference.
You just save a redundant null check. That is why you can create also an empty list for example.

A: An empty array can be used in thread synchronization when the goal is to use the least amount of memory for a locking object. Recall that arrays are objects, so if you wish to synchronize multiple threads on a single dummy object, the smallest object you can utilize is an empty array (possibly byte size):
byte bLock = new byte[0];
// Thread T1 synchronizes on this empty array object
synchronize(bLock) {
    // perform some task while blocking other threads
    // synchronizing on bLock
}

A: The why new [0] returns null instead of [], is because the system acnnot allocate (no space), it needs to allocate at least 1.
So that is why it returns null.
A list is different because a list is a class somehow that internally has an array or tree or something similar so it manages it internally.
but
int[] is just an array and that is just those ints in memory. (so int[0], is actually nothing, so why will alocate to have nothing? is good it givse null).
why is it allowed, well imagine you do
new int [x+y]; where you do not know x, or y, and they can be both 0, without allowing this you need to check for it before and act different before eacn time.

A: As in the API Documentation, it can also be used like this:
String[] a = c.toArray(new String[0]); // c: List<String>

instead of calculating the array length yourself:
String[] a = new String[c.size()];
c.toArray(a);


text:
Q: How to highlight two different labels when hovered on any one of them in tkinter? I am building a small application using tkinter where it shows you the list of work done in the particular given interval ,the format is as below
      co11              col2

   Time done         Activity name

Below is the code.since the two columns are far away when i hover on one of the two labels inside the for loop, i want both the labels to be highlight for easy identification of time done-activity name. i have implemented the labels in a grid layout as separate labels.
                def on_click(e):
                    e.widget['bg']='#fafafa'
                def on_leave(e):
                    e.widget['bg']='#dcdcdc'
                if result1:
                    Label(second_frame, text=start_time[11:], width=115, font=('Tahoma', 15),
                          fg='black',bg='#aaaaaa').grid(row=x,column=0, columnspan=2)
                    x += 1
                    for j in result1:
                        temp = int(j[2]) * int(j[3])
                        # print(j[0][11:], j[1], j[2], j[3], temp)
                        sub_total += temp
                        total_pts += temp
                        e1=Label(second_frame, text=j[0][11:], font=('Tahoma', 12), bg='#dcdcdc', width=71)
                        e1.grid(row=x,column=0)

                        e2=Label(second_frame, text=str(j[1]), font=('Tahoma', 12), bg='#dcdcdc', width=71)
                        e2.grid(row=x,column=1)
                        e1.bind('<Enter>',on_click)
                        e1.bind('<Leave>',on_leave)
                        e2.bind('<Enter>', on_click)
                        e2.bind('<Leave>', on_leave)
                        x += 1

A: You can link the pair buttons in each row to each other using a user-defined attribute of the button, then you can highlight them together easily.
Below is an example:
import tkinter as tk

root = tk.Tk()

def on_click(e):
    e.widget['bg'] = "#fafafa"
    e.widget.peer['bg'] = "#fafafa" # set the peer as well

def on_leave(e):
    e.widget['bg'] = "#dcdcdc"
    e.widget.peer['bg'] = "#dcdcdc" # set the peer as well

for i in range(10):
    e1 = tk.Label(root, text=f"Left {i+1}", width=10, bg="#dcdcdc", font="Tahoma 12")
    e1.grid(row=i, column=0, padx=(0,300))

    e2 = tk.Label(root, text=f"Right {i+1}", width=10, bg="#dcdcdc", font="Tahoma 12")
    e2.grid(row=i, column=1, padx=(300,0))

    e1.bind("<Enter>", on_click)
    e1.bind("<Leave>", on_leave)
    e2.bind("<Enter>", on_click)
    e2.bind("<Leave>", on_leave)

    # link the pair buttons together
    e1.peer = e2
    e2.peer = e1

root.mainloop()

Update: example with more than 2 entries in a row:
import tkinter as tk

root = tk.Tk()

def on_click(e):
    for entry in rows[e.widget.row]:
        entry['bg'] = "#fafafa"

def on_leave(e):
    for entry in rows[e.widget.row]:
        entry['bg'] = "#dcdcdc"

# use 2-dimensional list to store the entries
rows = []
for i in range(10):
    entries = []  # store entries in a row
    for c in range(4):
        e = tk.Label(root, text=f"Item {i+1},{c+1}", width=10, bg="#dcdcdc", font="Tahoma 12")
        e.grid(row=i, column=c, padx=50)
        e.bind("<Enter>", on_click)
        e.bind("<Leave>", on_leave)
        e.row = i  # save the row number
        entries.append(e)
    rows.append(entries)

root.mainloop()

A: An easy solution could be to group the items that need to be configured like in a list
Example
from tkinter import *

def on_enter(event):
    if event.widget in labels:
        for label in labels:
            label['bg']='#fafafa'

def on_leave(event):
    if event.widget in labels:
        for label in labels:
            label['bg']='#dcdcdc'

root=Tk()

hello_label=Label(root,text='Hello')
hello_label.pack(side='left',pady=20)
world_label=Label(root,text='World')
world_label.pack(side='left',pady=20)
labels=[hello_label,world_label]

root.bind_all('<Enter>',on_enter)
root.bind_all('<Leave>',on_leave)

root.mainloop()


text:
Q: Can an arbitrary quantum system of finite size be made to reliably relax to its ground state? Is there a physical principle prohibiting this? I am talking about the possibility of reliably cooling an arbitrary quantum system of FINITE size (for example, localized on earth), to its ground state through any means, like exposure to a special kind of environment etc. By reliable, I mean that for the given system, can we calculate a finite time T after which it has a high probability, lets say 75%, of relaxing to the ground state?
Can this always be done? If not, is there a physical argument prohibiting it?
More Details for context: I read a [paper][1] that gives a physical argument why this may not be possible. It asserts that the ground state of carbon is known to be graphite, yet tiny pieces of diamond have been found to survive in meteorites for billions of years.
I tried to set up the GKSL equation for the relaxation of a two state system exposed to some environment at temperature T. I found that a quantum cooling analogous to newton cooling in the sense that there are exponential decay terms for the off diagonal elements and so on, can be incorporated as the lindblad equation.
So the catch may be that the system may get caught somewhere in a local minima for an indefinite amount of time, prohibiting it from reaching the ground state.
[1]: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.85.6029&rep=rep1&type=pdf " Smith, Warren D. "Three counterexamples refuting Kieu's plan for "quantum adiabatic hypercomputation"; and some uncomputable quantum mechanical tasks." Applied Mathematics and Computation 178.1 (2006): 184-193."
Note: to get to the relevant paragraph of the paper above, search for the term 'cool' in the pdf.

A: Yes, in principle at least. A number of points

*

*Cooling down corresponds to a time-evolution in imaginary time $\tau$ i.e. $\hat{\rho}(t)=e^{-\hat{H}\tau}\hat{\rho}_0 e^{-\hat{H}\tau}$, and it is easy to see that this leads to the ground state.

*The whole notion of cooling down relies on the Second Law of Thermodynamics: basically, any (equilibrium) system will tend towards a Boltzmann-Gibbs state at infinite time, and the corresponding temperature will go to the one of its environment. So if you put the system in a $T=0$ bath, eventually it goes to its ground state. The assumption is here that thermodynamics is valid, meaning we are relying on ergodicity (for any microstate, there exist some incoherent process connecting it to the other microstates), but this is widely accepted except for some very specifically engineered cases. Thermodynamics doesn't tell anything about the timescales involved, though.

*Consider as a practical setup, that the system couples with empty space, a bath at $T=0$. Cooling down occurs by spontaneous emission, single-photon losses in the simplest case. We can describe this process with a Lindblad equation, and an associated Liouvillian superoperator $\mathcal{L}$. In case where where the quantum-dynamical semigroup is irreducible (basically, this is the same assumption as ergodicity), $\mathcal{L}$ has a unique lowest eigenvector, the steady state (also known as Spohn's theorem). If the emission process can only decrease energy, the steady state is the same as the ground state. The spectrum of $\mathcal{L}$ has also a gap, and the inverse of this Liouvillian gap corresponds to the slowest timescale associated with cooling.
Of course, metastabilities exist, but that's what they are, metastable so at some point, possibly longer than the age of the universe, the system will decay further. A good example of long-living metastabilities are glasses. Typically, slow cooling or thermal annealing where the temperature is decreased slowly, overcomes metastabilities faster than connecting it to a $T=0$ bath as described above.


text:
Q: Sprintf crashing my program
I am just tryng to use sprintf to concatenate some strings but I had this problem,
  I don't understand why my program is crashing using sprintf in C. Why this code runs?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* dateTime = malloc(16*sizeof(char));

    printf("Date: %s\n", __DATE__);
    printf("Time: %s\n", __TIME__);

    sprintf (dateTime, "%s, %s\0", __DATE__, __TIME__);

    printf("%s", dateTime);
    free(dateTime);

    return 0;
}

And this one not?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* dateTime = malloc(16*sizeof(char));

    //printf("Date: %s\n", __DATE__);
    //printf("Time: %s\n", __TIME__);

    sprintf (dateTime, "%s, %s\0", __DATE__, __TIME__);

    printf("%s", dateTime);
    free(dateTime);

    return 0;
}

A: On my compiler, the string you're creating is 21 characters long (Dec 23 2016, 23:29:57), so you're basically allocating too few bytes for your string.
You get undefined behaviour. So it crashes without the printf statements, and kind of works with them because the computer is not doing the exact same thing, but it's still wrong.
BTW you could achieve what you want safely by just doing this:
const char *dateTime= __DATE__ " " __TIME__;

since __DATE__ and __TIME__ are already string macros. Preprocessor can do the concatenation at compile time.
If you want to compute the numbers of characters needed you could use snprintf with a NULL buffer (c99 only):

Calling snprintf with zero bufsz and null pointer for buffer is useful to determine the necessary buffer size to contain the output:

const char *fmt = "sqrt(2) = %f";
int sz = snprintf(NULL, 0, fmt, sqrt(2));
char buf[sz + 1]; // note +1 for terminating null byte
snprintf(buf, sizeof buf, fmt, sqrt(2));

http://en.cppreference.com/w/c/io/fprintf

A: It appears that your buffer is too small for sprintf:
char* dateTime = malloc(16*sizeof(char));

The __DATE__ and __TIME__ always takes more than 15 bytes (not including NUL character). Writing past the array boundary causes undefined behaviour.


text:
Q: Calculating over records/rows found in different tables In MariaDB, if I have 300 tables that have an identical quantity of rows (basically names and the same names are in the same row positions/indeces across all tables) and each table has, say, three columns, how do I calculate an average, or any other calculation, for the third row item for just one name across all 300 tables?
`    TABLE 1                          TABLE 2

NAMES
DATA 1
SCORE

NAMES
DATA 1
SCORE

Jim
30
12

Jim
20
200

John
40
30

John
30
100

Jill
50
27

Jill
15
300

Jerry
20
50

Jerry
17
400

Jack
10
14

Jack
16
100

I am trying to calculate quantites (i.e. averages, standard deviations, and other custom calculations/formulae) for the "SCORE" for each name across all tables (two tables only shown for brevity) and then have such calculated quantities stored in a separate table that has each name listed.  So for instance, I'd like to be able to calculate the average "SCORE" for Jim across all 300 tables and store that in some separate results table that has a dedicated row for his name and then move down to the next name and do the same.
How would I do this/approach this?  I tried looking into UNIONS and and JOINS but couldn't see how to obtain what I'm looking for with those operations.


text:
Q: How to load the Java Mongo driver's MongoClientOptions from a file? It feels weird to configure MongoClientOptions inside my code like options.socketTimeout(30000); where I have to recompile to change a setting in production. I can't see any good way to load config via the builder from an XML or YAML file.
Am I missing something in the docs, or is there a neat implementation/snippet someone can share?

A: I don't think there is anything in the driver for managing how and where you get these settings from. Not sure it's drivers' job..  I keep properties file with needed mongo settings and do something like this:
import org.apache.commons.configuration.PropertiesConfiguration;
PropertiesConfiguration props = new PropertiesConfiguration();
props.load(fileName);

MongoClientOptions copts = MongoClientOptions.builder()
   .connectionsPerHost(props.getInt("connectionsPerHost", 100))
   .connectTimeout(props.getInt("connectTimeout", 10000))
   ...
   .build();


text:
Q: What does the semicolon represent in an awk action? I'm attempting to decipher the action in the following awk statement specifically what the ; after the first user defined variable refers to.
{ num_gold++; wt_gold += $2 }

A: In awk, you can write two statements in one line separated by ;(semi-colon)
{ num_gold++; wt_gold += $2 }

Otherwize, you should put them into separated lines:
{
    num_gold++
    wt_gold += $2
}

To print the variables, you just add print before the variables:
{
    num_gold++
    wt_gold += $2

    print num_gold
    print wt_gold
}

As I said, you can put them all in one line:
{ num_gold++; wt_gold += $2; print num_gold; print wt_gold; }

It's too long!
print also accepts multiple arguments, so try print num_gold, wt_gold.


text:
Q: Angular nativeElement offsetTop alway 0 Im working in a menu where the current section is gonna be select it on scroll, but when i try to get the offsetTop of the elements i get alway 0 for some reason, on the parentElement a get value for offsetTop but in this case does not work for me using the offsetTop of the parentElement because i have many childElements inside with different offsetTop.
Template

 page.service-detail.available-plan.menu.limit-pricing

        <mat-list class="mat-list-padding-none">
            <mat-list-item>global.label.limits</mat-list-item>
            <mat-divider></mat-divider>
            <mp-service-plan-limit-display [limits]="selectedPlan?.limits"></mp-service-plan-limit-display>
        </mat-list>

        <mat-list class="nx-margin-top-m mat-list-padding-none">
            <mat-list-item>page.service-detail.pricing</mat-list-item>
            <mat-divider></mat-divider>
            <mp-service-plan-price-display
                [prices]="selectedPlan?.prices"
                [planId]="selectedPlan?.id"
                [availablePlans]="true"
            ></mp-service-plan-price-display>
        </mat-list>

        <ng-container *ngIf="planSpecDocuments.length > 0">

                page.service-detail.available-plan.menu.documentation

Details how to embed the Service into your application.

            <mat-list class="mat-list-padding-none mat-file-list">
                <ng-container *ngFor="let specDocument of planSpecDocuments">
                    <mat-list-item>
                        <ng-container *ngIf="(partnerId$ | async)?.length && !isPreview; else documentSpecDisabledTpl">

                                {{ specDocument.name }}

                        </ng-container>
                        <ng-template #documentSpecDisabledTpl>

                                {{ specDocument.name }}

                        </ng-template>
                    </mat-list-item>
                </ng-container>
            </mat-list>
        </ng-container>

Component
@ViewChild('limitPricing') limitPricing!: ElementRef;
@ViewChild('documentation') documentation!: ElementRef;
@ViewChild('swaggerSpec') swaggerSpec!: ElementRef;

    timer(500).subscribe(() => {
        console.dir(this.limitPricing?.nativeElement);
        this.limitPricingOffset = this.limitPricing?.nativeElement.offsetTop - 100; // offsetTop here is always zero
        this.documentationOffset = this.documentation?.nativeElement.offsetTop - 100;
        this.swaggerSpecOffset = this.swaggerSpec?.nativeElement.offsetTop - 100;
    });

A: Declare the element in the constructor, as private _element: ElementRef) { ...}
this._element.nativeElement.getBoundingClientRect().top


text:
Q: Best practice to compress bitmap with LZ4 I'm packing some image resources for my game, and since this is a typical "compress once, decompress multiple" scenario, LZ4 High Compression fits me well (LZ4HC take longer time to compress, but decompress very fast).
I compressed a bitmap from 7.7MB to 3.0MB, which looks good to me, until I found that the PNG version is only 1.9MB.
I know that LZ4 HC do not have the ratio that deflate (which is used by PNG) does, but the ratio  2.55 vs 4.05 looks not right.
I searched and find that before compressing, PNG format will perform a Filtering operation, though I don't the details, it looks like that the Filtering move manipulate the data to fits the compress algorithm better.
So my question is:

*

*Do I need to perform a filtering move before compressing using lz4?

*If yes, where can I get a library (or code snippet) to perform filtering?

*If no, is there any solution to make a PNG (or other lossless image formats) compress slow but decompress fast?

A: The simplest filtering in PNG is just taking the difference of subsequent pixels. The first pixel is sent as is, the next pixel is sent as the difference of that pixel and the previous pixel, and so on. That would be quite fast, and provide a good bit of the compression gain of filtering.


text:
Q: Calculating capacitance on breadboard vs PCB tracks Is there an equation I can use to calculate:

*

*the actual capacitance between two PCB tracks close together and

*the actual capacitance between two adjacent holes of a breadboard

I believe such capacitance is called stray capacitance but I'm not 100% sure.
The reason why I ask is because I make super-regenerative receivers and the results are different when I transfer the circuit to PCB from a breadboard, most notably capacitance values, and I verify this because the reception frequency (station) is different even though I haven't change any values of any components.
The rest of the parts that form the circuit in both cases are exactly the same including the wall wart 5VDC power supply.
I also would like equations in order to make successful tests on the breadboard, so then I don't have to waste solder, or PCB material over failed attempts, and yes I removed and re-soldered components in the past which can be a pain so I want to avoid that route.
Any ideas on how to calculate the capacitance?

A:
so then I don't have to waste solder, or PCB material over failed attempts, and yes I removed and re-soldered components in the past which can be a pain

*

*Solder is cheap.

*Design your PCB using larger parts than are strictly necessary. 0805 parts are much easier to rework than 0402.

*Design your footprints with slightly more fillet area than the minimum. If the pad extends a bit beyond the end of the part, it will be much easier to rework.

*Design your PCB with extra part locations for trimming. This lets you adjust effective part values in smaller steps than the standard values allow.
Now you don't need to muck around with crummy breadboards.

A: There is a fantastic, free piece of software called Saturn PCB Design Toolkit that will help you out with this and pretty much any other calculation you need to do when creating PCBs.
I can't remember off the top of my head whether it offers a calculator for capacitance between two tracks (with varying voltages) though, but it offers pretty much anything related to microstrips over a plane or a track with regards to surrounding ground and a lot of other useful stuff.
Link here
With regards to your question though, I would assume you would be more interested in capacitance related to ground rather than between two tracks or two via's? This is something Saturn definitely can help you with.


text:
Q: Ellipsis (abbreviate text) with JSP / EL I was wondering what is the best way to implement an ellipsis abbreviation with JSP / Expression Language.
For now, I've been using fn:substring, which is ok, but I would like to have the three dots "...", in case the text was truncated.
With a web search I found that Java Web Parts has an AbbreviateTag. However I was wondering if there are better libraries, or if it's better I roll my own custom tag. What do you suggest?

A: The MMBase tag library has a tag that supports ellipsis.
However, implementing your own could be a good option ... depending on exactly how you expect the ellipsis to work.

A: Since I couldn't understand how to use mmbase, I built my own custom tag extending SimpleTagSupport.
It works in this way:
<%@ taglib prefix="sti" uri="/WEB-INF/tlds/stivlo.tld" %>

<sti:ellipsis>What a beautiful day.</sti:ellipsis>

<sti:ellipsis maxLength="10">What a beautiful day.</sti:ellipsis>

Output:
What a beautiful day.
What a bea…

I've also documented the custom tag implementation on my blog. This is my first custom tag, if anything can be done better, I'd be happy to hear from you.

A: Old thread, but I am posting this for anyone searching for an answer. Below is how I handled this. The code was inside a loop creating td elements, hence the reference to columns. If the text needs truncation I adjusted the substring allowing room for the ellipsis and then appended the ellipsis.
<c:if test="${columnMaxLength ge 0}">
  <c:set value="" var="ellipsis" />
  <c:if test="${fn:length(colTxt) gt columnMaxLength}">
    <c:set value="..." var="ellipsis" />
  </c:if>
  <c:set value="${fn:substring(colTxt, 0, (columnMaxLength - fn:length(ellipsis)))}${ellipsis}" var="colTxt" />
</c:if>
<c:out value="${colTxt}" />


text:
Q: How can I setup View helpers in the views directory? I want to setup a helpers directory under views and place my view helpers there.
I have setup a test view helper in application/My/App/View/Helper/
I declared the class like so: class My_App_View_Helper_test extends Zend_View_Helper_Abstract
I setup the the Bootstrap.php file like so: $view->setHelperPath(APPLICATION_PATH.'/My/App/View/Helper','My_App_View_Helper');
This is working perfectly. I learned to do this from zendcasts.
But I cannot set it up the way I want to. How do I set up helpers in views/helpers/ ?
What are the rules regarding the directory naming conversion? Where do I use plural and where do I use capitalization when naming directories?
I thank you in advance for your help.
sincerely,
a complete noob

A: You can place the helpers in /view/helpers but you'll need to change your class name. The prefix needs to be Zend_View_Helper_
So, a class like Zend_View_Helper_MyHelper should work for you.
I found a blog post on usage, if you're interested : http://akrabat.com/zend-framework/zend-framework-view-helpers/
From the post

A typical Zend Framework project using
  Zend_Application, such as that
  generated using the zf command line
  tool, will have a folder called
  helpers within the views folder for
  each module. There will also be a
  helpers folder within the layouts
  folder too. If you place your view
  helper in one of these helpers
  folders, then the prefix is
  Zend_View_Helper_.

A: You can have a helper named Application_View_Helper_MyHelper in application/views/helpers.
In your bootstrap you should have the following:
$view->setHelperPath(APPLICATION_PATH.'/views/helpers','Application_View_Helper');

Here, you simply register new plugin prefix for view helpers - Application_View_Helper and point Zend Framework to look for classes with this prefix in the following path - APPLICATION_PATH.'/views/helpers


text:
Q: Multiple images with the same source? When I have multiple Images with the same source, does WPF create a separate copy of image data for each Image object, or they share it?

A: can u be a bit more specific ? have a look at BitmapImage on MSDN. you can use CacheOption property to handle how it caches it.

A: i think, the share
a. added an Image element with image A as source
b. added two Image elements with image A as source for both
c. added three Image elements with image A and image B as sources one for each
looked at the memory consumption in task manager
a < b << c


text:
Q: Changing the eyes camera's direction We are trying to get the experience like you were an animal. And animals have different eye positions and rotations.
We wanted to use google cardboard because it's the most accessible for us as a preview.
But the question is, is there a way to change the angle of the eye cameras in the google vr SDK?
Thanks in advance,
Olivierus


text:
Q: How can I set up short forms for commands on Unix shell? If some frequently used commands in Unix shell are given short forms, it reduces programmer's effort.
example :
How can I use e instead of "emacs -nw".

A: In your .bashrc in your home directory add
alias e='emacs -nw'
to the end of the file. Either source the .bashrc file or open a new terminal to see the effects.

A: You can create command aliases. Open the ~/.bashrc file and add this line:
alias e='emacs -nw'

Then re-load it to apply changes:
source ~/.bashrc

A: If you aren't already aware of aliases, skip them and move straight to shell functions:
e () {
    emacs -nw "$@"
}


text:
Q: map iterator not dereferencable I am getting compile error "map/set" iterator not dereferencable". What is going on here?
#include<iostream>
#include<map>

using namespace std;

int main(){
    map<int, int> m;
    map<int, int>::iterator itr=m.begin();

    itr->first = 0;
    itr->second = 0;

    cout << itr->first << " " << itr->second;
    return 0;
}

A: The map is empty, so m.begin() is equal to the past-the-end iterator and is therefore invalid.
You first have to insert elements somehow (you can also do that implicitly by using operator[]) to make it useful.
Also, you cannot modify the key of an element like this. You would have to remove (erase) the element from the map and insert a new one with the new key.
Here's an example about that:
#include<iostream>
#include<map>

using namespace std;

int main(){
    map<int, int> m;

    // insert element by map::insert
    m.insert(make_pair(3, 3));

    // insert element by map::operator[]
    m[5] = 5;

    std::cout << "increased values by one" << std::endl;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it)
    {
        it->second += 1;
        cout << it->first << " " << it->second << std::endl;
    }

    // replace an element:
    map<int, int>::iterator thing = m.find(3);
    int value = thing->second;
    m.erase(thing);
    m[4] = value;

    std::cout << "replaced an element and inserted with different key" << std::endl;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it)
    {
        cout << it->first << " " << it->second << std::endl;
    }

    return 0;
}

A: Your map's empty! What your iterator is pointing to is undefined.
What you wanted to do is
int main(){
    map<int, int> m;
    m[0] = 0;
    map<int, int>::iterator itr=m.begin();

    cout << itr->first << " " << itr->second;
    return 0;
}

A: Here you have not assign any value. and you can not change the key of itr->first of it. It can be read only. But you can edit itr->second.
map<int, int> m;
    m[10]=0;
    map<int, int>::iterator itr=m.begin();

      itr->second=10;
    cout << itr->first << " " << itr->second;


text:
Q: Is a Spring Boot microservice with a non-Java front-end client possible? I've implemented the shell of a microservices-based REST API application. I have simply followed the guides on Pivotal Springs' own documentation using Eureka and Ribbon for load balancing. Everything works. I have a discovery server with a handful of independent services which can register with the discovery server.
Now, my problem is that I might prefer not to write my client-side app in Java - maybe Angular or node.js, etc. However, the load balancing and connecting to the discovery server is all done in Java in the examples I've followed.
Is it possible to use JavaScript to do the same things that the Eureka client does with the Spring Boot microservices so that I don't need to be constrained in my choices of browser client technology? Does anybody have any advice for how this should be approached? I had difficulty finding any articles that cover this, to be honest.

A: Yes. Definitely you can choose technology of your choice for developing front end application. From your front end application, you make calls to API endpoint that you expose via your spring boot application.
You might want to expose your services via single API gateway that will help you route requests to designated micro services using your discovery server.

A: Actually you should not be doing load balancing/service discover etc. in the front-end. So the question about whether it is possible in JavaScript or with which libraries is irrelevant.
Typically you'll have an API gateway or a (load balancing) proxy which works with your service registry and routes requests accordingly. In the current project we use Consul for service registry and Nginx + consul-template as proxy. We plan to migrate to some API gateway.
With this setup your front-end will connect to just one central endpoint which would do load balancing/routing to individual service instances behind the scenes. Thus your front-end will not need to implement anything like Eureka/Ribbon etc.


text:
Q: Errors in installing Firebase CLI in Command Promt I'm trying to host a web app using firebase, installed nodejs, got the point where I have to install the Firebase CLI, ran it in the command prompt and now getting loads of errors.
C:\Users\hp>npm install -g firebase-tools
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated har-validator@5.1.3: this library is no longer supported
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR! network request to https://registry.npmjs.org/ws/-/ws-7.4.6.tgz failed, reason: socket hang up
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hp\AppData\Local\npm-cache\_logs\2022-08-08T22_58_54_984Z-debug-0.log


text:
Q: I need some help diagnosing the problem with this code I'm having trouble with some code. This code's purpose is just to take user-inputted numbers, append them to a string, and create a histogram representing the amount of numbers in each 5 number range from 1 to 50. Ex.
1 - 5: ***
6 - 10: ********
11 - 15: *
etc.

Here is the code:
public class Ch10Ex4 {

    public static int number;
    public static ArrayList<Integer> numbers = new ArrayList<>();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            getNums(1, 50);
        }

        histogram(1, 50, 5);
        System.out.println();
    }

    public static void getNums(int low_num, int high_num) {
        Scanner sc = new Scanner(System.in);

        do {
            System.out.print("Enter a number between " + low_num +
                    " and " + high_num + ": ");
            number = sc.nextInt();

        } while (number < 1 || number > 50);

        System.out.println(number + " has been added sucsessfully.");

        numbers.add(number);
    }

    public static void histogram(int low, int high, int range) {
        int temp_low = low;
        int temp_high = low + (range - 1);

        for (int i = 0; i < high / range; i++) {
            System.out.print("\n" + temp_low + " - " + temp_high + ": ");
            for (int arr:numbers) {
                if (arr >= temp_low && i <= temp_high) {
                    System.out.print("*");
                } else {
                }
            }
            temp_low += range;
            temp_high += range;
        }

    }

}

I had a previous version of this code where I would call histogram() with two parameters. These would be the lowest number and the highest number like usual but no int range parameter. And I didn't have the outermost for-loop. I would have to call histogram 10 times ex.
histogram(1, 5);
histogram(6, 10);
histogram(11, 15);
etc.

Basically, I would call it for every set of five numbers. It worked but it was super inefficient and not very reusable. The problem is that when I run this code (entering numbers 1- 10), I get this:
1 - 5: **********
6 - 10: *****
11 - 15:
16 - 20:
etc.

The first set of five outputs an asterix for every number in the array.
Sorry for the incredibly long post. Any help is much appreciated and thank you in advance.

A: The bug is that you are using i in this if-statement.
if (arr >= temp_low && i <= temp_high) {
    System.out.print("*");
} else {
}

Switch it to arr and you should be good.


text:
Q: Easy way to set index.html title to child iframe title? Is there an easy way to set the <title>*</title> of my index.html by looking at the <title>*</title> of a child iframe?
My site as example
When the content in the iframe changes, will the title change with it then?

A: For Only Web Pages are on same Domain.
var title = $("#IframeID").contents().find("title").html();
 $(document).attr('title',title);


text:
Q: How to configure preferred region list in ARM template for COSMOS DB? I have a Cosmos DB set up in two regions "A" and "B" where "A" is the write region. Recently "A" region failed and no reads were served even though "B" region was on.
It makes sense because the PreferredLocations is not set as explained in here or here.
The problem is that I don't want to set ConnectionPolicy.PreferredLocations in code since the exact locations are set in ARM templates.
How do I add the PreferredLocations properties in ARM template?

A: You don't set Preferred Locations in an ARM template. This is set in the Cosmos client SDK when you initialize a new client in your application. In an ARM template you set the failover priority, which will direct the service to specify which region to promote to the write region should a write region fail when automatic failover is set in your Cosmos account. Failover priority in an ARM template is set by the order in which regions are specified in the ARM template. Example is below.
"locations": [
    {
        "locationName": "[parameters('primaryRegion')]",
        "failoverPriority": 0,
        "isZoneRedundant": false
    },
    {
        "locationName": "[parameters('secondaryRegion')]",
        "failoverPriority": 1,
        "isZoneRedundant": false
     }
]

To specify preferred locations you do this when initializing a new SDK client instance. Example for this is below.
CosmosClientOptions options = new CosmosClientOptions
{
    ApplicationPreferredRegions = new List<string>
    {
        "West US",
        "East US",
        "Central US"
    }
};

CosmosClient client = new CosmosClient(connection, options );

PS: we have fairly details docs on this service. You should refer to these as much as possible rather than 4 year old docs written by a third party as the service and SDK have drastically changed. You can find our docs here


text:
Q: Might $a(x)$ be irreducible in $F[x]$ but reducible in $F[x]/\langle p(x)\rangle$, where $a(x)$ is not a multiple of $p(x)$? Might $a(x)$ be irreducible in $F[x]$ but reducible in $F[x]/\langle p(x)\rangle$, where $a(x)$ is not a multiple of $p(x)$?
$F[x]/\langle p(x)\rangle $ does not have to be a field. Could you name an example, preferably one for a field another for a non-field just so I can see the difference?
It was suggested by Arturo that I should re-edit this question since it was not clear enough:
Let F be a field, and say $a(x)∈F[x]$ be irreducible. If $p(x)$ is not constant and not equal to an associate of $a(x)$, and we let $R=F[x]/(p(x))$, and identify F with its image in R, can $a(y)$ be reducible in $R[y]$?

A: If you quotient by a reducible polynomial, you'll end up with zero divisors.
Consider $\mathbb{Q}[x]/(x^2-1)$. I'll refer to cosets "$f(x)+(x^2+1)$" just by their representatives "$f(x)$".
Notice that $x+1,x-1$ are non-zero in this quotient, but $(x+1)(x-1)=x^2-1=0$ (mod $x^2-1$).
So we've got zero divisors.
If you want a better feel for what this ring "really" looks like. It's not hard to show that
$\mathbb{Q}[x]/(x^2-1) \cong \mathbb{Q}[x]/(x-1) \times \mathbb{Q}[x]/(x+1) \cong \mathbb{Q} \times \mathbb{Q}$. [Use the map $f(x) \mapsto (f(x)+(x-1),f(x)+(x+1))$ it's not hard to show this map is a homomorphism from $\mathbb{Q}[x]$ to $\mathbb{Q}[x]/(x-1) \times \mathbb{Q}[x]/(x+1)$ has kernel $(x^2-1)$ and using Chinese remaindering you can show it's onto. Then the result follows form the 1st isomorphism theorem.]

A: First, let's be clear:
If $R$ is a commutative ring with $1$, then an element $a\in R$ is irreducible if and only if $a$ is not a unit, $a$ is not a zero divisor, and whenever $a=bc$ in $R$, either $b$ is a unit (invertible) or $c$ is a unit. Added. Elements are not usually called "reducible", though. Elements that are not irreducible are "not irreducible".
In the particular case of $R=F[x]$ with $F$ a field, this agrees with the "usual" notion of "irreducible polynomial", since the units are precisely the nonzero constant polynomials.
Now, if $F$ is a field, then $F[x]$ is a unique factorization domain (even more, a Euclidean domain). If $a(x)$ is irreducible, then it is a prime in $F[x]$. So for any $p(x)\in F[x]$ there are only three possibilities: either $a(x)$ divides $p(x)$, or $p(x)=0$, or else $a(x)$ and $p(x)$ are relatively prime, and in particular, there exist polynomials $r(x)$ and $s(x)$ such that
$$a(x)r(x) + p(x)s(x) = 1.$$
Now, suppose that $p(x)$ is a polynomial. The only way for $a(x)$ to be a multiple of $p(x)$ is for $a(x)$ to be of the form $a(x)=\lambda p(x)$ for some nonzero constant $\lambda\in F$.  Assume that $a(x)$ is not a multiple of $p(x)$.
If $p(x)\neq 0$ and $a(x)$ divides $p(x)$, then $p(x) = a(x)q(x)$ for some $q(x)\notin F$. We cannot have $p(x)$ dividing $q(x)$, so then $\overline{q(x)}$ is not zero in $F[x]/\langle p(x)\rangle$. Neither is $\overline{a(x)}$. Yet
$$\overline{a(x)}\times\overline{q(x)} = \overline{a(x)q(x)} = \overline{p(x)} = 0.$$
So $\overline{a(x)}$ is not irreducible, because it is a zero divisor.
If $a(x)$ does not divide $p(x)$, then we can write $1 = a(x)r(x)+p(x)s(x)$ for some polynomials $r(x)$ and $s(x)$. But then in $F[x]/\langle p(x)\rangle$ we have:
$$1 = \overline{1} = \overline{a(x)r(x) + p(x)s(x)} = \overline{a(x)}\overline{r(x)} + \overline{p(x)}\overline{s(x)} = \overline{a(x)}\overline{r(x)},$$
so $\overline{a(x)}$ is not irreducible because it is a unit.
Finally, if $p(x)=0$, then $F[x]/\langle p(x)\rangle$ is essentially just $F[x]$ itself again, so $a(x)$ is irreducible in the image because it's just $a(x)$ in $F[x]$.
So, to answer the question that was posed, if $p(x)\neq 0$ then $a(x)$ will not be irreducible in $F[x]/\langle p(x)\rangle$ no matter what.

That said...
But your use of the word "reducible" suggests that you are actually wondering about something else: whether "as a polynomial" it can be written as a product of two nonconstant polynomials, or perhaps whether "it has a root" when considered in $F[x]/\langle p(x)\rangle$.
In other words: say $p(x)$ is a nonconstant polynomial in $F[x]$. Then $R=F[x]/\langle p(x)\rangle$ is a ring that contains a copy of $F$. We can then consider the polynomial $a(x)$ as having coefficients in $R$ and ask whether it is reducible or irreducible over $R$. However, using $x$ here is confusing because $x$ is already playing a role in the definition of $R$, so it's better to switch to a different letter in order to talk about "polynomials with coefficients in $R$". So let's use $y$ to denote polynomials with coefficients in $R$, and so we will be asking whether $a(y)$ is irreducible over $R$ or reducible over $R$.
If $p(x)$ is irreducible over $F$, then $F[x]/\langle p(x)\rangle$ is a field that contains $F$, and you can consider $a(y)$ as a polynomial in $(F[x]/\langle p(x)\rangle[y]=R[y]$. There, it may be that $a(y)$ is irreducible or that it is reducible.
For an example where it is reducible, take $a(x) = x^4 + 1$ in $\mathbb{Q}[x]$, and $p(x) = x^2+1$, both irreducible. Since $\mathbb{Q}[x]/\langle p(x)\rangle = \mathbb{Q}(i)$, the rational complex numbers, in $\mathbb{Q}(i)[y]$ we have $a(y) = y^4+1 = (y^2+i)(y^2-i)$, reducible.
For an example where it is irreducible, take $a(x) = x^2 - 2$ and $p(x) = x^2-3$ in $\mathbb{Q}[x]$. Then $\mathbb{Q}[x]/\langle p(x)\rangle$ is just $\mathbb{Q}(\sqrt{3})$, and $a(y)$ has no roots in $\mathbb{Q}(\sqrt{3})$; being degree $2$, it is irreducible in $\mathbb{Q}(\sqrt{3})[y]$.
If $p(x)$ is reducible, then you end up with a ring that is not a field and has zero divisors.  In any case, as a consequence of the Chinese Remainder Theorem, if we factor $p(x)$ into irreducibles,
$$p(x) = q_1(x)^{\alpha_1}\cdots q_m(x)^{\alpha_m},$$
with $q_i$ and $q_j$ coprime for $i\neq j$, $\alpha_i\gt 0$, then
$$R=F[x]/\langle p(x)\rangle \cong \frac{F[x]}{\langle q_1(x)^{\alpha_1}\rangle}\times\cdots\times \frac{F[x]}{\langle q_m(x)^{\alpha_m}\rangle},$$
and this $a(y)$ may or may not be irreducible over this ring.
For an example where it is reducible, take the example above in which $a(y)$ was reducible, but replace $p(x)$ with $(x^4+1)(x^2+2)$ or some other reducible polynomial that has $x^4+1$ as a factor. Then $a(y)$ will have a root in the quotient, because it will have a root in one of the factors. Actually, since $F$ is embedded into the quotient "diagonally", you need two irreducible polynomials over which $a(x)$ was reducible, or a power of one over which $a(x)$ was reducible.  For an example where it is irreducible, do the same but now take the product of two polynomials over which $a(y)$ was irreducible. you can take $F=\mathbb{Q}$, $a(x) = x^2-2$, $p(x) = (x^2-3)(x^2-5)$. Then $F[x]/\langle p(x)\rangle \cong \mathbb{Q}(\sqrt{3})\times\mathbb{Q}(\sqrt{5})$, and that ring does not have a square root of $2$ either, so $a(y)$ is still irreducible.

A: I will address what I believe you are trying to ask for in the first scenario.
Let $F = \mathbb{Q}$,  $a(x) = x^4-5$, $p(x) = x^2-5$.
Note that both $a(x)$ and $p(x)$ are both irreducible by Eisenstein criterion. But $F[x]/(p(x)) = F[\sqrt{5}] = F(\sqrt{5})$, and over the  polynomial ring $F(\sqrt{5})[x]$ we can factor $a(x) = (x^2-\sqrt{5})(x^2+\sqrt{5})$.


text:
Q: trouble with numpy power function arguments I can't figure out what's wrong with this section of code.
def f1_x(xvec):
    yvec = 1/(np.sqrt(2 * np.pi)) * np.power(np.exp,(np.power(xvec,2)/4))
    print(yvec)
    return yvec

Every time I attempt to run the line, it outputs:
TypeError: unsupported operand type(s) for ** or pow(): 'numpy.ufunc' and 'float'

Everything else in the code is working like a charm to my knowledge, just this little block is giving me trouble.
P.S., the function I am attempting to describe is
f(x)=1/(√2π)*e^(-(x)^2/(4)),


text:
Q: transition effect in windows phone 7 I am currently working in Visual studio 2010 Express Edition For Windows Phone 7.I want to apply transition effects like dissolve,fading,slide at various places in my application.I am a newbie in windows phone 7 so not able to understand how and where to start?
Also I downloaded WPFSLFx library from HLSL Shader Effect Lab..?But no idea how to use it?

A: Download the wp7 toolkit from here:
http://silverlight.codeplex.com/releases/view/55034
And use the page transitions.
They are very simple to use, just some xaml added to the page:
<toolkit:TransitionService.NavigationInTransition>     <toolkit:NavigationInTransition>         <toolkit:NavigationInTransition.Backward>             <toolkit:TurnstileTransition Mode="BackwardIn"/>         </toolkit:NavigationInTransition.Backward>         <toolkit:NavigationInTransition.Forward>             <toolkit:TurnstileTransition Mode="ForwardIn"/>         </toolkit:NavigationInTransition.Forward>     </toolkit:NavigationInTransition> </toolkit:TransitionService.NavigationInTransition> <toolkit:TransitionService.NavigationOutTransition>     <toolkit:NavigationOutTransition>         <toolkit:NavigationOutTransition.Backward>             <toolkit:TurnstileTransition Mode="BackwardOut"/>         </toolkit:NavigationOutTransition.Backward>         <toolkit:NavigationOutTransition.Forward>             <toolkit:TurnstileTransition Mode="ForwardOut"/>         </toolkit:NavigationOutTransition.Forward>     </toolkit:NavigationOutTransition> </toolkit:TransitionService.NavigationOutTransition>

Here is a tutorial:
http://www.windowsphonegeek.com/articles/wp7-transitions-in-depth--key-concepts-and-api

A: One possible approach is to use Expression Blend for Windows Phone, which is part of the free developer tools: http://create.msdn.com/en-us/home/getting_started
You can have a look at the Expression Blend reference documentation beforehand:
http://msdn.microsoft.com/en-us/library/ff979338%28v=Expression.40%29.aspx
Specifically, look at the "Animation behaviors" here:
http://msdn.microsoft.com/en-us/library/ff979326%28v=Expression.40%29.aspx
Once Blend has generated this initial XAML, it is a good idea to study it a little further, which will hopefully give you sufficient ground to write some similar behaviors on your own.

A: <toolkit:TransitionService.NavigationInTransition>
    <toolkit:NavigationInTransition>
        <toolkit:NavigationInTransition.Backward>
            <toolkit:SlideTransition Mode="SlideRightFadeIn"/>
        </toolkit:NavigationInTransition.Backward>
        <toolkit:NavigationInTransition.Forward>
            <toolkit:SlideTransition Mode="SlideLeftFadeIn"/>
        </toolkit:NavigationInTransition.Forward>
    </toolkit:NavigationInTransition>
</toolkit:TransitionService.NavigationInTransition>
<toolkit:TransitionService.NavigationOutTransition>
    <toolkit:NavigationOutTransition>
        <toolkit:NavigationOutTransition.Backward>
            <toolkit:SlideTransition Mode="SlideRightFadeOut"/>
        </toolkit:NavigationOutTransition.Backward>
        <toolkit:NavigationOutTransition.Forward>
            <toolkit:SlideTransition Mode="SlideLeftFadeOut"/>
        </toolkit:NavigationOutTransition.Forward>
    </toolkit:NavigationOutTransition>
</toolkit:TransitionService.NavigationOutTransition>


text:
Q: Python number formatting difference I am a beginner without much knowledge of number formatting and could not find resources on this topic. Could someone explain what these notations mean or direct me to some resources?
I understand that format #1 means that d is formatted to have two fixed digits, and is padded by zeros on the left.

*

*'%02d/%04d/%03d' % (x, y, z)

*format(x, '100,d'))


text:
Q: Unable to create 3 tier-architecture I have this code. I have to transform it into 3-tier architecture. But I am getting multiple errors such as: TypeError: 'function' object has no attribute and TypeError: 'function' object is not subscriptable.
## This key will serve all examples in this document.
KEY = "PASTE_YOUR_FACE_SUBSCRIPTION_KEY_HERE"

## This endpoint will be used in all examples in this quickstart.
ENDPOINT = "PASTE_YOUR_FACE_ENDPOINT_HERE"

## Create an authenticated FaceClient.
face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))

# Base url for the Verify and Facelist/Large Facelist operations
IMAGE_BASE_URL = 'https://csdx.blob.core.windows.net/resources/Face/Images/'

# Create a list to hold the target photos of the same person
target_image_file_names = ['Family1-Dad1.jpg', 'Family1-Dad2.jpg']
# The source photos contain this person
source_image_file_name1 = 'Family1-Dad3.jpg'
source_image_file_name2 = 'Family1-Son1.jpg'

# Detect face(s) from source image 1, returns a list[DetectedFaces]
# We use detection model 3 to get better performance.
detected_faces1 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03')
# Add the returned face's face ID
source_image1_id = detected_faces1[0].face_id
print('{} face(s) detected from image {}.'.format(len(detected_faces1), source_image_file_name1))

# Detect face(s) from source image 2, returns a list[DetectedFaces]
detected_faces2 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name2, detection_model='detection_03')
# Add the returned face's face ID
source_image2_id = detected_faces2[0].face_id
print('{} face(s) detected from image {}.'.format(len(detected_faces2), source_image_file_name2))

# List for the target face IDs (uuids)
detected_faces_ids = []
# Detect faces from target image url list, returns a list[DetectedFaces]
for image_file_name in target_image_file_names:
    # We use detection model 3 to get better performance.
    detected_faces = face_client.face.detect_with_url(IMAGE_BASE_URL + image_file_name, detection_model='detection_03')
    # Add the returned face's face ID
    detected_faces_ids.append(detected_faces[0].face_id)
    print('{} face(s) detected from image {}.'.format(len(detected_faces), image_file_name))

# Verification example for faces of the same person. The higher the confidence, the more identical the faces in the images are.
# Since target faces are the same person, in this example, we can use the 1st ID in the detected_faces_ids list to compare.
verify_result_same = face_client.face.verify_face_to_face(source_image1_id, detected_faces_ids[0])
print('Faces from {} & {} are of the same person, with confidence: {}'
    .format(source_image_file_name1, target_image_file_names[0], verify_result_same.confidence)
    if verify_result_same.is_identical
    else 'Faces from {} & {} are of a different person, with confidence: {}'
        .format(source_image_file_name1, target_image_file_names[0], verify_result_same.confidence))


text:
Q: How to change the "Account already exists" error in Woocommerce on checkout, into a login box? Woocommerce checkout throws an error "An account is already registered with your email address", when you did not log in before checkout.
This is so clumsy. What I want in this case is to immediately show a popup with a login box, with the email address already populated.
It looks a little like this question: Woocommerce: Override login required for existing email. Add order to user account
But it is different.
I can't find anything that comes close.

A: I have looked for a solution as well.  The closest I have found is the plugin linked below.
What I like is that when an email is added it will recognize if they are a past customer and automatically reveals a password input box underneath the email box.  https://www.checkoutwc.com
This article describes more of what I mean under Login Lookup heading:  https://oceanwp.org/blog/optimizing-your-woocommerce-checkout-page-with-checkout-for-woocommerce/
I have been testing it and so far I am happy with it.  I signed up for the monthly subscription and will see if it helps increase sales.  We get a 7-day free trial to play with it.
I also agree that Woo's solution is a little clumsy.  :)
Best of luck! :)


text:
Q: UIActivityIndicatorView doesn't appear anymore during web service call Yesterday I added a UIActivityIndicatorView to my iOS application and everything was fine, now I'm trying to run the same application but the UIActivityIndicatorView is not showing anymore and the agenda view (which calls the web service) takes very long time (more than yesterday) to appear and often it does not appear at all. How can I fix this problem, please? Here is my code:
- (IBAction)agenda:(id)sender {

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake(160, 240);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];
    // how we stop refresh from freezing the main UI thread
    dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
    dispatch_async(downloadQueue, ^{

        // do our long running process here
        // [NSThread sleepForTimeInterval:10];
        AgendaViewController *agenda = [[ AgendaViewController alloc] initWithNibName:nil bundle:nil];

        // do any UI stuff on the main UI thread
        dispatch_async(dispatch_get_main_queue(), ^{

            [spinner stopAnimating];
            [self.navigationController pushViewController:agenda animated:YES];
        });

    });
    dispatch_release(downloadQueue);

}

A: Your code looks strange to me.
If AgendaViewController is a UIViewController then it should be touched on the main thread.
Hence I would separe code that you uses for retrieve data from your service to the code related to UIViewController.
I would modify the code as follows. This is a possible solution.
// spinner could become a strong property int the presenter controller
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.spinner.center = CGPointMake(160, 240);
self.spinner.hidesWhenStopped = YES;
[self.view addSubview:self.spinner];
[self.spinner startAnimating];

__weak typeof(self) weakSelf = self;

// moved the dispatch_queue into an instance variable or property but do not forget to release
dispatch_async(downloadQueue, ^{

    // call the service here to retrieve serverData

    // do any UI stuff on the main UI thread
    dispatch_async(dispatch_get_main_queue(), ^{

        typeof(self) strongSelf = weakSelf;
        if(strongSelf) {
            AgendaViewController *agenda = [[ AgendaViewController alloc] initWithNibName:nil bundle:nil];
            agenda.serverData = serverData;
            [strongSelf.navigationController pushViewController:agenda animated:YES];
            [strongSelf.spinner stopAnimating];
        }
    });

});

A: The problem has to be related to the way you are instantiating your agenda VC. If you are using xib files, then you need to pass the name of the xib to your initWithNibName. Calling initWithNibName: with nil arguments is the same as just calling init. It will create an object directly from the class definition but it will not have anything that you customly created on the xib file.
I believe that when you uncomment the sleepForTimeInterval: line "you think" it works because it has enough time to show the spinner before pushing a blank agenda VC.
Note: The only way the initWithNibName: works with nil arguments (which I still think you should just call  init instead), is when the xib file is named after your VC. More info here.
Update
Based on the commenst to this answer, your long running process is not inside the async code but in the viewDidLoad: method inside your AgendaViewController. Therefore, one solution would be:

*

*Remove the async code completely from the action and replace it by just the init/push logic of the AgendaViewController.

*Add/start the UIActivityIndicatorView inside your AgendaViewController's viewDidLoad:.

*Make your call to the mySQL DB (the actual "long running process").

*Stop the spinner/activityIndicator when you receive the data.

I don't know how you are implementing your mySQL call (web service/api) but it should provide either a block or a protocol method that gets called when it is done. That is where you need to add your logic to stop the spinner.


text:
Q: Zero Padding a Date with JavaScript I want to format a date like this:
May 02 2013
but at the moment, my formatting looks like this:
May 2 2013
How can I zero pad this type of date so that the day in the date is something like 02 instead of just 2?

Here is the code I am using:
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
alert( m_names[curr_month] + " " +curr_date + " " + curr_year);

jsFiddle code here

A: This is what you could to. Just see if the date is bigger than 9. If so use it, if not add a leading zero
var curr_date = d.getDate();
curr_date = curr_date > 9 ? curr_date : "0" + curr_date;

A: You can implement this logic like:
var d = new Date();
var curr_date = ("0" + d.getDate()).slice(-2);
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
console.log( m_names[curr_month] + " " +curr_date + " " + curr_year);

FIDDLE

UPDATES - ( October 1st, 2017 )
EcmaScript 2017 or ES8 has introduced two new String prototype methods:
padStart() and padEnd(). We can add some extra spaces or dashes (or any other character), before or after a string. We can utilise it here like:
var curr_date = d.getDate().toString().padStart(2,0);

( This syntax could have been shorter if we didn't need to convert d.getDate() to string, as padStart only works on string )
Demo:

var m_names = new Array("January", "February", "March",
  "April", "May", "June", "July", "August", "September",
  "October", "November", "December");

var d = new Date('10/1/2017');
var curr_date = d.getDate().toString().padStart(2, 0);
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var formatted_date = m_names[curr_month] + " " + curr_date + " " + curr_year;

console.log(formatted_date);

A: Solution
Verify if curr_date is lower than 9. If yes, add "0" + curr_date.
So, you do this inline like bellow:
curr_date = (curr_date <= 9 ? "0" : "") + curr_date

Or, directly in alert:
alert( m_names[curr_month] + " " +
       (curr_date <= 9 ? "0" : "") + curr_date +
       " " + curr_year);

Explanation
As you can see, I used ?: operator.

In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.

How does it work?
It's simple! Look:
condition ? value_if_true : value_if_false`

or
variable1 === variable2 ? value_if_true : value_if_false

See updated FIDDLE.

A: In the current dev version of Chrome (v28.0.1496.0), there is a toPaddedString(n) function on each Number object.
Number(16).toPaddedString(4)
"0016"

That's a pretty narrow browser to target, though, so I doubt it will do you much good.  It might be a part of the production version of Chrome too, but I don't have that version in front of me at the moment.  That function isn't part of EcmaScript 5.1, so it's best not to rely on it.  However, it isn't [native code], so...
Number(1).toPaddedString
function g(k,j){var i=this.toString(j||10);return"0".times(k-i.length)+i}

So, to use this feature in any browser, include this line of code:
Number.prototype.toPaddedString = function g(k,j){var i=this.toString(j||10);return"0".times(k-i.length)+i};

Then your month can be padded, like so:
var curr_month = d.getMonth().toPaddedString(2);

A: $("#cuentapendiente").focusout(function(){
    if($(this).val()!=""){
        $(this).val(zeroFill($(this).get(0).value,6))
    }
}

A: This solution in coffeescript (wrapped into eco file) worked for me
<% zero_pad = (x) -> if x < 10 then '0'+x else ''+x %>
<% d = new Date() %>
<% m = d.getFullYear() %>
<% m += "-"+zero_pad (d.getMonth()+1) %>
<% m += "-"+zero_pad d.getDate() %>
<input type="date" name="date" width="20" value="<%- m %>">