text:
Q: How to use dotty in scala project? I am working on a Scala project that I run using sbt. I want to use union types which is provided by dotty. I am having trouble in using dotty in my project.
I did this:

*

*Added ./projects/plugins.sbt and ./projects/build.properties with content as mentioned in sbt-dotty.

*Added ./projects/scalafix.sbt and a configuration file
./.scalafix.conf with content scalafixEnabled in ThisBuild := true in it. This is provided in sbt-scalafix
Now if I compile the project, I get a huge list of Migration Warnings and errors like Member Not Found Error, Ambiguous overload, and ends with java.lang.AssertionError: no TypeBounds allowed. Is correcting each of these errors the only way to avoid these?
The project was running fine (with scalaVersion := 2.12.1) before making these changes. Can anyone please help me in making it work?
Edit: sbtVersion = 0.13.13

A: Dotty is currently in an experimental stage (pre-alpha, no public release at the time of writing). The fact that you get compilation errors means the following:

*

*Your setup to compile your project with sbt & dotty is probably correct (that answers the question?)

*Your code base might trigger new bugs in dotty

StackOverflow is not the correct place to discuss bugs in unreleased software. If you manage to minimize your issue please report it on the dotty issue tacker (or come chat gitter). If you are interested in hacking on a compiler there are also plenty of opportunities in these early stages, external contributors are always very welcome!

Even if it's not part of your question I feel obliged to address @JörgWMittag comment. Dotty is not a new programming language. The long-term goal is to be able to cross compile the majority of the Scala ecosystem with both compiler, as it's currently the case with Scala 2.10/2.11/2.12. Dotty itself is an example of such project, every test is run with a version of compiler compiled by scalac (currently the default), and with a bootstrapped version of the compiler (dotty compiled with dotty).
In addition, a community-build infrastructure is currently being setup. It's a repository to gather (forks of) open source Scala projects that can be cross compile with scalac/dotty, which serves as an addition test infrastructure for the compiler.


text:
Q: How to build a dimension from two separate hierarchies in the source data I am trying to create a dimension for the organisation (called DimOrganisation), but I am not sure what to use as the key.
Here is a diagram of the organisation tables...

Enterprises is the top parent table. All data relating to Stock is stored by LocationID (this is called the Stock hierarchy) and all data relating to sales is stored by RevenueCentreID (this is called the Revenue Hierarchy). At the moment, the cubes are only required to show data by ProfitCentreID (we would group the dimension by ProfitCentreID in a view before loading the cube).
Here are a few solutions that I have been considering:

*

*Create a composite key (RevenueCentreLocationKey). You would never want to see the data like that, but I would link the fact table to the correct key when building the cubes (e.g. ProfitCentreKey)

*Only go as far a ProfitCentreID, because that is all that we need. The source data is stored in the data warehouse (together with the fact and dimension tables), so we can get to the more granular data later.

*Create a separate RevenueCentre and Location dimension in the database. However, in the cube, you would only see a dimension going to ProfitCentreKey

I know this is quite subjective, but I would like any advice or ideas that you think might be helpful. Thanks.
I'm using SQL Server 2008 (both for the data warehouse database and the Analysis Services cubes)

A: I would go with solution 3.
While your company doesn't look at RevenueCentres by Location now. having that ability could prove useful in the future.
Are your CostCentres and RevenueCentres real entities, or are they just logical mechanisms to aid in the bookkeeping?
Is there a CostCentre for each RevenueCentre?

redpajama_set_name: RedPajamaStackExchange


text:
Q: transition : resize a div before to display image I wonder me if it's possible in css / pure JS to display an image after that the container has reaches it's size after a transition...
Now the image is displayed before the transition, so sometimes the image is overlapping the container!
Here's what I done so far...
Is there a simplest way to resize images?
What about resizing if I don't specify the width and height of the image?
I'm lost in translation, so if you have a different approach it will be more than appreciate!
Thanks to you folks and have a nice day!!!

function resizePopupToH800(){
            let popup = document.getElementById("popup");
            popup.style.width="800px";
            popup.style.height="600px";
            popup.style.marginLeft="-400px";
            popup.style.marginBottom="-300px";
            setImage("https://dummyimage.com/700x500/c9c9c9/fff","big image");
        }
        function resizePopupToV400(){
            let popup = document.getElementById("popup");
            popup.style.width="400px";
            popup.style.height="550px";
            popup.style.marginLeft="-200px";
            popup.style.marginBottom="-275px";
            setImage("https://dummyimage.com/300x400/c9c9c9/fff","vertical");
        }
        function resizePopupToSQ500(){
            let popup = document.getElementById("popup");
            popup.style.width="500px";
            popup.style.height="500px";
            popup.style.marginLeft="-250px";
            popup.style.marginBottom="-250px";
            setImage("https://dummyimage.com/400x400/c9c9c9/fff","autoportrait");
        }
        function resizePopupToSQ300(){
            let popup = document.getElementById("popup");
            popup.style.width="300px";
            popup.style.height="300px";
            popup.style.marginLeft="-150px";
            popup.style.marginBottom="-150px"; setImage("https://dummyimage.com/200x200/c9c9c9/fff","autoportrait");
        }
        function resizePopupToH550(){
            let popup = document.getElementById("popup");
            popup.style.width="550px";
            popup.style.height="400px";
            popup.style.marginLeft="-275px";
            popup.style.marginBottom="-200px";
            setImage("https://dummyimage.com/475x300/c9c9c9/fff","horizontal");
        }
        function setImage(url,text){
            openPopup();
            let imageRessource = url;
            let legend = document.getElementById("popupTitleDiv");
            let img = document.getElementById("popupImage");
            img.src = imageRessource;
            legend.innerHTML = text;
        }
        function addListeners(){
            let resizerH = document.getElementById("resizerH800");
            resizerH.addEventListener("click", resizePopupToH800);
            let resizerV = document.getElementById("resizerV400");
            resizerV.addEventListener("click", resizePopupToV400);
            let resizerSQ = document.getElementById("resizerSQ500");
            resizerSQ.addEventListener("click", resizePopupToSQ500);
            let resizerSQ3 = document.getElementById("resizerSQ300");
            resizerSQ3.addEventListener("click", resizePopupToSQ300);
            let resizerHL = document.getElementById("resizerH550");
            resizerHL.addEventListener("click", resizePopupToH550);
            let popup= document.getElementById("popup");
            popup.addEventListener("click", closePopup);
            let pop= document.getElementById("openPop");
            pop.addEventListener("click", openPopup);
        }
        function closePopup(){
            let popup= document.getElementById("popup");
            popup.style.display = "none";
        }
        function openPopup(){
            let popup= document.getElementById("popup");
            popup.style.display = "grid";
        }
#test p{
            cursor:pointer;
        }
    /* popup classes */
            *{
                box-sizing: border-box;
            }
            #popup{
                display:grid;
                grid-template-columns: repeat(2, 1fr);
                grid-template-rows:20px auto 20px;
                gap:20px;
                position:absolute;
                color:#ffffff;
                width:500px;
                height:500px;
                opacity:1;
                background-color: #666666;
                z-index:3;
                padding:10px;
                left:50%;
                margin-left:-250px;
                bottom:50%;
                margin-bottom:-250px;
                cursor:pointer;
                border:1px solid #ffffff;
                transition:0.5s;
            }
            #popupTitleDiv{
                grid-column-start:1;
                grid-column-end:3;
            }
            #popupImageDiv{
                position:static;
                grid-column-start:1;
                grid-column-end:3;
                margin-top:auto;
                margin-bottom:auto;
                text-align:center;
            }
            #popupFooterDiv{
                grid-column-start:1;
                grid-column-end:3;
                text-align:right;
            }

    /* popup classes */

brume

©2022

openGalery

resize to 800 x 600 (large)

resize to 400 x 550 (verical)

resize to 500 x 500 (square)

resize to 300 x 300 (square)

resize to 550 x 400 (horizontal)

[EDIT] :
The only turnaround I found at this moment is to display a 1px x 1px image during the transition, then display the image with setTimeOut but it's tricky AMO...
function setImage(url,text){
            openPopup();
            let imageRessource = url;
            let legend = document.getElementById("popupTitleDiv");
            let img = document.getElementById("popupImage");
            img.src = "https://dummyimage.com/1x1/c9c9c9/fff";
            legend.innerHTML = text;
            let timeOut = setTimeout(displayImage,1000,imageRessource);
        }
        function displayImage(img){
            let myimg = document.getElementById("popupImage");
            myimg.src = img;
        }

So there's no image visible during the transition So I changed my transition to : transition:2s; to get a smoother effect.
Any better suggestion if possible?
Thanks.
Nicolas.


text:
Q: When printing array it prints arbitrary symbols because I don't use all array values I'm learning about arrays now in C. The problem that I'm having is that if i give an array a value of for example
char message[100], ch;

but then if I don't use all the chars it gives me some arbitrary symbols. Example
while(toupper(ch = getchar()) != '\n')
{
    message[i] = ch;
    i++;
}

If I would enter 50 chars press enter and then print it with:
for(i = 0; i <= 100 - 1; i++)
    printf("%c", message[i]);

It would print the 50 symbols and then 50 arbitrary sybols more.
in a previous question that I had someone told me that I don't have to use the 100 in the for loop, but with what I replace it.
I hope this gives a full picture of what my problem is, if not let me know.

A: To print 50 characters you need to make sure you have 50 characters in the message array,
The simplest way would be to use i itself.
You have to loop till i ( no. of entered characters <= 100 )
int j ;
for( j = 0; j < i; j++)
    printf("%c", message[j]);

A: An alternative method is to add:
message[i] = '\0';

after the while loop. This will add the terminating byte to message. Then when you output it you can use:
printf("%s", message);

instead of the for loop.

A: In C, strings are terminated with a null character, '\0'. So after your loop, you need to set the last character to that, and then you should print with a single %s (or puts) instead of  looping over the characters again.
while(toupper(ch = getchar()) != '\n')
{
    message[i] = ch;
    i++;
}
message[i] = '\0';
...
printf("%s\n", message);
// or
puts(message);

A: There are two ways to handle this. You can either keep track of the length of the string, or you can use a "sentinel" value, which in C is traditionally a 0 byte (not a '0' character).
Given functions like this:
void print_null_terminated_string(char* s)
{
    while (*s != 0) {
        printf("%c", *s);
        ++s;
    }
}

