text:
Q: Does loop back interface generates interrupt on NIC/Hardware Does loop back interface generates interrupt on NIC/Hardware

A: The loopback interface is a virtual network interface. It doesn't correspond to any actual hardware, and packets transmitted through it therefore do not generate hardware interrupts.
It's possible that linux has some concept of a "soft interrupt", i.e. an inter-thread/process signalling mechanism, and that packets over the loopback will cause these. Older Linux versions definitely had these "soft interrupts", but I'm not sure if the 2.6 series does, and I'm not sure if packets over the loopback do or ever did generate them.


text:
Q: Typescript mocking named export singleton class in Jest I have a very simple class (GraphQlProxy) which I am instantiating as singleton (graphQlProxyService) and exporting as a named module, and I am trying to mock a public method () with Jest but I am troubles doing this.
Below is the class and test module:
class GraphQlProxy {
  public async request(req: NextApiRequest) {
    if (!req.body) return new Error('The request body cannot be empty!')
    ...
  }
}

export const graphQlProxyService = new GraphQlProxy()

import { createMocks } from 'node-mocks-http'
import graphql from './graphql'

describe('when there is an error with the request', () => {
  beforeAll(() => {
    jest.mock('@services/graphql-proxy.service', () => ({
      graphQlProxyService: jest.fn().mockImplementation(() => ({
        request: () => {
          throw new Error()
        }
      }))
    }))
  })
  it('returns status code 500', async () => {
    const { req, res } = createMocks({
      method: 'POST',
      body: {},
    })
    await graphql(req, res)
    expect(res._getStatusCode()).toBe(500)
  })
})

The test currently fails because it's hitting the real endpoint rather than the desired request method.
I've spent a few hours on this one and I am stumped!

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'Tiling' a graph in NetworkX So, if I have a basic Graph created in NetworkX, is there a way to 'tile' it such that it kind of multiplies the graph many times? It would be good if they were still connected. I've tried some fcns like nx.Union() but it seems to overlay the graphs rather than multiplying it out many times. I can't find any fcns that seem to accomplish this, any ideas?
EDIT: Input would be a graph with maybe up to 50 nodes. Output would be that very same graph, but iterated n times (such that there's n50 nodes in output graph). I would like however, for the iterations of the original graph to be connected, so either overlaying some nodes (st output nodes'<'n50) or creating new edges to connect iterations (st output edges'>'n(input edges))
Does that make sense?

A: The function you're looking for is nx.disjoint_union, which will let you add two graphs and give them distinct node values.
 def n_disjoint_unions(G, n):
     H = nx.Graph()
     for _ in range(n):
         H = nx.disjoint_union(H, nx.copy(G))
     return H

You will need to specify how you want to connect these new graphs however.


text:
Q: Why is the distribution of d̄ normal? (d̄ = x̄₁ - x̄₂ when both sampling distributions are normal) I'm learning about doing inference with two samples. $d̄ = x̄₁ - x̄₂$. Sampling is independent. Let's suppose $x̄₁$ and $x̄₂$ are both normally distributed. My understanding is that this means $d̄$ will also be normally distributed. Why is this?
I'm looking for an intuitive explanation, not a derivation of the pdf.

My attempt:
Say that these are our two sampling distributions:

How can we get $d̄ = 0$? Some possibilities:

*

*$x̄₁ = 10$ and $x̄₂ = 10$. P(this happening) = very unlikely * very very unlikely = not gonna happen.

*$x̄₁ = 20$ and $x̄₂ = 20$. P(this happening) = likely * very unlikely = very very unlikely.

*$x̄₁ = 30$ and $x̄₂ = 30$. P(this happening) = very unlikely * likely = very very unlikely.

*$x̄₁ = 40$ and $x̄₂ = 40$. P(this happening) = very very unlikely * very unlikely = not gonna happen.

So overall, $P(d̄ = 0)$ is the sum of all of these, which is a very small number.
What about $d̄ = 10$? How can we get that? Some possibilities:

*

*$x̄₁ = 15$ and $x̄₂ = 25$. P(this happening) = unlikely * unlikely = very unlikely.

*$x̄₁ = 17.5$ and $x̄₂ = 27.5$. P(this happening) = solid chance * solid chance = plausible.

*$x̄₁ = 20$ and $x̄₂ = 30$. P(this happening) = likely * likely = solid chance.

Hopefully you see where this is going. To construct the distribution of $d̄$'s, ask yourself, "How many ways can I get this value of $d̄$?" and "How likely is it that each of these ways occur?". Use those questions to arrive at the value for $P(d̄)$, and repeat this procedure for each $d̄$.
To help visualize, you could slide the bottom distribution. In the picture, 20 lines up with 20, 30 lines up with 30 etc. If you go "straight down" and subtract, you get zero. By "going straight down at all the different points", it allows you to calculate $P(d̄ = 0)$. To get $P(d̄ = x)$, offset the axis by $x$.


text:
Q: Panel DefaultButton not works when Textbox is extended by AJAX Toolkit AutoComplete I am using ASP.NET Panel to set Default Button for some Controls like TextBox but it seems to not work due to AJAX Control Toolkit's AutoCompleteExtender.
Pls help.. !
Code is as below:
<asp:Panel ID="pnlSearchBox" runat="server" class="search-main-box" DefaultButton="lnkSearch">
        <asp:TextBox ID="txtLocation" runat="server" CssClass="input-field" MaxLength="200" style="width: 182px; margin-bottom: 7px;"></asp:TextBox>
        <ajaxToolkit:AutoCompleteExtender runat="server" BehaviorID="AutoCompleteEx" ID="aceLocation" TargetControlID="txtLocation" ServicePath="~/autocomplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionInterval="1000" EnableCaching="true" CompletionSetCount="20" CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" DelimiterCharacters=";, :" ShowOnlyCurrentWordInCompletionListItem="true" >
            <Animations>
                <OnShow>
                    <Sequence>
                        <%-- Make the completion list transparent and then show it --%>
                        <OpacityAction Opacity="0" />
                        <HideAction Visible="true" />
                        <%-- Expand from 0px to the appropriate size while fading in --%>
                        <Parallel Duration=".4">
                            <FadeIn />
                            <Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
                        </Parallel>
                    </Sequence>
                </OnShow>
                <OnHide>
                    <%-- Collapse down to 0px and fade out --%>
                    <Parallel Duration=".4">
                        <FadeOut />
                        <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
                    </Parallel>
                </OnHide>
            </Animations>
        </ajaxToolkit:AutoCompleteExtender>

<asp:LinkButton ID="lnkSearch" runat="server" class="btn-search-bg" OnClick="lnkSearch_Click">Search</asp:LinkButton>

</asp:Panel>

A: do like this:
 <asp:TextBox onkeydown="KeyDownHandler();" ID="txtLocation" runat="server"
     CssClass="input-field" MaxLength="200" style="width: 182px; margin-bottom: 7px;">
 </asp:TextBox>

add this in script tag in your page head tag :
function KeyDownHandler()
{
   if (event.keyCode == 13)
   {
      event.returnValue=false;
      event.cancel = true;
      document.getElementById('<%=lnkSearch.ClientID%>').click();
   }
}

Edited to use jQuery
there is no much difference between code above and jquery :
function KeyDownHandler()
{
   if (event.keyCode == 13)
   {
      event.returnValue=false;
      event.cancel = true;
      $('#<%=lnkSearch.ClientID%>').click();
   }
}


text:
Q: C# Sqlite Parameter Working/Not working in different pages First time posting. I am trying sqlite for a little project of mine and I have encountered something really weird. The problem seem to be with the parameter but I don't understand it. Maybe someone here could explain me why it work in some place but not in another one.
Here it is: in this code everything is working perfectly:
    public void SaveObject(PlayerCharacter playerCharacter)
    {
        SQLiteConnection sqliteConnection = new SQLiteConnection(ConnectionString.Connection);
        sqliteConnection.Open();

        String query = String.Empty;

        switch (playerCharacter.InternalState)
        {
            case InternalStates.New:
                query = "INSERT INTO PlayerCharacters(Id, Name, ArmorClass, InitiativeBonus) VALUES (@Id, @Name, @ArmorClass, @InitiativeBonus)";
                break;

            case InternalStates.Modified:
                query = @"  UPDATE PlayerCharacters
                            SET Name = @Name,
                                ArmorClass = @ArmorClass,
                                InitiativeBonus = @InitiativeBonus
                            WHERE Id = @Id";
                break;

            case InternalStates.Deleted:
                //To maybe implement in the future
                break;
        }

        List<SQLiteParameter> parameters = new List<SQLiteParameter>()
        {
            new SQLiteParameter("@Id", playerCharacter.Id),
            new SQLiteParameter("@Name", playerCharacter.Name),
            new SQLiteParameter("@ArmorClass", playerCharacter.ArmorClass),
            new SQLiteParameter("@InitiativeBonus", playerCharacter.InitiativeBonus)
        };

        SQLiteCommand command = new SQLiteCommand(query, sqliteConnection);
        command.Parameters.AddRange(parameters.ToArray());

        command.ExecuteNonQuery();

        playerCharacter.SetInternalState(InternalStates.UnModified, true);

        sqliteConnection.Close();
    }

Here I tried to isolate the problem. When I remove the parameter Id and the Where clause, everything is updated like it should be, but when I try with the parameter, it never find the row to update:
    public void SaveObject(Monster monster)
    {
        SQLiteConnection sqliteConnection = new SQLiteConnection(ConnectionString.Connection);
        sqliteConnection.Open();

        String query = String.Empty;

        switch (monster.InternalState)
        {
            case InternalStates.New:
                query = @"  INSERT INTO Monsters(Id,
                                                Name,
                                                Size,
                                                Type,
                                                Subtype,
                                                Alignment,
                                                ArmorClass,
                                                HitPoints,
                                                HitDice,
                                                Speed,
                                                DamageVulnerabilities,
                                                DamageResistances,
                                                DamageImmunities,
                                                ConditionImmunities,
                                                Senses,
                                                Languages,
                                                ChallengeRating)
                            VALUES (@Id,
                                    @Name,
                                    @Size,
                                    @Type,
                                    @Subtype,
                                    @Alignment,
                                    @ArmorClass,
                                    @HitPoints,
                                    @HitDice,
                                    @Speed,
                                    @DamageVulnerabilities,
                                    @DamageResistances,
                                    @DamageImmunities,
                                    @ConditionImmunities,
                                    @Senses,
                                    @Languages,
                                    @ChallengeRating)";
                break;

            case InternalStates.Modified:
                query = @"  UPDATE Monsters
                            SET Name = @Name
                            WHERE Monsters.Id = @Id";

                //Size = @Size,
                //                Type = @Type,
                //                Subtype = @Subtype,
                //                Alignment = @Alignment,
                //                ArmorClass = @ArmorClass,
                //                HitPoints = @HitPoints,
                //                HitDice = @HitDice,
                //                Speed = @Speed,
                //                DamageVulnerabilities = @DamageVulnerabilities,
                //                DamageResistances = @DamageResistances,
                //                DamageImmunities = @DamageImmunities,
                //                ConditionImmunities = @ConditionImmunities,
                //                Senses = @Senses,
                //                Languages = @Languages,
                //                ChallengeRating = @ChallengeRating
                break;

            case InternalStates.Deleted:
                //To maybe implement in the future
                break;
        }

        List<SQLiteParameter> parameters = new List<SQLiteParameter>()
        {
            new SQLiteParameter("@Id", monster.Id ),
            new SQLiteParameter("@Name", monster.Name)
            //new SQLiteParameter("@Size", monster.Size),
            //new SQLiteParameter("@Type", monster.Type),
            //new SQLiteParameter("@Subtype", monster.Subtype),
            //new SQLiteParameter("@Alignment", monster.Alignment),
            //new SQLiteParameter("@ArmorClass", monster.ArmorClass),
            //new SQLiteParameter("@HitPoints", monster.HitPoints),
            //new SQLiteParameter("@HitDice", monster.HitDice),
            //new SQLiteParameter("@Speed", monster.Speed),
            //new SQLiteParameter("@DamageVulnerabilities", monster.DamageVulnerabilities),
            //new SQLiteParameter("@DamageResistances", monster.DamageResistances),
            //new SQLiteParameter("@DamageImmunities", monster.DamageImmunities),
            //new SQLiteParameter("@ConditionImmunities", monster.ConditionImmunities),
            //new SQLiteParameter("@Senses", monster.Senses),
            //new SQLiteParameter("@Languages", monster.Languages),
            //new SQLiteParameter("@ChallengeRating", monster.ChallengeRating)
        };

        SQLiteCommand command = new SQLiteCommand(query, sqliteConnection);
        command.Parameters.AddRange(parameters.ToArray());

        int i = command.ExecuteNonQuery();

        monster.SetInternalState(InternalStates.UnModified, true);

        sqliteConnection.Close();
    }

