text:
Q: jQuery trigger callback function with vclick on jQuery Mobile I am using jQuery Mobile v1.2.0 and i'm attempting to implement a callback function with the jQuery trigger function on a click/vclick on a link.
This is my callback function and the trigger below it.
var callback = function() {
   console.log('in the callback, yo!');
   var mainContainer = $.mobile.activePage.find('.main');
   // do some stuff...
};

$.mobile.activePage.find('.new_link').trigger('click', [callback]);

What I am finding is that Callback is pulling through as undefined when I do a typeof on it. My understanding is this should be a function, which is what i'm checking for, but for some reason it does not find it.
var page = $.mobile.activePage;

page.on('vclick', '.new_link', function(e, Callback) {
    e.stopPropagation();
    e.preventDefault();

    // comes through as 'undefined'
        console.log(typeof(Callback));

    if (typeof Callback === 'function') {
        Callback();
    }

});

I can see that the code gets as far as checking for the type of Callback, but it does not have a function. I see nothing in the jQuery trigger documentation for a callback such as this, but i'm led to believe it does work.


text:
Q: How do I make this NHibernate QueryOver query return rows for empty groups The following NHibernate QueryOver query is counting the number of applications for each month, within a given date range.
However, I don't get any results for months that don't have any applications in them but I want to actually have Count = 0 returned for those months.
So how would I change the query to return a row as well for months that don't have any applications in them?
DateTimeOffset endDate = DateTimeOffset.Now;
DateTimeOffset startDate = endDate.AddMonths(-12);

var result = Session.QueryOver<Application>()
    .WhereRestrictionOn(c => c.SubmissionDate).IsBetween(startDate).And(endDate)
    .SelectList(list => list
        .Select(Projections.SqlGroupProjection(
            "YEAR(SubmissionDate) As [Year]",
            "YEAR(SubmissionDate)",
            new[] { "YEAR" },
            new IType[] { NHibernateUtil.Int32 }))
        .Select(Projections.SqlGroupProjection(
            "MONTH(SubmissionDate) As [Month]",
            "MONTH(SubmissionDate)",
            new[] { "MONTH" },
            new IType[] { NHibernateUtil.Int32 }))
        .SelectCount(x => x.Id))
    .OrderBy(Projections.SqlFunction(
        "YEAR",
        NHibernateUtil.Int32,
        Projections.Property<Application>(item => item.SubmissionDate))).Asc
    .ThenBy(Projections.SqlFunction(
        "MONTH",
        NHibernateUtil.Int32,
        Projections.Property<Application>(item => item.SubmissionDate))).Asc
    .List<object[]>()
    .Select(n => new
    {
        Year = n[0],
        Month = n[1],
        Count = (int)n[2]
    }));

A: Update: taking your idea with DateTime.AddMonths() it gets even shorter
    DateTime lastMonth = startdate;
    var unionresults = result.SelectMany(r =>
    {
        var actualDate = new DateTime(r.Year, r.Month, 1);

        var results = Enumerable.Repeat(1, Months)
            .Select(i => lastMonth.AddMonths(i))
            .TakeWhile(date => date < actualDate)
            .Select(date => new { Year = date.Year, Month = date.Month, Count = 0 })
            .Concat(new[] { r });

        lastMonth = actualDate;

        return results;
    });

Original:
i think you have to add that data after the query. here an example using linq to fill in missing months
var result = <query>;

int lastMonth = 1;
var unionresults = result.SelectMany(r =>
{
    var results = new[] { r }.AsEnumerable();

    if (lastMonth > r.Month)
    {
        results = Enumerable.Range(lastMonth, 12 - lastMonth).Select(month => new { Year = r.Year, Month = month, Count = 0 })
            .Concat(Enumerable.Range(1, r.Month).Select(month => new { Year = r.Year, Month = month, Count = 0 }))
            .Concat(results);
    }
    else if (lastMonth < r.Month)
    {
        results = Enumerable.Range(lastMonth, r.Month - lastMonth)
            .Select(month => new { Year = r.Year, Month = month, Count = 0 })
            .Concat(results);
    }

    lastMonth = r.Month + 1;
    if (lastMonth > 12)
    {
        lastMonth = 1;
    }

    return results;
});

A: It cannot be done with a few simple changes. The SQL query that is generated by your QueryOver() cannot count what does not exist in the first place.
You could probably do it with a UNION or a JOIN using a virtual/temporary table (depending on the DBMS) but that would make the query overly complicated.
I suggest adding a loop after your query that iterates through the list, copies the elements to a new list and adds any non-existing months to that new list. Something like this:
class YearMonthCount
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Count { get; set; }
}

// Start and End dates
DateTime startDate = new DateTime(2011, 9, 1);
DateTime endDate = new DateTime(2012, 6, 1);
// this would be a sample of the QueryOver() result
List<YearMonthCount> result = new List<YearMonthCount>();
result.Add(new YearMonthCount { Year = 2011, Month = 10, Count = 2 });
result.Add(new YearMonthCount { Year = 2011, Month = 11, Count = 3 });
result.Add(new YearMonthCount { Year = 2012, Month = 1, Count = 4 });
result.Add(new YearMonthCount { Year = 2012, Month = 2, Count = 1 });
result.Add(new YearMonthCount { Year = 2012, Month = 4, Count = 1 });
result.Add(new YearMonthCount { Year = 2012, Month = 5, Count = 1 });

int i = 0;
List<YearMonthCount> result2 = new List<YearMonthCount>();
// iterate through result list, add any missing entry
while (startDate <= endDate)
{
    bool addNewEntry = true;
    // check to avoid OutOfBoundsException
    if (i < result.Count)
    {
        DateTime listDate = new DateTime(result[i].Year, result[i].Month, 1);
        if (startDate == listDate)
        {
            // entry is in the QueryOver result -> add this
            result2.Add(result[i]);
            i++;
            addNewEntry = false;
        }
    }
    if (addNewEntry)
    {
        // entry is not in the QueryOver result -> add a new entry
        result2.Add(new YearMonthCount {
            Year = startDate.Year, Month = startDate.Month, Count = 0 });
    }
    startDate = startDate.AddMonths(1);
}

This could probably be done more elegantly but it gets the job done.

A: Thanks to all the answers, this is how I ended up doing it:
DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddMonths(-Months);

var result = Session.QueryOver<Application>()
    .WhereRestrictionOn(c => c.SubmissionDate).IsBetween(startDate).And(endDate)
    .SelectList(list => list
        .Select(Projections.SqlGroupProjection(
        "YEAR(SubmissionDate) As [Year]",
        "YEAR(SubmissionDate)",
        new[] { "YEAR" },
        new IType[] { NHibernateUtil.Int32 }))
    .Select(Projections.SqlGroupProjection(
        "MONTH(SubmissionDate) As [Month]",
        "MONTH(SubmissionDate)",
        new[] { "MONTH" },
        new IType[] { NHibernateUtil.Int32 }))
    .SelectCount(x => x.Id))
    .List<object[]>()
    .Select(n => new
    {
        Year = (int)n[0],
        Month = (int)n[1],
        Count = (int)n[2]
    }).ToList();

var finalResult = result
    .Union(
        Enumerable.Range(0, Months - 1).Select(n => new
        {
            Year = startDate.AddMonths(n).Year,
            Month = startDate.AddMonths(n).Month,
            Count = 0
        })
        .Where(n => !result.Any(r => r.Year == n.Year && r.Month == n.Month)))
    .OrderBy(n => n.Year).ThenBy(n => n.Month);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Splitting a column horizontally into multiple columns based on a common value in other column I have table A as my input in Oracle SQL.
Table A:
+-----------+---------+------+-----+
|    Col1   |  Col2   | Col3 | Col4|
+-----------+---------+------+-----+
|      a    |    g    |   1  | ABC |
|      b    |    h    |   2  | ABC |
|      c    |    i    |   1  | DEF |
|      d    |    j    |   2  | DEF |
|      e    |    k    |   1  | GHI |
|      f    |    l    |   2  | GHI |
+-----------+---------+------+-----+

I want to split each of column 1 and column 2 horizontally based on the value of col4. Col3 is either 1 or 2 as shown.
Output table:
+-----------+---------+------+-----+----+
|    Col5   |  Col6   | Col7 | Col8|Col9|
+-----------+---------+------+-----+----+
|      a    |    g    |   b  |  h  | ABC|
|      c    |    i    |   d  |  j  | DEF|
|      e    |    k    |   f  |  l  | GHI|
+-----------+---------+------+-----+----+

A: Oracle Setup:
CREATE TABLE table_name ( Col1, Col2, Col3, Col4 )
  SELECT 'a', 'g', 1, 'ABC' FROM DUAL UNION ALL
  SELECT 'b', 'h', 2, 'ABC' FROM DUAL UNION ALL
  SELECT 'c', 'i', 1, 'DEF' FROM DUAL UNION ALL
  SELECT 'd', 'j', 2, 'DEF' FROM DUAL UNION ALL
  SELECT 'e', 'k', 1, 'GHI' FROM DUAL UNION ALL
  SELECT 'f', 'l', 2, 'GHI' FROM DUAL;

Query:
SELECT N1_C1 AS Col5,
       N1_C2 AS Col6,
       N2_C1 AS Col7,
       N2_C2 AS Col8,
       Col4 AS Col9
FROM   table_name
PIVOT ( MAX( Col1 ) AS C1, MAX( Col2 ) AS C2
        FOR Col3 IN ( 1 AS N1, 2 AS N2 ) );

Output:
COL5 COL6 COL7 COL8 COL9
---- ---- ---- ---- ----
a    g    b    h    ABC
c    i    d    j    DEF
e    k    f    l    GHI

A: This is a straight application of a self-join:
with
     test_data (col1, col2, col3, col4) as (
       select 'a', 'g', 1, 'ABC' from dual union all
       select 'b', 'h', 2, 'ABC' from dual union all
       select 'c', 'i', 1, 'DEF' from dual union all
       select 'd', 'j', 2, 'DEF' from dual union all
       select 'e', 'k', 1, 'GHI' from dual union all
       select 'f', 'l', 2, 'GHI' from dual
     )
select td1.col1 as col5, td1.col2 as col6, td2.col1 as col7,
       td2.col2 as col8, td1.col4 as col9
from   test_data td1 inner join test_data td2 on td1.col4 = td2.col4
where  td1.col3 = 1 and td2.col3 = 2
;

