text:
Q: How to change label text with click event I have a label in called "lblnotify" in site.Master(asp.net).
 *<div class = "notification">
         <asp:Label ID="lblnotify" runat="server" text ="0 "></asp:Label>
          </div>*

And in the code behind file, i have a method that is supposed to replace the text of "lblnotify" with another.
*public void notificationManager()
    {

       try
       {
            string i = lblnotify.Text;
            i = i + "new";
            lblnotify.Text = i ;

            Label1.Text = (i);

       }
       catch (Exception er)
        {
            Response.Write("Exception Occured:   " + er);
        }
    }*

notificationManager is triggered in a submit button in another class
*protected void btnSubmit_Click(object sender, EventArgs e)
    {
            appSite call = new appSite();
            call.notificationManager();

    }*

but this gives me the error Object reference not set to an instance of an object at
 *string i = lblnotify.Text;*

in the try block when i comment  try-catch and the same error  at
 *Response.Write("Exception Occured:   " + er);*

in the catch block when i do not comment try-catch. have tried all i can but still get the error. Your help will be very much appreciated.

A: I'm not sure what are you going to do!, but controls are initialized in init page life cycle ,
and only thing you can do is to init your label control in constructor of you page class :
public appSite()
{
  lblnotify = new Label();
}


text:
Q: Dimension of Prym variety of cover I am reading the article by Lawrence and Venkatesh on diophantine problems and $p-$adic period mappings. At page $35$ they say that the dimension of the Prym variety of an (unramified) cover of curves $C_1' \to C_2$ of degree $q$ is
$$(2g-1) \cdot \frac{q-1}{2},$$
where $g$ is the genus of $C_2$. The Prym variety is defined as
$$\text{coker}(\text{Pic}^0(C_2) \to \text{Pic}^0(C_1')).$$
Riemann-Hurwitz tells us that the genus of $C_1'$ is
$$g' = q(g-1)+1.$$
Since the cover is surjective, I expected the map of Jacobians to be injective (is this true?). If that is the case, the dimension of the cokernel should be just the difference of the dimensions of the Jacobians, which are just the genera of the curves:
$$ g'-g=(q-1)(g-1).$$
This is off by $\frac{q-1}{2}$ with respect to the correct dimension. What am I doing wrong?

A: It's rather a comment that an answer, which requires me more reputation than I own. See the discussion about the fundamental group above Theorem 5.4, we see that a loop around $y_0$ is in the commutator subgroup, so is its image in $Aff(q)$. But $[Aff(q),Aff(q)]=F_q$. See the three possibilities above Lemma 8.2 and we are in the second case. Now read the second paragraph of Section 8.2.2. The monodromy around $y$ is a $q$-cycle acting on a fiber $Z_{y'}$ for $y'\in Y-y$ (the base point of a loop around $y$), so the ramification locus of the brached cover $Z\to Y$ is a singleton. Now apply Riemann-Hurwitz formula to get the genus of $Z$, $gq-\frac{q-1}{2}$ and use your idea to compute the dimension of the cokernel, i.e. the Prym variety. (Told by Mme.Cadoret)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Specify x-axis labels in D3 I have a stackedAreaChart in d3.js
X-axis labels are 9 dates which I have formatted using tickFormat method. However, I want chart to take each date. Currently it takes every 2nd date.
var dates = ["Jun 07","Jun 08","Jun 09","Jun 10","Jun 11","Jun 12","Jun 13"];
                chart.xAxis.ticks(9);
                chart.xAxis
                    .tickFormat(function(d,e,f) {
                        if(d===1||d==7){
                            return ''
                        }
                        return dates[d-1];
                    });

How can I do that?
Thanks!


text:
Q: Stop all symbols being changed to mathbb after specifying \mathbb When using this format, I encountered very interesting phenomena, where \mathbb mode does not stop even after putting "}".
By compiling the following,
\documentstyle[amsfonts]{jcss}
\begin{document}
$\mathbb{R}D$ % Please note that putting "}" before "D"
\end{document}

I got

although the below should be rendered:

Do you know why? Is it possible to fix this?
Maybe the above TeX document will raise an error. If so, please use this TeX file and add $\mathbb{R}D$ to the TeX file.

A: LaTeX2e has many improvements, for example: font selection and stuff. Here, with ancient LaTeX 2.09, \mathbb is rather a font switch than a command with argument. A group is needed to limit its scope:
\documentstyle[amsfonts]{article}
\begin{document}
$\begingroup\mathbb{R}\endgroup D$
${\mathbb{R}}D$
\end{document}

\begingroup and \endgroup is longer for writing, but free of side effects. Curly braces and \bgroup/\egroup also act as math subformula, which can change the horizontal spacing around symbols. But here, the letter is a \mathord anyway, thus curly braces are fine here, too.
Consider switching to LaTeX2e, if the document class/style jcss allows this.

A: From the header of the file amsfonts.sty:
\NeedsTeXFormat{LaTeX2e}[1994/12/01]

This package is not intended to be backward compatible with LaTeX2e formats prior to 1994/12/01. By implication, it is not meant to be compatible with LaTeX2.09, the format that became deprecated in 1994 but which is loaded (in emulation mode) by the first line of your code, viz.,
\documentstyle[...]{jcss}


text:
Q: How to add Canon LBP2900b printer to a Raspberry Pi 4 The printer Canon LBP2900b is not listed in the Cups of the Raspberry pi..
I have searched a lot on that but unfortunately haven't found any such working method.
Please help

A: I had an issue getting Canon LBP6020 working with cups on pi. Found the *nix driver but no version of armhf so I did not manage to get it to work. Sharing this in case if you are lucky with your model:
Get the driver from https://www.canon.ie/support/consumer_products/products/printers/laser/i-sensys_lbp2900b.html?type=drivers&language=&os=windows%2010%20(64-bit)
Untar and find the ppd file in Src\cndrvcups-capt-2.71-1\cndrvcups-capt-2.71\ppd
Add it via cups admin when adding the printer
If you are getting the filter related error rastertosfp, then oof! My understanding of this error is you have to install it proper (using the proper ./install.sh script)


text:
Q: Problem with ExportAsFixedFormat , Excel proccess not closing We have a code that exports some data to excel, then uses that excel file to generate a pdf file using the exportAsFixedFormat function. Now it is failing with system exception regularly.
the below is the code
oBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,
                      paramExportFilePath, paramExportQuality,
                      paramIncludeDocProps, paramIgnorePrintAreas,
                      paramFromPage, paramToPage, paramOpenAfterPublish)

        ' Close book
        oBook.Close()
        '
        'Exit Excel
        oExcel.Quit()

below is the exception error we are getting

System.Exception: System.Exception:
System.Runtime.InteropServices.COMException (0x800A03EC): Exception
from HRESULT: 0x800A03EC     at
Microsoft.Office.Interop.Excel._Workbook.ExportAsFixedFormat(XlFixedFormatType
Type, Object Filename, Object Quality, Object IncludeDocProperties,
Object IgnorePrintAreas, Object From, Object To, Object
OpenAfterPublish, Object FixedFormatExtClassPtr)


text:
Q: cannot get url query params to appear? I am trying to make a link set a query string param in the url...
In my view, I am doing:
<a (click)="selectPage(123)">123</a>

and in my component:
selectPage(page: number) {
  this.router.navigate([], { relativeTo: this.route, queryParams: { 'page': page}, queryParamsHandling: 'merge', skipLocationChange: true});
}

I click the link, the selectPage function fires, but the url in the browser does not have a page parameter show up..

A: You have to omit skipLocationChange property, then it would work.


text:
Q: Returning cross join instead of inner join I have two result sets from database into object and when I inner join them, it returns cross join. Following is my code:
var nw = new NorthwindEntities();
var employee1 = (from emp in nw.Employees
                 join ord in nw.Orders on emp.EmployeeID equals ord.EmployeeID
                 where emp.EmployeeID == 5
                 select new
                 {
                     empID = emp.EmployeeID,
                     empName = emp.FirstName,
                     ordDate = ord.OrderDate
                 }).ToList();

var employee2 = (from emp in nw.Employees
                 join ord in nw.Orders on emp.EmployeeID equals ord.EmployeeID
                 where emp.EmployeeID == 5
                 select new
                 {
                     empID = emp.EmployeeID,
                     empName = emp.FirstName,
                     shpAddress = ord.ShipAddress
                 }).ToList();

var employee = from e1 in employee1
               join e2 in employee2 on new { e1.empID } equals new { e2.empID }
               select new
               {
                   empID = e1.empID,
                   empName = e1.empName,
                   ordDate = e1.ordDate,
                   orAdd = e2.shpAddress
               };

gvAll.DataSource = employee.ToList();

Now when I join employee1 and employee2 into employee, I get a cross join of those data set. Any help would be highly appreciated.
My main target behind this is to have data returned from database stored in some place temporarily so I can work it with later with other data retrieved from database.
employee1 and employee2 uses same query for employee id (5) except employee1 has empID, empName and OrderDate where as employee2 has empID, empName and shipAddress. Now I want empID, empName, OrderDate and ShipAddress out of employee1 and employee2 in employee. empID is common in both but I am getting a cross join. Thank you.

A: In employee1 and employee2 you will aslo need the OrderId column to and then join them by both cos you need to get an equal unique key on both tables.
and from what you wrote I think that empID is not unique in either tables cos you can have more orders for same empID
So first you need a unique key on both employee1 and employee2 then you can join on that.

A: The result returned from function  is logically correct, it is not a cross join. empID has some duplicate row in some table so, data is looking like a cross join.
Use distinct then it will return your desired output.


text:
Q: Firewall: allow all traffic from sources authenticated via. an open ssh connection I'm looking for a way to avoid the editing of the firewall rules all the time on test and dev servers. I don't want to open up all ports. So I thought maybe there is a way to allow all traffic from sources with an established ssh connection automatically. (Years back someone told me they did it like this for dev/test servers -> no root and firewall editing required and applications don't need to be secured)
I know I could use an ssh tunnel, but the issue with this is with dynamic port applications, multi port applications and the sheer overhead of work.
IpTables and other firewalls probably don't know if an ssh connection was authenticated but is there maybe a work around or alternative? (e.g. established for more than 5 seconds -> pub/private key auto disconnect on fail)

*

*INPUT DROP

*ALLOW LOOPBACK

*ALLOW SSH

*ALLOW LOCAL NETWORK

*ALLOW all traffic from sources with an established ssh connection.

All the rules are straight forward besides the last one. Unfortunately I don't have contact information of the person I once talked to about it and i couldn't dig anything related/similar up within a good hour of research.
Is something like this even possible? I appreciate any input :)

A: You could probably bend 'fail2ban' to your desires, using a custom filter to detect successful logins, and a custom action to add iptables rules for the detected source IP rather than banning them.
It's a bit odd so you'd want some really good comments in your configuration for the next person coming along to be able to understand what on earth you were doing :)


text:
Q: How to get all text between just two specified tags using BeautifulSoup? html = """
...
<tt class="descname">all</tt>
<big>(</big>
iterable
<big>)</big>
¶
...
"""

I want to get all text between starting tag big upto before the first occurrence of a tag. This means if I take this example, then i must get (iterable) as a string.

A: An iterative approach.
from BeautifulSoup import BeautifulSoup as bs
from itertools import takewhile, chain