I already checked and the Id exist in the database. It should find a result.
If someone know why and can explain it to me it will make my day !
UPDATE
I still don't know why it work in the first sample and not the other one but here a solution that work for me.
The sql parameter have a DbType property and it is automatically set to fit the value, in my case it is set to Guid. In Sqlite uniqueidentifier type doesn't exist and it is process like a string. So here is what i did :
        ...

        List<SQLiteParameter> parameters = new List<SQLiteParameter>()
        {
            new SQLiteParameter("@Id", monster.Id ) {DbType = DbType.String},
            new SQLiteParameter("@Name", monster.Name)
            //new SQLiteParameter("@Size", monster.Size),
            //new SQLiteParameter("@Type", monster.Type),
            //new SQLiteParameter("@Subtype", monster.Subtype),
            //new SQLiteParameter("@Alignment", monster.Alignment),
            //new SQLiteParameter("@ArmorClass", monster.ArmorClass),
            //new SQLiteParameter("@HitPoints", monster.HitPoints),
            //new SQLiteParameter("@HitDice", monster.HitDice),
            //new SQLiteParameter("@Speed", monster.Speed),
            //new SQLiteParameter("@DamageVulnerabilities", monster.DamageVulnerabilities),
            //new SQLiteParameter("@DamageResistances", monster.DamageResistances),
            //new SQLiteParameter("@DamageImmunities", monster.DamageImmunities),
            //new SQLiteParameter("@ConditionImmunities", monster.ConditionImmunities),
            //new SQLiteParameter("@Senses", monster.Senses),
            //new SQLiteParameter("@Languages", monster.Languages),
            //new SQLiteParameter("@ChallengeRating", monster.ChallengeRating)
        };

        ...

A: Can you try changing this:
UPDATE Monsters
SET Name = @Name
WHERE Monsters.Id = @Id

To
UPDATE Monsters SET Name = @Name
WHERE Monsters.Id like @Id

And in C#:
    new SQLiteParameter("@Id", "%" + monster.Id + "%");

Now, you have to declare the list above the switch/case statement:
 List<SQLiteParameter> parameters = new List<SQLiteParameter>()
        {
            // remove the @id parameter here
            new SQLiteParameter("@Name", monster.Name)
            //new SQLiteParameter("@Size", monster.Size),
            //new SQLiteParameter("@Type", monster.Type),
            //new SQLiteParameter("@Subtype", monster.Subtype),
            //new SQLiteParameter("@Alignment", monster.Alignment),
            //new SQLiteParameter("@ArmorClass", monster.ArmorClass),
            //new SQLiteParameter("@HitPoints", monster.HitPoints),
            //new SQLiteParameter("@HitDice", monster.HitDice),
            //new SQLiteParameter("@Speed", monster.Speed),
            //new SQLiteParameter("@DamageVulnerabilities", monster.DamageVulnerabilities),
            //new SQLiteParameter("@DamageResistances", monster.DamageResistances),
            //new SQLiteParameter("@DamageImmunities", monster.DamageImmunities),
            //new SQLiteParameter("@ConditionImmunities", monster.ConditionImmunities),
            //new SQLiteParameter("@Senses", monster.Senses),
            //new SQLiteParameter("@Languages", monster.Languages),
            //new SQLiteParameter("@ChallengeRating", monster.ChallengeRating)
        };

In your case for insert:
parameters.Add(new SQLiteParameter("@Id", monster.Id ));

In your case for Update:
parameters.Add(new SQLiteParameter("@Id", "%" + monster.Id + "%"));

Your final code:
public void SaveObject(Monster monster)
{
    SQLiteConnection sqliteConnection = new SQLiteConnection(ConnectionString.Connection);
    sqliteConnection.Open();

    String query = String.Empty;
    List<SQLiteParameter> parameters = new List<SQLiteParameter>()
    {
        new SQLiteParameter("@Name", monster.Name)
        //new SQLiteParameter("@Size", monster.Size),
        //new SQLiteParameter("@Type", monster.Type),
        //new SQLiteParameter("@Subtype", monster.Subtype),
        //new SQLiteParameter("@Alignment", monster.Alignment),
        //new SQLiteParameter("@ArmorClass", monster.ArmorClass),
        //new SQLiteParameter("@HitPoints", monster.HitPoints),
        //new SQLiteParameter("@HitDice", monster.HitDice),
        //new SQLiteParameter("@Speed", monster.Speed),
        //new SQLiteParameter("@DamageVulnerabilities", monster.DamageVulnerabilities),
        //new SQLiteParameter("@DamageResistances", monster.DamageResistances),
        //new SQLiteParameter("@DamageImmunities", monster.DamageImmunities),
        //new SQLiteParameter("@ConditionImmunities", monster.ConditionImmunities),
        //new SQLiteParameter("@Senses", monster.Senses),
        //new SQLiteParameter("@Languages", monster.Languages),
        //new SQLiteParameter("@ChallengeRating", monster.ChallengeRating)
    };

    switch (monster.InternalState)
    {
        case InternalStates.New:
            query = @"  INSERT INTO Monsters(Id,
                                            Name,
                                            Size,
                                            Type,
                                            Subtype,
                                            Alignment,
                                            ArmorClass,
                                            HitPoints,
                                            HitDice,
                                            Speed,
                                            DamageVulnerabilities,
                                            DamageResistances,
                                            DamageImmunities,
                                            ConditionImmunities,
                                            Senses,
                                            Languages,
                                            ChallengeRating)
                        VALUES (@Id,
                                @Name,
                                @Size,
                                @Type,
                                @Subtype,
                                @Alignment,
                                @ArmorClass,
                                @HitPoints,
                                @HitDice,
                                @Speed,
                                @DamageVulnerabilities,
                                @DamageResistances,
                                @DamageImmunities,
                                @ConditionImmunities,
                                @Senses,
                                @Languages,
                                @ChallengeRating)";
                parameters.Add(new SQLiteParameter("@Id", monster.Id ));
            break;

        case InternalStates.Modified:
            query = @"  UPDATE Monsters
                        SET Name = @Name
                        WHERE Monsters.Id like @Id";

            //Size = @Size,
            //                Type = @Type,
            //                Subtype = @Subtype,
            //                Alignment = @Alignment,
            //                ArmorClass = @ArmorClass,
            //                HitPoints = @HitPoints,
            //                HitDice = @HitDice,
            //                Speed = @Speed,
            //                DamageVulnerabilities = @DamageVulnerabilities,
            //                DamageResistances = @DamageResistances,
            //                DamageImmunities = @DamageImmunities,
            //                ConditionImmunities = @ConditionImmunities,
            //                Senses = @Senses,
            //                Languages = @Languages,
            //                ChallengeRating = @ChallengeRating
            parameters.Add(new SQLiteParameter("@Id", "%" + monster.Id + "%"));
            break;

        case InternalStates.Deleted:
            //To maybe implement in the future
            break;
    }

    SQLiteCommand command = new SQLiteCommand(query, sqliteConnection);
    command.Parameters.AddRange(parameters.ToArray());

    int i = command.ExecuteNonQuery();

    monster.SetInternalState(InternalStates.UnModified, true);

    sqliteConnection.Close();
}