COL5 COL6 COL7 COL8 COL9
---- ---- ---- ---- ----
a    g    b    h    ABC
c    i    d    j    DEF
e    k    f    l    GHI

A: I think you just want conditional aggregation:
select max(case when col3 = 1 then col1 end) as col5,
       max(case when col3 = 1 then col2 end) as col6,
       max(case when col3 = 2 then col1 end) as col7,
       max(case when col3 = 2 then col2 end) as col8,
       col4 as col9
from tablea a
group by col4;


text:
Q: Usage of Negatives in Everyday Speach: Unnecessary or Incorrect I frequently have this debate with my fiancée about whether it is as appropriate to use a negative in the following examples as it is to omit it.
I am frequently found making statements using the negative form seen below:

*

*"I wonder if they wouldn't mind taking us with them this weekend."
vs

*

*"I wonder if they would mind taking us with them this weekend."
or

*

*"I wonder if it wouldn't be possible to substitute ham for turkey in my sandwich."
vs

*

*"I wonder if it would be possible to substitute ham for turkey in my sandwich."
Question

*

*Is it appropriate to use the negative form "wouldn't" in these sentences?

Author's Viewpoint
The way I see it, it is just as appropriate to wonder if something was possible is it would be to wonder if it was not possible. One may view this as inefficient speech but I don't believe it is incorrect; grammatically or otherwise.
I would greatly appreciate it if someone could give an explanation as to why this is correct or incorrect and the reasoning behind their position.


text:
Q: enrollment profile won't install - apple configurator 1.5 - OTA - iOS7.1 I'm having a hard time in deploying iPads the OTA-way using Profile Manager 3 and Apple Configurator 1.5.
Under Profile Manager (OS X Mavericks) I have a valid trust certificate and a created enrollment profile (for the iPads).
Under Apple Configurator 1.5 I prepare an iPad using Supervised mode and added the trust certificate and a WiFi-setting. In the Supervise-tab I add the enrollment profile (created in Profile Manager). Everything works nice until the enrollment profile needs to be installed. Every time I get an error stating the profile could not be installed...
AC 1.5 has a new feature on the Prepare-tab: anchor profiles. Is it possible this has something to do with the error I get? I can't find any info on that new feature...
Extra info: I'm using the same Profile Manger to deploy iMacs and this works without problems. So the trust certificate is valid.
I've been watching so many video's demonstrating the deployment-process of iPads using AC and PM. Those installments all work. Very frustrating... I can't get it to work...
I've to state that all those video's use AC 1.4.x and the iPads have versions prior to iOS7.1.
I even have tried to enroll the iPads on a manual basis but I always end up with the same error.
Can anyone help me or give some tips in order to get my iPads enrolled?

A: I would try the following:

*

*Prepare new iPad and only use your Wi-fi Profile

*Once Supervised, add your trust certificate profile and Apply

*Finally add your enrollment profile and Apply

Even though Apple Configurator 1.5 help pages stats that it will load the Profiles in the correct order this is not necessarily the case. Try the above to see if this helps.


text:
Q: Missing artifact org.springframework.boot:spring-boot-starter-parent:jar:1.3.2.RELEASE I am getting the following error in POM.xml for spring boot dependency.

Missing artifact org.springframework.boot:spring-boot-starter-parent:jar:1.3.2.RELEASE

I tried all the solutions given in the following link but nothing solved my problem:
Maven2: Missing artifact but jars are in place

A: You're getting this error because there is no jar artifact for spring-boot-starter-parent in maven central, since spring-boot-starter-parent uses pom packaging. The reason for that is because it's intended to be used as a parent pom:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.2.RELEASE</version>
</parent>

Alternatively, you can just import the managed dependencies if that is what you intended to do:
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.3.2.RELEASE</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

You can read more about importing dependencies in the Importing Dependencies section of the Introduction to the Dependency Mechanism article.