def get_text(html, from_tag, until_tag):
    soup = bs(html)
    for big in soup(from_tag):
        until = big.findNext(until_tag)
        strings = (node for node in big.nextSiblingGenerator() if getattr(node, 'text', '').strip())
        selected = takewhile(lambda node: node != until, strings)
        try:
            yield ''.join(getattr(node, 'text', '') for node in chain([big, next(selected)], selected))
        except StopIteration as e:
            pass

for text in get_text(html, 'big', 'a'):
    print text

A: I would avoid nextSibling, as from your question, you want to include everything up until the next , regardless of whether that is in a sibling, parent or child element.
Therefore I think the best approach is to find the node that is the next  element and loop recursively until then, adding each string as encountered. You may need to tidy up the below if your HTML is vastly different from the sample, but something like this should work:
from bs4 import BeautifulSoup
#by taking the `html` variable from the question.
html = BeautifulSoup(html)
firstBigTag = html.find_all('big')[0]
nextATag = firstBigTag.find_next('a')
def loopUntilA(text, firstElement):
    text += firstElement.string
    if (firstElement.next.next == nextATag):
        return text
    else:
        #Using double next to skip the string nodes themselves
        return loopUntilA(text, firstElement.next.next)
targetString = loopUntilA('', firstBigTag)
print targetString

A: you can do like this :
from BeautifulSoup import BeautifulSoup
html = """
<tt class="descname">all</tt>
<big>(</big>
iterable
<big>)</big>

"""
soup = BeautifulSoup(html)
print soup.find('big').nextSibling.next.text

For details check dom traversing with BeautifulSoup from here

A: >>> from BeautifulSoup import BeautifulSoup as bs
>>> parsed = bs(html)
>>> txt = []
>>> for i in parsed.findAll('big'):
...     txt.append(i.text)
...     if i.nextSibling.name != u'a':
...         txt.append(i.nextSibling.text)
...
>>> ''.join(txt)
u'(iterable)'


text:
Q: Python 2.5 to Python 2.2 converter I am working on a PyS60 application for S60 2nd Edition devices. I have coded my application logic in Python 2.5.
Is there any tool that automates th conversion from Python 2.5 to Python 2.2 or do I need to do in manually?

A: The latest Python for S60, 1.9.0, actually includes Python 2.5.1. So maybe you don't need to convert.

A: I don't know of any tool that would go from 2.5 to 2.2 automatically; but there was one a while ago that did 2.3 to 2.2 by RADLogic.
Depending on how many recent features your code uses, it may be trivial to convert it manually.
I had to backport some code a while back and all it actually took was to define True and False if they weren't already defined, write up some simple replacements for sum(), enumerate(), etc, and grab old versions of modules like datetime and logging that weren't yet in the 2.2 standard library.


text:
Q: iOS Gamecenter Programmatic Matchmaking I'm trying to implement a real-time multiplayer game with a custom UI (no GKMatchMakerViewController). I'm using startBrowsingForNearbyPlayersWithReachableHandler:
^(NSString *playerID, BOOL reachable) to find a local player, and then initiating a match request with the GKMatchmaker singleton (which I have already initiated).
Here's where I'm having trouble. When I send a request, the completion handler fires almost immediately, without an error, and the match it returns has an expected player count of zero. Meanwhile, the other player definitely has not responded to the request.
Relevant code:
- (void) findMatch
{
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = NUM_PLAYERS_PER_MATCH; //2
request.maxPlayers = NUM_PLAYERS_PER_MATCH; //2
if (nil != self.playersToInvite)
{
    // we always successfully get in this if-statement
    request.playersToInvite = self.playersToInvite;
    request.inviteeResponseHandler = ^(NSString *playerID, GKInviteeResponse
                                       response)
    {
        [self.delegate updateUIForPlayer: playerID accepted: (response ==
                                                              GKInviteeResponseAccepted)];
    };
}
request.inviteMessage = @"Let's Play!";

[self.matchmaker findMatchForRequest:request
    withCompletionHandler:^(GKMatch *match, NSError *error) {
        if (error) {
            // Print the error
            NSLog(@"%@", error.localizedDescription);
        }
        else if (match != nil)
        {
            self.currentMatch = match;
            self.currentMatch.delegate = self;

            // All players are connected
            if (match.expectedPlayerCount == 0)
            {
                // start match
                [self startMatch];
            }
            [self stopLookingForPlayers];
        }
    }];
}

A: Figured it out!  I needed to call - (void)matchForInvite:(GKInvite *)invite completionHandler:(void (^)(GKMatch *match, NSError *error))completionHandler in my invitation handler so that both players have the same match data.


text:
Q: Expression must have pointer to struct or union error t variable is coming up with an error from assigntime function onwards saying it must have a  pointer to a struct or union type. pointers are my weakness, if anyone could explain, not just give me the answer, what i need to do to fix this that would be most helpful! cheers.
//MY TIME C FILE
#include "my_time.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct my_time_int
{
    int hour;
    int minute;
    int second;
};

void init_my_time(my_time *t)
{

    t=(my_time)malloc(sizeof(struct init_my_time*));
}

/*
 * Alter hour, minute, and second
 * Param h new value for hour
 * Param m new value for minute
 * Param s new value for second
*/
void assignTime(my_time *t, int h, int m, int s)
{
    t->hour = h;
    t->minute = m;
    t->second = s;
}
//FOLLOWING CODE T VARIABLE HAS RED UNDERLINE ERROR SAYING EXPRESSION MUST HAVE POINTER TO STRUCT OR UNION>
char *toString(my_time t)
{
    char *r = (char *)malloc(12 * sizeof(char));

    if (t.hour >= 12) {
    if (t.hour == 12)
        sprintf(r, "%02d:%02d:%02d PM", 12, t.minute, t.second);
    else
        sprintf(r, "%02d:%02d:%02d PM", t.hour - 12, t.minute, t.second);
    }
    else {
        if (t.hour == 0)
        sprintf(r, "%02d:%02d:%02d AM", 12, t.minute, t.second);
        else
        sprintf(r, "%02d:%02d:%02d AM", t.hour, t.minute, t.second);
    }

    return r;

}

/*
 * Find printable form of time in 24 hour mode
 * Return String form of time in 24 hour mode for printing etc.
*/
char *toMilString(my_time t)
{
    char *s = (char *)malloc(9 * sizeof(char));

    sprintf(s, "%02d:%02d:%02d", t.hour, t.minute, t.second);
    return s;
}

/*
 * Find number of seconds elapsed since midnight
 * Return number of seconds elapsed since midnight as int
*/
int secsSinceMidnight(my_time t)
{
return t.second + (60 * t.minute) + (60 * 60 * t.hour);
}

Header File Here:
#include <stdbool.h>

struct my_time_int;
typedef struct my_time_int *my_time;

void init_my_time(my_time *t);
void assignTime(my_time *t, int h, int m, int s);
void addTime(my_time t, double s);
char *toString(my_time t);
char *toMilString(my_time t);
bool equals(my_time this, my_time that);
bool my_timeIncHour(my_time *t);
bool my_timeIncMinute(my_time *t);
bool my_timeIncSecond(my_time *t);

A: There are a couple of errors in your code.
Primarily the use of pointers it's not correct in respect to the desired outcome. In the header you have the line:
typedef struct my_time_int *my_time;
which effectively declares my_timebeing a pointer type to the struct my_time_int. But in your function's prototypes (and definitions too) you use a pointer to my_time as argument: my_time* t. In fact here you are using a pointer to a pointer to the struct my_time_int.
So when you try to assign to tusing the deference arrow operator -> you make a  mistake, because in fact you are assigning to a pointer to a pointer to a struct not to a plain pointer to a struct as you wish.
You should also avoid using the . operator on variables of type my_time because they are in facts pointers. You should use instead the arrow ->operator on them.
Here the proposed solution:
//MY TIME C FILE
#include "prova.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct my_time_int
{
    int hour;
    int minute;
    int second;
};

//void init_my_time(my_time *t)
my_time init_my_time()
{
    //t=(my_time)malloc(sizeof(struct init_my_time*));
    return (my_time)malloc(sizeof(struct my_time_int));
}

/*
 * Alter hour, minute, and second
 * Param h new value for hour
 * Param m new value for minute
 * Param s new value for second
*/
//void assignTime(my_time *t, int h, int m, int s)
void assignTime(my_time t, int h, int m, int s)
{
    t->hour = h;
    t->minute = m;
    t->second = s;
}

//FOLLOWING CODE T VARIABLE HAS RED UNDERLINE ERROR SAYING EXPRESSION MUST             HAVE POINTER TO STRUCT OR UNION>
char *toString(my_time t)
{
char *r = (char *)malloc(12 * sizeof(char));

//if (t.hour >= 12) {
if(t->hour >= 12){
//if (t.hour == 12)
if(t->hour == 12)
    //sprintf(r, "%02d:%02d:%02d PM", 12, t.minute, t.second);
    sprintf(r, "%02d:%02d:%02d PM", 12, t->minute, t->second);
else
    //sprintf(r, "%02d:%02d:%02d PM", t.hour - 12, t.minute, t.second);
    sprintf(r, "%02d:%02d:%02d PM", t->hour - 12, t->minute, t->second);
}
else {
    //if (t.hour == 0)
    if (t->hour == 0)
    //sprintf(r, "%02d:%02d:%02d AM", 12, t.minute, t.second);
    sprintf(r, "%02d:%02d:%02d AM", 12, t->minute, t->second);
    else
    //sprintf(r, "%02d:%02d:%02d AM", t.hour, t.minute, t.second);
    sprintf(r, "%02d:%02d:%02d AM", t->hour, t->minute, t->second);
}

return r;

}

/*
 * Find printable form of time in 24 hour mode
 * Return String form of time in 24 hour mode for printing etc.
*/
char *toMilString(my_time t)
{
    char *s = (char *)malloc(9 * sizeof(char));

    //sprintf(s, "%02d:%02d:%02d", t.hour, t.minute, t.second);
    sprintf(s, "%02d:%02d:%02d", t->hour, t->minute, t->second);
    return s;
}

/*
 * Find number of seconds elapsed since midnight
 * Return number of seconds elapsed since midnight as int
*/
int secsSinceMidnight(my_time t)
{
//return t.second + (60 * t.minute) + (60 * 60 * t.hour);
return t->second + (60 * t->minute) + (60 * 60 * t->hour);
}

And header too:
#include <stdbool.h>

struct my_time_int;
typedef struct my_time_int *my_time;

//void init_my_time(my_time *t);
my_time init_my_time();
//void assignTime(my_time *t, int h, int m, int s);
void assignTime(my_time t, int h, int m, int s);

//and son on removing the unnecessary pointer types
void addTime(my_time t, double s);
char *toString(my_time t);
char *toMilString(my_time t);
bool equals(my_time this, my_time that);
bool my_timeIncHour(my_time t);
bool my_timeIncMinute(my_time t);
bool my_timeIncSecond(my_time t);

As you can se in the commented code there are the previous erroneous declarations and definitions.
EDIT
As pointed in the comments, the init_my_time, as defined, leaks memory because allocates a pointer that it doesn't return to the caller. The right thing to do here is to allocate the memory and return the pointer to that memory to the caller. This requires changing the declaration and definition of init_my_time as already done above in the code.