Update:
There is no GUId support for sqllite. Converting Guid to String or changind datatype of id to string may help you.
See here:
SQLite Parameter Issue with Guids


text:
Q: ormlite: sql statement not like throws exception I use ormlite. I want to execute the sql statement "not like".
I used not().like() but I got exception "can't add: NOT without comparison".
What did I do wrong? I have looked for examples using "not like" with ormlite but
I haven't found anything online.

A:
I used not().like() but I got exception "can't add: NOT without comparison".

This turned out to be a bug in ORMLite that was fixed in version 4.48.  It specifically was not handling queries that did something similar to:
where.eq(...).and().not().like(...);

If there is any problem with the in-line mechanisms for building queries, you can always switch to the operations that take arguments which is more straightforward.  See the docs on the various ways to build queries.

A: Looking at source code from trunk, I assume that you get exception because of some previous clause (probably and() or or()). Make sure that all methods requiring future clause are followed up by proper clause. and().not() will not work...

A: Try this
.queryBuilder().where().rawComparison("column", "NOT LIKE", "value")


text:
Q: dplyr grouped sum returning wrong value I incurred in a weird error I could not find a solution for. I already checked several related post here on stack overflow, but they are not really addressing the issue I am facing here.
I am trying to create grouped summation from logical vectors. The data are structured as follows:
For each unit of observation (country) I have a list of events, which are reported weekly. So, if I have 105 weeks (roughly 2 years), and supposing a country to have experienced 3 events, I have a dataframe with 315 observation (country-week-event).
I want to group and summarize the data at (country-week level). To stay with the previous figures, I want 105 observation for each country.
If I check the result of the summation however, I notice that an error returns, and a sum that shoulg return value 1 actually returns value 2. In particular, the summation of the column restriction should return 1 (as, for each week, I am summing up two "FALSE" statements and only one "TRUE" statement)
Any idea for why this might be happening? Other summations (like the facilitation one reported below) work fine
Below my data
data <- structure(list(ccode = c("AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO", "AGO",
"AGO", "AGO", "AGO"), week = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L,
22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L,
35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L,
48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L,
61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L,
74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L,
87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L,
100L, 101L, 102L, 103L, 104L, 105L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L,
34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L,
47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L,
60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L,
73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L,
86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L,
99L, 100L, 101L, 102L, 103L, 104L, 105L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L,
19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L,
45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L,
58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L,
71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L,
84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L,
97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L), medical_any_lib = c(TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), medical_any_res = c(FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)), row.names = c(NA,
-315L), class = c("tbl_df", "tbl", "data.frame"))

And here the operation I am running

data %>%
  group_by(ccode,week) %>%
  summarise(
    facilitations = sum(medical_any_lib, na.rm = T),
    restrictions = sum(medical_any_res, na.tm = T)
    )

A: The solution, as @Ali wrote in the comments, simply lied in the na.tm = T option, that of course is wrong.
Strange enough, my RStudio does not flag the error.


text:
Q: Getting Error While doing pagination in angular 4 I am new to angular 4. I am working in pagination using angular 4.I ahve installed "npm install ngx-pagination --save". I followed the instruction which was in internet. But I am getting error like "The pipe 'paginate' could not be found ("

                    ]game of games | paginate: { itemsPerPage: 2, currentPage: p }">
                        {{i}}
    "): ng:///ActivityChartModule/ActivityComponent.html@235:32
    'pagination-controls' is not a known element:". I tried More. Can any one help me to comeout from this problem. Below are my code,
app.module.ts
import {NgxPaginationModule} from 'ngx-pagination';
imports: [NgxPaginationModule]

in component.ts
p: number = 1;

    games = [
        {
            "id": "1",
            "name": "DOTA 2",
            "genre": "Strategy"
        },
        {
            "id": "2",
            "name": "AOE 3",
            "genre": "Strategy"
        },
        {
            "id": "3",
            "name": "GTA 5",
            "genre": "RPG"
        },
        {
            "id": "4",
            "name": "Far Cry 3",
            "genre": "Action"
        },
        {
            "id": "5",
            "name": "GTA San Andreas",
            "genre": "RPG"
        },
        {
            "id": "6",
            "name": "Hitman",
            "genre": "Action"
        },
        {
            "id": "7",
            "name": "NFS MW",
            "genre": "Sport"
        }, {
            "id": "8",
            "name": "Fifa 16",
            "genre": "Sport"

        }, {
            "id": "9",
            "name": "NFS Sen 2",
            "genre": "Sport"

        }, {
            "id": "10",
            "name": "Witcher Assasins on King",
            "genre": "Adventure"
        }

    ];

in component.html

            <input class="form-control" type="text" name="search">

                    #
                    Name
                    Genre

                    {{i}}
                    {{game.name}}
                    {{game.genre}}

            <pagination-controls (pageChange)="p($event)"></pagination-controls>

A: If you have already import NgxPaginationModule into app.module.ts, I think it is because you need to restart your project after npm install.
Try ctrl+c and ng serve to restart it again.

A: I resolved this problem, you need to include in your module.ts following code:
import {NgxPaginationModule} from 'ngx-pagination';

@NgModule({
    imports: [ NgxPaginationModule ]
})

A: You should add CUSTOM_ELEMENTS_SCHEMA in angular-core
and
schemas: [ CUSTOM_ELEMENTS_SCHEMA ] ----add it in your @NgModule({})
refer this link: https://hassantariqblog.wordpress.com/2016/10/12/angular2-template-parse-errors-add-custom_elements_schema-to-the-ngmodule-schemas/

A: I copied your code and did not face the error you faced. However, the variable p used is actually an event and not a number[].
Replace the table and pagination-control element as per below in app.component.html:

              #
              Name
              Genre

              {{game.id}}
              {{game.name}}
              {{game.genre}}

      <pagination-controls (pageChange)="p = $event"></pagination-controls>

Also, declaring p within app.component.ts isn't required as its the paginationApi that gets used internally.
Side note: The error you are getting suggests that the ngx-pagination is not installed successfully. Please check if you have the ngx-pagination folder copied within your project's node_modules folder successfully.
Demo: https://angular-ijtgcv.stackblitz.io

A: Try changing the order of "import {NgxPaginationModule} from 'ngx-pagination';"
in app.module.ts
It works out for me

A: after importing NgxPaginationModule to app.module.ts and stop the local server 'npm update' worked for me !