void print_string_with_known_length(char* s, size_t length)
{
    for (size_t i = 0; i < length; ++i) {
        printf("%c", s[i]);
    }
}

You could use them like this:
while(toupper(ch = getchar()) != '\n')
{
    message[i] = ch;
    i++;
}
message[i] = 0; // Add null terminator
print_null_terminated_string(message); // or just printf("%s", message)

Or:
while(toupper(ch = getchar()) != '\n')
{
    message[i] = ch;
    i++;
}
size_t length = i;
print_string_with_known_length(message, length); // or printf("%.*s", length, message) if you want to be fancy


text:
Q: How to fix 'qr_code' is not a registered tag library. in Django and HTML How to fix 'qr_code' is not a registered tag library. I use Django version 4.1.4.
setting.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'qrcode',
]

In setting.py, if I use qr_code instead of qrcode, this error will occur ModuleNotFoundError: No module named 'qr_code'.
It will display the error 'qr_code' is not a registered tag library.
{% load qr_code %}
{% qr_from_text request.build_absolute_uri size="T" image_format="png" error_correction="T" %}

In HTML, how should I edit?
Command I used to install
django-qr-code 3.1.1
pip install django-qr-code

And I tried installing it with conda after trying it in pip and it didn't work.
conda install -c auto django-qrcode

A: You installed a different library. Indeed, you installed django-qrcode [pypi], not django-qr-code [pypi].
The two are however very similar, you only need to work with:
{% load qr_tags %}

{% qr_from_text request.build_absolute_uri size="T" image_format="png" error_correction="T" %}


text:
Q: RequireJS - Lazy load templates on Marionette ItemView I'm trying to lazy load a template for a Marionette ItemView but things are not working the way I expected.
Following some tips about how to override the getTemplate method, I did the Following:
getTemplate: function () {
    var template = require(['text!templates/login/loginbox-template.html'], function (template) {
        return template;
    });
    return _.template(template);
}

But the output is the function body of the require method.
function localRequire(deps, callback, errback) (... and so on)

And returning the require method is not working too:
getTemplate: function () {
    return require(['text!templates/login/loginbox-template.html'], function (template) {
        return _.template(template);
    });
}

This gives me some errors in the console:
Uncaught RangeError: Maximum call stack size exceeded jquery-1.11.js?v=1393591915026:5801
Uncaught TypeError: Object #<Object> has no method 'slice'

It seems that the getTemplate method is being returned before require is completed. I could wrap the return in a  setTimeout function but this is not by far a good solution.
Any ideas about how to handle this?

A: When require() is used to lazy-load stuff, it is asynchronous. The returned value is irrelevant. What you need is something like:
getTemplate: function () {
    var template;
    require(['text!templates/login/loginbox-template.html'], function (t) {
        template = t;
        // signal the application that template is resolved; I suggest promises
    });
}

Asynchronous means that the result of the execution is not available immediately. The comment signal the application... is a placeholder for the code that will notify the other parts of your application that the result is actually available and they can continue processing. This is tedious if you were not expecting it, but it is how things are.
Take a look at the JS Promise API, implemented by many great libraries, from jQuery to the standalone Q library.


text:
Q: jquery-chosen Dropdown is not populated when all Gridview items are deleted I have a jquery-chosen dropdown box within a Gridview in the FooterTemplate when the user wants to add to the table.
If there are no items in the table, the dropdown properly displays the list that the user can select.  However, if the user deletes all of the items in the table, the dropdown in the EmptyDataTemplate does not display any items.
I believe I have to update the chosen dropdown but is has not worked.
This is my markup:
<asp:GridView ID="DelegateInfoGridView" runat="server"
        AutoGenerateColumns="false" Caption="Delegate Information"
        CaptionAlign="Top" CssClass="grid" RowStyle-Wrap="true"
        HorizontalAlign="Left" ShowFooter="true"
        AllowPaging="true" PageSize="5"  ShowHeaderWhenEmpty="false" onrowediting="DelegateInfoGridView_RowEditing"
        onrowcancelingedit="DelegateInfoGridView_RowCancelingEdit" onrowdeleting="DelegateInfoGridView_RowDeleting"
        onrowupdating="DelegateInfoGridView_RowUpdating"
        ondatabound="DelegateInfoGridView_DataBound"
        onrowcommand="DelegateInfoGridView_RowCommand">
        <Columns>
             <asp:TemplateField HeaderText="Recipient ID">
                <ItemTemplate>
                    <asp:Label ID="deligvLblRecipientID" runat="server" Text='<%# Bind("RecipientID") %>'></asp:Label>
                </ItemTemplate>
             </asp:TemplateField>

             <asp:TemplateField HeaderText="Delegate" ItemStyle-Wrap="false">
                <ItemTemplate>
                    <asp:Label ID="deligvLblRecipientName" runat="server" Text='<%# Bind("RecipientName") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="deligvDDLRecipientName" runat="server"
                                        data-placeholder="Choose delegate…" class="chosen-single">
                    </asp:DropDownList>
                </FooterTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Active">
                <ItemTemplate>
                    <asp:Label ID="deligvLblActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'></asp:Label>
                </ItemTemplate>
                 <EditItemTemplate>
                    <asp:DropDownList ID="deligvDDLActive" runat="server" Text='<%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %>'>
                        <asp:ListItem>Yes</asp:ListItem>
                        <asp:ListItem>No</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
                        <asp:ListItem Selected="True">Yes</asp:ListItem>
                        <asp:ListItem>No</asp:ListItem>
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
                 <ItemTemplate>
                    <asp:Button ID="deligvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
                                Text="Edit" CssClass="gridActionbutton">
                    </asp:Button>
                     <asp:Button ID="deligvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
                                Text="Delete" CssClass="gridActionbutton"  OnClientClick="return confirm('Are you sure you want to delete this Delegate Information?')" >
                    </asp:Button>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:Button ID="deligvUpdateButton" runat="server" CausesValidation="False" CommandName="Update"
                                    Text="Update" CssClass="gridActionbutton"></asp:Button>
                     <asp:Button ID="deligvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
                                    Text="Cancel" CssClass="gridActionbutton"></asp:Button>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Button ID="deligvAddButton" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
                                CssClass="gridActionbutton">
                    </asp:Button>
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>

                Recipient ID
                Delegate
                Active
                Action

                    No Delegates were found for you. Delegates can be added by clicking the 'Add Delegate' Button.

                    <asp:DropDownList ID="deligvDDLRecipientName" runat="server"
                                        data-placeholder="Choose delegate…" class="chosen-single">
                    </asp:DropDownList>

                     <asp:DropDownList ID="deligvDDLActiveInsert" runat="server">
                        <asp:ListItem Selected="True">Yes</asp:ListItem>
                        <asp:ListItem>No</asp:ListItem>
                    </asp:DropDownList>

                    <asp:Button ID="deligvAddButton" runat="server" CommandName="Add" Text="Add Delegate" Width="90%" CausesValidation="false"
                        CssClass="gridActionbutton">
                    </asp:Button>

        </EmptyDataTemplate>
     </asp:GridView>

This is the code-behind that populates the dropdown in the Footer:
 protected void DelegateInfoGridView_DataBound(object sender, EventArgs e)
    {
        try
        {
            m_strUserID = CommonMethods.ParseUserID(User.Identity.Name);

            //Get the Footer controls that have the new entry data
            Control tFooterControls = getFooterControls(DelegateInfoGridView);
            DropDownList ddlRecipientNames = tFooterControls.FindControl("deligvDDLRecipientName") as DropDownList;
            m_strXmlTableData = m_pagingClient.GetAllPossibleDelegates(m_strUserID);
            DataTable tdtAllDelegates = CommonMethods.ParseXML(m_strXmlTableData);
            ddlRecipientNames.DataSource = tdtAllDelegates;
            ddlRecipientNames.DataTextField = "RecipientName";
            ddlRecipientNames.DataValueField = "RecipientID";
            ddlRecipientNames.DataBind();
            ddlRecipientNames.Items.Insert(0, new ListItem("", "0"));//This is needed for the jquery-chosen dropdown to add data-holder text
        }
        catch (Exception ex)
        {
            //TO DO: Response.Redirect("~/Error.aspx");
        }
    }

This is my javascript:

So when the button, deligvAddButtonEmpty, is clicked the items are not added to the dropdown.  I stepped thru the code and the method, DelegateInfoGridView_DataBound, is called at the data is returned.  But the dropdown is empty.
I believe my javascript is not correct but I don't know how to fix it.
Any suggestions would be appreciated.
Thanks.
UPDATE
I changed the javascript on the button click to this:
 $('#deligvAddButtonEmpty').click(function () {
        $("#deligvDDLRecipientName").trigger("chosen:updated");
    });

But still the dropdown is empty when the grid is empty.
UPDATE
I am trying to debug the javascript using Firebug and it seems that the .click function is not called. At least, when I put a breakpoint within the function it does not stop as it does in the document.ready function.
I am using MasterPages and I have the attribute, ClientIDMode = 'Static' but I might not have the 'selector' defined correctly.
UPDATE
It is not when the 'Add Button' is clicked but when the 'Delete button' is clicked and there are no more items in the grid that the chosen dropdown list is not refreshed.
However, I cannot seem to get the click event to trigger for the button.  This is my jquery click function:
 $(document).on("click", "input[id$=deligvDeleteButton]", function () {
        alert("Delegate delete button clicked");
    });

UPDATE
At least, now the click function is being triggered...
I added ClientIDMode-'Static' to the controls that I am accessing and I put the 'click' function within the document.ready() function. However, the update is not adding the list to the dropdown.  This is the function:
$("input[id$=deligvDeleteButton]").click(function () {
              $("input[id$=deligvDDLRecipientName]").val('').trigger("chosen:updated");
            });