A: Try malloc(sizeof(struct my_time_int)); instead of malloc(sizeof(struct init_my_time*)); You are allocating memory for a pointer to init_my_time instead of for my_time.
t is a pointer to a pointer to a my_time_int that means you need to allocate enough memory to store a my_time_int object. The pointer itself is stored on the stack so you don't need to allocate memory for it.
void init_my_time(my_time *t)
{
    *t=(my_time)malloc(sizeof(struct my_time_int));
}


text:
Q: Determine the density function of the maximum of a random sample Determine the density function of the maximum of a random sample of size $n$ from an exponential distribution with rate parameter $\eta$
So I don't really know where to start with this, any help appreciated.

A: HINT
$$P(\max X_i\le x) = P(X_1\le x,X_2\le x,\ldots,X_n\le x).$$ For most exercises about the maximum of random variables, this is how the solution starts.


text:
Q: Supremum of a family of subobjects in an abelian category So this question follows on from an earlier one here. Suppose we are in a cocomplete abelian category. Say we have a (small) family of subobjects of some object $A$, which we will write as $\{  \mu_{i} : A_{i} \hookrightarrow A \}_{i \in I}$. Define the categorical sum as the image of the canonical morphism
$$
\phi: \bigoplus_{i \in I} A_{i} \longrightarrow A.
$$
Order the subobjects by inclusion: That is $A_{i} \leq A_{j}$ if there is a monomorphism $u: A_{i} \rightarrow A_{j}$ compatible with the inclusions $\mu_{i}$ and $\mu_{j}$). Then it is not hard to find that $\text{im}(\phi)$ is a subobject of $A$ and provides an upper bound for this family under the partial ordering. However, it seems to be assumed in the literature that this is in fact a supremum. Is anyone able to help me show this? In other words, if $B$ is some other subobject of $A$ acting as an upper bound, I need to find a morphism,
$$
\rho: \text{im} (\phi) \longrightarrow B
$$
compatible with the subobject structure. I feel like this should follow from universal properties of the image and direct sum, but I haven't been able to get it. I also tried to use epi-mono factorization properties. Is it actually true if the family isn't directed? Any help is appreciated.

A: It is true !
Assume $\iota : B\hookrightarrow A$ is a subobject and for each $i\in I$ we have an inclusion $\delta_i : A_i\hookrightarrow B$ such that the obvious diagram commutes ($\iota\circ \delta_i = \mu_i$)
Then we also get an induced morphism $\psi: \displaystyle\bigoplus_{i\in I} A_i \to B$. But of course, since the morphisms were coherent in the beginning, the uniqueness part of the definition of coproduct makes it clear that $\iota\circ \psi = \phi$. Indeed, for each $i\in I$, $\iota\circ \psi\circ m_i = \iota\circ \delta_i= \mu_i = \phi\circ m_i$, where $m_i : A_i \to \displaystyle\bigoplus_{j\in I} A_j$ is the inclusion.
$\iota \circ \psi = \phi$, with $\iota$ monic. So if we write $\psi$ in its epi-mono-factorisation, we get an epi-mono factorisation for $\phi$. These are essetially unique and so $\text{im}(\phi) \hookrightarrow A$ factors through this, in particular it factors through $B$.

A: Since $B$ is an upper bound for each $A_i$, they all factor through $B$: there are maps $\nu_i:A_i\to B$ such that the composition $A_i\to B\to A$ is the inclusion $A_i\to A$.  These maps $\nu_i$ combine to give a map $\nu:\bigoplus A_i\to B$ whose composition with $B\to A$ is $\phi$.  Thus the image of $\phi$ factors through $B$.


text:
Q: Induction proof: $\det(M) = \prod_{1 \le j \le n} (x_j - x_i)$ Following problem:

Let $\mathbb{K}$ be a Field and
$M = \begin{pmatrix}    1 & x_1 & \ldots & x_1^{n-1} \\    \vdots &
 \vdots & & \vdots \\    1 & x_n & \ldots  & x_n^{n-1} \end{pmatrix} \in
 Mat(n, \mathbb{K})$
Proove with induction that: $$\det(M) = \prod_{1 \le i < j \le n} (x_j -
 x_i)$$

Unfortunately I am totally lost here. I have confirmed $n = 1$ and for the rest I got the following:
$$\prod_{1 \le i < j \le n + 1} (x_j - x_i) = \prod_{1 \le i < j \le n} (x_j - x_i) \prod_{1 \le i < n + 1} (x_{n+1} - x_i) = \det(M_n) \prod_{1 \le i < n + 1} (x_{n+1} - x_i) $$
From there on I don't know how to continue.
Any ideas? :S Thanks!


text:
Q: Entity Framework: Include and Explicitly defined foreign keys
Possible Duplicate:
Linq-to-entities - Include() method not loading

I have something like this
public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public int CategoryId { get; set; }
    [ForeignKey("CategoryId")]
    public virtual Category Category { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
}

In context I have:
public DbSet<Product> Products { get; set; }

But when I try to use it like this:
List<Product> foo = (from p in Context.Products
                     where p.Category.Name = "something"
                     select p).ToList();

Product first = foo.First();

I get the value of Product.CategoryId set but null inside Category
Note: I've tried with 'Context.Products.Include("Category")' and doesn't work.
This works (Category is loaded into first):
List<Product> foo = (from p in Context.Products
                     where p.Category.Name = "something"
                     select p).ToList();

Product first = foo.First();

List<Category> categories = Context.Categories.ToList();

So do I have to load category everytime? Why is include not working?


text:
Q: Issue with table's td element with bootstrap HTML

    test
    tesst
    test
    test
    test
    test
    test
    test

CSS
table,td
{
  border:1px solid black;

}
td
{
  background-color:red;
}
table
{
  background-color:green;
}
*
{
  padding : 0 !important;
  margin:0 !important;
}

Here is the fiddle
As in fiddle you can see although sum of grid value for td value equals 12 but it ain't covering the entire table , there is left over spaces (green background area) at the end of the table? Why ?How to overcome this issue?
edit
As ShinDarth suggested

You should always wrap the columns (col-*) inside a row:

but I don't agree to him , I have created another fiddle now replacing table element with div, now why this difference?
Update Fiddle

A: You should always wrap the columns (col-*) inside a row:

    test
    tesst
    test
    test
    test
    test
    test
    test

https://jsfiddle.net/o30L1t70/2/

A: All you needed, to add class table into table tag instead col-xs-12. In this case other classes col-xs-12 are extra too:

      test
      tesst
      test
      test
      test
      test
      test
      test

JSfiddle-example


text:
Q: Jquery loops through php array, taps API and pushes back results to mysql I have a php array - say startups[] - containing 36000 startup names. I want to use those names to construct a URL API endpoint.
I have failed to figure out how to use Jquery to loop through this php array, and for each of those 36000 entries make an api call to retrieve the id attached to the name of the startup.
I am also wondering how I could update the id  column in mysql corresponding to the name of the startup.
Thanks for your suggestions!

A: If you have a page where you need to echo out an php array, probably the easiest way is to just json encode the array and print it where you need it like:
Using PHP 5.4+ short open/echo
  <?=json_encode($startup)?>

As noted in the comments to your question, this will trigger a large number of http requests and may not be the best approach.


text:
Q: Invertibility of Set Intersection Signed matrix I am interested in looking at the following problem in combinatorial matrix theory. Since I could not find a reference related to this types of matrices, I hope someone here could help me.
Let $n \geq 1$ and $X=\{1, \ldots, n\}$. Assume that $\mathcal{F}(X)$ is the collection of all subsets of $X$. Now let $A$ be a matrix of size $2^n \times 2^n$ defined as follows:
$A_{S_1, S_2}=(-1)^{|S_1 \cap S_2|}$,
where $S_1, S_2 \in \mathcal{F}(X)$.
Define $J_n$ as the matrix (size $n$) whose entries are $1$ everywhere.
Another related one is the matrix $B=(A+J_n)/2$, i.e., $B_{S_1, S_2}=1$ if $|S_1 \cap S_2|$ is even and $B_{S_1, S_2}=0$ if $|S_1 \cap S_2|$ is odd.
Question: My main concern is whether $A$ or $B$ is invertible.
Remark: We can define a matrix $C$ such that $C_{S_1, S_2}=|S_1 \cap S_2|$, where $S_1, S_2 \subseteq X$. This matrix $C$ is related to the incident matrix (see e.g., "Matrices and set intersections" by H. J. Ryser (1981))
Then our matrix $B$ can be regarded as the image of the matrix $J_n-C$ modulo $\mathbb{Z}_2$.

A: The key is to order the subsets of $X$ (and thus the rows and columns of the corresponding matrix) in a "nice" way for the purpose of induction. I will write $A_n$ for the matrix $A$ corresponding to a set $X$ with $|X|=n$. Then $A_1=\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}$ if we order the subsets by $\emptyset,X$. For $A_2$, we want to have $A_1$ in the top left corner, which can be achieved by ordering the subsets of $X=\{a,b\}$ by $\emptyset,\{a\},\{b\},X$. In fact, with respect to this ordering, one sees that $A_2=\begin{pmatrix} A_1 & A_1 \\ A_1 & -A_1 \end{pmatrix}$. For $A_3$, we want to have $A_2$ in the top left corner so we order the subsets of $X=\{a,b,c\}$ by $\emptyset,\{a\},\{b\},\{a,b\},\{c\},\{a,c\},\{b,c\},X$. With respect to this ordering, one sees that $A_3=\begin{pmatrix} A_2 & A_2 \\ A_2 & -A_2 \end{pmatrix}$. Continuing in this way, one shows by induction that $A_n$ is invertible for all $n\geq 1$.
Now writing $B_n$ for the matrix $B$ when $|X|=n$, $B_n$ is invertible if and only if $A_n+J_n$ is invertible. For this, we can use the matrix determinant lemma: If we let $u=v=(1,1,\ldots,1)^T$, then $A_n+J_n=A_n+uv^T$ so $\det(A_n+J_n)=\det(A_n+uv^T)=(1+v^T A_n^{-1}u)\det(A_n)=(1+v^Te_1)\det(A_n)=2\det(A_n)$ where $e_1=(1,0,0,\ldots,0)^T$. Hence $A_n+J_n$ is invertible, and so $B_n$ is invertible for all $n\geq 1$.


text:
Q: How to include a list of variables in a Spinbox in Python Tkinter I'm trying to create a Spin-box using Tkinter in Python that contains days of the month (strings), yet only know how to include numbers in a range. e.g.; from_ = 1900, to = 2016.
How can I include a list of strings in the spin box? do I need to create an actual list?
Here is the specific code:
w = StringVar()
Spinbox(root, from_ = 1900, to = 2017, textvariable = w, width = 5).place(x = 315, y = 60)

A: Just pass a list of strings to the values option of the spinbox:
from tkinter import Tk, Spinbox
root = Tk()
months = ["January", "February", "March"]
spinbox = Spinbox(root, values=months)
spinbox.pack()
root.mainloop()


text:
Q: loading secondary resources like images and such I want to show image and its text initially as we open the page for my Image Slider.
This is my demo: http://codebins.com/bin/4ldqp9c/15
here i am showing as all the DOM elements is loaded, but the need is to show the first image and its text initially for my slider as we open the page.
So I am not understanding how to load my initial image for my slider, so that its functionality starts after all DOM elements load.