text:
Q: How to create a class method that references a parent object? Currently I have a an object (I'll call it class A) that contains another separate class (class B)  as a value. I'm trying to make everything chainable but if I call a method of class B, there is no way for me to return a reference to class A without adding a separate property to class B referencing class A and making it a circular reference (so far that's not a problem but I want to avoid it if possible). Is it possible to define a class method on class B that references it? If it helps class A is always used to initialize class B.
edit with code:
class A {
    constructor(age,sex){
        this.b=new B
        this.c=0
   }
    exampleMethod (){
        this.c +=1 ;
        return this;
   }

class B {
    constructor(){
        this.d=0
   }
    exampleMethodB (){
        this.d +=1
        return this;
   }

Say I create a new instance of A. If I call exampleMethod() on A, I could keep chaining the exampleMethod() together indefinitely. But the moment I call A.b.exampleMethodB(), I can't return to chaining exampleMethod() because it's referencing an object of the B class now. I can get by this by adding a an object to B that references A, but at the moment I'm wondering if there's a way to keep it in the class methods instead of adding another property to B.

A: You can have A delegate to B. You can create B inside of A and make the B setters chainable. You can define the parent of B to be A (the thing that created it).

class B {
  constructor(parent) {
    this.parent = parent;
    this.name = null;
  }
  setName(name) {
    this.name = name;
    return this;
  }
  getParent() {
    return this.parent;
  }
}

class A {
  constructor(id) {
    this.id = id;
    this.b = null; // AKA child
  }
  create() {
    this.b = new B(this);
    return this.b;
  }
  getId() {
    return this.id;
  }
  getB() {
    return this.b;  // AKA getChild
  }
}

const id = new A(123).create().setName('B').getParent().getId();
console.log(id);

A: Consider using a Facade Design pattern. The facade C will wrap B and A and will always returns the instance of C. The methods in C will be delegated to A or B.
Facade design pattern link https://www.geeksforgeeks.org/facade-design-pattern-introduction/
class B {
  constructor(parent) {
    this.name = null;
  }
  setName(name) {
    this.name = name;
    return this;
  }

}

class A {
  constructor() {
    this.id = null;
  }
  setId() {
    return this.id;
  }
}

class C {
  constructor(id) {
    this.A = new A(id);
    this.B = new B();
  }

  setName(name) {
    this.B.setName(name);
    return this;
  }

  setId(id) {
    this.A.setId(id)
  }
}

//You can chain like below
//new C().setName("name").setId(1);

A: How about inheritance?

class B {
  constructor() {
    this.d = 0;
  }
  exampleMethodB() {
    this.d += 1;
    return this;
  }
}

class A extends B {
  constructor() {
    super();
    this.c = 0;
  }
  exampleMethod() {
    this.c += 1;
    return this;
  }
}

const a = new A();

a.exampleMethod()
 .exampleMethodB()
 .exampleMethod()
 .exampleMethodB()
 .exampleMethodB()
 .exampleMethod();

console.log(a);     // { d: 3, c: 3 }


text:
Q: Id of documentset is starting from 2 instead of 1 In a new document library, when I am creating a new DocumentSet, it is having ID as 2. Is there any reason for it ? Is it not that first item in a document library should have ID as 1 and this values gets incremented for new item created ?
Thanks.

A: I haven't worked with document sets much, but this is my theory.
Document sets are a beefed up version of a folder. When a folder (or document set in this case) is created the folder has a list item id as well and is presumably created first before any of the files. That's why you'd see the first document in the set with an ID of 2 rather than 1 as the document set folder is actually id 1.


text:
Q: Magento 2 Plugin - What is the $subject What is the $subject in a plugin?
My code is:
 Class Product {
          public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result) {
               return $result*2;
               }
}

A: The parameter $subject is the original object or class you are writing a plugin for.
See:
https://alanstorm.com/magento_2_object_manager_plugin_system/

An after plugin method has two parameters. The first ($subject above), is the object the method was called on (in our case, that's Pulsestorm\TutorialPlugin\Model\Example\Interceptor object). The second parameter ($result above) is the result of the original method call.

Also explained here:
https://devdocs.magento.com/guides/v2.2/extension-dev-guide/plugins.html

The first argument for the before, after, and around methods is an object that provides access to all public methods of the observed method's class.

A: Plugin concepts introduced to do some function which was declared in public methods in core functions.

getPrice() -> function available extended methods "before, after and around".

For example:

For "x" product want to add extra price while loading product
  page.

In our custom module will declare,

BeforeGetPrice - this method will execute before execution core
  Catalog Model getPrice function.
AfterGetPrice - method will execute after execution core Catalog Model
  getPrice function.
AroundGetPrice - execute before and after execution core Catalog Model
  getPrice function.

I was given simple explanation, these function have limitation please go through Magento devdocs plugin concepts.

afterGetPrice($subject, $procees)

Parameters

$subject -> denotes the public function which going to be replace or
  extend the parent or original Class object.
$proceed -> core function final result or return output.


text:
Q: VBA Excel - Check the validation of multiple textboxes upon clicking a button I'm new to this VBA thing. My concern is I'm trying to validate multiple textboxes to only accept numbers between 60 to 100. I just want to ask if it is possible to use Loop for it or I need to create a Sub for each textbox or is there something else that I can do?
Userform:

My idea is that when the 'Calculate' button is clicked, the validation runs.
I tried to use the IF statement but I think I used it in the wrong way.
If tb_mtb <=60 And tb_mtb >=100 And tb_fil <=60 And tb_mtb >=100 And tb_eng <=60 And tb_eng >=100 And _
tb_math <=60 And tb_math >=100 And tb_sci <=60 And tb_sci >=100 And tb_ap <=60 And tb_ap >=100 And _
tb_mapeh <=60 And tb_mapeh >=100 And tb_music <=60 And tb_music >=100 And tb_arts <=60 And _
tb_arts >=100 And tb_pe <=60 And tb_pe >=100 And tb_health <=60 And tb_health >=100 And _
tb_esp <=60 And tb_esp >=100 Then
'More codes here
End If

I also tried this Loop as well, but it checks the value and opens a MsgBox one by one.
For Each Ctrl In Me.Frame3.Controls
        If TypeName(Ctrl) = "TextBox" Then
            If Ctrl.Text >= 60 And Ctrl.Text <= 100 Then
                CheckTB
                MsgBox "Yey!"
            Else
                MsgBox "Error"
            End If
        End If
    Next Ctrl

A: You would keep count of any problems and then message once the loop is done.
Untested so may need tweaks:
Dim v, nProb As Long

For Each ctrl In Me.Frame3.Controls
    If TypeName(ctrl) = "TextBox" Then
        v = ctrl.Text
        ctrl.Font.Color = vbBlack
        If Len(v) > 0 Then
            v = CDbl(v) 'or Clng() ?
            If v < 60 Or v > 100 Then
                nProb = nProb + 1
                ctrl.Font.Color = vbRed 'flag error
            End If
        End If
    End If
Next ctrl

If nProb > 0 Then
    MsgBox "'Subjects' values must be between 60 and 100"
Else
    MsgBox "All good!"
End If


text:
Q: android Image problem Actually I have 52 images which r basically cards.
images names are from 1 to 52.
when I put all the 52 images in my drawable folder then it is showing an error in R.java file which is:

Syntax error on token "image name(any
  between between 1 to 52)", invalid
  VariableDeclaratorId

what is the problem?

thanks for replying.
i think u didnt get my problem.
i have given name to my cards from 1 to 52 because i need to randomly select one card from it.

A: Resource names have to be proper Java identifiers. Call them card1 through card52 instead of just their numbers (if I understand you correctly).
EDITED TO ADD: To map an integer to the correct image, your code should manage the mapping itself. One (not terribly elegant) way is to explicitly create a Bitmap[] cardImages = new Bitmap[52]; array and assigning each resource into the array, as in e.g.
Resources r = context.getResources();
cardImages[0] = loadBitmap(r.getDrawable(R.drawable.card1));
// ...
cardImages[12] = loadBitmap(r.getDrawable(R.drawable.card13));
// ...
cardImages[51] = loadBitmap(r.getDrawable(R.drawable.card52));

A: The problem is that Android doesn't allow to use spaces in a file identifier

A: Pontus Gagge is right. Android will take the name of the everything in the drawable folder and will try to generate an R file that contains an int for every image that you are using in your app. The ints are named after the file names of your drawables. You can then later use this ints as ids to load the images from your app.
The problem is that Java does not allow a vairable name to start with a number. Your images start with a number therefore your variables in the R file will start with a number. You have to choose another name for your images.


text:
Q: TIMESTAMP column issue CDH5 vs CDH6 in parquet table We recently upgraded our server from CDH 5 to CDH 6 . When inserting data to TIMESTAMP columns using SPARK in parquet tables there is difference how data is inserted.
CDH 5:
HIVE:
If we insert 2019-01-30 to TIMESTAMP column of parquet table and select data from Hive value is '2019-01-30 00:00:00 0'
CDH 6:
HIVE:
If we insert 2019-01-30 to TIMESTAMP column of parquet table and select data from HIVE value is '2019-01-30 04:00:00'
IMPALA:
If we insert 2019-01-30 to TIMESTAMP column of parquet table and select data from  IMPALA value is '2019-01-30 04:00:00'
Please let me know if there is any spark properties we can use . My primary goal is to match HIVE value in CDH5 vs CDH6 and If possible when we select from IMPALA if should be 2019-01-30 00:00:00'

A: To skip issues with data type between Spark and Hive the convention used by Spark to write Parquet data is configurable.
This is determined by the property spark.sql.parquet.writeLegacyFormat. The default value is false. If set to true, Spark will use the same convention as Hive for writing the Parquet data.
val spark = SparkSession
    .builder()
    .appName("MyApp")
    .master("local[*]")
    .config("spark.sql.shuffle.partitions","200") //Change to a more reasonable default number of partitions for our data
    .config("spark.sql.parquet.writeLegacyFormat", true)


text:
Q: Drawing multipe items in svg g elements using d3 I want to draw three different shapes collected inside a g element. I want to draw text, line and a graph. The problem im having with the code below is that the text is shown but the line does not show. It is drawn and I can see it in the source but it is not visible on the screen. What am I missing here?
  //Bind data to a new g element
  line = svg.selectAll("g")
  .data(source)
  .enter()
  .append("g")
  .attr({
    "transform": function(d,i){ return "translate(50 " + (height - 50 + 15 * i) + ")"}
  });

  line.append("text")
  .text(function(d,i){
    return d.name;
  });

  line.append("line")
  .attr({
    "opacity" : 1,
    "stroke-width" : 2,
    "stroke" : "blue",
    "class" : "crisp",
    "x1" : function (d) { return vfTimelineScale(d.start); },
    "y1" : function (d,i) { return (height - 50 + 15 * i); },
    "x2" : function (d) { return vfTimelineScale(d.stop); },
    "y2" : function (d,i) { return (height - 50 + 15 * i); },
  })

A: You are already positioning through the transformation, I presume you don't need the lines to be 450 px offset vertically from the text. Change the formula to something such as...
"x1" : function (d) { return vfTimelineScale(d.start); },
"y1" : 50,
"x2" : function (d) { return vfTimelineScale(d.stop); },
"y2" : 50

You will need to change the 50 value to suit your needs of course.


text:
Q: ROLL_OVER event on all flash content I'm trying to send a hover event from flash to js (in some browsers, the mousemove / mouseover events won't trigger over flash content). I've tried to do     this:
stage.addEventListener(MouseEvent.ROLL_OVER, function():void {
    ExternalInterface.call("alert", "Rolled over!!");
});

But it didn't work. I'm an AS newbie, can you point me to the right direction?

A: also, you have to define a function to the externalinterface to be called.. its a bit overhead:
ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);

more info here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html
use last example.


text:
Q: Upstart script doesn't work I'm trying to create my own script that gets executed on startup and stopped on shutdown (referring to the classic System-V init style), but it won't work!
I've created this script (/etc/init.d/mlogscript):

#!/bin/bash
### BEGIN INIT INFO
# Provides:             logging down time and date of your start/shutdown behaviour
# Required-Start:       $all
# Required-Stop:        $all
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    logs down your start/shutdown behaviour
# Description:          script for logging when you start or shutdown the operating system
### END INIT INFO
# Author: x

# log-file info
FILENAME="logscript.log"
FILEPATH="$HOME/myScripts/"

# other files
UPTIMEFILE=${FILEPATH}"LASTUPTIME.DONOTDELETE"

# fetch specific data
DATE=`date +%m.%d.%Y`
CLOCK=`date +%X`

case "$1" in
    start)
    if [ ! -e "${FILEPATH}${FILENAME}" ]; then
        echo "creating log-file"
        echo -ne "mLog: start/shutdown behaviour\n" >> "${FILEPATH}${FILENAME}"
        echo -e "-------------------------------\n" >> "${FILEPATH}${FILENAME}"
    fi
    echo -e '[' $DATE "]\nuser:\t" $USER "\nstart:\t" $CLOCK >> "${FILEPATH}${FILENAME}"

    # create/update uptime-file
    UPTIME=$(</proc/uptime)
    UPTIME=${UPTIME%%.*}
    echo -ne $UPTIME > $UPTIMEFILE

    echo "log-script started at" $DATE "."
        ;;
    stop)
    if [ -e "${FILEPATH}${FILENAME}" ]; then
        # get uptime from /proc/uptime
        UPTIME=$(</proc/uptime)
        UPTIME=${UPTIME%%.*}

        #
        if [ -e "${UPTIMEFILE}" ]; then
            LASTUPTIME=$(head -n 1 "${UPTIMEFILE}")
            UPTIME=`expr $UPTIME - $LASTUPTIME`
            echo $UPTIME
        fi

        SECONDS=$((UPTIME%60))
        MINUTES=$((UPTIME/60%60))
        HOURS=$((UPTIME/60/60%24))
        DAYS=$((UPTIME/60/60/24%365))
        YEAR=$((UPTIME/60/60/24/365))
        # write to file
        echo -ne "end:\t" $CLOCK "\nuptime:\tY" $YEAR ' D' $DAYS ' H' $HOURS ' M' $MINUTES ' S' $SECONDS "\n\n" >> "${FILEPATH}${FILENAME}"
        echo "log-script stopped"
    else
        echo "log-file doesn't exist"
    fi
        ;;
    restart)
    if [ -e "${FILEPATH}${FILENAME}" ]; then
        exec $(readlink -f "$0") stop
        $(readlink -f "$0") start
        echo -e "log-script restarted"
    fi
        ;;
    reset)
    echo -e "log-script reset"
    if [ -e "${FILEPATH}${FILENAME}" ]; then
        rm "${FILEPATH}${FILENAME}"
        exec $(readlink -f "$0") start
    fi
    ;;