text:
Q: Jquery calling same functions on ajaxComplete and ready? I have few functions like foundation() and jScrollPane() that I am calling on page load, but I also call them on ajaxComplete
Is there an easier way to do this except adding the same content bellow
$(document).ready(function() {

and bellow
$(document).ajaxComplete(function(){

despite the fact that the current one is working fine ?

A: You can simply move your initialization to the separate function, let say initUI and call if from both event handlers:
function initUI() {
    foundation();
    jScrollPane();
}

$(function() {
    initUI();
});

$(document).ajaxComplete(function() {
    initUI();
});

or even shorter
$(initUI);
$(document).ajaxComplete(initUI);

or the shortst version I can think of and my favorite:
$(document).on('ajaxComplete ready', initUI);


text:
Q: How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover I have created a button class in pygame and although the button itself is displaying, my text is not showing up. Also I have some conditions to change the colour when the mouse is over the button. I have achieved the desired result using hard coded values in my main function, however I want to use a class the handle my various button as I might have quite a few buttons.

Given below are some classes that I'm using

Fonts
class Fonts:
    def __init__(self, font, antialias, text, color, x, y):
        self.font = font
        self.antialias = antialias
        self.text = text
        self.color = color
        self.x = x
        self.y = y

    def draw(self, win):
        win.blit(self.font.render(self.text, self.antialias, (self.color)), (self.x, self.y))

Button
class Button:
    def __init__(self, color, x, y, width, height, text, fontsize):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text
        self.fontsize = fontsize
        self.courier_button_font = pygame.font.SysFont("Courier", self.fontsize)

    def draw(self, pos):
        x, y = pos
        text_width, text_height = self.courier_button_font.size(self.text)
        if self.x < x < self.width and self.y < y < self.height:
            pygame.draw.rect(screen, (211, 211, 211), (self.x, self.y, self.width, self.height))
            buttontext = Fonts(courier_font, True, f"{self.text}", BLACK,
                               int(self.width / 2 - text_width / 2), int(self.height / 2 - text_height / 2))
            buttontext.draw(screen)

        else:
            pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
            buttontext = Fonts(courier_font, True, f"{self.text}", BLACK,
                               (self.width / 2 - text_width / 2), (self.height / 2 - text_height / 2))
            buttontext.draw(screen)

    def isOver(self, pos):
        x, y = pos
        if self.x < x < self.width and self.y < y < self.height:
            return True
        else:
            pass

The functions where I'm using my button
FireTowerButton = Button(BLACK, 810, 200, 80, 30, "Fire Tower", 20)

def ShowTowers(mouse):
    mousex, mousey = mouse
    screen.fill((147, 207, 14))
    FireTowerButton.draw(mouse)

def main():
    run = True
    screen.fill(BLACK)
    # screen.blit(enemy1, (90, 90))
    while run:
        mouse = pygame.mouse.get_pos()
        ShowTowers(mouse)
        screen.blit(money_image, (790, 0))
        screen.blit(background_image, (0, 0))
        enemy1_spawn(wave_number)
        pygame.draw.rect(screen, BLACK, (770, 75, 30, 90))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

        clock.tick(FPS)
        pygame.display.update()

A: The condition

if self.x < x < self.width and self.y < y < self.height:

is wrong. You have to evaluate if x < self.x + self.width and y < self.y + self.height:
if self.x < x < self.x + self.width and self.y < y < self.y + self.height:
    # [...]

Anyway, I recommend to pygame.Rect / collidepoint() for the collision test:
button_rect = pygame.Rect(self.x, self.y, self.width, self.height)
if button_rect.collidepoint((x, y):
    # [...]

button_rect can be used further for drawing the rectangle:
pygame.draw.rect(screen, (211, 211, 211), button_rect)

The code can be simplified a lot by the use of an attribute rect rather than the separate attributes x, y, width, height:
class Button:
    def __init__(self, color, x, y, width, height, text, fontsize):
        self.color = color
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.fontsize = fontsize
        self.courier_button_font = pygame.font.SysFont("Courier", self.fontsize)

    def draw(self, pos):

        button_color = (211, 211, 211) if self.rect.collidepoint(pos) else self.color
        pygame.draw.rect(screen, button_color, self.rect)

        text_width, text_height = self.courier_button_font.size(self.text)
        textpos = (self.rect.centerx - text_width // 2, self.rect.centery - text_height // 2)
        buttontext = Fonts(courier_font, True, self.text, BLACK, textpos)
        buttontext.draw(screen)

    def isOver(self, pos):
        return self.rect.collidepoint(pos)


text:
Q: If $f(x)$ is in the Schwartz space then $\left| x \right|f\left( x \right)$ is bounded How to show that given a function $f(x)$ in the Schwartz space, $\left| x \right|f\left( x \right)$ is bounded
Edit: we are operating in the space $\mathbb R^n$

A: The Schwartz space is the space of rapidly decreasing functions, then if $f$ belong to Schwartz space,
$$\displaystyle\lim_{|x|\to\infty}|x|^kD^\beta f(x)< \infty \mbox{ for all } k\in \mathbb N \mbox{ and } \beta\in\mathbb{N}^n.$$
In particular, if $k=1$ and $\beta = (0,0, \cdots,0)$,
$$\displaystyle\lim_{|x|\to\infty}|x|f(x)=L< \infty.$$
This means that, given $\varepsilon>0$, exist $A>0$ such that $|x|>A$, $|x||f(x)|<\varepsilon+L$.
It remains to be seen what happens to $|x|f(x)$ when $|x|\leq A$, but of course this remains bounded as it is a continuous function in the compact $|x|\leq A.$


text:
Q: Singular points of equation We have the linear differential equation
$$9x^2y''+9xy'-(1+x)y=0.$$
I want to determine and characterize the singular points of the equation in $\mathbb{R}$.
I have done he following.
A Sturm-Liouville problem has the following form.
$$-(p(x)\phi'(x))'+q(x) \phi(x)=\lambda \phi(x), x \in [a,b].$$
If $p$ gets zero at some point, then the Sturm Liouville problem is singular.
$$(x^2 y')'=2xy'+x^2 y''$$
$$9x^2 y''=9(x^2 y')'-18 xy'$$
So, $9(x^2y')'-9xy'-(1+x)y=0$.
Can this be writtenin the form of the Sturm-Liouville problem?

A: Instead take your original equation and divide by $x$. You get:
$$9xy''+9y'-(1+1/x)y=0.$$
Now notice the first two terms are $(9xy')'$. Can you finish from here?


text:
Q: Sunspot Solr handling a boolean logic Can sunspot handle a logic having AND and OR operators?
And Sunspot is using the dismax request handler where minimum_match field is used to implement OR queries/ AND queries
Now the problem is when we need to combine AND and OR operators together. How to implement the same.
text = "Hot Air Balloon"

search = Video.solr_search, :minimum_match => text.size do
  fulltext text do
    fields :title
  end
end

I need something like HOT AND AIR OR BALLOON

A: If you have a limited number of possible text combination, you can force OR with any_of:
text1=["hot","air"]
text2=["balloon"]

search = Video.search do
    any_of do
        fulltext text1, fields: :title
        fulltext text2, fields: :title
    end
end

A: Unfortunately, any_of and all_of only works for scalar fields (strings, integers), not for fulltext search (see documentation, it says about these two methods in context of scalar fields). If you want to achieve such effect on one field, you have to create your query manually:
fulltext "Hot AND Air OR Balloon" do
    fields :title
end

It gives you a query to Solr:
 q=Hot AND Air OR Balloon&qf=title&rows=1&start=0

I didn't test it but this should also work:
"+hot +air ballon"

'+' sign means that word is mandatory. 'Balloon' can be left without any operator as the default for dismax is 'OR' operator (you can check your settings for default operator in schema.xml, solrQueryParser node).

A: As of version 2.2.0, sunspot_solr defaults to edismax parser, which supports queries using AND, OR, NOT, -, and +.
text = "HOT AND AIR OR BALLOON"

search = Video.search do
  fulltext text
end


text:
Q: Executing a Pentaho Job or Transformation when database changes Typically Pentaho transformations/jobs are executed on a schedule, but to cut down on the delay between the database (pgAdmin) update and work, is it possible to trigger a job to run when the connected database is updated/changed (Such as creating a new PO)? The database is also accessible through API. I attempted to make this happen through an event trigger that creates a Windows event which runs a tasks but I couldn't find a way for pgAdmin to create a Windows event.

A: There's not a single answer to this, I suppose you could schedule a Pentaho job looking for something else that gets informed when the database is updated, so the job runs every X seconds/minutes/hours/whatever looking for that information, if the information is not found, the job ends, if it's found, the job continues to capture the changes in the database.
Now, the information to look for to trigger the capture, is whatever you can think that you look for or that is similar to something you already have implemented. It could be simply comparing timestamps in a table, or it could be a file available in a certain location that gets moved one the database change is processed and is created anew when there's a new change in the database, you could create an API to handle these changes... there are multiple possibilities, usually you just choose something you are familiar with and create the process.


text:
Q: Found fatal error after firebase config I am not able to sort out this exception. I have googled a lot about it but didn't find anything related to this!
Note: when I remove FIRApp.configure() from appDelegate then it works fine.

Any help will be really really appreciated!!!

A: I found my answer while checking the viewDidLoad()
What I was doing wrong is that I was checking the FBSDKAccessToken before authentification (that was a silly one). So just removed the below code from the viewDidLoad()
//MARK: - VIEW DID LOAD
override func viewDidLoad() {
    super.viewDidLoad()

    if (FBSDKAccessToken.current() != nil) {
        // User is already logged in, do work such as go to next view controller.
    }

    // Do any additional setup after loading the view.
}


text:
Q: Comparing posteriors when the same data are examined with different priors I have two Bayesian regression models: both use the same data $D$ and all same specification $M$ but the different priors $p_1(\theta)$ and $p_2(\theta)$.
Can I interpret the posteriors from the two models, $p(\theta|D,M,p_1(\theta))$ and $p(\theta|D,M,p_2(\theta))$ independently and compare them? One example of comparing the results is something like "one model results in an expected loss of 1 while the other results in an expected loss of 2, so that given the different priors, the range of the expected loss is between 1 and 2." Or do I actually have to condition each model not only on its own prior but also on the prior of the other model, in order to estimate the single posterior that captures the uncertainty of the prior choice, using a hyperprior on the prior choice, such that the posterior to be estimated is $p(\theta|D,M,p(p_i(\theta)))$? My intuition is that interpreting each posterior independently means I implicitly assume that the hyperprior is a uniform distribution.
I have come across this question, which talks about estimating a posterior using all different datasets together while using the same prior. My setting is opposite, using the same dataset while using different priors.
I would appreciate your suggestions.


text:
Q: Update XML nodevalue with C++ I have an XML as below
<ROOT>
  <Device>
    <host>localhost</host>
    <Port>52000</Port>
  </Device>
  <DeviceHost>
    <Server>Server.exe</Server>
    <Port>81</Port>
  </DeviceHost>
  <Settings>
<Flag1>100</Flag1>
<Flag2>2000</Flag2>
  </Settings>
</ROOT>

How can I update the Flag1 and Flag2 to 200 and 4000 respectively without changing other values using VC++?
I have two function wrote using api MSXML.
 doc.LoadXml(Data);//for loading the xml data
 doc.Save(FilePath);//for saving the xml data

But my issue is before saving how can i update two node values

A: You would need to get the correct node by calling getElementsByTagName (which should return a NodeList containing one item) and then call put_nodeValue to write the value -- there are some MSDN samples here and here
EDIT: you should also be able to use doc.selectSingleNode("/ROOT/Flag1", &pNode) as per this MSDN article


text:
Q: OpenQA.Selenium.WebDriverException: The HTTP request to the remote WebDriver server for URL timed out after 60 seconds Here is my issue:
I am just trying to run basic tests, just to try this out, and I keep running into the exception: "OpenQA.Selenium.WebDriverException: The HTTP request to the remote WebDriver server for URL (url here) timed out after 60 seconds".
I am using the most up to date Selenium, which is 3.3.0, and the most current Selenium Support, which is also 3.3.0.
I have set up the driver:
    public static class Driver
{
    public static IWebDriver Instance { get; set; }

    public static void Initialize()
    {

        Instance = new ChromeDriver();
    }

    public static void Close()
    {
        Instance.Close();
    }
}

And I am running a basic test to login to a wordpress account, from a different class, to keep the test separated from the logic:
    [TestMethod]
    public void Test_LogIn()
    {
        WordPressLoginPage.GoTo();
        WordPressLoginPage.LoginAs("*******").WithPassword("*******").Login();
    }

And here is the methods that the test is calling:
    public class WordPressLoginPage
{
    private const string LoginUrl = "https://wordpress.com/wp-login.php";

    public static void GoTo()
    {
        Driver.Instance.Navigate().GoToUrl(LoginUrl);
        var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(5));

        wait.Until(d => d.SwitchTo().ActiveElement().GetAttribute("id") == ("user_login"));
    }

    public static LoginCommmand LoginAs(string userName)
    {
        return new LoginCommmand(userName);
    }
}

public class LoginCommmand
{
    private readonly string _userName;
    private string _password;

    public LoginCommmand(string userName)
    {
        _userName = userName;
    }

    public LoginCommmand WithPassword(string password)
    {
        _password = password;
        return this;
    }

    public void Login()
    {
        var loginInput = Driver.Instance.FindElement(By.Id("user_login"));
        loginInput.SendKeys(_userName);

        var passwordInput = Driver.Instance.FindElement(By.Id("user_pass"));
        passwordInput.SendKeys(_password);

        var loginSubmit = Driver.Instance.FindElement(By.Id("wp-submit"));
        loginSubmit.Submit();

        var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(65));

        wait.Until(d => d.SwitchTo().ActiveElement().GetAttribute("id") == ("search-component-1"));
    }
}

The exception tells me that the timeout happens here:
                loginSubmit.Submit();

and I can see that the page is still loading for probably more than two minutes after I started running it.
I have looked at other questions here regarding the same exception, but none of the answers from those seems to help here.

A: I, too, was coming across this issue in my framework, but not when individual tests were run. This was posing an issue when I was running multiple tests in parallel, and always on the .Submit() method with ChromeDriver.
In order to rectify this, I had to modify my scripts to click on a submit button instead. After this, my scripts ran fine.
For the record, I am using WebDriver and Support packages v3.4.0, ChromeDriver v2.29.0 and Chrome v58.0.3029.110.

A: I also encountered this problem. The issue occurred as a result of password pass through. The test team were all signing into their Virtual machines with the same credentials, Username: X and Password: Y. Similarity, the Virtual machine which stored the application we were testing against also had the same credentials.
However, at a particular point in time one of the developers changed Password from Y to Z. So the authentication for requesting a server response was failing in the background. You effectively need some form of an authentication service for your test project. See below for a good start point:
https://sqa.stackexchange.com/questions/2277/using-selenium-webdriver-with-windows-authentication


text:
Q: Show files and contents of files created by my app to User in iOS in Swift I am creating an OCR app where I am saving results of scans in files with this code.
let localFileName = String("file.rtf")
let text = String("Scan result text")

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let fileURL = dir.appendingPathComponent(localFileName)

    do {
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
    }
    catch {}

    do {
        let text2 = try String(contentsOf: fileURL, encoding: .utf8)

        print("Read from file \(text2)")
    }
    catch {}
}

This code is working and creating files somewhere and I am able to verify that this code is working. Now I want that files and their contents accessible to user of my app. How can I do that? Is there a way to create files in public directory?


text:
Q: Add Kinetic to ChicagoBoss App I am looking to add Kinetic to my chicago boss app, I have added the kinetic library to the deps directory within my chicago boss app. When I run the erlang shell from within the kinetic directory I have a development.config in the root of the kinetic directory that looks like the below:
[{kinetic,
    [{args, [
        % All of these values are optional
        % kinetic will get all of the context from the instance
        {region, "us-east-1"},
        {aws_access_key_id, "AKAAAAAABABABA"},
        {aws_secret_access_key, "3/Fx9987sxc352728181892838bhbjkd"},
        {iam_role, "kinetic"},

        {lhttpc_opts, [{max_connections, 5000}]}
    ]}]
}].

when I start the chicago boss app and run a kinetic command Im getting an invalid credentials error so it seems the kinetic library loaded properly but not the constants for my aws keys...Any idea how to do this in chicago boss?
Thanks!

A: Solution
Just paste your tuple {kinetic, [...]} from development.config to boss.config which contains list of configurations for your erlang applications.
More general about configuration files
In each application which depends on configuration we can see code like application:get_env(App, Key) or application:get_env(App, Key, SomeDefault). It's in fact call to application_controller which briefly manages application loading/unloading/starting/stoping and keeps informations about it. You can check how much it knows with io:format("~n~p~n",[ets:tab2list(ac_tab)]). These are mostly taken from .app files in ebin/ directory which are mostly generated by rebar from app.src in src/ during compilation.
The most interesting key for us in .app.src is env which should contain default configuration for application which will be loaded as first and then some of those values will be overridden by your system config which is now boss.config.
When you were playing with kinetic in it's development environment you were starting it by erl -pa ebin -pa deps/*/ebin -s inets -s crypto -s ssl -s lhttpc -config development -s kinetic with -config you passed your system config and overridde default environment values which in this case are not specified and defaults are resolved after application is started in kinetic_config.erl but look at lager.app.src and compare it to one within your boss.config. Now you see how to tweak it. Let's start with colouring logs ;)
From official documentation: Configuring an Application and config


text:
Q: Frobenius splitting of affine flag varieties NOTE: I am very much not an expert on affine Kac-Moody groups or ind-varieties, so the following may be vague.
The first question is: Has anyone developed a theory of Frobenius splitting for ind-varieties in positive characteristic? (This might be very easy for all I know). Following from that, my main question is: If there is a reasonable theory of Frobenius splitting of ind-varieties, has anyone thought about whether affine flag varieties or affine Grassmannians corresponding to semisimple algebraic groups in positive characteristic are Frobenius split?

A: If you have a strict ind-scheme (inductive limit of schemes with maps closed imersions), for example affine flag varieties as a limit of schubert cells, then you can ask that all these varieties are compatably Frobenius split, so the notion of a Frobenius splitting makes sense.
Then you can ask if the affine flag variety admits a Frobenius splitting. The asnwer is yes. I learnt this under mild conditions from a course of Xinwen Zhu, from which the original reference appears to be Faltings' paper "Algebraic loop groups and moduli spaces of bundles". Here the affine flag variety is defined in a particular way, and of course if you want to define it in a different way (eg using Kac-Moody) groups, then you must do some work to show that definitions agree.
This result is harder than in finite type since you don't have the smooth Schubert cell associated to the long word as a crutch to get you started.


text:
Q: PHP Curl upload file with file browse button I want to remote upload my file into a server that accept uploads
using curl , but without typing the full file path every time with "@" symbol
can i make a browse button to select files then proceed to curl upload
this is my code ::
$post = array("file_box"=>"@/path/to/myfile.jpg");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://remote-site");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$output = curl_exec($ch);
curl_close($ch);

return $output;

just want to change "@/path/to/myfile.jpg" by browse button which passes it's value to php variable
I want to change this  [[ $post = array("file_box"=>"@/path/to/myfile.jpg"); ]]
to something like that
[[ $post = array("file_box"=>"@".$variable_contains_file_path_from_browse_button); ]]
to prevent upload the file to middle server(host this script) in the temp path just from the client to the remote server directly
is there any solutions around this
thanks all for any help.

A: There are several questions in SO which deals with this
here are some of the links
uploading files using curl
Curl php file upload
And also google search strategy is http://bit.ly/PMUf2b
But still since you are asking for a browse button upload from front end, here is the complete set along with the tutor link
you can follow the tutor here which has both front end and php code
upload using curl
Here is the php code
    $request_url = 'http://www.example.com/test.php';
    $post_params['name'] = urlencode('Test User');
    $post_params['file'] = '@'.'demo/testfile.txt';
    $post_params['submit'] = urlencode('submit');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
    $result = curl_exec($ch);
    curl_close($ch);

here is the html code
<form method="post" action="test.php" enctype="multipart/form-data">
    <input type="text" name="name" value="Test User" />
    <input type="file" name="file" />
    <input type="submit" name="submit" value="submit" />
</form>


text:
Q: How to modify an element when another element has an .active class with CSS? How to select the .field-wrapper element when the .list-nav element has the .active class?
The objective is that .field-wrapper z-index = -1 only with CSS.

Chat GPT proposed two solutions but neither works
    nav .nav-list.active + .main .field-wrapper {
    z-index: -1;
}

and
    .nav-list.active ~ .field-wrapper {
    z-index: -1;
}


text:
Q: I want to create tables in Django database by which may have dynamic fields by uploading a excel or csv sheet from a web interface
*

*How can we create a DB table in db using django framework by
uploading a unique CSV/excel files
In front end there will be an upload button for uploading a CSV/excel and once user clicks submit a table should be created based on the fields in file uploaded
Help me on django dynamic models (if it can be implemented)
note: the columns may contain  fields of different datatype like int,CharField

A: You can use Django import-export feature, or ImportExportModelAdmin.


text:
Q: How to get generic's class Class Model<T>{

   private T t;

   .....

   private void someMethod(){
       //now t is null
       Class c = t.getClass();
   }

   .....

}

Of course it throws NPE.
Class c = t.getClass();

What syntax should i use to get class of T if my instance is null?
Is it possible?

A: It's not possible due to type erasure.
There is the following workaround:
class Model<T> {

    private T t;
    private Class<T> tag;

    public Model(Class<T> tag) {
       this.tag = tag;
    }

    private void someMethod(){
       // use tag
    }
}

A: You can do this with reflection:
Field f = this.getClass().getField("t");
Class tc = f.getType();

A: You can do it without passing in the class:
class Model<T> {
  Class<T> c = (Class<T>) DAOUtil.getTypeArguments(Model.class, this.getClass()).get(0);
}

You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java
For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860


text:
Q: OpenCV: Add text to image and get the bounding box of each letter I read the documentation of the OpenCV function putText(). I could not find there any parameter or returned value that tells where each printed letter is located.
Is there some OpenCV API that gives this data while adding text to images, or maybe in some different library?

A: You can calculate the width and height of the text you're putting on image by:
cv::Size textSize = cv::getTextSize(text, fontFace, fontScale, thickness, &baseline);

Check for example here.

A: Take a look at my answer, the code may be interesting for your purpose: Detect space between text (OpenCV, Python)
It is used to recognize handwriting text and do ROI on given image.


text:
Q: Why doesn't Qemu boot my custom linux kernel? I was watching this tutorial https://www.youtube.com/watch?v=awik6Iittu4 on building our custom linux os.
The problem is that when I do qemu-system-x86_64 -hda image I get this output

And then it instantly reboots, in loop. What am I doing wrong? Is the tutorial old?
Note that I didn't modify even one line of the kernel, I only did what the tutorial did.
I did this stuff on an Ubuntu x64 machine in VMware, and my main machine is Windows 10.
What i did:
1 - sudo apt install build-essential musl-tools grub-pc-bin
2 - git clone https://github.com/MichielDerhaeg/build-linux
3 - cd build-linux/    (where the git cloned)
4 - git submodule init && git submodule update
5 - make -j4 image
6 - i said the command above


text:
Q: RxJS Observable - subscribe once every time a condition met Observables are new to me, so I'm not even sure it's possible (but I would guess it is). What I would like to achieve is having an observable (Angular 2 http.get call), and subscribe to it once whenever a variable is changed. An example flow would be something like this:
let x = false;
// ... somewhere later I change "x" to true
subscribe gets called once, x => false
// stuffs happening, 10 minutes later x => true again
subscribe gets called once, x => false

The bigger concept is that I would have a UserService and in the constructor I would subscribe to /api/user/me once, whenever there is a token change in the localStorage. Is this a valid use case, and if so, how can I do it with observables?

A: Something like this should do the trick:
// Observable that on subscription will result in an api call. It would
// naturaly have another type in an acaual use case.
let apiCallObservable : Rx.Observable< { someResult: any }>;

let localStorageChangedObservable = new Rx.Subject<boolean>()

localStorageChangedObservable
    // only care about local storage change if not null
    // This is just an example the type of localStorageChangedObservable
    // could be anything you want, and you could check anything you want in the
    // "where"
    .where(v => v != null)
    .selectMany(() =>
        // Take one is to make sure we terminate apiCallObservable after recieving
        // one result from it.
        apiCallObservable.take(1))
    .subscribe(
        (result: { someResult: any}) => {

            // here we would have the result from the call to apiCallObservable
        });

// To execute the chain abouve we would pass values to the localStorageChangedObservable
// subject like this:

localStorageChangedObservable.onNext(true); // results in api call and result in subscribe
localStorageChangedObservable.onNext(null); // results in nothing.
localStorageChangedObservable.onNext(false); // results in api call and result in subscribe

So basically pass something to localStorageChangedObservable.onNext(...) when you want to trigger an api call.


text:
Q: Configuring Apache to return 404 with every request I have an Apache 2 running on a Linux box. Currently there at only 2 webpages in different paths:
/website1/site
/website2/site
I set apache to not server directory listings and I set the error documents to show a blank page when hitting something that doesn't exit.
I was wondering, is there any way force Apache to always return 404 or other error every time something other than those two websites are hit?
We are experiencing a lot of probes from proxy list sites and other places and all I want to do is just send an error every time they try / or any other path, without serving anything, not error pages, blank pages, etc.
helps is appreciated.

A: You could add a few mod_rewrite directives to throw them for a loop:
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^1\.2\.3\.4$
    RewriteRule .* http://%{REMOTE_ADDR} [R=301]
</IfModule>

(where 1\.2\.3\.4 is a regexp matching your server's IP address(es) ...)


text:
Q: Why is the return type of the "ceil()" function "double" instead of some integer type? I've just implemented a line of code, where two numbers need to be divided and the result needs to be rounded up to the next integer number. I started very naïvely:
i_quotient = ceil(a/b);

As the numbers a and b are both integer numbers, this did not work: the division gets executed as an integer division, which is rounding down by default, so I need to force the division to be a floating point operation:
i_quotient = ceil((double) a / b);

Now this seems to work, but it leaves a warning saying that I am trying to assign a double to an integer, and indeed, following the header file "math.h" the return type of the ceil() function is "double", and now I'm lost: what's the sense of a rounding function to return a double? Can anybody enlighten me about this?

A: ceil() takes a double as an argument. So, if it were to return an integer, what integer type would you choose that can still represent its ceiled value?
Whatever may be the type, it should be able to represent all possible double values.
The integer type that can hold the highest possible value is uintmax_t.
But that doesn't guarantee it can hold all double values even in some implementations it can.
So, it makes sense to return a double value for ceil(). If an integer value is needed, then the caller can always cast it to the desired integer type.

A: OP starts with two integers a,b and questions why a function double ceil(double) that takes a double, does not return some integer type.
Most floating-point math functions take floating point arguments and return the same type.
A  big reason double ceil(double) does not return an integer type is because that limited functionality is rarely needed.  Integer types have (or almost always have) a more limited range that double.  ceil(DBL_MAX) is not expected to fit in an integer type.

There is little need to use double math to solve an integer problem.
If code needs to divide integers and round up the quotient, use the following.  Ref:@mch
i_quotient = (a + b - 1) / b;

The above will handle most of OP's cases when a >= 0 and b > 0.  Other considerations are needed when a or b are negative or if a + b - 1 may overflow.

A: A double has a range that can be greater than any integer type.
Returning double is the only way to ensure that the result type has a range that can handle all possible input.

A: Because why should it? Converting betwen int and double takes time. This overhead can become significant. If you want to convert a double to int do so explicitly:
i_quotient = (int)ceil((double) a / b);

Check this answer if you want to know more about this latency. You have to consider that C is quit old and achievable performance was one of the top priorities. But even C# and other modern languages usually return a floating value for ceil just for consistency.

A: Leaving technical discussions apart, couldn't be simply for consistency?
If the function takes a double it should return a result of the same type, if there's no particular reasons to return a different type.
It's up to the user to transform it to an integer if he needs to.
After all you may be working only with doubles in your application.
Although ceil means to round up to the next whole number , it doesn't mean strictly that it is an integer, it's obvious that an integer is a whole number but that doesn't have to prejudice our mind.


text:
Q: Focusout function negates submit on click I have an animating search bar that is meant to hide when the user clicks outside of it. This however causes a direct click on the submit button next to it to be ignored. How can I go around this?
HTML,
    <form role="search" id="searchform" method="get" action="/">

      <input type="submit" value="">
      <input id="search" type="text" name="s" value="">
    </form>

CSS (SCSS),
form {
            margin: 0;
            input {
                float: right;
            }
            input[type="text"] {
                height: 3rem;
                margin: 5px 0 0 0;
                padding: 0;
                width: 0;
                @include transition(all, .2s, ease-in-out);
                &.active {
                    width: 80%;
                    padding: .5rem 1rem;
                }
            }
            input[type="submit"] {
                width: 4rem;
                background-color: transparent;
            }
        }
    a, i {
        position: absolute;
        line-height: 4rem;
        width: 4rem;
        height: 4rem;
        text-align: center;
        top: 0;
        right: 0;
    }
    i {
        pointer-events: none;
        color: $light-grey;
        font-size: 1.6rem;
        z-index: 30;
        padding: 3px 0 0 0;
        @include transition(color, .2s, ease);
    }

JS,
  $('#search').focusout(function() {
    $(this).removeClass('active');
  });

Also tried using blur() instead of focusout(), same result.

Edit: Added some additional code. I'm having an icon and invisible link button overlaying the submit button to prevent it from submitting at once - I want to animate and display the search box first. After that box is revealed and the user types in something, this is when I run into trouble reaching the submit event. Now it requires two clicks, one to first close the box, then a second to trigger the button.

A: I know this is an old question, but it happens that I had the same issue and resolved it other way, so maybe the following code could be handy to someone else:
$('#text_input_id').blur(function(event){

    //event.relatedTarget gets the object that triggered the blur event(or "focus
    // out" event), in this case if it is a submit input, ignore the blur event.
    if($(event.relatedTarget).prop('type') === 'submit'){
        event.preventDefault();
    }
    else {
        //Do whatever you want when focusing out. For instance:
        $('#search').css('display', 'none');
    }

});

¿Why this works?
The focusout or blur events (see the difference here) do prevent the submit button to work properly, because some how it overrides the submit event, which then causes the odd behavior of clicking twice to submit. The trick here is to use the event.relatedTarget, which gets the object that triggered the blur event. In this case, if it is any submit button <input type="submit" value="Search">), then call event.preventDefault() to workaround the issue.

A: There are a few issues here, and maybe you can clarify your reasoning.
Is there are reason you're toggling the class active instead of using the :focus pseudo class for styling? This still allows keyboard usage, and you could bind something to that toggle link like this:
$('#search-toggle').click(function(){
    $('#search').focus();
});

https://developer.mozilla.org/en-US/docs/Web/CSS/:focus
If you don't want it to shrink down, you could apply the style when anything in that form is focused via css (note that I use a recommend a search input type instead of text):
form *:focus ~ input[type="search"] {
     width: 80%;
     padding: .5rem 1rem;
}

A: If you want to prevent the submit button from being pushed when the user hasn't entered anything in the search box, you can disable it by default, and then enable it once the user types something into the search input (this would allow you to not cover up the submit button with your anchor tag):
Submit button HTML:
<input type="submit" value="" disabled>

jQuery to enable the submit button only after keyup event in the search box:
$(document).ready(function () {

    $("#search").on("keyup", function () {
        if ($(this).val() != "") $(":submit").prop("disabled", false);
    });

});


text:
Q: Prevent updateUIView() from being called in UIRepresentableView? I think I need to change a boolean in a UIRepresentableView before removing it from the ContentView but can't find a way, since I can't mutate the struct properties.
Why do I need that? Because I need to prevent updateUIView() from being called one last time before the view being released.
So probably this is an XY problem... anyway, I'm lost.

I have a model like this:
class PlayerModel: NSObject, ObservableObject {

    @Published var lottie: [LottieView]

Where LottieView is this:
struct LottieView: UIViewRepresentable {
    var name: String
    var loopMode: LottieLoopMode = .playOnce

    func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
        let view = UIView()
        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {
        uiView.subviews.forEach({ sub in
            sub.removeFromSuperview()
        })

        let animationView = AnimationView()
        animationView.translatesAutoresizingMaskIntoConstraints = false
        uiView.addSubview(animationView)

        NSLayoutConstraint.activate([
            animationView.widthAnchor.constraint(equalTo: uiView.widthAnchor),
            animationView.heightAnchor.constraint(equalTo: uiView.heightAnchor)
        ])

        animationView.animation = Animation.named(name, animationCache: LRUAnimationCache.sharedCache)
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = loopMode
        animationView.play()
    }
}

In my ContentView I only display a LottieView if there's a recent one in the published array:
struct ContentView: View {

    @ObservedObject var model: PlayerModel

    var body: some View {
        NavigationView {
            VStack {
                // ...

                if let lottie = model.lottie.last {
                    lottie
                }

                // ...
            }
        }
    }

}

Now this works ok, but when in the model I remove the last LottieView from the published array, the updateUIView() func is called one last time by SwiftUI, resulting in the animation being recreated again just before the LottieView is removed from the view, resulting in a visible flicker.
So I thought I'd add a boolean that I could update just before removing the last LottieView from the published array, and do an if/else in the updateUIView(), but... is this even possible? I can't find a way.
Ideally I would just have the animation view created in makeUIView() and nothing done in updateUIView() but this is not possible, I need to remove the subviews first, otherwise the previous shown animation is not replaced by the new one.

A: While I would still love to have someone give me a proper solution to my issue, or  tell me an alternative way of doing things, I found a workaround.
In the model, I was previously emptying the published array by doing
lottie = []

But if instead we do this:
lottie.removeAll()

We see no flicker anymore (however updateView() is still called!!).


text:
Q: SDWebImage Downloading Multiple Images (iOS) For my iPhone app, I am trying to use SDWebImage to download multiple images from a list of links. The problem is after the images are downloaded, I don't know how to find out which image was downloaded from what link.
For example, I have a list of 25 image links. I use the following code for each link, where downloader is an instance of SDWebImageDownloader:
downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self];

The above code starts the downloading process and once the image is downloaded, the following code is called:
- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithImage:(UIImage *)image

From the above method, I can see the list of all my 25 images, but they are not in order (obviously). I was wondering if there is a way to keep a track of images and their corresponding image links. Any suggestions?

A: SDWebImageDownloader has an URL property, which is the corresponding image link:
- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithImage:(UIImage *)image
{
    NSString* url = downloader.url;
}


text:
Q: Prevent Guests in same vSwitch talking to one another Long story short.   I would like to prevent guests in the same vSwitch from communicating to one another.  I am at a loss as to how to make this happen.  Any ideas please?
I have been reading on vShield, but I don't this this helps?
I have Standard, with Support Subscription if that helps.
Update Edits as requested:
They do not need connectivity to the physical network, but they need to be on the same vSwitch. And on the same Subnet
To add some extra context, this will form part of a multi site HA solution, using Veeam Backup and Recovery. With 2 vSwitch in one site, and 2 vSwitch in remove site. And in either site, the connectivity is reversed.

A: Here are a few ways you could do it:

*

*Create a separate vSwitch for each group of virtual machines that DO need to communicate with each other. Virtual machines on different vSwitches won't be able to communicate with each other.

*Create separate port groups on the same vSwitch and assign each port group a different VLAN ID. Then connect the relevant virtual machines to the appropriate port groups.
NOTE: There are other design considerations if these virtual machines need connectivity to the physical network, but you didn't specify that in your question (at the time of this answer).
EDIT: Based on your comment, you could create a separate port group on a single vSwitch, using a different VLAN ID for each port group. You would then connect the relevant virtual machines to the appropriate port groups. You'll need to connect the physical switch ports as trunk/tagged ports (Cisco/HP).


text:
Q: Mysql query only showing rows affected and not the table The following query is only returning rows affected and not the table.
SET @sql = NULL;
 SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
  'max(case when department = ''',
  department,
  ''' then questionValue end) ',
  department
)
) INTO @sql
FROM
jos_survey_submission_values;
SET @sql = CONCAT('SELECT  questionNumber AS "", category AS Category, dimension AS Dimension, subDimension AS `Sub-Dimension`, ', @sql, '
              FROM jos_survey_submission_values
              WHERE company_id = "180"
               GROUP BY category, dimension, subDimension, questionNumber
               ORDER BY questionNumber ASC');

PREPARE stmt FROM @sql;
EXECUTE stmt;

What can I do to get it to return the table?


text:
Q: Find Children In Parent in Jquery I am working with Visual Studio 2010 C# and jQuery. On my web form I have one main div(divMain). Inside this div some children are created dynamically namely divValue0,divValue1....divValuen. I want to access each div whose id starts with divValue.

A: Assuming I've understood your question correctly, you want to find all div elements whose id starts with "divValue" that are children of divMain. If that's right then something like this should work:
var yourDivs = $("#divMain").children("div[id^='divValue']");

It uses an "attribute starts-with" selector to match any element with an id value starting with "divValue". The children method returns all of the children of the selected element, but if you wanted descendants further down the DOM, you'll have to use find instead.


text:
Q: "Is there any news" or "are there any news"? Which is better? Which is grammatically correct?

*

*Is there any news about my candidacy?

*Are there any news about my candidacy?

A: I don't agree with the answer provided by @vickyace. News is uncountable and cannot be countable. So to answer your question, the first is the correct example.


text:
Q: What is the grammatical logic and meaning of "going to" in the sentence "we are going to need them"? Even though I am a native English speaker, I am old and have forgotten my English grammar lessons. Need a little help to understand why I would write a sentence that way using the words going to even though I've always done it that way.

A: It's a form of the future tense in English.
ThoughtCo.com: "expressing future tense with 'will' and 'going to'
As to why "going to" is used as future tense in English, I'm going to pass on that one. Maybe someone else will chime in.


text:
Q: FTP server not sending data to proxy in Python with sockets I'm building a proxy in Python between a ftp client and a ftp server. All the control phase and data phase is well done (currently on active mode), but when I send the request (LIST, for example), server does not send the information back. I don't know what is causing this fault...
Here is the Wireshark capture:

And the corresponding code:
print(f"Waiting for a message from the server to the PORT message")
answer = fw_proxy_server.recv(BUFFER_FTP)
print(answer) # 200 PORT command successful
fw_proxy_client.send(answer) # forward to client

# Create the socket to listen on 192.168.30.80:port (IP_PROXY:port)
server_socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket2.setsockopt(socket.SOL_SOCKET, 25, str(INTERFACE_PROXY_SERVER + '\0').encode('utf-8'))
server_socket2.bind((IP_PROXY, port))
server_socket2.listen()

print(f"Waiting for a message from the client")
message = fw_proxy_client.recv(BUFFER_FTP) # REQUEST: LIST

print(f"Forwarding message from the server")
message = send(fw_proxy_server, "LIST") # REQUEST: LIST (sent to port 21)

# Accept an incoming connection from the Server with data

server_socket2, data_address = server_socket2.accept() # HERE PROGRAM HANG
print(f"Data connection from {data_address} has been established!")

print(f"Waiting for a message from the data from server")
message = fw_proxy_server.recv(BUFFER_FTP) # never executed

The IPs are the following:
Client: 192.168.40.50
Proxy-client: 192.168.40.80
Proxy-server: 192.168.30.80
Server: 192.168.30.90
Thanks in advance.
EDIT:
Changed order of listening to port, so that the port is listened before sending the PORT command and the LIST request. Same result, connection refused:
start = str(message).find("(")
end = str(message).find(")")
tuple = str(message)[start+1:end].split(',')
port = int(tuple[4])*256 + int(list(filter(str.isdigit, tuple[5]))[0])
#Create the socket to listen on 192.168.40.80:port
server_socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket2.setsockopt(socket.SOL_SOCKET, 25, str(INTERFACE_PROXY_SERVER + '\0').encode('utf-8'))
server_socket2.bind(("192.168.40.80", port)) # With 192.168.30.80 it doesn't work too
server_socket2.listen()

answer = send(fw_proxy_server, "PORT 192,168,30,80," + tuple[4] + "," + tuple[5])
print(f"Waiting for a message from the server to the PORT message")
print(answer) # 200 PORT command successful
fw_proxy_client.send(answer)

#Create the socket to forward the data to the server

print(f"Waiting for a request from the client") # REQUEST: LIST
message = fw_proxy_client.recv(BUFFER_FTP)
print(message)

fw_proxy_server.send(message)
print(f"Waiting for an answer from the server") # Response 425: Unable to build data connection: Connection refused
answer = fw_proxy_server.recv(BUFFER_FTP)
print(answer)

#Accept an incoming connection from the Client
server_socket2, data_address = server_socket2.accept() #Program hang
print(f"Data connection from {data_address} has been established!")

print(f"Waiting for a message from the server")
print(answer)

A: From the Wireshark capture session, it sounds like the port you are sending to the FTP server and the port you are actually listening for data-connection on the proxy-server are not same hence FTP server reporting connection refused. Make sure the port server_socket2 is binding i.e, port is equal to 256 * tuple[4] + tuple[5]. I believe the socket_option 25 refers to SO_BINDTODEVICE, in that case when you are binding the socket using bind() then there is no need to explicitly bind the socket to interface (in general use case). Can you remove that line and check if it is still working ? It will be a learning for me too ! Thanks.


text:
Q: How can I share GoogleDrive's file/folder using JavaScript API? Using GoogleDrive JavaScript API I was being able to develop a sharing file/folder with another Gmail user.
I'm using this example but I get the follwing error:

Uncaught Reference Error: 'drive' is not defined.

A screenshot of the error is here.
Do you have any solution to share file/folder using GoogleDrive JavaScript API?

A: Based from this related post, for "shared" to be true, each file permission needs to specifies a role, type, and email address or domain. As an owner of the file (Docs, Sheets, etc.), you will need to provide the appropriate permission to be set to.
Additional reference: make folder shared google drive api v3?


text:
Q: Query failed: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected dbConn.php
<?php
function getConnection()
{
    try {
        $connection = new PDO("mysql:host=localhost;*****=username", "*****", "*****");
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $connection;
    } catch (Exception $e) {
        throw new Exception("Connection error " . $e->getMessage(), 0, $e);
    }
}

?>

Admin page:
<?php
try {
    require_once("dbconn.php");
    $dbConn = getConnection();

    $sqlQuery = "SELECT eventID, eventTitle, eventDescription, NE_events.venueID, venueName, location, NE_events.catID, catDesc, eventStartDate, eventEndDate, eventPrice
            FROM NE_events
            INNER JOIN NE_category
            ON NE_category.catID = NE_events.catID
            INNER JOIN NE_venue
            ON NE_venue.venueID = NE_events.venueID
            ORDER BY eventTitle";
    $queryResult = $dbConn->query($sqlQuery);

    while ($rowObj = $queryResult->fetchObject()) {
        echo "
\n
        {$rowObj->eventTitle}\n
        {$rowObj->catDesc}\n
        {$rowObj->venueName}\n
        ($rowObj->eventStartDate)\n
        ($rowObj->eventEndDate)\n
        ($rowObj->eventPrice)

\n";
    }
} catch (Exception $e) {
    echo "
Query failed: " . $e->getMessage() . "
\n";
}
?>

I'm trying to retrieve data from MySQL database, but for some reason I get an error saying:

Query failed: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.

A: As Nigel Ren mentioned you should specify the database name in a DSN string (1st param of PDO constructor).
$connection = new PDO("mysql:host=localhost;dbname=yourDbName", "login", "password");

The error you get clearly states that you don't have DB selected.

A: $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
write this line correctly


text:
Q: I have a website into cackephp v1.3.14 and i want to upgrade into cakephp v3.x Can I easily upgrade cake PHP v1.3.14 to v3.x ? If it is possible, then what are the changes after upgrading? Give me the best way to how can upgrade it?

A: Since cakephp 1.3 to cakephp 3 there is lot of changes in framework so i would suggest first update to cakephp 2.x and if its ok then continue with it else from 2.x upgrade to 3.x
For updating follow the steps:
Download the cakephp 2.x

*

*Then add all your controllers from 1.3 to 2.x, models and views.

*Then run the code if and fix the errors like functions that are not supported in controller and view.

*Then optimise the code according the best usage of the latest code.

Here is link for learning cakephp few concepts:
https://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html
http://www.onenightstudy.com/search/label/CakePhp


text:
Q: Why does this kind of MDX Query always changed? I'm currently dealing with FoodMart DB in Mondrian.
Whenever I'm executing query which has this element:
...[Time].[Quarter].[Q1]...
...[Time].[Quarter].[Q2]...
...

After parsing the query, Mondrian always changes that query into this form:
...[Time].[1997].[Q1]...
...[Time].[1997].[Q2]...
...

Generally, both forms yield the same result. The problem is I have to keep the level from that query ([Quarter]) in order to achieve all its member later. What I mean is that I need to execute this kind of query:
...[Time].[Quarter].Members...

which apparently its result can not be achieved from this form:
...[Time].[1997].Members...

Does anyone know how to set Mondrian to keep my original query form? Or are there any way to get the level name ([Quarter]) from the given level ([1997]) ?
Thanks a lot!


text:
Q: UTF-8 encoding in InputStreamReader I'm using openCSV to generate CSV file and OutputStreamWriter to attach that file to http response.
The biggest issue here is that for example '€' in downloaded CSV file is '€'. Obviously the encoding is wrong but I've set it to 'UTF-8'. Additionally I've set the encoding in pom.xml to 'UTF-8'.
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
response.setContentType(BulkListExportConstants.CSV_CONTENT_TYPE);
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");

List<String[]> result = iSmsExportService.csvExport(columnNames);
CSVWriter csvWriter = new CSVWriter(osw, BulkListSharedConstants.CSV_SEPARATOR);
csvWriter.writeAll(result);
csvWriter.flush();
csvWriter.close();
osw.flush();
osw.close();

Any suggestions?

A: as McDowell said, your encoding is done correctly, but if you want to read this csv from any BOM aware products (like Excel for example) you need to insert the BOM into the beginning of the file/stream
So you could change the response:
OutputStream os = response.getOutputStream();
os.write(239); //0xEF
os.write(187); //0xBB
os.write(191); //0xBF

// then write your data normally
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

This will insert the BOM into the beginning of the file.


text:
Q: Loop through multiple workbooks not working I have a code that loops through all the workbooks in a user selected folder and fetch the column names from all the sheets. Note that there may be multiple column names in a single sheet tab. So, the code searches in first column that contains "Product" in it and copies the entire row until last non empty column and pastes them in ThisWorkbook.Sheets("Column Names").
This code opens the workbook, searches for the text "Product" in each sheet tab, copies the column names and closes the workbook without saving.
I am using the below code to fetch the column names. It works completely fine for only 1 workbook and when the code opens the second workbook, it throws error in the line highlighted.
Anybody please help me to identify where I have done wrong.
Option Explicit
Dim i, ShtCnt As Integer
Dim ws, CurSht As Excel.Worksheet
Dim cell As Range
Dim EmpCell As Integer
Dim NonEmpCell As Integer
Dim lRow As Long
Dim ThiswblRow, ThiswblRow2 As Long
Dim lCol As Long
Dim FldrPicker As FileDialog
Dim wb As Workbook
Dim myExtension, filepath, filepathSrc, filepathDest, fileSaveName, filename, Template, TempLocPath, ShtNameRaw, ShtNameTemp, SlrName As String

'Step 1

Public Sub LoopAllExcelFilesInAFolder()

'Optimize Macro Speed
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        filepath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  filepath = filepath
  If filepath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  TempLocPath = Dir(filepath & myExtension)

'Loop through each Excel file in folder
  Do While TempLocPath <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(filename:=filepath & TempLocPath)

    filename = ActiveWorkbook.Name
    Workbooks(filename).Activate

'Call Find_Product_in_each_sheet_loop

For ShtCnt = 1 To ActiveWorkbook.Worksheets.Count
'On Error Resume Next
Set ws = ActiveWorkbook.Worksheets(ShtCnt)
lRow = ws.Range("A100000").End(xlUp).Row     -->  Getting error in this line

'Call Find_Product(ws)

For i = 1 To lRow

    lRow = ws.Range("A100000").End(xlUp).Row

    If InStr(ws.Cells(i, 1), "Product") <> 0 Or InStr(ws.Cells(i, 1), "Model") <> 0 Then

    ThiswblRow = ThisWorkbook.Sheets("Column Names").Range("B100000").End(xlUp).Row + 1
'Workbook Name
    ThisWorkbook.Sheets("Column names").Range("B" & ThiswblRow) = ActiveWorkbook.Name
    ws.Activate
'Sheet Name
    ThisWorkbook.Sheets("Column names").Range("C" & ThiswblRow) = ActiveSheet.Name

    lCol = ws.Cells(i, Columns.Count).End(xlToLeft).Column

    ws.Range(Cells(i, 1), Cells(i, lCol)).Select

'Column Names

    ws.Range(Cells(i, 1), Cells(i, lCol)).Copy ThisWorkbook.Sheets("Column Names").Range("D" & ThiswblRow)

End If

Next i

ThiswblRow = Empty
lRow = Empty

'Next j

Next ShtCnt

    ThiswblRow = ThisWorkbook.Sheets("Column Names").Range("A100000").End(xlUp).Row + 1
    ThiswblRow2 = ThisWorkbook.Sheets("Column Names").Range("B100000").End(xlUp).Row

'Partner Name

    Workbooks(filename).Sheets("Request Form").Activate
    Workbooks(filename).Sheets("Request Form").Columns(1).Select
    With Selection
    .Find(What:="Partner Name", After:=ActiveCell, LookIn:= _
            xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
            xlNext, MatchCase:=False, SearchFormat:=False).Activate
        ActiveCell.Offset(0, 1).Copy ThisWorkbook.Sheets("Column Names").Range("A" & ThiswblRow & ":A" & ThiswblRow2)
    End With

lRow = Empty
ThiswblRow = Empty
ThiswblRow2 = Empty

'Close Workbook without saving
      wb.Close SaveChanges:=False

'Get next file name
      TempLocPath = Dir
  Loop

ThisWorkbook.Sheets("Column Names").UsedRange.WrapText = False

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

MsgBox ("Done")

End Sub

A: Most likely you have an Excel file in the old format (*.xls). In the old format, sheets had only 64k rows, so using something like A100000 fails because there is simply no such cell.
Don't use such magic numbers. The total number of rows in a sheet is ws.rows.count, and
that works no matter how many rows a sheet has. Change the line to
lRow = ws.Cells(ws.rows.count, 1).End(xlUp).Row

or, if you prefer
lRow = ws.Range('A' & ws.rows.count).End(xlUp).Row

P.S.: You should indent your code, the way you presented it is nearly unreadable. I was about to give because it is nearly impossible to tell where loops start and end.


text:
Q: jQuery Convert string to url replacing brackets slashes and dash Can anyone help me with replacing this string into desired url link please?
1080 Center - (previously) Old/New

to
1080-center-previously-old-new

A: This will solve your single example (regex's shamelessly stolen from Rails' parameterize method:
"1080 Center - (previously)".toLowerCase().replace(/[^a-z0-9\-_]+/g, "-").replace(/-{2,}/, "-").replace(/^-|-$/, '');

But it's hard to come up with a generalized solution without more example input and output.
That being said, you'll probably have an easier time if you come up with a precise specification for what you want to accomplish. For instance, at first it looks like the rule might be "Replace all non-word characters with dashes", but that would turn Center - (previously) into center----previously- which is not what you want. On the other hand, you can't just strip out whitespace, as that will lose the separation between 1080 and Center.

A: To achieve this you can replace any non-word character with a - using a Regular Expression. Try this:

var input = '1080 Center - (previously) Old/New';
var output = input.replace(/\W+/g, '-').toLowerCase();

console.log(output);


text:
Q: How can i put a values in a response of cmd command with subprocess in python I'm trying to automatize a CMD command  process in windows
I try this:
import subprocess
cmd = 'net use * /delete'
p1 = subprocess.Popen(cmd,shell=True)
p1.wait()
I have this response:
Continuing will cancel the connections.
Do you want to continue this operation? (Y/N) [N]:
I want to put a Y for automatize the process


text:
Q: How to call a method that creates a JFileChooser dialog from a different class I have been trying to call a method in another class that instantiates a new JFileChooser dialog. Everything seems to work ok except that the APPROVE_OPTION code
        int userSelection = chooser.showSaveDialog(chooser);
    if (userSelection == JFileChooser.APPROVE_OPTION) {
        System.out.println("File saved " + chooser.getSelectedFile().getName());
    }

doesn't appear to work.
Below is the method contains the createFile method that has the JFileChooser within
public class TextFileHandler {

private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
private static JFileChooser chooser;
private static int userSelection;

public void createFile(String shiftPattern) {

    chooser = new JFileChooser();

    chooser.setSelectedFile(new File(shiftPattern + "_export"));
    chooser.setDialogTitle("Save shift pattern to CSV format");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV", "csv");
    chooser.setFileFilter(filter);
    int userSelection = chooser.showSaveDialog(chooser);
    if (userSelection == JFileChooser.APPROVE_OPTION) {
        System.out.println("File saved " + chooser.getSelectedFile().getName());
    }

}

The below file is an excerpt of the class that calls the above method from a button press action.
else if (action.equals("EXPORT_CSV_BUTTON")) {

        TextFileHandler textFile = new TextFileHandler();
        String temp = copyPatternController.getShiftPatCode();

        messageShow(new Integer(TextFileHandler.getUserSelection()).toString() + " and "
                + (TextFileHandler.getChooser().APPROVE_OPTION)); //for debugging

        textFile.createFile(temp);

            FileWriter fw = null;
            try {
                File file = new File(temp + "_export.csv");

                fw = new FileWriter(file);
                fw.append("testing");

            } catch (IOException e) {
                System.out.println("Error in writing csv file !!!");
                e.printStackTrace();

            } finally {
                try {
                    fw.flush();
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

The save dialog appears ok but when i press save the dialog closes and nothing is created. Appreciate any ideas

A: In the EXPOPRT_CSV_BUTTON I was missing a getSelectedFile() call.
File file = new File(TextFileHandler.getChooser().getSelectedFile().getPath() + ".csv");

The creates the file with no problems. I have also refactored my obfuscated code thank you for pointing that out.


text:
Q: Android Studio and Getting Maps Correctly installed I am new to Android Studio, but I currently get this error:

error: package com.google.android.gms.maps does not exist

Now, if I in
project/module/build.gradle I do this
apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion '19.0.1'

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 17
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    } }

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile files('src/main/libs/google-play-services.jar') }

I currently get this error:

Could not find method
  android.webkit.WebView.setWebContentsDebuggingEnabled

And earlier I got this

Could not find class 'com.google.android.gms.maps.SupportMapFragment'

Whatt is the correct thing to do here / how do I solve above errors?
For reference: I orignally manually converted this project form a broken Eclipse project - sadly, for both Eclipse builds and Android Studio builds, it is the map/library thing that I seem unable o solve. The app is otherwise still working as it was before.

A: Replace
compile files('src/main/libs/google-play-services.jar')

with
compile 'com.google.android.gms:play-services:4.0.30'

or use newer version if you want.
You need to have Google Play Services downloaded in SDK.


text:
Q: Laravel/Blade: pre-selected dropdown option I am using a foreach loop to generate a drop down list via bensampo's ENUMS library, but I need to be able to preselect one of them as I have an edit view and I need it to load the option that is in my database.
My select in my edit view:
<select name="type" id="type" class="form-control">
    @foreach ($MailMessageTypes as $value =>$label)
        <option value="{{$value}}">{{$label}}</option>
    @endforeach
</select>

My function edit in my MailMessageController:
return view('MailMessage.edit', [
    'MailMessage' => $MailMessage],
    ["MailMessageTypes" => MailMessageType::toSelectArray()
]);

I tried to use the enum library's getValues() and getKeys() in the controller but that generates (duplicates) for me, since the foreach keeps generating all options.  I am using the select2 plugin
Added: I'm using the select2 plugin for the list.

A: On your Edit page, you are passing the existing mail message as $MailMessage. I am assuming your database has its value as id, so it can be accessed as $MailMessage->id. While you are looping through and displaying each option, you need to check if that option's value equals the id of the message you are editing. If it matches, you set the selected attribute on the <option>:
<select name="type" id="type" class="form-control">
    @foreach ($MailMessageTypes as $value => $label)
        <option value="{{$value}}" {{($MailMessage->id == $value) ? 'selected' : ''}}>
            {{$label}}
        </option>
     @endforeach
</select>

In your HTML your <select> would end up looking something like:
<select name="type" id="type" class="form-control">
    <option value="1">COM01</option>
    <option value="2" selected>COM02</option>
    <option value="3">COM03</option>
    // ... the rest of the options
</select>


text:
Q: How to query for VM compliance report in Google Cloud Logs Explorer I am able to see the compliance state for VMs(on whom I have applied custom OS policy via OS Configuration Management in VM Manager) in a given project and zone in the Google Cloud console as well as via using API like below:
GET https://osconfig.googleapis.com/v1alpha/projects/PROJECT_ID/locations/ZONE/instanceOSPoliciesCompliances

Is there a way I can view compliance state via Google Cloud Logs Explorer?

If I click on View in the Logs tab above, I am directed to Logs Explorer with the Query framed as:
resource.type="gce_instance"
resource.labels.instance_id="<instance_id>"
labels.os_policy_assignment="projects/<project_id>/locations/<zone>/osPolicyAssignments/<assignment>@<some_alphanumeric_id>"
labels.os_policy_id="<custom-policy-id>"
labels.task_type="APPLY_CONFIG_TASK"

But this does not provide me any information on the Compliance State as shown in the screenshot above.
How can I frame a query to get the Compliance State related logs?

A: To view compliance state in Logs use the following query,
resource.type="gce_instance"
resource.labels.instance_id="<instance_id>"
labels.os_policy_assignment="projects/<project_id>/locations/<zone>/osPolicyAssignments/<assignment>@<some_alphanumeric_id>"
labels.os_policy_id="<custom-policy-id>"
labels.task_type="APPLY_CONFIG_TASK"
jsonPayload.message:"state: COMPLIANT"

We can find compliant state of VM in "jsonPayload.message" field of a log.


text:
Q: Refresh Office AutoCorrect List I'm using some VBA to manipulate the Office autocorrect list in real time. For the most part I have the modification working by calling the AutoCorrect methods in Word. The problem is that only Word seems to know that a change has been made. Is there a way to trigger the other Office apps (Outlook, PowerPoint) to refresh autocorrect so that they are working from the updated list? It seems like there is something happening when you manually navigate to the AutoCorrect Options screen that informs the apps that a change occurred so I'm hoping to automate it (without presenting any dialog). Any insight is much appreciated.
Thanks

A: You want to implement functionality in Outlook. However, there is no autocorrect object in outlook.
In the Outlook Object Model, assuming a message is being displayed in an inspector, Application.ActiveInspector.WordEditor.Application will give you the Word Application object which exposes the AutoCorrect property.
You can refer to the following code to get the document object.
Dim oDoc As Word.Document   ' Or add a reference to the Microsoft Word Object Library for IntelliSense
    Dim oMail As Outlook.MailItem

    If TypeOf Application.ActiveInspector.CurrentItem Is Outlook.MailItem Then
        Set oMail = Application.ActiveInspector.CurrentItem
    Else
        Exit Sub
    End If

    Set oDoc = oMail.GetInspector.WordEditor


text:
Q: chrome.storage.local.get not working Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and  Base64File is the base64 string of the pdf
 var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
    chrome.storage.local.set({ 'MyFile': obj });

In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
     chrome.storage.local.get('MyFile', function (result) {
        var PdfBase64 = result.MyFile.Base64File;
        var DocumentName = result.MyFile.DocName;
        var arr=new Array();
        var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
        "OptionalParam1": "sample string 5"};
        arr.push(item);

        $.ajax({
            type: "POST",
            url: Documentupload,
            headers: {
                'Authorization': headerdata,
                'Content-Type':'application/json'
            },
            data:JSON.stringify(arr),
            dataType: 'json',
            success: function (res) {
                if (res.IsSuccess) {
                    setTimeout(function () {
                    $("#divLoading").hide();
                    }, 2000);
                    //$("#divLoading").hide();
                    $(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
                    //window.location.reload();
                }else{
                    alert(res.Messages);
                    window.location.href='/PdfLogin.html';
                }
            },
            error: function (error) {
                //alert("Error while communicating to the server");
                alert(error.responseText);
                window.location.href='/PdfLogin.html';
            }
        });
    });
});

[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one?  it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.


text:
Q: Wifi driver install authorization Bought a Netis wireless adapter. It comes with quick install directions that only covers WINDOWS although the driver CD has a Linux driver. Tried to install the driver (which was zipped) and was told that I didn't have sufficient permissions to extract the file. I am the only user and the administrator for the computer. How do I get to the Ubuntu 12.04 permission screen to put in my password and gain authorization?

A: Sometimes the Archive Manager, when invoked within the GUI, prevents extraction of archives that can be extracted in a terminal window using "sudo tar" followed by the appropriate tar options and filename. sudo allows you to supply your password (to
authorize an operation) before it is done.


text:
Q: Creating Template with Transformed PDF Form Fields I have a need to add Docusign templates programmatically, configured with a single PDF document containing multiple form fields.  I'm presently able to create a new template, although the PDF form fields are not being transformed to docusign fields.
When creating the template, the JSON payload looks as follows, submitted with an HTTP POST to [baseUrl]/templates as a multipart request, PDF included.
{
  "documents": [
    {
      "documentId": "1",
      "name": "fillable-form.pdf",
      "transformPdfFields": "true"
    }
  ],
  "emailSubject": "Default Blurb",
  "enableWetSign": "false",
  "envelopeTemplateDefinition": {
    "name": "My Template Name",
    "shared": "false",
    "folderName": "Template Folder"
  },
  "recipients": {
    "signers": [
      {
        "routingOrder": "1",
        "recipientId": "1",
        "roleName": "primary-signer",
        "defaultRecipient": "true"
      }
    ]
  }
}

The Post Template Documentation claims that you should be able to enable the transformPdfFields property, in accordance with the Document parameter specification, but setting that property seems to have no effect.
I found a similarly related question asked in DocuSign API auto convert PDF fields to SecureFields, but there was no real sufficient response.  I'd like to know if Docusign can weigh in and provide some guidance.

Update #1
Heeding the advice provided by @ergin, I've altered my request payload slightly (note, this is similar to the attempt made earlier in response to @c-davis).
Unfortunately, following the suggestion described in Case 2 (It can be used to CREATE NEW TABS from existing PDF Form Fields), it doesn't seem to work as expected.
It's important to note that this is Template creation, rather than Envelope creation.
Attempt #1:
{
  "envelopeTemplateDefinition": {
    "name": "Test Template Name",
    "shared": false,
    "folderName": "test-folder"
  },
  "emailSubject": "Test Subject",
  "enableWetSign": false,
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": 1,
          "recipients": {
            "signers": [
              {
                "recipientId": 1,
                "roleName": "primary-signer",
                "defaultRecipient": true
              }
            ]
          }
        }
      ],
      "document": {
        "documentId": 1,
        "name": "test-document.pdf",
        "transformPdfFields": true
      }
    }
  ]
}

The result, when sending that in the multipart request, with the second bit of the multipart being the PDF document as normal is that the Template both has no recipient specified and no document.

Attempt #2 (denoting the recipient property of the template request):
{
  "envelopeTemplateDefinition": {
    "name": "Test Template Name",
    "shared": false,
    "folderName": "test-folder"
  },
  "emailSubject": "Test Subject",
  "enableWetSign": false,
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": 1,
          "recipients": {
            "signers": [
              {
                "recipientId": 1,
                "roleName": "primary-signer",
                "defaultRecipient": true
              }
            ]
          }
        }
      ],
      "document": {
        "documentId": 1,
        "name": "test-document.pdf",
        "transformPdfFields": true
      }
    }
  ],
  "recipients": {
    "signers": [
      {
        "recipientId": 1,
        "roleName": "primary-signer",
        "defaultRecipient": true
      }
    ]
  }
}

The result is slightly closer – the recipient is now listed as one would expect, however the document is still not being considered as part of this template.  The only way that the document is associated with the template is when I set that as the outer property of the template creation.

Attempt #3 (denoting both the recipient & document properties of the template request):
{
  "envelopeTemplateDefinition": {
    "name": "Test Template Name",
    "shared": false,
    "folderName": "test-folder"
  },
  "emailSubject": "Test Subject",
  "enableWetSign": false,
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": 1,
          "recipients": {
            "signers": [
              {
                "recipientId": 1,
                "roleName": "primary-signer",
                "defaultRecipient": true
              }
            ]
          }
        }
      ],
      "document": {
        "documentId": 1,
        "name": "test-document.pdf",
        "transformPdfFields": true
      }
    }
  ],
  "recipients": {
    "signers": [
      {
        "recipientId": 1,
        "roleName": "primary-signer",
        "defaultRecipient": true
      }
    ]
  },
  "documents": [
    {
      "documentId": 1,
      "name": "test-document.pdf",
      "transformPdfFields": true
    }
  ]
}

The result on this final attempt is similar to that of including the recipients and documents properties and eliminating the compositeTemplates property entirely (it seems that property has no effect whether it's present or not).  The recipient placeholder is present and the document is associated with the template, however the PDF fields within the PDF document are not "assigned"/converted to Docusign fields.

A: as far as the transormPdfFields parameter is concerned, I've only ever been able to make this parameter work when associated with a document that is inside a CompositeTemplate. Granted, I'm talking about sending an envelope here, but I bet the same is true when creating a template, even though the documentation may appear otherwise.
I don't have a code sample for this specific call, but if I get some free time I'll try to put one together.

A: So this is not well documented (soon to be improved) but the transformPdfFields property has two different purposes based on how/where you use it in your request body.

*

*Case 1: It can be used to TRANSFER THE VALUES contained within existing PDF Form Fields into DocuSign tabs.

*Case 2: It can be used to CREATE NEW TABS from existing PDF Form Fields.

For #1 the names of the PDF form fields need to correspond to the tabLabels of your DocuSign tabs.  Sample JSON for to accomplish this would be:
{
    "emailSubject": "test subject",
    "documents": [
    {
        "documentId": "1",
        "name": "document.pdf",
        "transformPdfFields": true
    }
}

For #2, you need to use the compositeTemplates structure with the transformPdfFields property enabled in the inline template section to have the platform CREATE new DocuSign tabs.  You should also remember to set the defaultRecipient property to true for your recipient so the system knows who to assign thew newly created tabs to (i.e. you can't have un-assigned tabs).
For instance, the following JSON should work:
{
    "compositeTemplates": [{
        "inlineTemplates": [{
            "sequence": 1,
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "defaultRecipient": true
                }]
            }
        }],
        "document": {
            "documentId": 1,
            "name": "Contract.pdf",
            "transformPdfFields": true
        }
    }]
}


text:
Q: When does the expected value of a random variable grow faster than the upper limit of its support? I have the following problem: Consider a random variable $x\sim F$, where $F$ is some continous probability distribution with support $[\underline{x},\bar{x}]$.
Also assume there is some threshold $y\in [\underline{x},E[x]]$. Then the expected value of $x$ conditional on $x\leq y$ is
$$E[x\,\big|~x\leq y]=\frac{\int_{\underline{x}}^y x\,f(x)dx}{\int_{\underline{x}}^{y} f(x)dx}~.$$
I need to establish whether and when $\frac{\partial}{\partial y}E[x\,|~x\leq y]<1$.
My intuition is that it must always be lower than one, since increasing the upper limit of the conditional support has two effects. It adds a very small amount to the numerator of the fraction above (small because continous distribution). And it increases the normalizing value in the denominator of the fraction.
Is my intuition right? And how can I prove it? Any ideas would help me a lot, as I have pondered this problem for a couple of months now.
Thanks in advance!