A: I believe the term is "bootstrapping". You want the first image to load in as the DOM is loading, and before your script sets up the image slider.
One way to achieve this is to actually put the image in as part of the DOM. So, instead of an empty src in your image tag, put an actual url. Same for title and description.
I assume you're going to be doing an ajax request for the XML you're building in your example. If that's the case, then you probably have no way of knowing what the first image is, which means you'll still need a script to load data.
The performance gains from having two scripts will probably be negligible, but if you take that approach, make sure you load the smaller script in the head section of your html, and the longer one at the end of your body.


text:
Q: Segmentation fault when trying to traverse a double linked list This is the piece of code I am using:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int wordlen = 4;
typedef struct Node
{
    char* word;
    struct Node* next;
    struct Node* prev;
}node;
 node* head;

 node * getWord(char* x)
 {
    node* newNode = malloc(sizeof(node));
    newNode->word = x;
    newNode->next = NULL;
    newNode->prev = NULL;
    return newNode;
 }

 void insertion(char* x)
 {
    node* temp = head;
    node* newNode = getWord(x);
    if (head == NULL)
    {
        head = newNode;
        return;
    }
    while(temp->next != NULL)
    temp = temp->next;
    temp->next = newNode;
    newNode->prev = temp;
 }

 void print()
 {
    node* temp = head;
    while (temp != NULL)
    {
        printf("%s", temp->word);
        temp = temp->next;
        printf(" ");
    }
    printf("\n");
 }

 void sort()
 {
    char* a = malloc((wordlen + 1)*sizeof(char));
    char* b = malloc((wordlen + 1)*sizeof(char));
    node* temp = head;
    while (temp != NULL)
    {
        a = temp->word;
        temp = temp->next;
        b = temp->word;
        if (a[0] < b[0])
        {
            //temp->word = a;
            //temp = temp->prev;
            //temp->word = b;
        }
    }
 }

int main(int argc, char *argv[])
{
    insertion("asdk");
    insertion("mapa");
    insertion("klop");
    sort();
    print();
    return 0;
}

The segmentation fault appears in the sort() function and especially in the variable b. What I have in mind is when the pointer reaches NULL and so the end of the list when I am trying to go back (using the prev pointer) I get the error since I don't have access to that particular block of memory. How exactly could I access once again the last node of my linked list once I have fully traversed through it?

A: You have a big memory leak in sort:
char* a = malloc((wordlen + 1)*sizeof(char));
char* b = malloc((wordlen + 1)*sizeof(char));
...
    a = temp->word;        // This leaks a
    ...
    b = temp->word;        // This leaks b

You can't assign strings in C, you need to copy them with strcpy.
You also should test each malloc return for NULL. And please don't multiply by sizeof(char), it is 1 by definition in the C Standard. If you want to multiply, use sizeof(*a) which is always correct, no matter what type a points to.

A: The problem is your loop where you don't check whether temp->next is NULL before dereferencing it. When it the loop gets to the end of the list, you temp->next is NULL. Change your loop conditions in sort and insertion to:
  void sort()
  {
    char* a;
    char* b;
    node* temp = head;
    while (temp && temp->next != NULL)
    {
        a = temp->word;
        temp = temp->next;
        b = temp->word;
        if (a[0] < b[0])
        {
            temp->word = a;
            temp = temp->prev;
            temp->word = b;
        }
    }
  }

 void insertion(char* x)
 {
    node* temp = head;
    node* newNode = getWord(x);
    if (head == NULL)
    {
        head = newNode;
        return;
    }
    while(temp && temp->next != NULL)
    temp = temp->next;
    temp->next = newNode;
    newNode->prev = temp;
 }

Besides, you don't need to allocate memory for a and b. You just use temporary pointer variables to swap.

A: Well, there are many problems with your program (specially in sort function).
First, consider you are at last element in below while loop.
while (temp != NULL)
    {
        a = temp->word;
        temp = temp->next;
        b = temp->word;
        if (a[0] < b[0])
        {
            //temp->word = a;
            //temp = temp->prev;
            //temp->word = b;
        }
    }
 }

This line temp = temp->next; will lead temp to NULL when loop is executing for the last node. Deferencing temp after that is itself problemactic.
Solution: check temp->next !=NULl instead of temp==NULL.
Second, you are allocating memory but not freeing it.
char* a = malloc((wordlen + 1)*sizeof(char));
char* b = malloc((wordlen + 1)*sizeof(char));

Solution: Free this memory.
Third, the way you copy strings is not supported in C.
 a = temp->word;
 b = temp->word;

Solution: Use strcpy()


text:
Q: How to partition the local hard disk in Windows 8 I'm using Windows 8 and I want to partition my hard disk.
My local disk is of 440 GB and in disk management I partitioned the hard disk into local disk E and F from only one local disk C. But my local hard disk C is 221 GB and it is not further partitioned.
Also, it s saying that the available free space for partitioning is only of 110 MB.
So, I want to know how I partition the hard disk and have hard disk C with around 100 GB.

A: I won't be 100% sure until you post a screen shot of your disk management- but it sounds like you are running into an issue that I came across in the past where you can no longer partition the HDD even though you have plenty of available space.
If you are having the same issue I was then your disk management will show your C drive on the right side of the drive.  What I learned in this situation is that you cannot extend a drive to the left- only to the right.  To fix this I ended up booting into my ubuntu flash drive and using GParted to move my entire C drive to the left side of the disk (this was done with GParted because you cannot move the C drive on the disk while windows is booted).  But beware this will break your MBR and you will have to use your windows disc to boot into command prompt and repair the MBR.  Here are the commands that will fix your MBR (worked for me in Windows 7 and 8):
/FixBoot. Writes a boot sector onto the system partition to start Windows
/ScanOs. Scans all disks for Windows installations and displays them to you.
/RebuildBcd. Scans all disks for Windows installations and prompts you to pick the ones you want to add to the BCD.

A: there are several software available for the partition. We can use EASEUS partition master.
for download link click here

A: If you want to further partition an exisiting partition, the OS automatically calculates the amount of space that can be utilized to create the partition.
From your message, I assume that you do not have much free space left on your C drive, hence only option is to take a data backup and re-install windows and during installation create the required partition size.


text:
Q: Itemize clone for headers in table I'd like to define a command called \headers that takes an undefined number of parameters.
e.g. \headers{Category One}{Category Two}{Category Three}
And it would output the following:
\textbf{\textit{Category One}} &
\textbf{\textit{Category Two}} &
\textbf{\textit{Category Three}} \\
\hline
\hline

The idea is to use this inside a custom tabularx package I've used, so I could just go:
\begin{tabularx}{\hsize}{XXX}
    \headers{Category One}{Category Two}{Category Three}
\end{tabularx}

How could I achieve something like this? I saw a lot about xparse and \clist_map_inline:nn but none of that would allow the & character to join any parameter after the first.
Any help would be deeply appreciated.

A: You can get output like:

with the code:
\documentclass{article}
\usepackage{tabularx}
\usepackage{etoolbox}
\usepackage{booktabs}
  \makeatletter