esac
exit 0

After that I set the owner and group of the file to "root" by executing
sudo chown root:root /etc/init.d/mlogscript

Last but not least I created the runtime-specific symlinks within the rc[0-6].d folders:
sudo update-rc.d mlogscript defaults 98

After I rebooted my system nothing happens, why?

A: *

*Open Dash

*Search for "Startup Applications" and open it

*Click on "Add" button.

*The dialog lets you set a name, the command to be executed, and comments.

*Click on "Add" to save that command to the list.

Ubuntu will then run all the commands on this list during start-up.
I use this for running a wallpaper changing script of my own on start-up, and it has proved reliable.
I think you must be knowing this but still, remember to add an & at the end of the command to keep running your script in background, and prevent unnecessary debugging and frustration.
Sorry but I don't know a way to do this from the terminal.


text:
Q: What is the difference between those self-executing anonymous function (aka IIFE) implementation In many books / blog posts the self invoking anonymous function pattern is written like this:
(function() {
  var foo = 'bar';
})();

However running a JSLint on this gives this error:

Move the invocation into the parens that contain the function.

e.g. changing it to this works:
(function() {
  var foo = 'bar';
}());

Questions

*

*Why is the first implementation not good enough for JSLint? What are the differences?

*What is the preferred form? is JSLint always right?

*Why does it work? after all function(){}() throws a SyntaxError: Unexpected token (  But wrapping it with parens makes it all of a sudden work? e.g. (function(){}()) - works fine

(After all this is JavaScript, not Lisp, so what is the effect of the wrapping parens on the ohterwise syntax error?)

EDIT: this is somewhat of a followup to this (I would not say exact duplicate though): JSLint error: "Move the invocation into the parens that contain the function", so my main question is #3, why does it work at all?

A: I don't know how Crockford's opinions were developed, but I can explain why wrapping in parens works.
The function function() { ... } syntax in JavaScript can represent two different things: a function declaration or a function expression.
A function declaration is a statement that defines the function within the current scope under the specified name.
function example() {
    alert("Hello World");
}

example();

A function expression is an expression that evaluates to a new Function instance.
var secondExample = function example() {
    alert("Hello World");
};

secondExample();
example(); // <-- throws an Error: example is not defined.

Whether a occurrence of the syntax is a function declaration or function statement depends on what the parser was expecting. JavaScript's parser is simple. It won't look ahead and notice that the function is followed by (), therefore it should treat it as a expression. It just sees the function at the beginning of a line, and therefore treats it as a statement, which causes a syntax error when it's followed by (). When you wrap it in parentheses, the parser is instead expecting an expression, and it works.
Wrapping in parentheses (wherever you place them) is the the clearest way to do this, but anything that causes the parser to expect an expression will work. For example, the bitwise NOT operator ~:
~function() {
    alert("Hello World");
}();

A: 1.
Apparently this is an issue with conventions. Having the first example shows a "lack of convention" (source). As far as actual differences, there are none. Both will execute without error.
2.
In this case, I prefer your first example, but that is just my convention.  JSLint is often right. So if you want to follow their naming conventions then when it shows a warning based on convention it would make sense to conform to the convention.
3.
This works because wrapping the function(){} inside of a () makes it an expression, which once paired with the final () immediately invokes it. Hence you have an Immediately Invoked Function Expression.


text:
Q: How do you properly use WideCharToMultiByte I've read the documentation on WideCharToMultiByte, but I'm stuck on this parameter:
lpMultiByteStr
[out] Pointer to a buffer that receives the converted string.

I'm not quite sure how to properly initialize the variable and feed it into the function

A: Elaborating on the answer provided by Brian R. Bondy:  Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main()
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1,
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:
Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

A: You use the lpMultiByteStr [out] parameter by creating a new char array.  You then pass this char array in to get it filled.  You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it.  The function will use that pointer to fill your variable.
So you can understand this better:
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

A: Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.
// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
    if( str.empty() ) return std::wstring();
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

A: Here is a C implementation of both WideCharToMultiByte and MultiByteToWideChar.
In both cases I ensure to tack a null character to the end of the destination buffers.

MultiByteToWideChar does not null-terminate an output string if the input string length is explicitly specified without a terminating null character.

And

WideCharToMultiByte does not null-terminate an output string if the input string length is explicitly specified without a terminating null character.

Even if someone specifies -1 and passes in a null terminated string I still allocate enough space for an additional null character because for my use case this was not an issue.
wchar_t* utf8_decode( const char* str, int nbytes ) {
    int nchars = 0;
    if ( ( nchars = MultiByteToWideChar( CP_UTF8,
        MB_ERR_INVALID_CHARS, str, nbytes, NULL, 0 ) ) == 0 ) {
        return NULL;
    }

    wchar_t* wstr = NULL;
    if ( !( wstr = malloc( ( ( size_t )nchars + 1 ) * sizeof( wchar_t ) ) ) ) {
        return NULL;
    }

    wstr[ nchars ] = L'\0';
    if ( MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS,
        str, nbytes, wstr, ( size_t )nchars ) == 0 ) {
        free( wstr );
        return NULL;
    }
    return wstr;
}

char* utf8_encode( const wchar_t* wstr, int nchars ) {
    int nbytes = 0;
    if ( ( nbytes = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS,
        wstr, nchars, NULL, 0, NULL, NULL ) ) == 0 ) {
        return NULL;
    }

    char* str = NULL;
    if ( !( str = malloc( ( size_t )nbytes + 1 ) ) ) {
        return NULL;
    }

    str[ nbytes ] = '\0';
    if ( WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS,
        wstr, nchars, str, nbytes, NULL, NULL ) == 0 ) {
        free( str );
        return NULL;
    }
    return str;
}


text:
Q: finding duplicate field values in solr Using Solr 4.3
I have a field "digest" in a solr index - and I would like to execute a query that will return me all the cases where there are duplicate values of digest. Can this be done?
For the records that have duplicate values, I would like to return other values - such as "url" which may not be duplicated.