UPDATE
I don't know if this is the problem but it might have to do with the control IDs in the jquery script when in the GridView or in the EmptyDataTemplate.  I keep the IDs the same for the dropdown list in the GridView or in the EmptyDataTemplate.  In the code-behind, I identify which control is used by determining if the FooterControl is null.  Then the rest of the C# code is the same because the IDs are the same. However, in the javascript, this may be a problem if the ids are the same.
How can you identify the control in the EmptyDataTemplate and not the Gridview?
UPDATE
I don't know if this is the problem but it might have to do with the control IDs in the jquery script when in the GridView or in the EmptyDataTemplate.  I keep the IDs the same for the dropdown list in the GridView or in the EmptyDataTemplate.  In the code-behind, I identify which control is used by determining if the FooterControl is null.  Then the rest of the C# code is the same because the IDs are the same. However, in the javascript, this may be a problem if the ids are the same.
How can you identify the control in the EmptyDataTemplate and not the Gridview?
I used the following javascript to get the IDs of the 2 dropdown controls and update both of them and the dropdown list is still not populated:
 $("input[id$=deligvDeleteButton]").click(function () {
            $("[id*='deligvDDLRecipientName']").each(function () {
                alert($(this).attr('id'));
                $(this).val("").trigger("chosen:updated");
            });
        });

The alert displays the ID. One is 'deligvDDLRecipientName' and the other is deligvDDLRecipientName_chosen.  I update both of them with the .trigger function but the list is still not populated.

A: I figured this out...
In case anybody has this problem...
It had nothing to do with the chosen plugin.
It was the way I identified if the FooterControl was instantiated.  I checked for null.  But when a user deletes all of the rows, the FooterControl is not null but you still need to use the EmptyTemplateData control.
So instead of checking for null, I checked for Row Count > 0.
That worked.


text:
Q: Оптимизация работы запроса Как можно оптимизировать??? т е берется во внимание как запрос (таблица, бд) так и сам сервер). Записей 17 млн. минимум. Т к по результату запроса строится график - то он не самый лучший. Прошу помощи.
Запрос в принципе не сложный:
SELECT "Extent1"."shop_id",
"Extent1"."receipt_number",
"Extent1"."kassa_number",
"Extent1"."datetime_close",
"Extent1"."z_number",
"Extent1"."receipt_type",
"Extent1"."datetime_open",
"Extent1"."discount_sum",
"Extent1"."receipt_return_number",
"Extent1"."discount_info",
"Extent1"."user_info",
"Extent1"."system_info",
"Extent1"."kassir_id",
"Extent1"."summa",
"Extent1"."card_info",
"Extent1"."receipt_return_kassa_number"
FROM "public"."t_receipts" AS "Extent1"
WHERE "Extent1"."datetime_close" >= 1551444799 AND "Extent1"."datetime_close" <= 1564444799

Сама таблица:
-- Table: t_receipts

-- DROP TABLE t_receipts;

CREATE TABLE t_receipts
(
  kassa_number integer NOT NULL,
  z_number integer NOT NULL,
  receipt_type integer NOT NULL,
  datetime_open integer NOT NULL, -- время открытия чека (unix time)
  datetime_close integer NOT NULL, -- время закрытия чека (unix time)
  discount_sum numeric(12,2) NOT NULL,
  receipt_return_number integer,
  replicstatus integer NOT NULL DEFAULT 0,
  shop_id character varying(32) NOT NULL,
  receipt_number integer NOT NULL,
  discount_info character varying,
  user_info character varying,
  system_info character varying,
  kassir_id integer NOT NULL,
  summa numeric(12,2) NOT NULL,
  card_info character varying,
  receipt_return_kassa_number integer
)
WITH (
  OIDS=FALSE
);
ALTER TABLE t_receipts
  OWNER TO psp;
COMMENT ON TABLE t_receipts
  IS 'таблица чеков';

-- Index: ind_d_t_close

-- DROP INDEX ind_d_t_close;

CREATE INDEX ind_d_t_close
  ON t_receipts
  USING btree
  (datetime_close);

C track_io_timing


text:
Q: Implementing MADD instruction in a multicycle processor I need to modify the datapath of a multicycle processor shown here http://kujo.cs.pitt.edu/index.php/Image:Datapath.png with a multiplier and HI LO registers to enable it to perform the instruction
MADD rs,rt

with the following effect
HI,LO ← HI,LO + R[rs] × R[rt]

The multiplier forms the product in an internal 64-bit register, and the result is taken in the form of a high and low 32-bit halfs. I'm having trouble defining the control signals that are needed for this to work and actually understanding the way the instruction should be performed. Can anyone help me?


text:
Q: Syntax error checking in a Laravel controller I have a syntax error in this code, but I can't find it.
I need to use the Laravel framework.
public function create()

  {
    $users = User::where('user_type', 2)->get();
    $auto_email_templates=AutoEmailTemplate::all();

    foreach($auto_email_templates as $mail) {
        foreach ($users as $user) {

            if( $user->created_at < Carbon::now()->subDays($mail->days)){

                if (EmailSave::where('email_id','user_id')->count()< 1){

                    $mail = new EmailSave;
                    $mail->user_id = $user->id;
                    $mail->email_id =$mail->id;

                    Mail::to($user->email)->send(new Automail($mail));

                    $mail->save();
                }
            }
         }

A:
Last Curly Brace is Missing

    public function create()

      {
        $users = User::where('user_type', 2)->get();
        $auto_email_templates=AutoEmailTemplate::all();

        foreach($auto_email_templates as $mail) {
            foreach ($users as $user) {

                if( $user->created_at < Carbon::now()->subDays($mail->days)){

                    if (EmailSave::where('email_id','user_id')->count()< 1){

                        $mail = new EmailSave;
                        $mail->user_id = $user->id;
                        $mail->email_id =$mail->id;

                        Mail::to($user->email)->send(new Automail($mail));

                        $mail->save();
                    }
                }
             }
          }
    } //you missed it

A: Last two bracket was missing
  public function create()

  {
    $users = User::where('user_type', 2)->get();
    $auto_email_templates=AutoEmailTemplate::all();

    foreach($auto_email_templates as $mail) {
        foreach ($users as $user) {

            if( $user->created_at < Carbon::now()->subDays($mail->days)){

                if (EmailSave::where('email_id','user_id')->count()< 1){

                    $mail = new EmailSave;
                    $mail->user_id = $user->id;
                    $mail->email_id =$mail->id;

                    Mail::to($user->email)->send(new Automail($mail));

                    $mail->save();
                }
            }
         }
     }
 }


text:
Q: Remove duplicates form an array I have an array of objects that looks like this:
var array = [
    {id:123, value:"value1", name:"Name1"},
    {id:124, value:"value2", name:"Name1"},
    {id:125, value:"value3", name:"Name2"},
    {id:126, value:"value4", name:"Name2"}
    ...
];

As you can see, some names are repeated. I want to get a new array with names only, but if some name repeats I don't want to add it again. I want this array:
var newArray = ["Name1", "Name2"];

I'm trying to do this with map:
var newArray = array.map((a) => {
    return a.name;
});

But the problem is that this returns:
newArray = ["Name1", "Name1", "Name2", "Name2"];

How can I set some condition inside map, so it won't return an element that already exists? I want to do this with map or some other ECMAScript 5 or ECMAScript 6 feature.

A: Many good answers here. I just would like to contribute with some diversity with hopes to give you another perspective.
Arrays are of object type in JavaScript, so they can be used as a hash at the same time. By using this functionality we can greatly simplify the job to be done in a single reduce operation with O(n) time complexity.
If you are not happy with your array holding some properties other than the array keys you might consider keeping a separate hash object as well.

var array = [{id:123, value:"value1", name:"Name1"},
             {id:124, value:"value2", name:"Name1"},
             {id:125, value:"value3", name:"Name2"},
             {id:126, value:"value4", name:"Name2"}
            ],
result = array.reduce((p,c) => p[c.name] ? p : (p[c.name] = true, p.push(c.name), p), []);
console.log(result);

A: I agree that if you only need the name values, a Set is the way to go.
However, if you want to get an array of unique objects based on the name property, I'd suggest to use a Map. A quick way to create a Map, is via an array of [key, value] arrays:

const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }],
      unique = new Map(array.map(obj => [obj.name, obj]));

// To get the unique objects
const uniques = Array.from(unique.values());

// Get the names like you already did:
console.log("Names:", uniques.map(obj => obj.name));

// If you ever need the complete array of unique objects, you got a ref:
console.log(JSON.stringify(uniques));
.as-console-wrapper { min-height: 100%; }

An added benefit of Map is that you get both the filter functionality that cuts out the non-uniques, without loosing the connection with the source objects. Of course, it's only needed if you need to reference the unique set of objects multiple times.

A: If you are looking for a JavaScript solution that is not ES 6 (no Set) you can use the Array's reduce method:

var array=[
  {id:123, value:"value1", name:"Name1"},
  {id:124, value:"value2", name:"Name1"},
  {id:125, value:"value3", name:"Name2"},
  {id:126, value:"value4", name:"Name2"}
];
var names = array.reduce(function (a, b) {
  if (a.indexOf(b.name) == -1) {
    a.push(b.name)
  }
  return a;
}, []);

console.log(names);

A: With ES6 this should do the job.

var array=[
    {id:123, value:"value1", name:"Name1"},
    {id:124, value:"value2", name:"Name1"},
    {id:125, value:"value3", name:"Name2"},
    {id:126, value:"value4", name:"Name2"}
];

var set = new Set();

array.forEach((a)=>{
    set.add(a.name);
});

console.log(Array.from(set));

A: If you're limited to ES5, I would use Lodash's _.uniq
var newArray = _.uniq(array.map(function(a) {
  return a.name;
}));

A: With ES6, you could use Set for unique values, after mapping only the names of the objects.
This proposal uses a spread syntax ... for collecting the items in a new array.

const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }],
      names = [...new Set(array.map(a => a.name))];

console.log(names);

A: Using UnderscoreJS,

array = [{id:123, value:"value1", name:"Name1"}, {id:124, value:"value2", name:"Name1"}, {id:125, value:"value3", name:"Name2"}, {id:126, value:"value4", name:"Name2"}];
get_names =  _.pluck(_.uniq(array, 'name'), 'name')
console.log(get_names)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