\newcommand\headers[1]{%
  \def\sep{}%
  \def\realheader{}%
  \renewcommand*\do[1]{\protected@xappto\realheader{\sep\textbf{\textit{##1}}}\xdef\sep{&}}
  \docsvlist{#1}%
  \\\toprule\realheader\\\midrule
}
\makeatother

\begin{document}

\begin{tabularx}{\hsize}{XXX}
  \headers{Category one, Category two, Category three}
  stuff & stuff & stuff\\
  \bottomrule
\end{tabularx}

\end{document}

Rather than using \hline I have succumbed to my biases and used the booktabs package as I think this gives much better output.
Apart from using booktabs the main change from the OP is that I have changed the syntax to use a command separated list for the header, which is then turned into the table header using \docsvlist from the etoolbox package. Unfortunately, this seems to require a little bit of expansion trickery using \protected@xappto to construct the header piece by piece.
EDIT
Here is a fancier version that defines a new table environment mytable that takes one argument that specifies the column headers as a comma separated list, and where body of the environment contains the (tabularx) environment. Using this the code:
\begin{mytable}{Category one, Category two, Category three}
  stuff & stuff & stuff\\
\end{mytable}

produces

which is essentially the same as above except that I have used the OPs formatting. The main advantage of this approach is that you do not have the specify the column headers so that, for example,
\begin{mytable}{Category one, Category two, Category three, Column four}
  stuff & stuff & stuff & stuff\\
\end{mytable}

works as expected.
Here is the modified code (see the comments for an explanation of what the code is doing):
\documentclass{article}
\usepackage{tabularx}
\usepackage{etoolbox}
\makeatletter
\newcounter{mytablecolumns}% to automate the number of columns
\newenvironment{mytable}[1]{%
  \def\sep{}% will be the table column separator
  \setcounter{mytablecolumns}{0}% reset column counter
  \def\realheader{}% will become the table header
  \renewcommand*\do[1]{% construct each entry in the header
    \protected@xappto\realheader{\sep\textbf{\textit{##1}}}% add header
    \stepcounter{mytablecolumns}% increment column counter
    \xdef\sep{&}% set up next column separator
  }
  \docsvlist{#1}% create the table header
  \xdef\sep{*{\arabic{mytablecolumns}}X}% create the table specifications
  \expandafter\tabularx\expandafter\hsize\expandafter{\sep}% start tabularx
  \realheader\\\hline\hline% insert header and two \hlines
  }{\endtabularx}% end tabularx environment
\makeatother

\begin{document}

\begin{mytable}{Category one, Category two, Category three}
  stuff & stuff & stuff\\
\end{mytable}

\end{document}

A: Here's a LuaLaTeX-based solution. Note that it loads the booktabs package and employs \midrule instead of \hline\hline.
All of the actual work is performed by the Lua function called headers, which employs Lua's powerful string.gsub function. The headers function is assigned to LuaTeX's process_input_buffer callback, which operates at very early stage, before TeX starts its usual macro expansion work.

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{tabularx,booktabs}
\usepackage{luacode}
\begin{luacode}

-- start of Lua code
function headers ( s )
  if string.find ( s , "^%s-\\headers" ) then
    s = s:gsub ( "%b{}" , "&\\textbf{\\textit%0}" )
    s = s:gsub ( "\\headers&" , "" ) .. "\\\\ \\midrule"
  end
  return s
end
-- end of Lua code

\end{luacode}
%% assign 'headers' function to LuaTeX's 'process_input_buffer' callback
\AtBeginDocument{\directlua{luatexbase.add_to_callback(
  "process_input_buffer",headers,"headers")}}

\begin{document}
\noindent
\begin{tabularx}{\textwidth}{XXX}
  \toprule
  \headers{Category One}{Category Two}{Category Three}
\end{tabularx}
\end{document}


text:
Q: Is SameSite=Lax supposed to allow 3rd-party GETs? Reading MDN for SameSite=Lax, it says:

Cookies are allowed to be sent with top-level navigations and will be sent along with GET request initiated by third party website. This is the default value in modern browsers.

To me that sounds like I could initiate a fetch in JavaScript from a 3rd party, and as long as it's a GET the cookies will be sent.
But according to this answer, even GET requests are only sent during top-level navigation, ie not from JS.
I'm guessing the answer is correct. I really hope so because I'm trying to secure an API and I only want cookies being sent when the user navigates to the 1st-party site, ie for Oauth2 interactions etc. SameSite=Strict isn't working for me because if I link to a resource on the 1st-party server, it's still blocked if the referer indicates the navigation came from somewhere else. Refreshing the page doesn't work either. I have to manually navigate to the URL.
EDIT: I just tested this and the behavior is as I hoped. The cookies are not sent with SameSite=Lax fetches. Am I the only one confused by the MDN wording?

A: With SameSite=Lax GET requests are sent only with top level navigations i.e. when the URL bar changes, so the expected behavior is that a fetch initiated from javascript from a 3rd party would not result in cookies sent.
The quote is ambiguous but has fortunately been updated since this question was asked - the current version of the MDN docs on SameSite has a much clearer description of SameSite=Lax.

Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating to the origin site (i.e., when following a link).
This is the default cookie value if SameSite has not been explicitly specified in recent browser versions (see the "SameSite: Defaults to Lax" feature in the Browser Compatibility).

Internet archive sleuthing
From bisecting internet archive on that page, it appears that the wording was changed to make this clearer at some point between 2020-11-11 and 2020-11-28:
On the snapshot from 2020-11-11 (https://web.archive.org/web/20201111134030/https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) the quote from the question is present:

Cookies are allowed to be sent with top-level navigations and will be sent along with GET request initiated by third party website. This is the default value in modern browsers.

But in snapshots taken on or after 2020-11-28, starting with https://web.archive.org/web/20201128122348/https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite, the description for SameSite=lax now reads:

Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating to the origin site (i.e. when following a link).
This is the default cookie value if SameSite has not been explicitly specified in recent browser versions (see the "SameSite: Defaults to Lax" feature in the Browser Compatibility).


text:
Q: All controls are null within usercontrol I have a UserControl which uses a UserControl, among other controls.
In the ascx file I have the following code:
<%@ Register TagPrefix="tag" Namespace="some.name.space" Assembly="some.assembly" %>
<tag:control ID="test" runat="server" />

In my Page_Load method, I try to set a property on test like so:
test.Text = "Hello World!";

This actually sets the Text property of a literal control in my user control test.
This throws an exception:

Object reference not set to an instance of an object

When it tries to set the
lblTest.Text = value;

The object that is null is lblTest.
Am I not adding the user control correctly? Should I - or do I have to - specify the Src property when registering a Tag? If so, I'd have to register every usercontrol I use?
This also results in no controls loading in usercontrol and all controls are null within usercontrol.

A: I had this problem when I was adding a user control in the code behind the wrong way. You have to use the Page.LoadControl method to initialize the control you can't just use new.
        //WRONG
        UserControls.BingoCardPage bcp = new UserControls.BingoCardPage();
        form1.Controls.Add(bcp);
        //RIGHT
        UserControls.BingoCardPage bcp = (UserControls.BingoCardPage)Page.LoadControl("~/UserControls/BingoCardPage.ascx");
        form1.Controls.Add(bcp);

A: The issue here is usually due the the load mechanics of user controls, they load after the page typically. So as a result the controls have not yet been initialized on your usercontrol (causing the null ref) during the containing page_load method. One way to work around this is to just create and set a property on the usercontrol and have the usercontrol wire-up/populate its own UI in its Page_Load method.
Something like this:
//Page
protected void Page_Load(object sender, EventArgs e)
{
    test.Text = "Hello World!";
}

//User Control
public string Text {get; set;}

protected void Page_Load(object sender, EventArgs e)
{
    lblTest.Text = Text;
}

A: If the user control is in your current project, then you need to include the src in the register statement:
<%@ Register TagPrefix="uc1" TagName="NavTop" Src="controls/NavTop.ascx" %>

However, if you use this user control in more than one page, then you can also register it in web.config:
<system.web>
  <pages>
    <controls>
      <add tagPrefix="uc1" tagName="NavTop" src="~/controls/NavTop.ascx" />
    </controls>
  </pages>
</system.web>

One other thing to be aware of: there are times when the visual studio designer does not "see" your changes to controls on the page if you only make the changes in source view. If you change a control name, for example, you could end up with a control with the new name in the ascx but a reference to a control with the old name in the designer file. At runtime, this will result in the designer file property being null.
After having been burnt by this a number of times, if I make any changes in source view, I either check to see that the designer file has been updated correctly or I switch to design view, make a minor change, then save the page/user control.

A: Please try to put code in Page_prerender event of page. It will work for you.


text:
Q: Has/have the leaves been raked? This is a question about subject-verb agreement. I am having difficulty in deciding which version is correct.
Which one is correct? And why?

(Has, have) the leaves been raked?

A: Actually, subject-verb agreement is very easy.
The basic rule is: A singular subject (he, James, cat) takes a singular verb (is, runs, eats), whereas a plural subject (they, Mia and Amy, the dogs) takes a plural verb (are, run, eat).
After knowing the rule of subject-verb agreement, let's solve your problem.

(Has, have) the leaves been raked?

Do you know that answer now? It's

 Have

Why? Because the leaves is plural. A plural subject takes a plural verb form.
I found some exercise online, if you are still unsure about whether you fully understand or not, you can practice them. And if you have any questions after doing the exercise (or any questions about this answer), just tell me in the comments :)


text:
Q: How correct count distance from gpx file - php What am I doing wrong ? I'm, trying to  count distances from a gpx (lat, lon) file but I receives wrong result.
function distance($lat1, $lon1, $lat2, $lon2) {
   $theta = $lon1 - $lon2;
   $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
   $dist = acos($dist);
   $dist = rad2deg($dist);
   $kilometers = $dist * 60 * 1.1515 ;
   return $kilometers;
}

$gpx_file_source = simplexml_load_file($gpx_patch);
$j=0;
foreach($gpx_file_source->trk->trkseg->trkpt as $point){
        if($j%2==0){
             $lat1=$point->attributes()[0];
             $lon1=$point->attributes()[1];
        }else{
             $lat2=$point->attributes()[0];
             $lon2=$point->attributes()[1];
             $totaldistance=distance(''.$lat1.'', ''.$lon1.'', ''.$lat2.'', ''.$lon2.'').;
             $totaldistance+=$totaldistance;
        }
  $j++;
}
echo $totaldistance; //0.00011797444243905

My result is: 0.00011797444243905 km
Correct result: 17.35 km
GPX file: http://itros.us/distance.gpx

A: I changed counting function and is working !
3958*3.1415926*sqrt(($lat2-$lat1)*($lat2-$lat1) + cos($lat2/57.29578)*cos($lat1/57.29578)*($lon2-$lon1)*($lon2-$lon1))/180


text:
Q: Evision Argos/Oracle performance I have a report in Evisions Argos that runs in 1-2 minutes on one server and for almost an hour on another.  It is the exact same datablock with the exact same code, just running against a different database.
I won't display the script here, I just want to know what kinds of things our Argos Admin should check for (I don't have access to the server, I'm just a DataBlock Designer).

A: Oracle performance tuning is a vast topic.  There are people out there who make (very good) livings out of tuning other people's queries.  So you really aren't going to get much joy here.
But the general advice is actually pretty obvious: if the same query performs differently in two different environments the cause must be due to some difference between them.

*

*Volumes of data (number of rows)

*Distribution of data (development or test data may have different characteristics from live data)

*Data structures (indexes, materialized views)

*Stale statistics

*Hardware - amount of RAM, quality of IO, size and type of storage.

*Resource contention (more users, different types of users e.g. long running reports)

There are all sorts of tools you can use to diagnose performance problems.  These depend on which version of the database you have, which edition you've licensed and also whether you have any of the chargeable options.
But regardless, the first place to start is with the documentation.  Find out more.


text:
Q: Dockerized Rails app: slow after container start Our Rails (5.1.7) application runs inside docker-swarm container (Ruby 2.6.5, PostgreSQL 10).
We tried Puma web-server, and it wasn't good enough under heavy load, so we use Unicorn (5.5.2).
And we are facing a big problem.
After a container start, each page loads really slow for the first time, up to one minute. All subsequent requests to the same pages respond quickly.
It looks like it is not Unicorn problem, because after HUP (restart) or QUIT (shutdown) (+ start) signals pages load fast enough.
This problem occurs after deployment (docker stack deploy ...), or update (docker service update ...).
Docker schema:

*

*two separate servers

*two stacks (staging + demo);

*both stacks use the same Nginx container (+ external network created to connect them)

*each stack includes:

*

*PostgreSQL container

*Rails application container

*Redis container

*RabbitMQ container

*Background workers container

*Nginx service is defined only in docker-compose for demo, therefore deployment to staging does not restart Nginx container

It may be worth noting that all staging containers run on a server 1 (except Nginx), and demo containers are distributed between two servers: on server 1 we have demo PostgreSQL, Redis and RabbitMQ, and on server 2 we have Rails application, Background workers and Nginx. And the problem is reproduced on both stacks.
Any ideas how to fix the issue? Thanks in advance.
UPDATE (2020.02.24)
There seems to be a problem in the view layer caching. I can't show the full logs, but they are almost identical except for this line:
# SLOW request
I, [2020-02-24T09:47:55.634574 #464]  INFO -- : Completed 200 OK in 57087ms (Views: 56624.1ms | ActiveRecord: 104.7ms)

# FAST request
I, [2020-02-24T09:48:21.101165 #461]  INFO -- : Completed 200 OK in 993ms (Views: 486.6ms | ActiveRecord: 110.1ms)

A: After examining the logs, we've noticed, that the greatest subsidence in response time occurs on a view rendering stage:
# first SLOW request
I, [2020-02-24T09:47:55.634574 #464]  INFO -- : Completed 200 OK in 57087ms (Views: 56624.1ms | ActiveRecord: 104.7ms)

# second FAST request
I, [2020-02-24T09:48:21.101165 #461]  INFO -- : Completed 200 OK in 993ms (Views: 486.6ms | ActiveRecord: 110.1ms)

Therefore, we checked the default cache and realized that it simply did not persist between deployments, and on a first request application have to render view from scratch and cache it.
So, our solution was to save rails cache in a shared persistent docker volume and create a symlink to it before the application server starts. As a result, if page was cached, even the first request to open it will be super fast.


text: Q: Slow wifi ubuntu 16.04 I realise similar questions have been posted a lot and I've tried the solutions I've seen suggested but to no avail. I have a Ralink RT5372 wireless adapter on Ubuntu 16.04 that is acting very slow. Additionally, I use the same adapter on windows via a dual-boot and don't experience the same issue. I've tried turning power management off, and I've also tried editing my nsswitch.conf file but neither have helped. To give you an idea of speed, it's maxing out at a few 100kbps per second. Thanks for any responses.


text:
Q: Angular 1.5 Response status returning NULL (-1) instead of 503 due to cors I am getting response status of 503 on a No Access-Control-Allow-Origin  header error in the browser but Angular 1.5.5. $http is getting a status of NULL (-1). Is there any way for me to get the actual 503 error in Angular? Thanks.

A: please add it(Allow-Control-Allow-Origin: *) to browser from the browser store (App) section,
then check it again...
Thanks.


text:
Q: missing files in my pip project after upload Codes : https://github.com/rdvnszn1/TaPyFi
Pypi : https://pypi.org/project/tapyfi/
I want to share my package  and make some try however, I encounter a problem.
After upload my package with
twine upload dist/*
My files does not go totally to pip
I install it in other project and look at the files , see just  init and main file uploaded.
files in my other project
https://prnt.sc/qmw8x7

A: Either list all packages and sub-packages in the argument to the packages parameter of the setuptools.setup() function call. Or place (potentially empty) __init__.py files in all the packages and use packages=setuptools.find_packages().
setuptools.setup(
    # ...
    packages=['tapify', 'tapify.Helpers', ...],
    # ...
)

setuptools.setup(
    # ...
    packages=setuptools.find_packages(),  # make sure each package has __init__.py
    # ...
)


text:
Q: Executing a command in terminal using php I was trying to run an external command via php. Actually I want to compile a java file. I've tried this and this. But unfortunately, in my case the java file doesn't compiling.
what is wrong in this code  ?
exec("javac Main.java");

but when I compiled it manually, and then execute the follwing command, it works fine.
exec("java Main");


text:
Q: Counting functions satisfying $f(j)Ques : Let $N$ be the number of functions $f: \{1, 2, 3,\dots, 2018\} \to \{1, 2, 3,\dots, 2018\}$ satisfying $f(j) < f (i) + j - i$ for all integers $i,j$ such that $1 \leq i < j \leq 2018$.  Find $N$.
My development so far : difference of elements' value in domain is strictly greater than that in Co domain. Hence every consecutive number should be mapped to a lesser or equal number the previous number is mapped to. Hence the function should be non-strictly decreasing.


text:
Q: How to change object's properties' places? I have an object playerInfoObject with properties w1 and w2, which are also objects.
I need to change their places between each other
They become equal when I'm trying to do this:
    var tmp = playerInfoObject.w1;
    playerInfoObject.w1 = playerInfoObject.w2;
    playerInfoObject.w2 = tmp;

How can I solve this problem?
Thank you in advance

A: If you can use EcmaScript 6, a destructuring assignment can solve it without a temporary variable:
playerInfoObject = {
  w1: {w: '1'},
  w2: {w: '2'}
};

[playerInfoObject.w1, playerInfoObject.w2] = [playerInfoObject.w2, playerInfoObject.w1];

Or with object destructuring directly:
({w1: playerInfoObject.w2, w2: playerInfoObject.w1}) = playerInfoObject;

Otherwise, your code seems to be working fine.

A: = operator places a reference between the object, you need to clone it.
var tmp = JSON.decode(JSON.encode(playerInfoObject.w1));
playerInfoObject.w1 = JSON.decode(JSON.encode(playerInfoObject.w2));
playerInfoObject.w2 = tmp;

You can find more elegant ways of cloning objects but this should work.


text:
Q: How disable @DependsOn annotation in arquillian tests? I try to test singleton that have annotation @DependsOn where i mark another singletons that must be initialized before. But in test i don't want to load them, because its a lot of useless classes for my test. For ex:
@Singleton
@DependsOn({"anotherSingleton1", "anotherSingleton2"...})
public class SomeSingleton {
... methods and logic...
}

Here's example of test:
public class SomeSingletonIT extends Arquillian {

    @Mock SomeClassInSingleton;
    ... another mocks...

    @Inject
    @InjectMocks
    SomeSingleton instance;

    @BeforeClass
    public void initMocks() {
        mocks logic
    }

    @Deployment
    public static WebArchive createDeployment() {

        return ShrinkWrap.create(WebArchive.class, "test.war")
                .addClasses(
                        SomeSingleton.class
                        )
                .addAsLibraries(some Libs)
                .addAsWebInfResource(EmptyAsset.INSTANCE,"beans.xml");
    }

    @Test
    public void testGetProactiveSubjects() throws Exception {
        System.out.println("***----------------------------------***");
        assertNotNull(instance);
        ...some assertions...
        System.out.println("***----------------------------------***");
    }

}

I got exception that arquillian doesn't see classes of singletons in annotation @DependsOn. But if i include them in test archive - i will have to include all theirs dependencies too. And mock some logic in them that inits in @PostConstruct's. So... How can I disable or mock @DependsOn?
I use arquillian with wildfly managed container.

A: One idea which comes to my mind would be to implement a test double - dummy object - which you would substitute in your test deployment rather than deploying real singletons. This would save you from adding tons of dependencies and execution overhead when deploying your archive under test.


text:
Q: How to implement generic collection lookup method that can return class or nullable struct? I want a typed lookup helper function for a heterogenous collection: It should return a struct or class, else null if the item is not found.
Below is an example using a trivial collection lookup, but it could be a database call or whatever.
Is there any way to achieve this with a single method signature?
    public T GetClass<T>(string key)  where T : class
    {
        object o;
        if (Contents.TryGetValue(key, out o))
        {
            return o as T;
        }
        return null;
    }

    public T? GetStruct<T>(string key) where T : struct
    {
        object o;
        if (Contents.TryGetValue(key, out o))
        {
            if (o is T)
            {
                return (T?) o;
            }
        }
        return null;
    }

What I've already tried:

*

*I understand that generic restrictions can't be used to disambiguate overloads. So I can't simply give these two methods the same name.

*Returning (Default) T isn't an option, since 0 is a valid int value.

*I have tried calling with <int ?> as the type, but as discussed, Nullable<T> isn't a reference type.

Is there some way to indicate that I'm going to return a boxed int?

A:
Is there any way to achieve this with a single method signature?

There's a horrible (truly hideous) way to do it using optional parameters so that the calling code can look the same in both cases. It's icky though.
Options:

*

*Return a Tuple<T, bool> instead of using nullity

*Use an out parameter (like int.TryParse etc)

*Use different method names

Note that by signalling the absence of a value separately, you can make null a valid "found" result, which can be useful sometimes. Or you may want to just guarantee that it'll never be returned.
If you really want to use nullity, I'd go for the last option. I believe it will make your code clearer anyway. IMO, overloading should really only be used when the methods do exactly the same thing expressed using different parameters - whereas returning Nullable<T> as the return type in one case and T as the return type in the other case can't really be seen that way.

A: The following method works for both classes and nullable structures:
public static T GetValue<T>(string key)
{
    object o;
    if (Contents.TryGetValue(key, out o))
    {
        if (o is T)
        {
            return (T)o;
        }
    }
    return default(T);
}

Usage:
int?   result1 = GetValue<int?>("someInt");
string result2 = GetValue<string>("someString");

Notice how the ? is part of generic type argument and not defined by the method on the return type.

A: This should do exactly what you need it to. If the requested type is a nullable type, check the underlying type before casting.
public static T GetValue<T>(string key)
{
    object o;
    if (Contents.TryGetValue(key, out o))
    {
        if (o is T || Nullable.GetUnderlyingType(typeof(T)) == o.GetType())
        {
            return (T)o;
        }
    }

    return default(T);
}

My test code:
Contents.Add("a string", "string value");
Contents.Add("an integer", 1);
Contents.Add("a nullable integer", new Nullable<int>(2));

// Get objects as the type we originally used.
Debug.WriteLine(string.Format("GetValue<string>(\"a string\") = {0}", GetValue<string>("a string")));
Debug.WriteLine(string.Format("GetValue<int>(\"an integer\") = {0}", GetValue<int>("an integer")));
Debug.WriteLine(string.Format("GetValue<int?>(\"a nullable integer\") = {0}", GetValue<int?>("a nullable integer")));

// Get objects as base class object.
Debug.WriteLine(string.Format("GetValue<object>(\"a string\") = {0}", GetValue<object>("a string")));
Debug.WriteLine(string.Format("GetValue<object>(\"an integer\") = {0}", GetValue<object>("an integer")));
Debug.WriteLine(string.Format("GetValue<object>(\"a nullable integer\") = {0}", GetValue<object>("a nullable integer")));

// Get the ints as the other type.
Debug.WriteLine(string.Format("GetValue<int?>(\"an integer\") = {0}", GetValue<int?>("an integer")));
Debug.WriteLine(string.Format("GetValue<int>(\"a nullable integer\") = {0}", GetValue<int>("a nullable integer")));

// Attempt to get as a struct that it's not, should return default value.
Debug.WriteLine(string.Format("GetValue<double>(\"a string\") = {0}", GetValue<double>("a string")));

// Attempt to get as a nullable struct that it's not, or as a class that it's not, should return null.
Debug.WriteLine(string.Format("GetValue<double?>(\"a string\") = {0}", GetValue<double?>("a string")));
Debug.WriteLine(string.Format("GetValue<StringBuilder>(\"a string\") = {0}", GetValue<StringBuilder>("a string")));

Results:
GetValue<string>("a string") = string value
GetValue<int>("an integer") = 1
GetValue<int?>("a nullable integer") = 2

GetValue<object>("a string") = string value
GetValue<object>("an integer") = 1
GetValue<object>("a nullable integer") = 2

GetValue<int?>("an integer") = 1
GetValue<int>("a nullable integer") = 2

GetValue<double>("a string") = 0

GetValue<double?>("a string") =
GetValue<StringBuilder>("a string") =


text:
Q: Do exist an injective linear map from $\mathbb{R}^5\rightarrow\mathbb{R}^4$ I already asked If there exists an injective function $f:\mathbb{R}^5\rightarrow\mathbb{R}^4$ and I found that it exists a such function: Do exist an injective function from $\mathbb{R}^5 \rightarrow \mathbb{R}^4$
Now, I would like to know If there exist such an injective linear map. I was trying to find out but I am unable. In think it does not exists because of the difference between dimmnsions but I am really unsure.
Please help me. Thank you!!!!

A: The rank-nullity theorem tells us No. In fact
$$\dim\ker f=\dim\Bbb R^5-\operatorname{rank}f\ge 5-4=1$$
hence $\ker f\ne\{0\}$, and so $f$ isn't injective.

A: No: if $f:V\rightarrow W$ is an injective linear map, then $\dim V \leq \dim W$.  This is because if $v_1,\dots,v_n\in V$ are vectors such that $f(v_1),\dots,f(v_n)$ are dependent (i.e., there exist $c_1,\dots,c_n\in\mathbb{R}$ not all zero such that $c_1f(v_1)+\dots+c_nf(v_n)=0$), then $f(c_1v_1+\dots+c_nv_n)=0$, and injectivity implies $c_1v_1+\dots+c_nv_n=0$, hence the vectors are dependent.  Dimension is the maximum number of linearly independent vectors, so $\dim V$ cannot possibly exceed $\dim W$.
In your case, $\dim \mathbb{R}^n=n$, and it is not true that $5\leq 4$.


text:
Q: Ruby: Get filename without the extensions How can I get the filename without the extensions? For example, input of "/dir1/dir2/test.html.erb" should return "test".
In actual code I will passing in __FILE__ instead of "/dir1/dir2/test.html.erb".

A: Split by dot and the first part is what you want.
filename = 'test.html.erb'
result = filename.split('.')[0]

A: Read documentation:
basename(file_name [, suffix] ) → base_name

Returns the last component of the filename given in file_name, which
  can be formed using both File::SEPARATOR and File::ALT_SEPARATOR as
  the separator when File::ALT_SEPARATOR is not nil. If suffix is given
  and present at the end of file_name, it is removed.

=> File.basename('public/500.html', '.html')
=> "500"

in you case:
=> File.basename("test.html.erb", ".html.erb")
=> "test"

A: How about this
File.basename(f, File.extname(f))

returns the file name without the extension.. works for filenames with multiple '.' in it.

A: In case you don't know the extension you can combine File.basename with File.extname:
filepath = "dir/dir/filename.extension"
File.basename(filepath, File.extname(filepath)) #=> "filename"

A: Pathname provides a convenient object-oriented interface for dealing with file names.
One method lets you replace the existing extension with a new one, and that method accepts the empty string as an argument:
>> Pathname('foo.bar').sub_ext ''
=> #<Pathname:foo>
>> Pathname('foo.bar.baz').sub_ext ''
=> #<Pathname:foo.bar>
>> Pathname('foo').sub_ext ''
=> #<Pathname:foo>

This is a convenient way to get the filename stripped of its extension, if there is one.
But if you want to get rid of all extensions, you can use a regex:
>> "foo.bar.baz".sub(/(?<=.)\..*/, '')
=> "foo"

Note that this only works on bare filenames, not paths like foo.bar/pepe.baz. For that, you might as well use a function:
def without_extensions(path)
  p = Pathname(path)
  p.parent / p.basename.sub(
    /
      (?<=.) # look-behind: ensure some character, e.g., for '.foo'
      \. # literal '.'
      .* # extensions
    /x, '')
end

A: Thanks to @xdazz and @Monk_Code for their ideas. In case others are looking, the final code I'm using is:
File.basename(__FILE__, ".*").split('.')[0]

This generically allows you to remove the full path in the front and the extensions in the back of the file, giving only the name of the file without any dots or slashes.

A: Considering the premise, the most appropriate answer for this case (and similar cases with other extensions) would be something such as this:
__FILE__.split('.')[0...-1].join('.')

Which will only remove the extension (not the other parts of the name: myfile.html.erb here becomes myfile.html, rather than just myfile.

A: name = "filename.100.jpg"
puts "#{name.split('.')[-1]}"

A: Yet understanding it's not a multiplatform solution, it'd work for unixes:
def without_extensions(path)
    lastSlash = path.rindex('/')
    if lastSlash.nil?
        theFile = path
    else
        theFile = path[lastSlash+1..-1]
    end

    # not an easy thing to define
    # what an extension is
    theFile[0...theFile.index('.')]
end

puts without_extensions("test.html.erb")
puts without_extensions("/test.html.erb")
puts without_extensions("a.b/test.html.erb")
puts without_extensions("/a.b/test.html.erb")
puts without_extensions("c.d/a.b/test.html.erb")


text:
Q: Disabling Strict Standards Errors in WordPress 3.7 with PHP 5.4 I am trying to disable STRICT Error reporting in WordPress 3.7 via my php.ini file after updating my computer to OS X 10.9. I am running PHP Version 5.4.17, the one that ships with Mavericks.
In my wp-config.php file, I have enabled define('WP_DEBUG', true); which was on a working fine before upgrading my OS and as a result, PHP.
In the php.ini file, I have tried setting error_reporting to:
error_reporting = E_ALL

or
error_reporting = E_ALL & ~E_STRICT

or
error_reporting = E_ALL & ~E_DEPRECATED

even
error_reporting = 0

But the errors still appear.
display_errors is set to Off:
display_errors = Off

After each change to the file, I am restarting apache and httpd with these two commands:
httpd -k restart
apachectl restart

The php.ini file I am editing is the same one being pointed to in phpinfo() AND just to make sure changes are going through, I have been editing the error_prepend_string value:
error_prepend_string = "<span style='color: #ff0000'>ERROR: "

and those changes are coming through in the error.
Any thoughts on how to debug this would be much appreciated.

A: In Wordpress 3.7, the function wp_debug_mode (defined in wp-includes/load.php, and called from wp-setings.php) sets error_reporting( E_ALL ).
Since wp-settings.php is itself loaded at the end of wp-config.php, you cannot change this setting from wp-config.php (or rather, you can, but it will be overridden).
A solution is to create a "Must Use plugin", that is to say a .php file located in the /wp-content/mu-plugins/ folder containing :
<?php
if (WP_DEBUG && WP_DEBUG_DISPLAY)
{
   ini_set('error_reporting', E_ALL & ~E_STRICT & ~E_DEPRECATED);
}

A: I found that only
error_reporting = off

works, as STRICT errors have become part of ALL as of PHP 5.4 which is annoying.

A: If you set WP_DEBUG to 'false' in wp-config.php file. These do not affect your website.
Bot the problem is that above does not work sometime.
That can happen on cheap/shared hostings that force displaying PHP ERRORS, warnings and notices.
In that case, you can remove this line from your wp-config.php file:
define('WP_DEBUG', false);

and place this:
ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

in my case its working.


text:
Q: Laravel Eloquent model duplicate keys in model I cannot figure out what is the problem, I cannot remember when it firstly appeared, it doesn't make a lot of problems now, but it wastes connection and this is not last point in mobile communication.
The problem is following.
Here is output of model, such output is for any model, I mean it duplicates each associative value with index.
array:1 [
  0 => array:12 [
    "id" => "55"
    0 => "55"
    "user_id" => "199"
    1 => "199"
    "token" => "b7351fb13c5ce06a6f09ef6147c7d7d5"
    2 => "b7351fb13c5ce06a6f09ef6147c7d7d5"
    "expiration_time" => "1452795403"
    3 => "1452795403"
    "scope" => "0"
    4 => "0"
    "last_login_time" => "1452194400"
    5 => "1452194400"
  ]
]

I have tried to follow the stack of function call and stopped at
public static function hydrate(array $items, $connection = null)

The I got here dump as I described above.
I have no idea what can cause such behavior.
Maybe someone has idea what can cause such problem.
Thanks everyone.
EDIT
I have uploaded code to pastebin http://laravel.io/bin/VP435
I edited model for my needs, but it shouldn't affect this part.
I am trying to find the "root of evil" right now.
hybrate method is called by Builder
public function getModels($columns = ['*'])

This is query to DB
       $results = $this->query->get($columns);
Query is following
"select * from `tokens` where `token` = ? limit 1"

And it is correct request no issue with it

A: Please make sure that in config/database.php you have set fetch to PDO::FETCH_CLASS and not to PDO::FETCH_BOTH.
By default it's PDO::FETCH_CLASS and it seems you have somehow set it to PDO::FETCH_BOTH.
If it's not the case, show example how you get this object.


text:
Q: How to use variable templates to compare the types of variables in C++ 17? I have this beautiful piece of code, which is using C++14s variable templates:
#include <typeinfo>

template<typename T, typename U>
constexpr bool same_type = false;

template<typename T>
constexpr bool same_type<T,T> = true;

int main() {
    bool f = same_type<int, bool>; // compiles. Evals to false.
    bool t = same_type<int, int>; // compiles. Evals to true.
    int a;
    int b;
    return same_type<typeid(a), typeid(a)>; // does not compile.
}

It checks if two types are the same. I like this, but it seems quite useless to me if I have to pass in the types myself, instead of deriving them from some variables.
Is there a way to make this work? I would have expected that something like typeid(x) might to the trick.

A: same_type<decltype(a), decltype(a)>.
Note that the standard library already has this feature, it's called std::is_same_v<...>.


text:
Q: PHP error with using strings as an array I get a website as a cURL response, and I pass it to this function. Then I itterate through the string, doing some processing. It works, but I get this error:

Notice: Uninitialized string offset: 75817 in
  /var/www/html/wp-content/plugins/crg-daily/lib/CragslistRawDumpProcessor.class.php
  on line 7

Here is the code:
public function rollSausage($dump){
    $anchorArray = array();
    $dumpLength = strlen($dump);
    $skipToLetter = 1;
    while($skipToLetter < $dumpLength){
        $skipToLetter++;
        $letter = $dump[$skipToLetter];
        ...
    }
}

Any ideas? I think it has something to do with the type of string being submitted. It is a raw cUrl response. I'm scraping a web page.

A: Increment your $skipToLetter after you use it (preferably at the end of the while loop). And you might also start at 0, not 1
 $skipToLetter = 0;
 while($skipToLetter < $dumpLength){
            $letter = $dump[$skipToLetter];
    ...
            $skipToLetter++;
            }
        }

Here's the reason: assume you have a string with length of 4. This means that the last index in the string is 3. Your index goes up to 3. It gets compared in the while loop (3<4)? and the answer is true. The code enters the while loop and increments the value of the index which will be greater than the last index of the string, thus causing the warning.

A: Updated your code...
public function rollSausage($dump){
    $anchorArray = array();
    $dumpLength = strlen($dump);
    $skipToLetter = 1;
    while($skipToLetter < $dumpLength){
        $skipToLetter++;
         if( siset( $dump[$skipToLetter]) )
            $letter = $dump[$skipToLetter];
...
        }
    }

}


text:
Q: Bulk reading of data in hibernate using scrollable result set I was reading a blog regarding bulk fetching with hibernate http://java.dzone.com/articles/bulk-fetching-hibernate.
In this, ScrollableResults is used as a solution. Here still we need to evict objects from session.
I don't understand how using ScrollableResults(or scroll()) is different from using list().
In other words, how the below statements differ in terms of performance
 List<Employee> empList = session.createCriteria(Employee.class).list();
 ScrollableResults sc = session.createCriteria(Employee.class).scroll();

Please let me know.

A: The above code seems to be missing some settings.
Query query = session.createQuery(query);
query.setReadOnly(true);
// MIN_VALUE gives hint to JDBC driver to stream results
query.setFetchSize(Integer.MIN_VALUE);
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
// iterate over results
while (results.next()) {
    Object row = results.get();
    // process row then release reference
    // you may need to flush() as well
}
results.close();

Follow this link for more details and explanation.

A: I referred Hibernate API documentation to understand the difference between list() and scroll().
ScrollableResults is like a cursor . An important feature of ScrollableResults is that it allows accessing ith object in the current row of results, without initializing any other results in the row through get(int i) function.
It also allows moving back and forth the result set using next() and previous() function.
Example :
  ScrollableResults sc = session.createQuery("select e.employeeName,e.employeeDept FROM Employee e").scroll(ScrollMode.SCROLL_INSENSITIVE);
      while(sc.next()) {
         String empName = (String)sc.get(0);
         System.out.println(empName);
         String empdept = (String)sc.get(1);
         System.out.println(empdept);
      }

The output of above programm will values of employeeName and employeeDept .
Now suppose you want to get the last record of the resultSet. With list() you would need to iterate the whole result. With ScrollableResults, you can use last() function.
Note that for ScrollableResults sc = session.createCriteria(Employee.class).scroll(); should be iterated as
 while(sc.next()) {
     Employee emp = (Employee)sc.get(0);
     System.out.println(emp.getname);
 }


text:
Q: need help with DB design - Rails way I'm new to rails and need some help with DB design.
It is basically category, product, quantity, price...type of tables.
I have 4 categories: CatA CatB CatC CatD
Each category above will have multiple products in them:
CatA - ProductA1, ProductA2, ProductA3
CatB - ProductB1, ProductB2, ProductB3
CatC - ProductC1, ProductC2, ProductC3
CatD - ProductD1, ProductD2, ProductD3

Each Product then has a type, rating, quantity, price, volume
Would it be good to have one big Product table with columns: Category, Product Name, Type, Rating, etc..ec..
or have different tables for Category, Product, Type which relationship will they have belongs_to or has_many?
I'm looking at it from Admin Point of View. If a user wants to add a new product then they'll first select category from drop down, type product name, select product type etc. having everything in one table will be easy but is that efficient?

A: You're going to want products and categories tables.
Product will belong_to :category and Category will has_many :products.
You'll need a category_id column in the products table to make the association.
I wouldn't recommend a types table -- just have the type as a column in the products table.  Don't use the word "type" though, go with "kind" as Rails uses "type" for Single Table Inheritance so you might run into some weirdness if you're not using it for that.


text:
Q: merging a sort array and unsorted array Merge a sorted array with unsorted array to give a final sorted array. Can it be better done, the not obvious way.
final_sorted_array=merge(sort(unsorted_array), sorted_array)

I am assuming merge step similar to found in merge sort
and we know any best is limited by O(n log n) in general. I am trying to understand how a ordered data (knowing the information about data) can be useful to what extent in general.

A: Suppose your first array is called A1 of n1 elements and your second one is called A2 of n2 elements:
extend the length of A1 and append A2 to it at the cost of O(n2 + c), where c is a constant. Apply quick sort and get it ordered at another cost of O( (n1+n2)*log(n1+n2) ). You mentioned you didn't want the obvious way, however, you wanted to get the job done the best way. This is likely the best way, because it allows you to still use regular arrays which are usually the fastest data structures to work in general (of course it depends specifically on which task you are working on).
However, a different possibility, is to make A1 a linked list insetad of a regular array, for the purpose of this analysis we will not consider the costs of transforming A1 from an regular array into a linked list. Therefore, the approach would be to insert ordered each element of A2 into A1. The obvious way to insert ordered would be to verify each element of A1 and then decide where to insert, at the cost of O(n1 + c) for each insertion. However, a smarter method would be to make a binary search over A1 to decide where each element of A2 should be inserted in, at the cost of O(log(n1) + c) for each insertion. In this case, there would be n2 insertions, being the total cost n2*O(log(n1) + c). In this approach you wouldn't need to move any of A1 elements, since we are assuming you use a linked list, all you need is to check these elements. That's why this asymptotic function looks better, this data structure gives you the power to only look at A1 original elements without actually moving them.
To decide which approach you should use, I recommend that you analyse the algorithm which comes after the arrays merge, choosing the option that best fits your needs.


text:
Q: How do you get php to send an email I have a frontend in flutter that sends data to update mysql database in php. The form sends the data and the database updated just fine. However, it is bypassing or ignoring the section to send mail. I am not getting any errors for the mail. What am doing wrong?
<?php

    require_once('dbc.php');

    $name = $_POST["name"];
    $email= $_POST["email"];
    $phone= $_POST["phone"];
    $password = $_POST["password"];

    $findexist="select * from registered where name='$name'";

    $resultsearch=mysqli_query($conn,$find-exist);

    if(mysqli_num_rows($resultsearch)>0) {

        while($row=mysqli_fetch_array($resultsearch)) {
            $result["success"] = "3";
            $result["message"] = "user Already exist";
            echo json_encode($result);
            mysqli_close($conn);
        }
    } else {
        $sql = "INSERT INTO registered (name,email,phone,password) VALUES ('$name','$email','$phone','$password');";

        if ( mysqli_query($conn, $sql) ) {
            $result["success"] = "1";
            $result["message"] = "Registration success";
            echo json_encode($result);

            $to = $email;
            $subject = 'Signup | Verification';
            $message = 'Thanks for signing up with redhowler!';

            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers = "Content-Type: text/html; charset=utf-8" . "\r\n";

            $headers .= 'From: redhowler2@gmail.com'. "\r\n";

            mail($to, $subject, $message, $headers);

            mysqli_close($conn);

        }
    }

?>

A: Try to use PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
 $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";
        $mail->Username   = "xxxxxxxx@email.com";
        $mail->Password   = "xxxxxxxxxxxxxxx";

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("xxxxxxxxx@email.com", "from-name");
        $mail->AddReplyTo("xxxxxxxxx@email.com", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);

        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }

A: For setting up send mail on your computer. I didn't use PHPmailer. I used mail(). Nevertheless, you have to have some knowledge of UNIX or Linux script -- according to the operating system. You also have to search(like google search) for "how to setup send mail on mac (enter operating system)". Links such as those mention below helped me:
https://gist.github.com/haccks/7ec2fe500332a6d23ee68d1c1a2279d5
https://benjaminrojas.net/configuring-postfix-to-send-mail-from-mac-os-x-mountain-lion/#comment-87436


text:
Q: Is a symmetric positive definite matrix similar to a triadiagonal symmetric positive definite matrix? Is any real symmetric positive definite matrix similar to a triadiagonal symmetric positive definite matrix?
From Householder lemma it is known that if $B$ is symmetric, there exists a orthogonal matrix $H$ such that $C=H^\top B H$ is triadiagonal symmetric. The question is whether $C$ is definite positive; it has the same (positive) eigenvalues as $B$ so I would say yes.
Is this correct?


text:
Q: Rails s and rails console not working I haven't used Ruby in a while, so I just came back to it today and whenever I try to do rails s or rails console it spits out the generic help text, i.e.
    rails console                                                  ~
Usage:
  rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]              # Path to the Ruby binary of your choice
                                 # Default: /Users/cabelhigh/.rvm/rubies/ruby-1.9.2-p320/bin/ruby
  -b, [--builder=BUILDER]        # Path to a application builder (can be a filesystem path or URL)
  -m, [--template=TEMPLATE]      # Path to an application template (can be a filesystem path or URL)
      [--skip-gemfile]           # Don't create a Gemfile
      [--skip-bundle]            # Don't run bundle install

It just does this over and over. Any idea what's wrong?
Also, I'm running OSX, if that has anything to do with it.
EDIT: Version info: Rails 3.2.8, ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-darwin11.3.0]

A: You are not in a rails application directory when you execute the commands
Make a new rails app with
rails new blog

cd into the directory
cd blog

and run
rails s

or
rails c

A: rails console works only in Rails project directory

A: Rails console work only in rails project directory.
May be you want run ruby console? (like irb, pry, etc)


text:
Q: Unexpected returned value of a user defined function #include <iostream.h>

int someFunction(int &x, int c) {
    c=c-1;
    if(c==0) {
        return 1;
    }
    x=x+1;
    return someFunction(x,c) * x;
}

void main() {
    int p = 5;
    cout << someFunction(p,p);
}

This code return 6561 but I have no idea why. Can anyone help me with this?

A: You have 5 iterations here:
1st iteration - C is 5 and reduced by 1 -> c=4 which is not 0 so we go on to "(++x) * someFunc".
2nd iteration - C is 4 and reduced by 1 -> c=3 which is not 0 so we go on to "(++x) * someFunc".
3rd iteration - C is 3 and reduced by 1 -> c=2 which is not 0 so we go on to "(++x) * someFunc".
4th iteration - C is 2 and reduced by 1 -> c=1 which is not 0 so we go on to "(++x) * someFunc".
5th iteration - C is 1 and reduced by 1 -> c=0 so we return 1.

At this point we have x * x * x * x * 1 and after the 4 increments x = 9 and so the value is 9 * 9 * 9 * 9 * 1 = 6561
This happens because the function is evaluated before the actual multiplication can take place but as the stack unwinds, at the moment of each multiplication, x which is passed by reference is already at it's last value, which is 9.


text:
Q: How to determine if a PR has all required codeowner approvals using GH REST API? I would like to use the GH REST API to determine if a particular PR has all required codeowner approvals.  Then, if the answer is yes, I would like to further determine the date and time at which the final approval occurred.
I have tried a bunch of things.
The documentation suggests that if all approvals have been granted, the requested_reviewers and requested_teams array will be empty.  This does not appear to be true though.  As a test, I created a PR that required reviews from 3 different teams.  Then I manually added a couple of additional people.  I reached to people from the 3 different teams and asked them to approve my PR.  After doing this, in the GH html webpage, it shows "Changes Approved" with a green checkmark.  But when I do the GH API request, the requested_reviewers and requested_teams arrays are not empty.
I then tried appending /reviews to the end of the request URL, to get all of the reviews.  They all show up as APPROVED, but nothing in the response indicates whether the review was a required review, or someone who was just passing by and felt like hitting approve.
It feels like the best way is to do the following steps:

*

*Get the pull request object

*Examine the requested_teams field (we don't use individual names in our CODEOWNERS)

*Walk the list of reviews by querying the /reviews endpoint

*For each one, query the user's teams and see if any of them match any of the teams in requested_teams.

This is a lot of work and pretty complicated, but it seems do-able in theory.  Is there a simpler way?


text:
Q: Is pointer valid condition for a loop? Can someone carefully explain, why in this case for loop repeats 10 times?
#include <iostream>
using namespace std;
int main(){
    int length=-1;
    char s[]="Bad or nice";//10 characters

    for ( char *q = s; *q; ++q ){
    cout << *q;
    length++;
    }

    cout << "\n" << length;

return 0;
}

A: Total characters in the string is 11 excluding \0. Second for expression *q becomes false when q points to last character of the string s, which is \0.
Therefore, loop repeats 11 times. You are getting 10 output because you initialized length with -1.

A: The condition is the value at the memory location of the pointer (*q).
Therefore the loop terminates when the NULL character is reached (at the end of the string), which is evaluated as false.


text:
Q: Docker desktop automatically stopped on Windows 10 Recently I faced a problem that when I open docker desktop it's automatically stopped after a few seconds. I try to solve it in several ways like reinstalling the docker desktop and also trying some methods that are available on the internet as solutions. But these do not work for me.
Is anyone can help me, please.

A: I have had lots of problems with installing docker on windows .
make sue you are following docker's documentation step by step.
Most of the times the problem is related to wsl2 , hyper-v or cpu virtualization. check this parameters
Docker in windows


text:
Q: access append-query: set column to a literal for each record i have multiple tables containing similar records. i want to merge them into one table.
therefore i use an update query and map the fields from the various tables to the ones in my target-table. but i need to keep track from which table a record comes, so id like to add a literal "TABLE_XY" in the ORIGINALTABLE field in the resulting table to each record. but the query designer always wants a source-field. I cant just put a literal anywhere an select ORIGINALTABLE in "Append To"...
what to do? do i really have to add a NAMEOFTHISTABLE field to the original tables...?
thanks for your help!

A: Make a backup copy of your database. Create a new query and switch to SQL View.  Then paste in this statement, and modify the table and field names to match yours:
INSERT INTO master_table (
    ORIGINALTABLE
    , field1
    , field2
    )
SELECT
    "TABLE_XY" AS ORIGINALTABLE
    , field_a
    , field_b
FROM
    TABLE_XY;

A: Using the Query Designer in Design View for an Update Query:
Field: ORIGINALTABLE
Table: <tableName>, where tableName is the name of the table you are updating.
Update To: "TABLE_XY", make sure to include the quotes.

Using the Query Designer in Design View for an Append Query:
Field: Expr1: "TABLE_XY", where Expr1 is an alias name.
Table: <leaveBlank>
Append To: ORIGINALTABLE