A: You have two options, neither perfect.
You can use Grouping/Field Collapsing which will group by digest and can give you other fields, but does not allow you to avoid groups with only 1 element.
Or you can use Facets, which allow you to specify minimum number of elements for that facet value, but do not allow you to see which documents match that facet. Though you might be able to get something useful by using Pivot (nested) facets.


text:
Q: EJB remote invokation from Wildfly to Jboss5.x server Enviornment - Source server@Wildlfy_9.0.2.Final,Destination_Server@Jboss5.x, EJB3.0,BuildingTool@ant
1.Wildfly to Wildfly EJB client without remote-outbound-connections
2.https://docs.jboss.org/author/display/WFLY9/Developer+Guide#DeveloperGuide-EJBinvocationsfromaremoteserver
From above two link i have successfully remote EJB lookup for Wildfly_9.0.2.Final to Wildfly_9.0.2.Final server. After this i want to replace destination server to Jboss 5.x server. I have spent hours looking for tutorials on Google. However I cannot seem to find anything that holds the hand. Can anyone direct me to some link?

A: You have to add an extension for this as the JNDI lokup has changed between AS5  (jnp) and WildFly. I don't know what is thge current status of https://github.com/jboss-set/jboss-as-legacy but this was the goal of this extension.


text:
Q: Show native camera roll exaclty with PhoneGAP (cordova) for iOS I'm developing web app for iOS7 platform with PhoneGap and camera plugin. I want use camera roll with button for turn on capture-view(like as native picker or as facebook photo-mode).
I'm using Cordova Camera API and camera roll looks like otherwise(only photo/video, not button for turn on capture mode). I have read all documentation about plugin and tried use different set of options, but can't find solution.

<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>


text:
Q: jQuery validate max value on Form Submit I want to validate a form, when it gets submitted. I need to check the following things:

*

*Whether the user has selected any option from the dropdown.

*Whether the user has entered a value larger than the max-value

If any of this conditions is not matched, I want to show an error message in a modal window...
How can I achieve this behaviour? Below is a code snippet:

//This function sets max value, based on selected option's data-max
$('select').change(function(e) {
  var selectedIndex = $('select').prop("selectedIndex");
  var selectedOption = $('select').find("option")[selectedIndex];
  $('input[type=number]').attr('max', $(selectedOption).data('max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="./cart_update.php">
  Select Size:
  <select size="1" name="options" class="selectsize">
    <option value="">-- Select --</option>
    <option value="30" data-max="50">30</option>
    <option value="31" data-max="50">31</option>
    <option value="32" data-max="40">32</option>
    <option value="33" data-max="50">33</option>
    <option value="34" data-max="50">34</option>
  </select>
  Quantity
  <input type="number" class="cart_qty" name="product_qty" size="1" value="1" min="1" max="100" />
  <button class="orange medium full add-to-cart" type="submit">Add To Cart</button>
</form>

A: As you didn't give any information on whether you validate the form data within the backend as well, I assume that you don't.

*

*Validating form data only on the client side (i.e. within the client's webbrowser) is not advisable. That is because clients can easily manipulate the javascripte code you're using to validate data. By doing so, it is possible to import fraudulent data into your application (and many many more bad things could happen).

*Validating data on the client side should only be used to give your users a quick feedback on whether the entered information is correct and in accordance to your definitions. Real data validation, before you further use it within your application (i.e. store it within a database, or what ever), should happen on the server side.
I advise you reading these articles to further deep dive into the topic of data validation:

*

*Data form validation (mozilla.org)

*If you're using PHP as a server-side language: PHP 5 Form Validation (w3schools.com) or if you're using javascript as a server-side language: How to Easily Validate Any Form Ever Using AngularJS(thecodebabarian.com)

*Web Form Validation: Best Practices and Tutorials (smashingmagazine.com)
Coming to your question (and assuming you read the articles and now want to validate the data only for the user's sake), here's kind of a commented working code snippet:
$(document).ready(function () {
    // Whenever your form is submitted, execute this function
    $('#ourForm').submit(function (e) {
        // Prevent the browser from executing the default behaviour -> submitting the form
        e.preventDefault();
        // Now check the user's entered information for accordance to your definitions
        // #1: Check whether any checkbox is ticked
        var checkBoxValue = $('#ourCheckbox').val();
        // If checkBoxValue is undefined, there is no checkbox selected,
        if (!checkBoxValue) {
            // There is no checkBox ticked, throw error
            alert('Please select a checkbox!');
            return false;
        }
        // #2: Check whether entered value is smaller than the data-max field of the selected checkbox
        // Receive the user's entered value
        var enteredValue = $('#ourInputfield').val();
        // Receive the max value specified by you from the data-max field
        var maxValue = $('#ourCheckbox option:selected').attr('data-max');
        // If the entered value is bigger than the max-data value
        if (enteredValue > maxValue) {
            // The entered value is bigger than the data-max field of the selected checkbox, throw error
            alert('Your entered value is to large, please choose a value lower than ' + checkBoxValue.value);
            return false;
        }
        // Validating your form data is finsihed, go on with the real work
        alert('Your data looks fine, whoooo!');
    });
});

Here's a working JSFiddle: https://jsfiddle.net/77v1z18v/1/


text:
Q: Can we manually add one entry into dynamic drop down list, If then how in Ruby On Rails I have a student, student_parent and address_detail table i want to add student and it's parent(Father and Mother) address in address_detail table, I have folowing relation between tables
Student:-
has_many :student_parents
has_many :address_details
Student_parent:
belongs_to :student
has_many :address_detail
address_detail:
belongs_to :student
belongs_to :student_parent
In address_detail form i have a drop down for only Father and mother i want to add student entry manually how can i do, Here is my address_detail form``
    <%= simple_form_for @address_detail, :html => { :class => 'form-horizontal' } do |f| %>

   Address Correspond To *

    <%= f.collection_select(:student_parent_id, student_parent_relation_collection , :id, :relation_to_student, {:prompt => true}, :required =>true  )%>
    <%= f.hidden_field :student_id, :value => current_student_id %>

....
.....
Here is my Helper method for Address_correspond_to drop down method
# return collection of parent relation to student

def student_parent_relation_collection
if current_user != nil
  student =  Student.find_all_by_user_id(current_user.id)
  logger.info "student_is = #{student}"
  if student != nil
  return  StudentParent.find_all_by_student_id(student)
 end
end

end
current OutPut is
Father
Mother
I want Out
Student
Father
Mother

A:
if current_user
  student =  Student.find_by_user_id(current_user.id)
  return [student] + student.student_parents if student
end

A: Class AddressDetail < ActiveRecord::Base

  def student_and_parents
    [student, student_parent]
  end

end

Then, in the view you can either refer to
address_detail.student_and_parents

or in User
Class User < ActiveRecord::Base

  has_many :students
  has_many :student_parents, :through => :students

  def students_and_parents
    [students, student_parents].compact.flatten
  end

end

you can refer to
current_user.try(:students_and_parents)


text:
Q: Talend : modifying Webservice call timeout on a job I have a job, using a tESBConsumer component to call a distant webservice.
This webservice takes between 55-65s to answer : default timeout is set to 60s : I have sometimes read Timeout on this webservice call, I want to push it a bit.
I am deploying the job on a jobserver (not on karaf, as we have split configuration : karaf is for services only, jobserver for the jobs).
Thus, talend advice on configuring timeout is to use the org.apache.cxf.http.conduits-common.cfg file, which is a file only available on a Karaf, not on a jobserver ! (See talend doc)
=> Is there a way to configure read timeout option on a jobserver ?

A: Actually, using the advanced settings of tESBConsumer works in this case, even if it says that it is only working on the studio.
So the "timeout" fields could be used for a deployment on a jobserver.


text:
Q: Rewrite a complex link .htaccess My old website have product link like this
domain-name/index.php/product-category/detail/603/product-name.html

my new Wordpress website have product link like this
domain-name/product-category/product-name

i config in .htaccess:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^product-category/detail/([0-9]+)/([a-zA-Z-]*).html /product-category/$2 [QSA,L]

in permalink i config:
/%category%/%postname%

The new site works very correctly, but the old link is not working. Old link always redirect to error 404 absolute, i want to keep old link on google auto redirect to new link. Does anyone have a solution for this please, thank u very much.

A: This should be your rule modified to actually match the requested URL you show:
RewriteEngine On
RewriteRule ^/?index\.php/product-category/detail/\d+/([\w-]+)\.html /product-category/$2 [QSA,END]

But more likely you want the more flexible variant:
RewriteEngine On
RewriteRule ^/?index\.php/([\w-]+)/detail/\d+/([\w-]+)\.html /$1/$2 [QSA,END]

You should prefer to implement such rules in the actual http server's host configuration. If you have no access to that you can use a distributed configuration file (often called ".htaccess"), but that comes with some disadvantages.
I could imagine that it also makes sense to send an external redirection to clients still requesting those old URLs:
RewriteEngine On
RewriteRule ^/?index\.php/([\w-]+)/detail/\d+/([\w-]+)\.html /$1/$2 [QSA,R=301,END]

For that it might make sense to start out with a R=302 temporary redirection and to change that to a R=301 permanent redirection once you checked that everything works as expected. That prevents annoying caching issues...


text:
Q: Multiply values extracted with a select in SQL Using SQL I'd like to multiply values extracted using a select:
Here an example:
SELECT Number1, Number2
FROM myTable
WHERE PrimaryKey = MyPrimaryKey

And the result for example is: 3, 4.
Instead what I'd like to obtain is 12.
So it's possible to make something like this?
SELECT Number1 * Number2
FROM myTable
WHERE PrimaryKey = MyPrimaryKey

A: Yes, it is possible.
SELECT Number1 * Number2
FROM myTable
WHERE PrimaryKey = MyPrimaryKey

A: Yeah you got it
mysql> show create table numbers\G
*************************** 1. row ***************************
       Table: numbers
Create Table: CREATE TABLE numbers (
  'id' int(11) NOT NULL,
  'num1' int(11) DEFAULT NULL,
  'num2' int(11) DEFAULT NULL,
  PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

mysql> select * from numbers;
+----+------+------+
| id | num1 | num2 |
+----+------+------+
|  0 |    3 |    4 |
+----+------+------+
1 row in set (0.00 sec)

mysql> select num1 * num2 from numbers where id = 0;
+-------------+
| num1 * num2 |
+-------------+
|          12 |
+-------------+
1 row in set (0.01 sec)


text:
Q: What are the .htaccess elements REQUEST_FILENAME and THE_REQUEST? What is returned by %{REQUEST_FILENAME} and %{THE_REQUEST}?
I was just checking over our .htaccess file and it dawned on me, I have very little knowledge of this.  The code below uses both.  It works I just want understand it.
#remove / at the end of URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)/$ /$1 [L,R=301]

#remove /index.php at the end of URL
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]

Cheers,
Mark

A: Thanks to Ahmed for the link.
As a quick point of reference to anyone too lazy to click on it here's the bit I was after...

THE_REQUEST
      The full HTTP request line sent by the browser to the server (e.g., "GET /index.html HTTP/1.1"). This does not include any additional headers sent by the browser. This value has not been unescaped (decoded), unlike most other variables below.
REQUEST_URI
      The path component of the requested URI, such as "/index.html". This notably excludes the query string which is available as as its own variable named QUERY_STRING.
REQUEST_FILENAME
      The full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time REQUEST_FILENAME is referenced. Otherwise, such as when used in virtual host context, the same value as REQUEST_URI. Depending on the value of AcceptPathInfo, the server may have only used some leading components of the REQUEST_URI to map the request to a file.


text:
Q: XML Parsing Issue (Multiple Tags) I am parsing XML using a DOM parser but I seem to have come across an issue, I have XML data structured like the following:
    <Bookings>
  <BookingNo>12345678</BookingNo>
  <Pickup>
    <AddressLine>Line 1</AddressLine>
    <AddressLine>Line 2</AddressLine>
    <AddressLine>Line 3</AddressLine>
    <AddressLine>Line 4</AddressLine>
    <AddressLine>Line 5</AddressLine>
    <Postcode>
      <PostcodeOut>pstOut</PostcodeOut>
      <PostcodeIn>pstIn</PostcodeIn>
    </Postcode>
    <AddressCoords>
      <Latitude>1.12345670</Latitude>
      <Longitude>-1.1234567890</Longitude>
    </AddressCoords>
  </Pickup>
  <Destination>
    <AddressLine>Line 1</AddressLine>
    <AddressLine>Line 2</AddressLine>
    <AddressLine>Line 3</AddressLine>
    <Postcode>
      <PostcodeOut>pstOut</PostcodeOut>
      <PostcodeIn>pstIn</PostcodeIn>
    </Postcode>
    <AddressCoords>
      <Latitude>1.1234567890</Latitude>
      <Longitude>-1.1234567890</Longitude>
    </AddressCoords>
  </Destination>
  <PickupTime>DateTime</PickupTime>
  <DestinationTime>DateTime</DestinationTime>
  <VehicleType>Car</VehicleType>
  <NumberOfPassengers>1</NumberOfPassengers>
  <Passengers>
    <PassengerName>Name</PassengerName>
    <PassengerContactNo>123456</PassengerContactNo>
  </Passengers>
   <Mileage>2</Mileage>
</Bookings>

The problem that I am having is that I need to get the AddressLine from both pickup and destination but they need to be separate, with the current code I have, I am pulling them in separately but I am only pulling in the first line (Line 1) of both. The XML parser code I am using is:
public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            xml = EntityUtils.toString(httpEntity);
            InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sbtwo = new StringBuilder();
            String myfeed = null;
            while ((myfeed = reader.readLine()) != null) {
                final String newjsontwo = myfeed.replaceAll(
                        "throw 'allowIllegalResourceCall is false.';", "");
                sbtwo.append(newjsontwo);
            }
            is.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){

                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }

and the code within my main activity is:
XMLParser parser = new XMLParser();
                    Document doc = parser.getDomElement(xml); // getting DOM
                    references = new ArrayList<String>();
                    NodeList nl = doc.getElementsByTagName("Bookings");
                    NodeList nlpickup = doc.getElementsByTagName("Pickup");
                    NodeList nldestination = doc
                            .getElementsByTagName("Destination");
                    AddressData = new StringBuilder();

                    // looping through all item nodes <item>
                    for (int i = 0; i < nl.getLength(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();

                        Element e = (Element) nl.item(i);
                        resultCode = parser.getValue(e, "BookingNo");
                        Pickup = parser.getValue(e, "Pickup");
                        DateTime = parser.getValue(e, "PickupTime");

                        Element etwo = (Element) nlpickup.item(i);

                        PAddressTwo = parser.getValue(etwo, "AddressLine");

                        // System.out.println("/// "+ AddressData);
                        // System.out.println("/////"+parser.getValue(etwo,
                        // "AddressLine"));

                        PPostIn = parser.getValue(etwo, "PostcodeOut");
                        PPostOut = parser.getValue(etwo, "PostcodeIn");

                        Element ethree = (Element) nldestination.item(i);
                        DAddressOne = parser.getValue(ethree, "AddressLine");
                        DPostIn = parser.getValue(ethree, "PostcodeOut");
                        DPostOut = parser.getValue(ethree, "PostcodeIn");

                        splitDate();

                        map.put("BookNo", resultCode);
                        map.put("Datetime", TimeFinal + " on " + DateFinal);
                        map.put("PickupAddress", PAddressTwo + " " + PPostIn
                                + " " + PPostOut);
                        map.put("DestinationAddress", DAddressOne + " "
                                + DPostIn + " " + DPostOut);

                        references.add(resultCode);

                        mylist.add(map);
                    }

                    adapter = new SimpleAdapter(
                            MyJourney.this,
                            mylist,
                            R.layout.myjourneys_item,
                            new String[] { "BookNo", "Datetime",
                                    "PickupAddress", "DestinationAddress" },
                            new int[] { R.id.journeysRefText,
                                    R.id.journeysDateText,
                                    R.id.journeysFromText, R.id.journeysToText });

                }

Where am I going wrong?
I know that there is something called a SAX parser but I can find an example to match what i am looking for.

A: Try this :
    Element element = document.getDocumentElement();

    // For Pickup
    NodeList nodeListPickup = element.getElementsByTagName("Pickup");
    for (int i = 0; i < nodeListPickup.getLength(); i++) {
        Node node = nodeListPickup.item(i);
        NodeList pickUp = node.getChildNodes();

        for (int j = 0; j < pickUp.getLength(); j++) {

            Node nodePickup = pickUp.item(j);
            String name = nodePickup.getNodeName();

            if(name.equals("AddressLine")){
                System.out.println("Pickup > AddressLine > " +nodePickup.getFirstChild().getNodeValue());
            }
        }
    }

    // For Destination
    NodeList nodeListDestination = element.getElementsByTagName("Destination");
    for (int i = 0; i < nodeListDestination.getLength(); i++) {
        Node node = nodeListDestination.item(i);
        NodeList destination = node.getChildNodes();
        for (int j = 0; j < destination.getLength(); j++) {

            Node nodeDestination = destination.item(j);
            String name = nodeDestination.getNodeName();

            if(name.equals("AddressLine")){
                System.out.println("Destination > AddressLine > " +nodeDestination.getFirstChild().getNodeValue());
            }
        }
    }

I have created different NodeList for Pickup and Destination, you can get rest of the inner tags inside both, currently i am showing only for AddressLine. Let me know if this helps.


text:
Q: could not find a storyboard in xcode5 for ios 5 I just created a new iPhone app project in Xcode 5, and set the iOS Deployment Target to 5.0. I tried to run the app in the iOS 5.1 simulator, but I got the following error:
Could not find a storyboard named 'Main' in bundle NSBundle

A: Select Main.storyboard and Make the following changes to Localization section in File Inspector.

A: What kind of project have you choosed (empty, single view)?
Can you see Main.storyboard file in your project resources?
Make sure that in your target (General tab) under Deployment Info section you have selected 'Main' in Main Interface field.

A: Try this
open the info.plist of your project and remove the selected row displayed in screenshot


text:
Q: Mock/stub Arguments.createMap during testing In the React Native library theres a class https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java that is used for Bundles. I'm using PowerMockito to mock the Arguments.createMap() method and return an object with the following snippet:
PowerMockito.when(Arguments.createMap()).thenAnswer(
            new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    return new JavaOnlyMap();
                }
            });

The method I'm testing errors with the following message when the test is ran:
java.lang.UnsatisfiedLinkError: no reactnativejni in java.library.path

when executing this line:
WritableMap map = Arguments.createMap();

Any ideas?

A: Extract the Answer<Object> to a variable. Mockito doesnt like it when you use the new operator as a parameter.
Try something like this:
Answer<Object> answer = new Answer<Object>() {
  @Override
  public Object answer(InvocationOnMock invocation) throws Throwable {
    return new JavaOnlyMap();
  }
}

PowerMockito.when(Arguments.createMap()).thenAnswer(answer);


text:
Q: How to execute Python from NodeJS. Getting "invalid syntax" in my function from python I'm using NodeJS to fire a Python script by way of python-shell package for the cozmo api.
The problem I'm having is when I execute my nodecozmo.py script from the command like it works perfectly.   When I execute the exact same script from my node app, its giving me a syntax error when it executes the py.
Not sure how this could be a syntax error, maybe python-shell package somehow uses an older Python version?  Maybe it doesn't understand handling that syntax?  I tried to go through the source and couldn't see why its causing the issue.
Error
Error:   File "nodecozmo.py", line 16
    def cozmo_program(robot: cozmo.robot.Robot):
                           ^
    SyntaxError: invalid syntax

Python Script
import time
import cozmo

def cozmo_program(robot: cozmo.robot.Robot):
    robot.move_head(-5)
    time.sleep(3)
    robot.drive_wheels(50, -50)
    robot.move_lift(5)
    time.sleep(3)
    robot.move_lift(-1)
    time.sleep(3)

cozmo.run_program(cozmo_program)

Node App
var PythonShell = require('python-shell');
PythonShell.run('./nodecozmo.py', function (err) {
    if (err) throw err;
    console.log('finished executing');
  });

A: Your python script is using type hinting which is a new syntax introduced in Python 3.5. The def statement
def cozmo_program(robot: cozmo.robot.Robot):

is saying that the cozmo_program function takes one argument, robot, which should be of type cozmo.robot.Robot.
Since your script, nodecozmo.py, runs without errors from the command line, you must be running it with a version of Python >= 3.5.
Since NodeJS returns a SyntaxError, NodeJS must be running the script Python version < 3.5. Notice how the error message points directly at the colon:
Error:   File "nodecozmo.py", line 16
    def cozmo_program(robot: cozmo.robot.Robot):
                           ^
    SyntaxError: invalid syntax

Since type hinting is a nicety but not a necessity, you could make your script backwards compatible simply by removing the type hint:
Change
def cozmo_program(robot: cozmo.robot.Robot):

to
def cozmo_program(robot):


text:
Q: Login does nothing in Yii I am new to Yii. I am working in a project now using Yii. The login action does nothing, I really confused. I don't know what to do. So here's my code. Can anyone fix it for me? Thank to you all.

*

*This is the UserIdentity.php
class UserIdentity extends CUserIdentity
{
  private $_id;
  public function authenticate()
  {
   $user = User::model()->findByAttributes(array('username'=>$this->username));

    if ($user===null) {
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    }
    else if ($user->password !== md5($this->password) ) {
                $this->errorCode=self::ERROR_PASSWORD_INVALID;
    }
    else { // Okay!
            $this->errorCode=self::ERROR_NONE;

        }
        return !$this->errorCode;
}

 public function getId()       //  override Id
{
      return $this->_id;
 }
     }

*This is my actionLogin in SiteController.php
public function actionLogin()
{
$model=new LoginForm;

// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

// collect user input data
if(isset($_POST['LoginForm']))
{
    $model->attributes=$_POST['LoginForm'];
    // validate user input and redirect to the previous page if valid
    if($model->validate() && $model->login())
        $this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}

*At last, the authenticate function in LoginForm.php
public function authenticate($attribute,$params)
 {
     if(!$this->hasErrors())  // we only want to authenticate when no input errors
        {
                $identity=new UserIdentity($this->username,$this->password);
                $identity->authenticate();
                switch($identity->errorCode)
                {
                        case UserIdentity::ERROR_NONE:
                                Yii::app()->user->login($identity);
                                break;
                        case UserIdentity::ERROR_USERNAME_INVALID:
                                $this->addError('username','Username is incorrect.');
                                break;
                        default: // UserIdentity::ERROR_PASSWORD_INVALID
                                $this->addError('password','Password is incorrect.');
                                break;
                }
        }
}

A: Try this user identity class
class UserIdentity extends CUserIdentity {

private $_id;

public $role;

const ERROR_EMAIL_INVALID = 3;
const ERROR_STATUS_NOTACTIV = 4;
const ERROR_STATUS_BAN = 5;

/**
 * Authenticates a user.
 * The example implementation makes sure if the username and password
 * are both 'demo'.
 * In practical applications, this should be changed to authenticate
 * against some persistent user identity storage (e.g. database).
 * @return boolean whether authentication succeeds.
 */
public function authenticate() {
    if (strpos($this->username, "@")) {
        $user = User::model()->findByAttributes(array('email' => $this->username));
    } else {
        $user = User::model()->findByAttributes(array('username' => $this->username));
    }
    if ($user === null)
        if (strpos($this->username, "@")) {
            $this->errorCode = self::ERROR_EMAIL_INVALID;
        } else {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if (Yii::app()->getModule('admin')->encrypting($this->password) !== $user->password)
        $this->errorCode = self::ERROR_PASSWORD_INVALID;
    else if ($user->status == 0 && Yii::app()->getModule('admin')->loginNotActiv == false)
        $this->errorCode = self::ERROR_STATUS_NOTACTIV;
    else if ($user->status == -1)
        $this->errorCode = self::ERROR_STATUS_BAN;
    else {
        $this->_id = $user->id;
        $this->username = $user->username;
        $this->errorCode = self::ERROR_NONE;
    }
    return !$this->errorCode;
}

/**
 * @return integer the ID of the user record
 */
public function getId() {
    return $this->_id;
}

}

Here is login action
public function actionLogin() {
    if (Yii::app()->user->isGuest) {
        $model = new UserLogin;

        // collect user input data
        if (isset($_POST['UserLogin'])) {
            $model->attributes = $_POST['UserLogin'];
            // validate user input and redirect to previous page if valid
            if ($model->validate()) {
            /*=========changed HERE===============*/
            //previous code
            //$this->redirect(array("/profile"));
            $url = 'redirect where you want';
            $this->redirect(array($url));
            }
        }
        // display the login form

        $this->render('/user/login', array('model' => $model));

    }
    else
    {
        $user_id = Yii::app()->user->id;
        if($user_id != ''){
            $this->redirect(array("/profile"));
        } else
        $this->redirect(Yii::app()->controller->module->returnUrl);

    }
}

And here is your model
class UserLogin extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe;

/**
 * Declares the validation rules.
 * The rules state that username and password are required,
 * and password needs to be authenticated.
 */
    public function rules()
    {
        return array(
        // username and password are required
            array('username, password', 'required'),
        // rememberMe needs to be a boolean
            array('rememberMe', 'boolean'),
            // password needs to be authenticated
            array('password', 'authenticate'),
        );
    }

/**
 * Declares attribute labels.
 */
    public function attributeLabels()
    {
        return array(
            'rememberMe'=>"Remember me next time",
            'username'=>"username or email",
            'password'=>"password",
        );
    }

    /**
     * Authenticates the password.
 * This is the 'authenticate' validator as declared in rules().
 */
    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())  // we only want to authenticate when no input errors
        {
            $identity=new UserIdentity($this->username,$this->password);
            $identity->authenticate();
            switch($identity->errorCode)
            {
                case UserIdentity::ERROR_NONE:
                    $duration=$this->rememberMe ? Yii::app()->controller->module->rememberMeTime : 0;
                    Yii::app()->user->login($identity,$duration);
                    break;
                case UserIdentity::ERROR_EMAIL_INVALID:
                    $this->addError("username","Email is incorrect.");
                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError("username","Username is incorrect.");
                    break;
                case UserIdentity::ERROR_STATUS_NOTACTIV:
                    $this->addError("status","Your account is not activated.");
                    break;
                case UserIdentity::ERROR_STATUS_BAN:
                    $this->addError("status","Your account is blocked.");
                    break;
                case UserIdentity::ERROR_PASSWORD_INVALID:
                    $this->addError("password","Password is incorrect.");
                    break;
            }
        }
    }
}

By using all the above action model and user identity you can make login in yii easily.


text:
Q: Java: How to sort and show an array of complex object? I need help to find the better way to sort my array and show it on the screen. Here is the complex object:
Category category;
Article article;
BigDecimal price;

And I want to show an Array of this object on this way:
Category
->Article
  ->Price
->Article
  ->Price
  ->Price
->Article
  ->Price
Category
->Article
  ->Price
  ->Price
->Article
  ->Price

So, heres a example of array (Category and Article objects have Id's, but im gonna use name so its gonna be more easy to understand):
{"Kitchen", "Fork", 5}
{"Kitchen", "Fork", 8}
{"Kitchen", "Knife", 5}
{"Kitchen", "Spoon", 3}
{"Bathroom", "Soap", 5}
{"Bathroom", "Shampoo", 3}
{"Bathroom", "Shampoo", 7}

So, I want to show it like this:
Kitchen
->Fork
  ->5
  ->8
->Knife
  ->5
->Spoon
  ->3
Bathroom
->Soap
  ->5
->Shampoo
  ->3
  ->7

I know, im not posting any code, but its because I dont know how to do it. Maybe making a lot of loops, but im here for suggestions..
Sorry for my bad english, I hope you understand!