`

A: Personally I don't see why everyone is getting all fancy with ES 6. If it were my code I'd prefer to support as many browsers as possible.

var array=[
{id:123, value:"value1", name:"Name1"},
{id:124, value:"value2", name:"Name1"},
{id:125, value:"value3", name:"Name2"},
{id:126, value:"value4", name:"Name2"}
];

   // Create array of unique names
var a = (function(a){
  for (var i = array.length; i--;)
    if (a.indexOf(array[i].name) < 0) a.push(array[i].name);
  return a;
})([]);

console.log(a);

A: You could also simply combine map with filter

var array = [
  {id:123, value:"value1", name:"Name1"},
  {id:124, value:"value2", name:"Name1"},
  {id:125, value:"value3", name:"Name2"},
  {id:126, value:"value4", name:"Name2"}
];

var unique = array
  .map( item => item.name )
  .filter( ( item, idx, arr ) => arr.indexOf( item ) == idx )

console.log(unique)

A: You can use Object.keys() to get the array of a given object's own enumerable property names from the object result of iterating array variable with Array.prototype.reduce() where the keys are the destructed names
Code:

const array = [{id:123, value:"value1", name:"Name1"}, {id:124, value:"value2", name:"Name1"}, {id:125, value:"value3", name:"Name2"}, {id:126, value:"value4", name:"Name2"}],
      names = Object.keys(
        array.reduce((a, { name }) => (a[name] = 1, a), {})
      )

console.log(names)

A: That's how I did it, using a separate empty array.

var array = [
   {id:123, value:"value1", name:"Name1"},
   {id:124, value:"value2", name:"Name1"},
   {id:125, value:"value3", name:"Name2"},
   {id:126, value:"value4", name:"Name2"}
];

var array2 = []

for (i=0; i<array.length;i++){
   if (array2.indexOf(array[i].name) == -1){
     array2.push(array[i].name);
    }
}

console.log(array2)

A: Try this:
nArr = [];
array.forEach((a) => {
    if (nArr.indexOf(a.name) < 0) {
        nArr.push(a.name);
    }
});

A: In ES5, use an object as a dictionary for O(n) performance.
This will only work if all the keys are Strings.
var array = [
    {id: 123, value: "value1", name: "Name1"},
    {id: 124, value: "value2", name: "Name1"},
    {id: 125, value: "value3", name: "Name2"},
    {id: 126, value: "value4", name: "Name2"}
];

var allNames = array.map(item => item.name);

var map = {};
allNames.forEach(name => {
  map[name] = true;
});
var uniqueNames = Object.keys(map);

console.log(uniqueNames);

You could do the same thing in one expression if you like:
var uniqueNames = Object.keys(allNames.reduce((m, n) => (m[n] = true, m), {}));

but I find the imperative form easier to read.

A: Use array#forEach() and array#indexOf() methods like this if you want maximum compatibility yet, concise syntax:

const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }]

// initialize an empty array named names
let names = [];

// iterate through every element of `array` & check if it's 'name' key's value already in names array if not ADD it
array.forEach(function(element) { if (names.indexOf(element.name) === -1) names.push(element.name) });
// or use tilde like this:
//array.forEach(function(element) { if (~names.indexOf(element.name)) names.push(element.name) });

console.log(names);

However, if compatibility is not an issue use ECMAScript 6's Set object, array#map and Array.from() methods like this:

const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }];

// iterate through every element from array using map and store it in Set(a Set won't have duplicates) then convert the Set back to Array(using Array.from)
let names = Array.from(new Set(array.map(element => element.name)));

console.log(names);

A: I see there is a lot of spread-Set-like solutions, that aren't optimal.
This solution is simpler, more efficient and doesn't needs to recreate array:

const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }]

const res = array.map(e => e.name)
                 .filter((e, i, a) => a.indexOf(e) == i)

console.log(res)

A: For those seeking a 1 liner
const names = array.reduce((acc, {name}) => acc.includes(name) ? acc : [name, ...acc], []);

or without using methods on the array's prototype
const { reduce, includes } = Array;
const names = reduce(array, (acc, {name}) => includes(acc, name) ? acc : [name, ...acc], []);

could be usefull for writing some pure functions for dealing with this
const get_uniq_values = (key, arr) => reduce(arr, (a, o) => includes(a, o[key]) ? a : [o[key], ...a], []);

A: var __array=[{id:123, value:"value1", name:"Name1"},{id:124, value:"value2", name:"Name1"},{id:125, value:"value3", name:"Name2"},{id:126, value:"value4", name:"Name2"}];

function __checkArray(__obj){
    var flag = true;
    for(let i=0; i < __array.length; i++){
        if(__obj.id == __array.id){
            flag = false;
            break;
        }
    }

    return flag;
}

var __valToPush = {id: 127, value: "value5", name: "Name3"};
if(__checkArray(__valToPush)){
    __array.push(__valToPush)
}


text:
Q: neural netork from scratch using one hidden layer and sigmoid activation i am making a neural network for scratch from practise and i am not very experienced python programmer.
i know most of the maths concepts of neural network. my model is in not behaving well.derivation of sigmoid function is h(x)*(1-h(x)) but i am not sure that line of code is correct,i searched it on google and everyone have used tanh activation.and i am not really sure delta 2.i have no idea where my code is going wrong.i have few doubts of how do we subtract the prediction (y)-label(y). this is a three class classifier.
  delta3[range(m1), y] -= 1

this line of code is also not clear to me,i have copied it from online just putting my m1(total number of examples in it).because my y matrix(labels in form of 0,1,2) is a vector of order(150,1) and the the prediction matrix is of (151,21) sp how do we subtract them.
#labels or classes
#1=iris-setosa
#2=iris-versicolor
#0=iris-virginica

#features
#sepallength
#sepalwidth
#petallengthcm
#petalwidth

import pandas as pd
import matplotlib.pyplot as plt
import csv
import numpy as np
df=pd.read_csv('Iris.csv')

df.convert_objects(convert_numeric=True)
df.fillna(0,inplace=True)

df.drop(['Id'],1,inplace=True)
#function to convert three labels into values 0,1,2
def handle_non_numericaldata(df):
    columns=df.columns.values
    for column in columns:
        text_digit_vals={}
        def convert_to_int(val):
            return text_digit_vals[val]
        if df[column].dtype!=np.int64 and   df[column].dtype!=np.float:
           column_contents=df[column].values.tolist()
           unique_elements=set(column_contents)
           x=0
           for unique in unique_elements:
               if unique not in text_digit_vals:
                    text_digit_vals[unique]=x
                    x+=1
            df[column]=list(map(convert_to_int,df[column]))
      return(df)
handle_non_numericaldata(df)

x=np.array(df.drop(['Species'],1).astype(float))
y=np.array(df['Species'])

m1=np.size(y)

theta=np.ones(shape=(4,1))
theta2=np.ones(shape=(1,21))
#no of examples "m"

#learning rate alpha
alpha=0.01
#regularization parameter
lamda=0.01
for i in range(1,2):
    z1=np.dot(x,theta)
    sigma=1/(1+np.exp(-z1))

    #activation layer 2.
    a2=sigma
    z2=np.dot(a2,theta2)

    probs=np.exp(z2)

    softmax=probs/np.sum(probs,axis=1,keepdims=True)
    delta3=softmax

    print(softmax)

    delta3[range(m1), y] -= 1

    A2=np.transpose(a2)
    dw2 = (A2).dot(delta3)
    W2=np.transpose(theta2)

    delta2=delta3.dot(W2)*sigma*(1-sigma)
    X2=np.transpose(x)
    dw1=np.dot(X2,delta2)

    dw2=dw2-lamda*theta2
    dw1=dw1-lamda*theta

     theta =theta -alpha* dw1

    theta2= theta2-alpha * dw2
    correct_logprobs=-np.log(probs[range(m1),y])
    data_loss=np.sum(correct_logprobs)
    data_loss+=lamda/2*(np.sum(np.square(theta))+ np.square(theta2))
    ( 1./m1*data_loss)

my output for theta(weights)is
[[ 1.22833047]
 [ 1.22591229]
 [ 1.22341726]
 [ 1.22162091]]

which obviously can not be correct.


text:
Q: UITextView in a UITableViewCell: first responder problem I have a UITextView in a UITableViewCell which grows together with it.
Using
[myTableView beginUpdates];
[myTableView endUpdates];

in textViewDidChange and setting the height of the cell properly, I'm getting close to the solution.
But I've a problem tied to the first responder.
I set the textview in my custom cell to become the first responder ('cause I want to start with the open keyboard) on the view loading, but the textview is nil in viewDidLoad, viewWillAppear, viewDidAppear, only when I write a char I can see it's not nil.
I connected the textview in the IB custom cell with an IBOutlet in my viewcontroller.

A: I resolved putting
[myTextView becomeFirstResponder];

in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;


text:
Q: Search key by value in multi dimensional array Using PHP's website as a reference I'm trying to search for a key of the known value in associative array:
http://php.net/manual/en/function.array-search.php
The following code always returns 1, but suppose to return 120:
$location_key = array_search(1, array_column($locations, 'main'));

print_r($locations):
Array
(
    [120] => Array
        (
            [clientid] => 122103
            [name] => HQ
            [address] => 2013 BENSON GARDEN BLVD
            [address2] =>
            [city] => OMAHA
            [state] => NE
            [zip] => 68134
            [country] => UNITED STATES
            [lat] => 00.000
            [lng] => -0.0000
            [taxrate] => 0
            [main] => 1
            [active] => 1
            [contactid] => 14
        )

    [122] => Array
        (
            [clientid] => 122103
            [name] => Branch
            [address] => 515E E 72ND ST
            [address2] =>
            [city] => NEW YORK
            [state] => NY
            [zip] => 10021
            [country] => UNITED STATES
            [lat] => 40.766705
            [lng] => -73.952965
            [taxrate] => 0
            [main] => 0
            [active] => 1
            [contactid] => 0
        )

)

Not sure why PHP's website is referencing the highest up voted "User Contributed Note" which doesn't work.

A: This is because array_column() doesn't keep your keys. So you first need to array_combine() the keys with the array from array_column(), e.g.
$location_key = array_search(1, array_combine(array_keys($locations), array_column($locations, 'main')));


text:
Q: Performance and Load testing tools I am looking for open source tools that can assist me identify performance issues for a web application built using Asp.net MVC and SQL Server 2008. I may need to load test the application to identify the max concurrent users it supports. Any good collection of tools that can help ?

A: Apache JMeter is a good tool which has a rich set of components to test different aspects of  your application.  There are components for web and database aspects of your project.
As a follow up, this tool focuses on gather metrics about the 'externals' of your application.  Things such as http roundtrips, sql duration...  You wouldn't use this tool to measure your internal .NET performance.

A: The Load Testing tools that come with Visual Studio Ultimate are invaluable for load testing a .NET app.  You can get amazing insight into your app, ASP.NET and the limitations of your hardware.  I could not be more happy with it.  If you have issues setting it up, just browse the web and you will find lots of articles for troubleshooting setup issues.  That is probably the only drawback I can think of (initial setup can be a pain).

A: I use jMeter for my dev load testing, it is 100% open source.
http://jmeter.apache.org/
You can set the concurrent users, login parameters etc all from the UI.
I also use the jmeter-plugins for improved reporting within jMeter.
http://jmeter-plugins.org/?utm_source=jpgc&utm_medium=link&utm_campaign=main

A: I agree with others - JMeter is a perfect tool to load and functional testing. It has good original documentation and a lot of other sources, including video tutorials.

A: I really like dotTrace from jetbrains.
it lays out a very nice spectrum of what part of the code is using how much of your CPU but it is not open source.


text:
Q: Setting up programmatically the Youtube YTPlayer for iOS I am having problems setting up the YTPlayer from Youtube API programmatically and not over Storyboard as they show in their example..
This is what I have attempted to do but not luck, the video won't event load..
This is my viewDidLoad where I tried to set everything up.. Also, I almost forgot to say that I downloaded their master framework and added to my project. I changed the path as well for the .html file. I have already tried as they show with Storyboard and works but I really wanna to be able to do it programmatically.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.myView = [[YTPlayerView alloc] initWithFrame:CGRectMake(10, 80, 300, 275)];
    self.myView.backgroundColor = [UIColor lightGrayColor];

    [self.view addSubview:self.myView];

    [self.myYoutubePlayer loadWithVideoId:@"Yf5_ZQcP7y0"];

    self.playBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 400, 120, 80)];
    [self.playBtn setTitle:@"Play" forState:UIControlStateNormal];
    self.playBtn.backgroundColor = [UIColor redColor];
    [self.playBtn addTarget:self action:@selector(playVideo:) forControlEvents:UIControlEventTouchDown];

    self.stopBtn = [[UIButton alloc] initWithFrame:CGRectMake(190, 400, 120, 80)];
    [self.stopBtn setTitle:@"Stop" forState:UIControlStateNormal];
    self.stopBtn.backgroundColor = [UIColor redColor];
    [self.stopBtn addTarget:self action:@selector(stopVideo:) forControlEvents:UIControlEventTouchDown];

    [self.view addSubview:self.playBtn];
    [self.view addSubview:self.stopBtn];

}

And the play and stop methods...
- (IBAction)playVideo:(id)sender {
    [self.myYoutubePlayer playVideo];
}

- (IBAction)stopVideo:(id)sender {
    [self.myYoutubePlayer stopVideo];
}

If more information is needed please ask first, I will be happy to provide it.. :) thanks!

A: The problem I had here was that the YTPlayerView framework didn't had properly define the iframe.html file to be loaded and use for the player. So, I fixed changing the TYPlayerView.m within the function -loadWithPlayerParams: and change whatever is there for the path of this file..
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"YTPlayerView-iframe-player"
                                                 ofType:@"html"
                                            inDirectory:@""];

This will make the job done..! :)

A: I think you have an error on your code.
You're calling "loadWithVideoId" on "self.myYoutubePlayer" and it should on "self.myView"


text:
Q: Javascript: algorithm to convert Binary search tree to doubly linked list I am trying to write the algorithm to convert a BST to a doubly linked list. This is what I have so far. Below is the code:

function TreeNode(val) {
     this.val = val;
     this.left = this.right = null;
}

function BinaryTree() {
    this.root = null;
}

BinaryTree.prototype.push = function(val) {
    var root = this.root;

    if(!root) {
        this.root = new TreeNode(val);
        return;
    }

    var currentNode = root;
    var newNode = new TreeNode(val);

    while(currentNode) {
        if (val < currentNode.val) {
         if(!currentNode.left) {
            currentNode.left = newNode;
            break;
          } else {
              currentNode = currentNode.left;
          }
        } else if(val > currentNode.val) {
         if(!currentNode.right) {
            currentNode.right = newNode;
            break;
          } else {
              currentNode = currentNode.right;
          }
        }
    }
}
var bt = new BinaryTree();
bt.push(4);
bt.push(2);
bt.push(5);
bt.push(1);
bt.push(3);
//console.log(bt);
//var node = bt.root;
function Node(node) {
  //this.data = value;
  //this.previous = this.next = null;
  var head = null;
  var tail = null;
  var prev = null;
  console.log(bstToLL(node, head, prev, tail));
}

//function DoublyLinkedList() {
//  this.head = null;
//  this.prev = null;
//  this.tail = null;
//}

function bstToLL(node, head, prev, tail) {
 if (node === null) {
   return;
  }

  bstToLL(node.left, head, prev, tail);
  if (head === null) {
   head = node;
    //console.log(head)
  }
  if (prev === null) {
   prev = node;
    //console.log(prev)
  } else {
   //console.log(node);
    //console.log(prev);
    node.left = prev;
    prev.right = node;
  }
  prev = node
  bstToLL(node.right, head, prev, tail);
  if(node.right === null) {
   tail = node;
  }
  return head;
}

Node(bt.root);

The code works, but I don't think it is getting the right result. The binary tree looks like-
    4
   / \
  2   5
 / \
1   3

When I return the head from the bstToLL() method, I get an object with val 4 pointing to right child 5 and left child 2 and so on and so forth.
If you run the code, and check the debugger you will see the head object.
Can someone please guide me if I am doing this the right way, and how to fix the result?

A: Here is some code which converts a binary tree into a LinkedList. It will log 1, 2, 3, 4, and 5, in order:
function TreeNode(left, value, right) {
  this.left = left;
  this.value = value;
  this.right = right;
}

function ListNode(prev, value, next) {
  this.prev = prev;
  this.value = value;
  this.next = next;
}

function LinkedList(head, tail) {
  if (tail === undefined) tail = head;
  this.head = head;
  this.tail = tail;
}
LinkedList.prototype.addToStart = function(list) {
  this.head.prev = list.tail;
  list.tail.next = this.head;
  this.head = list.head;
}
LinkedList.prototype.addToEnd = function(list) {
  this.tail.next = list.head;
  list.head.prev = this.tail;
  this.tail = list.tail;
};

function bstToLL(tree) {
  var centerNode = new ListNode(null, tree.value, null);
  var list = new LinkedList(centerNode);
  if (tree.left) list.addToStart(bstToLL(tree.left));
  if (tree.right) list.addToEnd(bstToLL(tree.right));
  return list;
}

var tree = new TreeNode(
  new TreeNode(
    new TreeNode(null, 1, null),
    2,
    new TreeNode(null, 3, null)
  ),
  4,
  new TreeNode(null, 5, null)
);
var linkedList = bstToLL(tree);
for (var node = linkedList.head; node; node = node.next) console.log(node.value);


text:
Q: Filter excel spreadsheet by month and year So I need to find the max price and min price for each month of each year.
Sub Anaylze()
Dim datemonthcount As Long
Dim dateyearcount As Long
Dim yearcount As Long
Dim month As Long
Dim yearstart As Long
Dim maxprice As Long
Dim minprice As Long
Dim rowprice As Long
Dim percentchange

Dim counterlong As Integer

rowprice = 1
yearstart = 2002
counterlong = 0

    Range("A1").Select
    Do Until IsEmpty(ActiveCell) Or ActiveCell.Value = 0 Or IsNumeric(ActiveCell) = False
        counterlong = counterlong + 1 'Increments the counter
         If year(ActiveCell.Text) <> year((ActiveCell.Offset(-1, 0).Text)) Then
         dateyearcount = dateyearcount + 1
         End If
         ActiveCell.Offset(1, 0).Select ' Step down 1 row from present location.
    Loop

    For yearcount = 0 To dateyearcount
    For month = 1 To 12
    'Range("A1", "B" & counterlong).AutoFilter Field:=1, Criteria1:=">=" & month & "/01/" & yearstart, Operator:=xlAnd, Criteria2:="<=" & month & "/31/" & yearstart
    maxprice = WorksheetFunction.Max(Range("A1", "B" & counterlong).AutoFilter(Field:=1, Criteria1:=">=" & month & "/01/" & yearstart, Operator:=xlAnd, Criteria2:="<=" & month & "/31/" & yearstart))
    minprice = WorksheetFunction.Min(Range("A1", "B" & counterlong).AutoFilter(Field:=1, Criteria1:=">=" & month & "/01/" & yearstart, Operator:=xlAnd, Criteria2:="<=" & month & "/31/" & yearstart))
    Cells(rowprice, "g") = maxprice
    Cells(rowprice, "h") = minprice
    rowprice = rowprice + 1
    Next
    yearstart = yearstart + yearcount
    Next

End Sub

My biggest issue is trying to get the filter to work, my data is formatted in this manner
10/26/2012   61.66
10/25/2012   61.6

A: Yea, so as Nutsch pointed out - the easiest way to do this is probably with a pivot table:
First you can split up your date into month, day, year:

Then you can adjust your pivot table value field settings:

EDIT/ADDITION
So since you changed your question - here is how I would do what you have been saying in the comments:
=MAX(IF($B$2:$B$22=(B2-1),$E$2:$E$22))

This is an array formula you can enter with control-alt-delete.

And then you can summarize that data however you want.

A: I Think Stepan1010's answer is in the right direction
but if you want VBA code for customization , here is the code for your reference
Sub testing()
    Dim dataArray As Variant ' contains  DATE,VALUE
    Dim intArray As Variant ' contains uniqute identifer MM-YYYY,has operation or not ( BOOLEAN)
    Dim resultArray As Variant ' contains the min/max value, and min / max of the previous month
    Dim min As Double
    Dim max As Double
    With ActiveSheet
        Height = .Cells(.Rows.Count, 1).End(xlUp).Row
        If Height < 2 Then
            MsgBox "Are you sure there's only 1 line or 0 line of data and still want to process?"
            Exit Sub
        End If

        'FIRST SORT THE DATA BY date ascending order
        Application.CutCopyMode = False
        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=Range("A1:A" & Height), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange Range("A1:B" & Height)
            .Header = xlGuess
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        ReDim dataArray(1 To Height, 1 To 2)
        ReDim intArray(1 To Height, 1 To 2)
        ReDim resultArray(1 To Height, 1 To 3)
        dataArray = .Range(.Cells(1, 1), .Cells(Height, 2)).Value
        For i = LBound(intArray, 1) To UBound(intArray, 1)
            intArray(i, 1) = Month(dataArray(i, 1)) & "-" & Year(dataArray(i, 1))
            intArray(i, 2) = False
        Next i

        lastMax = 1
        For i = LBound(dataArray, 1) To UBound(dataArray, 1)
            If Not intArray(i, 2) Then ' not yet found
                    min = dataArray(i, 2)
                    max = dataArray(i, 2)
                For j = i To UBound(dataArray, 1) ' loop later elements
                    If intArray(j, 1) = intArray(i, 1) Then ' if same MM-YYYY
                        If dataArray(j, 2) < min Then
                            min = dataArray(j, 2)
                        End If

                        If dataArray(j, 2) > max Then
                            max = dataArray(j, 2)
                        End If

                        intArray(j, 2) = True 'mark as found(operated)
                    End If
                Next j

                resultArray(i, 1) = min
                resultArray(i, 2) = max

                If i = 1 Then
                    resultArray(i, 3) = 0
                Else
                    resultArray(i, 3) = (min / lastMax) * 100
                End If
                If resultArray(i, 2) > 0 Then
                    lastMax = resultArray(i, 2)
                End If
            End If
        Next i

        ' YOU CAN CHANGE THE VALUE  3 ,5  to the column you prefer
        .Range(.Cells(1, 3), .Cells(Height, 5)).Value = resultArray

    End With
End Sub


text:
Q: Why we need auxiliary instance in TSPITR Need help!
I've read Database Backup and Recovery User's Guide 11g but I can't uderstand why we need auxiliary instance to perform tspitr.
 We can do complete recovery of tablespace within same instance, why it's impossible for tspitr?
Here Hemant K Chitale says: "You cannot recover a tablespace to an SCN that is lower than the rest of the database.". Can anyone help me to uderstand why?
In this message is shown that when we turn tablespace offline, its SCN becomes lower than SCN of other tablespaces after a while, and when we turn it online "it will not apply redo it will just adopt current SCN".
So, why database cannot open recovered until time datafile adopting it's SCN to current? It'so due to technical aspects of OracleDB or there is another reason?

A: TL;DR to be able to restore data+undo without overwriting the entire current undo.
When you perform RMAN online backup, some transactions are in the middle of processing, they did change something but not yet performed their COMMIT. Transactional model of work ("atomicity") requires those transactions to be rolled back (completely undone) on recovery. Oracle engine does this automatically. Oracle engine does not allow onlining tablespace if this cannot be done, to protect user from seeing possibly inconsistent data. So do transactions save somehow the "consistent" data before they change it? Yes, in the undo tablespace (or a "rollback segment"). This is why, recovering a tablespace, you cannot "forget" it had undo, you need to recover undo from the same point in time (same SCN).
To sum up, Oracle engine needs to have undo data synchronized with from the same point in time as the main data.
Undo is, usually, put into a single tablespace despite it is being a mix of pieces of "consistent" information from many different data tablespaces. This is why you TSPITR to an auxiliary instance - to be able to restore data+undo without overwriting the entire current undo.
Once auxiliary is online, the auxiliary's data has been made consistent and auxiliary's undo is no longer needed.


text:
Q: how do I add an ajax response to my form without adding a new js file? I have this simple submission form and I want to "ajaxify" it so the user isn't redirected to this page thanks.php after submission. I want the content from thanks.php to respond and show inside the div.
What jquery code will plug right into this to show the response.

<form method="post" action="http://domain.com/thanks.php">
<input type="text" placeholder="Enter Email" name="email" id="email" >
<input type="submit" name="submit" value="Submit" ></form>

A: I would give 'form' and 'div' a class or id so it is not so generic, but this should work.
$("form").submit(function (){
    $.ajax({
        url: "http://{url}/thanks.php",
        type: 'POST',
        data: {email: $("#email").val()},
        success: function ( data ) {
          $("div").html(data);
        }
    });

    return false;
});


text:
Q: upload file to server and make a pointer to it using xml My web application allow the web admin to upload file to the server and name this file "input for file name and input for the file". On the files page the user can click the file name and get the file uploaded by the admin. My question is how I can upload a file and get the entered name using XML.  I know how to upload file to the server using JSP/servlet I just need to link the file name with the file uploaded to the server
thank you

A: When saving the file in your server, you will create a new File. You have the option to set the name here.
String fileName = request.getParameter("fileName");
File baseDir = new File("/path/to/save/the/files/");
File file = new File(baseDir, fileName);
//here you receive the InputStream that holds the data from the file uploaded
//since I don't know how you're retrieving it, I'll put three dots
InputStream inputStream = ...
//save the file in disk...


text:
Q: How to get Joomla login form url for redirection I have custom component. For now everyone can access the page with this component. I want to redirect user to login page if he is not loged in. How to get login page url?
In my components view I write:
if($user->id != 0) {
    ..
}
else {
    $link = JRoute::_(???????);
    $this->setRedirect($link);
}

Another question - is it ok to put into view or should I put it somwhere else?
I am using Joomla 2.5.

A: Try this ,
In that component view you have to restrict only for logged in users then,
$user = JFactory::getUser();
if($user->id != 0){

 // show your view
}
else{

$mainframe = JFactory::getApplication();
$mainframe->redirect('index.php?option=com_users&view=login');
}

You can use this code any where inside view.html.php,layouts etc.

A: You don't specify, so I'm presuming Joomla 2.5.x.
In you view class seems to be the standard place... e.g. com_content checks in it's article/view.html.php file, with the following:

// Check the view access to the article (the model has already computed the values).
if ($item->params->get('access-view') != true && (($item->params->get('show_noauth') != true &&  $user->get('guest') ))) {
    JError::raiseWarning(403, JText::_('JERROR_ALERTNOAUTHOR'));

    return;
}

As you can see, com_content doesn't redirect the user, it simply raises a blocking warning message.
com_users can be called with a redirect parameter that contain the URL you want the user sent to after they login. The parameter should be base64 encoded and escaped with urlendcode. You can read about the redirect after login mechanism on docs.joomla.org.
To achieve a redirect to the login and then return to the original request after a successful login you can use something similar to this in your else block:
// Redirect to login
$uri        = JFactory::getURI();
$return     = $uri->toString();

$url  = 'index.php?option=com_users&view=login&return=' . urlencode(base64_encode($return));

$jAp->redirect($url, JText::_('Message_about_this_view_requiring_login'));

A: This is ideally placed in the controller: but you could do much the same in the view.
first, encode your return link:
$link = base64_encode(JRoute::_("index.php?option=com_yourcomponent&view=someview&tmpl=somelayout", false));

then, build the route to the login page:
$rlink = JRoute::_("index.php?option=com_users&view=login&return=$link", false);
$msg = JText::_("COM_YOURCOMPONENT_LOGIN_TO_ACCESS");
$app = JFactory::getApplication();
$app->redirect($rlink, $msg);


text:
Q: What is the location of newly created folders from Imagemanager in OpenCart 2 on server? Guys I'm having a strange problem. I'm not able to find newly created folders from Imagemanager in OpenCart2 on server?
For instance:
I create a folder say New in Imagemanager while uploading product in Opencart. Image gets uploaded in folder and I get the link as domain.com/catalog/New/image.jpg
but when I open catalog folder on server, the New folder (and the image placed in it) is no where to be found ? How is this possible ?
Does Opencart just create a virtual path instead of a real folder on server ? And if yes, then where do real images go on server if not in that folder ?

P.S - I'm migrating from one server to another and when I upload
  imported SQL file from 1st Opencart onto 2nd Opencart. I get tables in
  the database but products does not show up on the front end part of
  website? so please give me tips for migrating and for my query above

Thanks! Help appreciated :)


text:
Q: Node.js socket.io handling users So at my server app when I get a socket request I send data based on what user is requesting the information...
server.on('connection', function(socket) {
    socket.on('login', function(data) {
        connection.query('SELECT * FROM users WHERE name = ? AND password = ? LIMIT 1', [data.name, data.password], function(err, result) {
            if(result.length === 0)
            {
                socket.emit('login-failed');
            }
            else
            {
                if(users.check(result[0].name))
                {
                    result[0].socket = socket.id;
                    users.add(result[0]);
                    console.log(colors.yellow('User: ' + result[0].name + ' connected.'));
                    socket.emit('login-success');
                }
            }
        });
    });

So when a user logs in I save some information like username, password, socketid.
var userList = [];

exports.add = function(data)
{
    userList.push(data);
}

exports.check = function(data)
{
    for(var i = 0; i < userList.length; i++)
    {
        if(userList[i].name === data)
        {
            return false;
        }
    }

    return true;
}

exports.remove = function(id)
{
    for(var i = 0; i < userList.length; i++)
    {
        if(userList[i].socket === id)
        {
            var index = userList.indexOf(i);
            userList.splice(index, 1);
            return true;
        }
    }

    return false;
}

So as you can see Im saving users data that I will access later for example on here
socket.on('test', function(data) {
   if(users.remove(socket.id)) console.log('Yes');
});

But the only way I have to identify a socket is by using its socket.id, now my question is if I can really trust socketid or if I should use another 'system' to actually manage my users logic.
I cant really figure any other system to actually check what socket is calling my server


text:
Q: How to automatically run a function after a page loads in react? In my componentDidMount(), I am calling an actionCreator in my redux file to do an API call to get a list of items. This list of items is then added into the redux store which I can access from my component via mapStateToProps.
const mapStateToProps = state => {
    return {
        list: state.list
    };
};

So in my render(), I have:
render() {
    const { list } = this.props;
}

Now, when the page loads, I need to run a function that needs to map over this list.
Let's say I have this method:
someFunction(list) {
    // A function that makes use of list
}

But where do I call it? I must call it when the list is already available to me as my function will give me an error the list is undefined (if it's not yet available).
I also cannot invoke it in render (before the return statement) as it gives me an error that render() must be pure.
Is there another lifecycle method that I can use?

A: These are two ways you can play with received props from Redux
Do it in render
  render() {
       const { list } = this.props;
       const items = list && list.map((item, index) => {
             return
{item.value}

       });
       return(

                 {items}

       );
    }

Or Do it in componentWillReceiveProps method if you are not using react 16.3 or greater
 this.state = {
      items: []
}
 componentWillReceiveProps(nextProps){
       if(nextProps.list != this.props.list){
            const items = nextProps.list &&    nextProps.list.map((item, index) => {
                  return
{item.value}

             });
             this.setState({items: items});
        }
    }

    render() {
        const {items} = this.state;
        return(

               {items}

        );
     }

You can also do it in componentDidMount if your Api call is placed in componentWillMount or receiving props from parent.

A: Just do this, and in redux store please make sure that initial state of list should be []
const mapStateToProps = state => {
    return {
        list: someFunction(state.list)
    };
};


text:
Q: How can a script know whether a user can input or not? Is there a way a bash script (or whatever language) can determine whether its being run in a headless way? I want to know whether a user can input or not. If they can, I am going to ask them something.

A: From man bash:
An  interactive  shell  is  one  started without non-option arguments and without the -c option whose standard input and
       error are both connected to terminals (as determined by isatty(3)), or one started with the -i option.  PS1 is  set  and
       $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.


text:
Q: How to convert PostGis Table (Grid data) to Continuous field using Qgis? I'd like to transform my Gridded Layer (generated form a PostGIS table of points) to a continuous and colored layer. How could I do this with Qgis or any other program?

A: There are two gdal functions in the QGIS Raster menu that you can use.

*

*If the points are already in a regular grid, then you can use gdal_rasterize. In the Menu: Raster->Conversion->Rasterize. Make sure to set the target resolution the same as the spacing of the points.

*You can also to choose to interpolate a raster from the points using gdal_grid. Raster->Analysis->Grid(Interpolation). This will work for any reasonable target resolution, and irregularly spaced points.

HTH


text:
Q: How to make the desktop pane that Netbeans has So when I start up Netbeans, they create a little panel on the desktop for showing the progress of loading. I'm pretty sure Microsoft Office 2010 uses this too. I was curious how to make one of those in java?
I looked through the API and saw JDesktopPane. But I don't think that's what I'm looking for unless you can take that and put in on the actual desktop, but I'm unsure. Thanks in advance!

A: you can actually do it using JPanel.. you don't need to do anything else..no need of desktop pane
all you need to do is design a JPanel and put a progress bar inside it that will link to a process and show how much it has been completed.
JPanel doesn't have normal frame functionality like minimize, Close etc and will act exactly as you are trying to make up.
Update : Just tried doing what you wanted.
You need to start working on JFrame. and set its decoration to false.
in Netbeans, you can just go to Frame properties and set Undecorated to true
or inside code you can just write setUndecorated(true);
then you have to design your frame, put a progress bar inside it, link it to a function, set its onTop value to true (which means it will always be on top) and set its position to center of screen. done!! you are ready with your window!!


text:
Q: LoopBack API - Built-in Models and Persistence I want to build an API, using Google auth (via the loopback-component-passport) and ACL for access control. I also need to extend the standard User model, as I have some additional data fields.
By default the User, AccessToken, ACL, RoleMapping and Role models use the in-memory storage, i.e. data will be lost once the app restarts. So, my questions are:

*

*To persist data to MySQL, I would need to automigrate these models from in-memory to MySQL data source. But, if I'm going to extend the User model as StaffUser, do I need to have tables for both User and StaffUser in the DB? Or, do I then keep User in-memory and StaffUser in MySQL?

*The passport component adds its own models (UserIdentity, UserCredential, ApplicationCredential,PassportConfigurator). Would there be any reason to persist these in MySQL, or do I keep these in-memory?

A:
To persist data to MySQL, I would need to automigrate these models from in-memory to MySQL data source. But, if I'm going to extend the User model as StaffUser, do I need to have tables for both User and StaffUser in the DB? Or, do I then keep User in-memory and StaffUser in MySQL?

I don't think you would need to auto-migrate these models from in-memory to your data source. Instead, you should just change the dataSource property of the model in your app's model-config.json from the default in-memory to the data source defined by you. If your app uses only StaffUser and doesn't need User, you may not need to put User in MySQL.

The passport component adds its own models (UserIdentity, UserCredential, ApplicationCredential,PassportConfigurator). Would there be any reason to persist these in MySQL, or do I keep these in-memory?

The section "Connectors" in this Strongloop article says that the in-memory data source is suitable only for development and debugging purposes. We shouldn't let the login related information lie in-memory and let them get wiped out in an app restart.


text:
Q: jquery mobile dialog not working I'm trying to make a dialog with jquery.mobile-1.0.min.
But the problem is when I click the button, the dialog is not popping up.
why it is not working this dialog?
Here is the fiddle
http://fiddle.jshell.net/xJ8D3/

*

*You can check it "Page2" on the menu.
main

    main
    Page 2
    Page 3

    main

Page Footer

page2

    main
    Page 2
    Page 3

    page2

    **Click Dialog

    Dialog Content

**

Page Footer

page3

    main
    Page 2
    Page 3

    page3page3

Page Footer

A: Your dialog page has to be on the same node level as the other pages. Corrected your fiddle to open page3:
script:

...

        Click Dialog

...

...

jsFiddle:
Fiddle

A: change
**Click Dialog

to
**Click Dialog


text:
Q: Confidence interval for maximum value in velocity time series I have a time series of velocity values, which is structured into two periods. The first period describes the baseline velocity ("pre"). At the beginning of the second period ("post"), a stimulus is applied and the velocity subsequently changes.
I'd like to assign a confidence interval/significance threshold to the maximum velocity of the "pre" series. I could then determine whether the maximum velocity of the "post" period exceeds that threshold, and thus whether the increase in the "post" period is a response to the stimulus applied, rather than fall within the normal range of maximum velocity to be expected based on the actual maximum velocity and the extent of variance shown in the "pre" period.
I have code that uses stationary bootstrap and the autocorrelation in the velocity time series to generate a bootstrap sampling population of velocity profiles of the "pre" period. I can then calculate a confidence interval of the maximum velocity in this bootstrap population. The problem is that the actual maximum velocity is sampled into most bootstrap samples, and so the variance is small and the resulting confidence interval extremely narrow.
Is there a way to permutate the maximum velocity of the "pre" period based on the overall variance in the "pre" period, and based on this permutation population, calculate a significance threshold? I'm also open to any other suggestions you might have for how to calculate a significance threshold for a "hard" boundary like the maximum.


text:
Q: Unable to create basic database or scale from web database in azure When attempting to either create a new basic database or upgrade from the web database to a basic database I get an error - "The operation is not supported for your subscription offer type."
I recently upgraded from the free trial to the pay-as-you-go option and the current database is in the North Europe location.
I have checked the preview features section but the ability to enable the premium database options are not there and I believe these are no longer in preview mode anyway.
Any assistance would be appreciated.


text:
Q: Bing maps geocode, use session key with search manager class? I need to use the session key with my geocode requests to limit my billable transactions. The search manager class takes the map as an argument but I see no way to set the session key. Cursory investigation with Charles seems to indicate it doesn't use the session key even after calling getCredentials on its own.
If this can't be done readily it would seem like a glaring oversight.

A: The Search, AutoSuggest and Direction modules all automatically use session keys when you pass a map in when loading the manager of that module. No need to get the session key yourself. You only really need to manually get the sessions key if you were to directly connect to the REST services which.
Depending on your application needs, directly accessing the REST services may be useful. Here are a couple of examples of when you would want to access the REST services directly:

*

*You only need the raw data.

*You want 100% full control over rendering of the results.

*You want to access one of the services that are not exposed as a module such as the elevation service.


text:
Q: Aws Error Could not load credentials from any providers I have a node service, which creates temporary AWS credentials using sts.assumeRole(params). If I set the accessKeyId,secretAccessKey,region in the environment. Credentials are generated successfully. If I store them in Mongo and read them. I get the following error.
Errors
Error Could not load credentials from any providers

Error region is missing

Code
const params = {
        RoleArn: `arn:aws:iam::${db.awsAccountId}:role/${db.awsRole}`,
        RoleSessionName: `Assumed-${db.awsRole}-Role-${timestamp}`,
        accessKeyId: db.accessId,
        secretAccessKey: db.accessToken,
        region: db.awsRegion,
      };

sts.assumeRole(params, (err, data) => {
    if(err) console.log(err);
    else console.log(data);
});

I don't understand, following the same procedure. Any ideas?

A: It looks like you are setting the AWS credentials for the STS service incorrectly. You should have a look at the user guide for the full explanation.
There are multiple ways to set credentials, so pick the one that works best in your situation. When you were using environment variables, they were picked up automatically, but if you're reading them from some other place, you'll have to create a Credentials object and add it to the AWS.config manually.
More info on the Credentials object can be found here and on the AWS.config here.


text:
Q: InvalidClassException on Serializable objects I'm having some problems integrating with my colleague's code.
He has an entity class, let's call it FooEntity:
@Entity
@XmlRootElement
@Table(name = "...")
public class FooEntity implements Serializable {

    private static final long serialVersionUID = ...;
    ...

    @Lob
    @Column(name = "OBJBYTES")
    private Serializable objBytes;

    ...
}

He is creating his DTO object
public class FooDTO implements Serializable {

    private static final long serialVersionUID = ...;

    ...

    private Serializable obj;
    ...
}

via helper class
public class FooHelper {

    ...

    public static Serializable createSBar() {
        Bar bar = generateBar();
        Serializable sBar = bar;
        return sBar;
    }

    ...

}

that creates a Bar object that implements Serializable interface:
public class Bar implements Serializable {

    private static final long serialVersionUID = ...;

    private String myString;
    private byte[] myBytes;
}

In his DAO, he's creating entity object from his DTO object and saving it to database and retrieving entity object and mapping it to a DTO object.
On retrieving the list of entries that match certain criteria via Query#getResultList an InvalidClassException is thrown with this message:
Local Exception Stack:
Exception [EclipseLink-66] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Could not deserialize object from byte array.
Internal Exception: java.io.InvalidClassException: com.my.package.Bar; local class incompatible: stream classdesc serialVersionUID = 4849912519109332230, local class serialVersionUID = -1015090985675288072
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[objBytes-->FOO_TABLE.OBJBYTES]
Descriptor: RelationalDescriptor(com.my.package.entity.FooEntity --> [DatabaseTable(FOO_TABLE)])
    at org.eclipse.persistence.exceptions.DescriptorException.notDeserializable(DescriptorException.java:1218)
    at org.eclipse.persistence.mappings.converters.SerializedObjectConverter.convertDataValueToObjectValue(SerializedObjectConverter.java:72)
    at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.getAttributeValue(AbstractDirectMapping.java:699)
    at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.valueFromRow(AbstractDirectMapping.java:1299)
    at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.buildCloneFromRow(AbstractDirectMapping.java:1258)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoWorkingCopyClone(ObjectBuilder.java:1548)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneFromRow(ObjectBuilder.java:1694)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:664)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:601)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:560)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:717)
    at org.eclipse.persistence.queries.ReadObjectQuery.registerResultInUnitOfWork(ReadObjectQuery.java:778)
    at org.eclipse.persistence.queries.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:457)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1081)
    at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1040)
    at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:418)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1128)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
    at org.eclipse.persistence.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolicy.java:323)
    at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2098)
    at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternal(OneToOneMapping.java:1695)
    at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1987)
    at org.eclipse.persistence.mappings.ForeignReferenceMapping.buildCloneFromRow(ForeignReferenceMapping.java:276)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoWorkingCopyClone(ObjectBuilder.java:1548)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneFromRow(ObjectBuilder.java:1694)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:664)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:601)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:560)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:717)
    at org.eclipse.persistence.queries.ReadAllQuery.registerResultInUnitOfWork(ReadAllQuery.java:769)
    at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:433)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1081)
    at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1040)
    at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:392)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1128)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:485)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
    at com.my.package.dao.FooDAO.getRange(FooDAO.java:584)
    ...
Caused by: java.io.InvalidClassException: com.my.package.Bar; local class incompatible: stream classdesc serialVersionUID = 4849912519109332230, local class serialVersionUID = -1015090985675288072
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:560)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1599)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1494)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1748)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1327)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:349)
    at org.eclipse.persistence.mappings.converters.SerializedObjectConverter.convertDataValueToObjectValue(SerializedObjectConverter.java:70)
    ... 165 more

It may also be relevant to note that when deploying the app in Glassfish 3.1.2.2, the following messages are displayed in the log:
[#|2014-06-05T12:39:01.301+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.FooEntity actually got transformed|#]

[#|2014-06-05T12:39:01.310+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo2Entity actually got transformed|#]

[#|2014-06-05T12:39:01.316+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo3Entity actually got transformed|#]

[#|2014-06-05T12:39:01.322+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo4Entity actually got transformed|#]

[#|2014-06-05T12:39:01.327+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo5Entity actually got transformed|#]

[#|2014-06-05T12:39:01.332+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo6Entity actually got transformed|#]

[#|2014-06-05T12:39:01.337+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo7Entity actually got transformed|#]

[#|2014-06-05T12:39:01.345+0200|INFO|glassfish3.1.2|javax.enterprise.system.core.classloading.com.sun.enterprise.loader|_ThreadID=28;_ThreadName=Thread-2;|com.my.package.entity.Foo8Entity actually got transformed|#]

Could someone explain why this exception is occurring and how to solve it?
Also, I'm assuming it's not a good practice to use entity objects as JAXB objects, right?

A: As the error message shows:

Internal Exception: java.io.InvalidClassException: com.my.package.Bar;
  local class incompatible: stream classdesc serialVersionUID =
  4849912519109332230, local class serialVersionUID =
  -1015090985675288072

There seem to be two different serialVersionUIDs, this seems to cause the error. You have to find out why there are different values, maybe the value was changed in the meantime.


text:
Q: "Does everyone want coffee?" propositional logic problem
When three professors are seated in a restaurant, the hostess asks them: "Does everyone want coffee?" The first professor says: "I do not know." The second professor then says: "I do not know." Finally, the third professor says: "No, not everyone wants coffee." The hostess comes back and gives coffee to the professors who want it. How did she figure out who wanted coffee?

The solution is that the first two professors who say they don't know if everyone wants coffee are the ones who want coffee.
However, I don't understand the logic. For example, the first professor may not want coffee, but does not know if the other professors want coffee, and thus can answer "I do not know." So how can the hostess take an answer of "yes" from that?

A: Suppose the first professor did not want coffee. Then, they would know that it is not the case that "everyone wants coffee" - so, when asked "Does everyone want coffee?," they would answer "no."

A: If he knew that he does not want coffee, then he could tell the waitress 'no', because he then knows that NOT everyone wants coffee. The only possibility that he doesn't know it when he is asked is that he does want coffee  but does not know if the other two want some too.
The same logic applies for the second professor. Only the third then has perfect knowledge and can say 'yes' if he also wants coffee, and 'no' if not.

A: The first professor wants coffee, because if he doesn't want coffee then saying "no" would mean that the question is False — he is operating on the assumption that yes he himself does want coffee and isn't sure if Professor 2 and Professor 3 also want coffee — which would be the requirement for the question to be True.
Professor 2 also wants coffee and for the same reason as Professor 1 — he knows now that Professor 1 wants coffee, and he himself wants coffee, but isn't sure about Professor 3 — again, all three must want coffee for the original question to be True (note the use of "everyone" in the question).
Therefore Professor 3 is the only remaining variable that can negate the question. He then does negate the question with his statement — hence Professor 3 is the only one who does not want coffee.


text:
Q: why python's apply function sometimes can, sometimes can not change the value of dataframe? def replace_name(row):
    if row['Country Name'] == 'Korea, Rep.':
        row['Country Name'] = 'South Korea'
    if row['Country Name'] == 'Iran, Islamic Rep.':
        row['Country Name'] = 'Iran'
    if row['Country Name'] == 'Hong Kong SAR, China':
        row['Country Name'] = 'Hong Kong'
    return row

GDP.apply(replace_name, axis = 1)

GDP is a 'pd.DataFrame'
In this time when I want to find 'South Korea', it doesn't work, the name is still 'Korea, Rep.'
but if I change the last row in the code to this
GDP = GDP.apply(replace_name, axis = 1)

it works.
At first, I thought the reason is that 'apply' function can't change the GDP itself, but when I dealt with another dataframe, it actually works. The code is below:
def change_name(row):
    if row['Country'] == "Republic of Korea":
        row['Country'] = 'South Korea'
    if row['Country'] == 'United States of America':
        row['Country'] = 'United States'
    if row['Country'] == 'United Kingdom of Great Britain and Northern Ireland':
        row['Country']  ='United Kingdom'
    if row['Country'] == 'China, Hong Kong Special Administrative Region':
        row['Country'] = 'Hong Kong'
    return row

energy.apply(change_name, axis = 1)

energy is also a 'pd.dataframe'.
This time when I search for 'United States', it works. And the original name is 'United States of America', so it changes the name successfully.
The only difference between energy and GDP is that energy is read from an excel file, and GDP is read from a CSV file. So what cause the different result?

A: I think better is use replace:
d = {'Korea, Rep.':'South Korea', 'Iran, Islamic Rep.':'Iran',
     'Hong Kong SAR, China':'Hong Kong'}
GDP['Country Name'] = GDP['Country Name'].replace(d, regex=True)

For difference is possible some whitespace in data, maybe help:
GDP['Country'] = GDP['Country'].str.strip()

Sample:
GDP = pd.DataFrame({'Country Name':[' Korea, Rep. ','a','Iran, Islamic Rep.','United States of America','s','United Kingdom of Great Britain and Northern Ireland'],
                    'Country':     ['s','Hong Kong SAR, China','United States of America','Hong Kong SAR, China','s','f']})

#print (GDP)

d = {'Korea, Rep.':'South Korea', 'Iran, Islamic Rep.':'Iran',
     'United Kingdom of Great Britain and Northern Ireland':'United Kingdom',
     'Hong Kong SAR, China':'Hong Kong', 'United States of America':'United States'}

#replace by columns
#GDP['Country Name'] = GDP['Country Name'].replace(d, regex=True)
#GDP['Country'] = GDP['Country'].replace(d, regex=True)

#replace multiple columns
GDP[['Country Name','Country']] = GDP[['Country Name','Country']].replace(d, regex=True)
print (GDP)
         Country    Country Name
0              s     South Korea
1      Hong Kong               a
2  United States            Iran
3      Hong Kong   United States
4              s               s
5              f  United Kingdom


text:
Q: pandas read_csv: pull multiple series out of a single column I have csv data like this:
requests_per_sec, 9:00, 100
requests_per_sec, 9:01, 101
...
response_time, 9:00, 40ms
repsonse_time, 9:01, 42ms
...
error_rate, 9:00, 0.01
...

so I have this:
pd.read_csv(csv_data,index_col=[1], names= ['metric', 'time', 'value'], parse_dates=True)

which gives me a dataframe indexed by time, with the columns: metric and value. But I'd need to split that dataframe so that I don't have 3 data sets in the same column but rather 3 independent series (requests_per_sec, response_time and error_rate). Is there a way to do that directly from read_csv? Or do I need some .groupby() or .select() manipulation?

A: You can do it just in two seperate steps: first read the data and then reshape it.
E.g.:
import pandas as pd
from StringIO import StringIO

s = """metric,timestamp,datapoint
A,2013-01-01,1
A,2013-01-02,5
A,2013-01-03,8
B,2013-01-01,2
B,2013-01-02,3
B,2013-01-03,4
C,2013-01-01,8
C,2013-01-02,7
C,2013-01-03,6"""

First you just read the data:
In [4]: df = pd.read_csv(StringIO(s), parse_dates=[1])

In [5]: df
Out[5]:
  metric           timestamp  datapoint
0      A 2013-01-01 00:00:00          1
1      A 2013-01-02 00:00:00          5
2      A 2013-01-03 00:00:00          8
3      B 2013-01-01 00:00:00          2
4      B 2013-01-02 00:00:00          3
5      B 2013-01-03 00:00:00          4
6      C 2013-01-01 00:00:00          8
7      C 2013-01-02 00:00:00          7
8      C 2013-01-03 00:00:00          6

And then you can transform it, in this case reshape it with pivot to create columns for the different metrics:
In [7]: df.pivot(index='timestamp', columns='metric', values='datapoint')
Out[7]:
metric      A  B  C
timestamp
2013-01-01  1  2  8
2013-01-02  5  3  7
2013-01-03  8  4  6