问:
BeamSQL Group By query problem with Float value
Tried to get the unique value from the BigQuery table using BeamSQL in Google Dataflow. Using Group By clause implemented the condition in BeamSQL (sample query below). One of the column has float data type. While executing the Job got below exceptions,

Caused by: org.apache.beam.sdk.coders.Coder$NonDeterministicException: org.apache.beam.sdk.coders.RowCoder@81d6d10 is not deterministic because:
    All fields must have deterministic encoding.
  Caused by: org.apache.beam.sdk.coders.Coder$NonDeterministicException: FloatCoder is not deterministic because:
    Floating point encodings are not guaranteed to be deterministic.

BeamSQL Query:

PCollection ST= mainColl.apply(SqlTransform.query("SELECT ID,ITEM,UNITPRICE FROM PCOLLECTION GROUP BY ID,ITEM,UNITPRICE"));

It would be good if some one help me to solve this issue.

Please note, if we remove the float column then BeamSQL query works fine.

答:
This is indicating that you should not use floating point values (in this case probably UNITPRICE value) in the aggregation (group by) scheme, because their output is non-deterministic (i.e. it can change based on the precision change). For instance, consider this example:

```<code>WITH
  data AS (
  SELECT 100 AS id, 'abc' as item, 0.3448473362800000001 AS unitprice
  UNION ALL
  SELECT 200 AS id, 'xyz' as item, 0.49300013 AS unitprice
  UNION ALL
  SELECT 500 AS id, 'pqr' as item, 0.67322332200000212 AS unitprice
)
select id, item, unitprice from data
group by id, item, unitprice
</code>```

Output for this comes to be:

```<code>100 abc 0.34484733628
200 xyz 0.49300013
500 pqr 0.6732233220000021
</code>```

in which, the unitprice values look a bit different.

To avoid this, you can go two routes:

You can cast your unitprice as a string and then continue with grouping. Something like cast(unitprice as string) as unitprice in your query.

You can simply choose to keep unitprice as non-grouped entity (which is a logical option in most cases), and just do max(unitprice) as unitprice or avg(unitprice) as unitprice in your query, while grouping by id, item.

Hope this helps.

Body:
This is indicating that you should not use floating point values (in this case probably UNITPRICE value) in the aggregation (group by) scheme, because their output is non-deterministic (i.e. it can change based on the precision change). For instance, consider this example:

WITH
  data AS (
  SELECT 100 AS id, 'abc' as item, 0.3448473362800000001 AS unitprice
  UNION ALL
  SELECT 200 AS id, 'xyz' as item, 0.49300013 AS unitprice
  UNION ALL
  SELECT 500 AS id, 'pqr' as item, 0.67322332200000212 AS unitprice
)
select id, item, unitprice from data
group by id, item, unitprice

Output for this comes to be:

100 abc 0.34484733628
200 xyz 0.49300013
500 pqr 0.6732233220000021

in which, the unitprice values look a bit different.

To avoid this, you can go two routes:

You can cast your unitprice as a string and then continue with grouping. Something like cast(unitprice as string) as unitprice in your query.

You can simply choose to keep unitprice as non-grouped entity (which is a logical option in most cases), and just do max(unitprice) as unitprice or avg(unitprice) as unitprice in your query, while grouping by id, item.

Hope this helps.


来源: stackexchange

问:
Examine two columns and delete lowest number of the id of column named contentid
Data comes from:

```<code>SELECT
    CONTENTID, t1.TITLE, t1.PAGEID, COUNT, SPACENAME, CREATIONDATE, LASTMODDATE, VERSION
FROM
    (SELECT
         SPACEID, TITLE, PAGEID, COUNT(*) AS COUNT
     FROM
         CONTENT
     WHERE
         CONTENTTYPE = 'ATTACHMENT'
     GROUP BY
         TITLE, PAGEID, SPACEID
     HAVING
         COUNT(TITLE) > 1 AND COUNT(PAGEID) > 1) t1
JOIN
    (SELECT
         CONTENTID, CREATIONDATE, LASTMODDATE, VERSION, TITLE, PAGEID
     FROM
         CONTENT
     WHERE
         VERSION = 1) t4 ON t4.PAGEID = t1.PAGEID
JOIN
    (SELECT
         SPACEID, SPACENAME
     FROM
         SPACES) t2 ON t1.SPACEID = t2.SPACEID
ORDER BY
    t1.PAGEID,t1.TITLE, CREATIONDATE, LASTMODDATE
</code>```

Output (removed some of the columns because it is just the first two needed to make the decision on what to remove and it is easier to display here):

```<code>CONTENTID   TITLE
--------------------------------------------
26902677    Time Logging Guidelines V5.docx
46170401    Time Logging Guidelines V5.docx
157909073   Time Logging Guidelines V5.docx
157909072   Time Logging Guidelines V5.docx
355860497   Time Logging Guidelines V5.docx
535953771   Time Logging Guidelines V5.docx
540117589   Time Logging Guidelines V5.docx
554729950   Time Logging Guidelines V5.docx
1246646     Induction Plan Template.docx
472350756   Induction Plan Template.docx
535953845   Induction Plan Template.docx
544508546   Induction Plan Template.docx
544508547   Induction Plan Template.docx
</code>```

I need to delete all but the highest contentid for each title.  There are actually about 66k of rows of this type of fix

The end result for the output above:

```<code>554729950   Time Logging Guidelines V5.docx
544508547   Induction Plan Template.docx
</code>```

答:
Not quite sure what you want.  I'm not sure what the purpose of the joins.  If all you want is to delete all records expect the higest CONTENTID, you can try this

```<code>WITH cte AS (
    SELECT *
        , ROW_NUMBER() OVER(PARTITION BY TITLE ORDER BY CONTENTID DESC) AS rn
    FROM Content
)
DELETE FROM cte
WHERE rn > 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Data comes from:

SELECT
    CONTENTID, t1.TITLE, t1.PAGEID, COUNT, SPACENAME, CREATIONDATE, LASTMODDATE, VERSION
FROM
    (SELECT
         SPACEID, TITLE, PAGEID, COUNT(*) AS COUNT
     FROM
         CONTENT
     WHERE
         CONTENTTYPE = 'ATTACHMENT'
     GROUP BY
         TITLE, PAGEID, SPACEID
     HAVING
         COUNT(TITLE) > 1 AND COUNT(PAGEID) > 1) t1
JOIN
    (SELECT
         CONTENTID, CREATIONDATE, LASTMODDATE, VERSION, TITLE, PAGEID
     FROM
         CONTENT
     WHERE
         VERSION = 1) t4 ON t4.PAGEID = t1.PAGEID
JOIN
    (SELECT
         SPACEID, SPACENAME
     FROM
         SPACES) t2 ON t1.SPACEID = t2.SPACEID
ORDER BY
    t1.PAGEID,t1.TITLE, CREATIONDATE, LASTMODDATE

Output (removed some of the columns because it is just the first two needed to make the decision on what to remove and it is easier to display here):

CONTENTID   TITLE
--------------------------------------------
26902677    Time Logging Guidelines V5.docx
46170401    Time Logging Guidelines V5.docx
157909073   Time Logging Guidelines V5.docx
157909072   Time Logging Guidelines V5.docx
355860497   Time Logging Guidelines V5.docx
535953771   Time Logging Guidelines V5.docx
540117589   Time Logging Guidelines V5.docx
554729950   Time Logging Guidelines V5.docx
1246646     Induction Plan Template.docx
472350756   Induction Plan Template.docx
535953845   Induction Plan Template.docx
544508546   Induction Plan Template.docx
544508547   Induction Plan Template.docx

I need to delete all but the highest contentid for each title.  There are actually about 66k of rows of this type of fix

The end result for the output above:

554729950   Time Logging Guidelines V5.docx
544508547   Induction Plan Template.docx

Body:
Not quite sure what you want.  I'm not sure what the purpose of the joins.  If all you want is to delete all records expect the higest CONTENTID, you can try this

WITH cte AS (
    SELECT *
        , ROW_NUMBER() OVER(PARTITION BY TITLE ORDER BY CONTENTID DESC) AS rn
    FROM Content
)
DELETE FROM cte
WHERE rn > 1


问:
Java Spring with thymeleaf checkbox non checked is Empty instead of false
I have checkbox inside of my form :

```<code>  <div class="form-check form-check-inline">
                        <input type="checkbox" th:field="${search.titleIncl}" />
                        <label class="form-check-label" th:for="${#ids.next('covered')}">Title</label>
                    </div>
</code>```

This checkbox by default should be on since search object has this value assigned as true. This works fine. What i expected from thsi checkbox is to send either true or false when its checked/unchecked. What i got now is True if its checked and nothing when not checked. That his a bit of an issue for me :

In controller:

```<code>@GetMapping(value = Utils.MAPPING_INDEX)
public ModelAndView index(@RequestParam("titleIncl") Optional<Boolean> titleIncl) {
    ...calling fillSearch inside of body....
}

private Search fillSearch(Optional<Boolean> titleIncl..) {

        Search search = new Search();

        //Get seach value if nothing provided give me default.
        search.setTitleIncl(titleIncl.orElse(search.isTitleIncl()));
        ...

        return search;
}
</code>```

Whole point of this form is to get user select what parts of the object he wants to search :

So if he unselects checkbox and i dont send FALSE in optional, I run into problem.

When user initialy goes into the site, he doesnt send any of these parameters so it behaves fine by setting everything to true.
Bud once he initiates search and deselects parts he doesnt wanna search in, he still ends up with defaults and searches in everything.

So is there a simple way of sending Optional FALSE if checkbox value is not selected?

Note :

By simple i mean without creating additional endpoint for this form search and no Javascript :)

And yes the form is under GET request

答:
No matter what you do , only checked checkboxes are sent to server, not unchecked one.You have to code it in server to handle unchecked checkboxes.

https://www.w3.org/TR/html401/interact/forms.html#form-controls

Checkboxes (and radio buttons) are on/off switches that may be toggled
  by the user. A switch is "on" when the control element's checked
  attribute is set. When a form is submitted, only "on" checkbox
  controls can become successful.

But with the thymeleaf you can try like below ,

```<code><ul>
  <li th:each="feat : ${allFeatures}">
    <input type="checkbox" th:field="*{features}" th:value="${feat}" />
    <label th:for="${#ids.prev('features')}"
           th:text="#{${'seedstarter.feature.' + feat}}">Heating</label>
  </li>
</ul>
</code>```

which  will produce below html ,

```<code><ul>
  <li>
    <input id="features1" name="features" type="checkbox" value="SEEDSTARTER_SPECIFIC_SUBSTRATE" />
    <input name="_features" type="hidden" value="on" />
    <label for="features1">Seed starter-specific substrate</label>
  </li>
  <li>
    <input id="features2" name="features" type="checkbox" value="FERTILIZER" />
    <input name="_features" type="hidden" value="on" />
    <label for="features2">Fertilizer used</label>
  </li>
  <li>
    <input id="features3" name="features" type="checkbox" value="PH_CORRECTOR" />
    <input name="_features" type="hidden" value="on" />
    <label for="features3">PH Corrector used</label>
  </li>
</ul>
</code>```

Don’t worry about those hidden inputs with name="_features": they are
  automatically added in order to avoid problems with browsers not
  sending unchecked checkbox values to the server upon form submission.

More on,

https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#checkbox-fields

Body:
I have checkbox inside of my form :

                        <input type="checkbox" th:field="${search.titleIncl}" />
                        Title

This checkbox by default should be on since search object has this value assigned as true. This works fine. What i expected from thsi checkbox is to send either true or false when its checked/unchecked. What i got now is True if its checked and nothing when not checked. That his a bit of an issue for me :

In controller:

@GetMapping(value = Utils.MAPPING_INDEX)
public ModelAndView index(@RequestParam("titleIncl") Optional<Boolean> titleIncl) {
    ...calling fillSearch inside of body....
}

private Search fillSearch(Optional<Boolean> titleIncl..) {

        Search search = new Search();

        //Get seach value if nothing provided give me default.
        search.setTitleIncl(titleIncl.orElse(search.isTitleIncl()));
        ...

        return search;
}

Whole point of this form is to get user select what parts of the object he wants to search :

So if he unselects checkbox and i dont send FALSE in optional, I run into problem.

When user initialy goes into the site, he doesnt send any of these parameters so it behaves fine by setting everything to true.
Bud once he initiates search and deselects parts he doesnt wanna search in, he still ends up with defaults and searches in everything.

So is there a simple way of sending Optional FALSE if checkbox value is not selected?

Note :

By simple i mean without creating additional endpoint for this form search and no Javascript :)

And yes the form is under GET request

Body:
No matter what you do , only checked checkboxes are sent to server, not unchecked one.You have to code it in server to handle unchecked checkboxes.

https://www.w3.org/TR/html401/interact/forms.html#form-controls

Checkboxes (and radio buttons) are on/off switches that may be toggled
  by the user. A switch is "on" when the control element's checked
  attribute is set. When a form is submitted, only "on" checkbox
  controls can become successful.

But with the thymeleaf you can try like below ,

<ul>
  <li th:each="feat : ${allFeatures}">
    <input type="checkbox" th:field="*{features}" th:value="${feat}" />
    <label th:for="${#ids.prev('features')}"
           th:text="#{${'seedstarter.feature.' + feat}}">Heating</label>
  </li>
</ul>

which  will produce below html ,

<ul>
  <li>
    <input id="features1" name="features" type="checkbox" value="SEEDSTARTER_SPECIFIC_SUBSTRATE" />
    <input name="_features" type="hidden" value="on" />
    <label for="features1">Seed starter-specific substrate</label>
  </li>
  <li>
    <input id="features2" name="features" type="checkbox" value="FERTILIZER" />
    <input name="_features" type="hidden" value="on" />
    <label for="features2">Fertilizer used</label>
  </li>
  <li>
    <input id="features3" name="features" type="checkbox" value="PH_CORRECTOR" />
    <input name="_features" type="hidden" value="on" />
    <label for="features3">PH Corrector used</label>
  </li>
</ul>

Don’t worry about those hidden inputs with name="_features": they are
  automatically added in order to avoid problems with browsers not
  sending unchecked checkbox values to the server upon form submission.

More on,

https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#checkbox-fields


问:
Can't find application.js with javascript_pack_tag(Webpacker)
I have installed Webpacker gem in my Rails app and don't really know how to include app.js file into app/javascript/packs folder.

I put

```<code><%= javascript_pack_tag 'application' %>
</code>```

into my application.html.erb layout and

```<code>//= require jquery/dist/jquery
//= require jquery-ui/ui/jquery-ui
//= require jquery-ujs
</code>```

into it.

After all in some view(ex. index.html.erb) I have some jQuery in script tag:

```<code><script>

  jQuery(document).ready(function(){...
</code>```

And when I refresh page and look in console I get:

```<code>GET http://localhost:3000/packs/application-5e96d8f9533313f79af6.js net::ERR_ABORTED 500 (Internal Server Error)
</code>```

and

```<code>Uncaught ReferenceError: jQuery is not defined
</code>```

The question is why javascript_pack_tag transforms application.js into application-5e96d8f9533313f79af6.js(with these numbers) in HTML and from where is that coming?

Also I'm mentioning that I'm transforming my app from Bower to Webpack(within Webpacker gem) and not really sure how to include my Bower components to be used with Webpacker.

Any reference would be appreciated

答:
Those numbers in pack name are normal, it's file digest, sprockets does this too in production (it's used for cache busting and ensuring correct code on client).

//= require directives are for sprockets (aka asset pipeline), in webpacker you should use javascript imports (or use webpack.ProvidePlugin in config so that jQuery identifier will be loaded automatically upon use).

Also you have to switch to npm dependencies - yarn add jquery jquery-ui jquery-ujs

```<code>plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery'",
        "window.$": "jquery"
    })
  ]
</code>```

and use individual imports (in each file import what is used there like there're no other files, webpack will deal with duplicates):

```<code>import $ from 'jquery';
import 'jquery-ui/themes/base/core.css';
import 'jquery-ui/themes/base/theme.css';
import 'jquery-ui/themes/base/selectable.css';
import 'jquery-ui/ui/core';
import 'jquery-ui/ui/widgets/selectable'; // and so on
import {} from 'jquery-ujs'
</code>```

Body:
I have installed Webpacker gem in my Rails app and don't really know how to include app.js file into app/javascript/packs folder.

I put

<%= javascript_pack_tag 'application' %>

into my application.html.erb layout and

//= require jquery/dist/jquery
//= require jquery-ui/ui/jquery-ui
//= require jquery-ujs

into it.

After all in some view(ex. index.html.erb) I have some jQuery in script tag:

Body:
Those numbers in pack name are normal, it's file digest, sprockets does this too in production (it's used for cache busting and ensuring correct code on client).

//= require directives are for sprockets (aka asset pipeline), in webpacker you should use javascript imports (or use webpack.ProvidePlugin in config so that jQuery identifier will be loaded automatically upon use).

Also you have to switch to npm dependencies - yarn add jquery jquery-ui jquery-ujs

plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery'",
        "window.$": "jquery"
    })
  ]

and use individual imports (in each file import what is used there like there're no other files, webpack will deal with duplicates):

import $ from 'jquery';
import 'jquery-ui/themes/base/core.css';
import 'jquery-ui/themes/base/theme.css';
import 'jquery-ui/themes/base/selectable.css';
import 'jquery-ui/ui/core';
import 'jquery-ui/ui/widgets/selectable'; // and so on
import {} from 'jquery-ujs'


问:
Creating a scrollable window without Layouts
I am trying to achieve something what, I thought, would be a super easy thing to do. But for some reason QtDesigner is driving me crazy, it simply won't work...

I created a GUI and freely arranged different elements in the window, without layout or anything like that. At some point there were to many elements, so all I wanted to to, was to make it scrollable up and down, to see all elements.

So I added a ScrollArea in QtDesigner and added all elements as children of this ScrollArea (which btw also was a pain in the ass, because apparently drag and drop in the Object viewer is not a thing, and editing the .ui file by hand, is also not allowed... great).

So the result I have now is the following:

before resize - no scrollbar, elements at bottom inaccessible

resized vertically - some stuff still snapped off at the bottom

So as you see, although I created a ScrollArea... There is no scroll area. So I googled a little bit and found out that you can add layouts to your scrollarea, and yey, finally, a scroll bar! But how in this world am I supposed to arrange the elements in the way you see in the screenshots, with layouts. They are so super restrictive.

How am I supposed to simply get a vertical scrollbar, without this restrictive layout stuff?!

Here is how my object viewer looks

And here is what is called upon GUI creation:

```<code>ui->setupUi(this);
//setCentralWidget(ui->scrollArea);
//ui->scrollArea->setWidgetResizable(true);
</code>```

I tried it with, and without the commented lines. No scrollbar, no matter what I do.

答:
Try this to fix it:

In Qt Designer:

Select QScrollArea object.

Uncheck the QScrollArea properties widgetResizable.

In C++:

```<code>// If you want to set `widgetResizable` programmaticly
ui->scrollArea->setWidgetResizable(false); // Optional if you did it in Qt Designer
ui->scrollArea->widget()->adjustSize();
</code>```

Body:
I am trying to achieve something what, I thought, would be a super easy thing to do. But for some reason QtDesigner is driving me crazy, it simply won't work...

I created a GUI and freely arranged different elements in the window, without layout or anything like that. At some point there were to many elements, so all I wanted to to, was to make it scrollable up and down, to see all elements.

So I added a ScrollArea in QtDesigner and added all elements as children of this ScrollArea (which btw also was a pain in the ass, because apparently drag and drop in the Object viewer is not a thing, and editing the .ui file by hand, is also not allowed... great).

So the result I have now is the following:

before resize - no scrollbar, elements at bottom inaccessible

resized vertically - some stuff still snapped off at the bottom

So as you see, although I created a ScrollArea... There is no scroll area. So I googled a little bit and found out that you can add layouts to your scrollarea, and yey, finally, a scroll bar! But how in this world am I supposed to arrange the elements in the way you see in the screenshots, with layouts. They are so super restrictive.

How am I supposed to simply get a vertical scrollbar, without this restrictive layout stuff?!

Here is how my object viewer looks

And here is what is called upon GUI creation:

ui->setupUi(this);
//setCentralWidget(ui->scrollArea);
//ui->scrollArea->setWidgetResizable(true);

I tried it with, and without the commented lines. No scrollbar, no matter what I do.

Body:
Try this to fix it:

In Qt Designer:

Select QScrollArea object.

Uncheck the QScrollArea properties widgetResizable.

In C++:

// If you want to set `widgetResizable` programmaticly
ui->scrollArea->setWidgetResizable(false); // Optional if you did it in Qt Designer
ui->scrollArea->widget()->adjustSize();


问:
Exception thrown: Access violation writing location for Matlab Coder in Visual Studio
I have the following code:

addstruct.h:

```<code>#ifndef ADDSTRUCT_H
#define ADDSTRUCT_H

typedef struct {
    double* x;
    double* y;
} StructC;

void addstruct(double *a, double *b, const StructC *structc, int len);

#endif
</code>```

addstruct.c:

```<code>#include "addstruct.h"

void addstruct(double *a, double *b, StructC *structc, int len)
{
    for (int i=0; i<len; i++)
    {
        structc->x[i]=a[i]+b[i];
        structc->y[i]=-1*(a[i]+b[i]);
    }
}
</code>```

calladdstruct.m:

```<code>function S = calladdstruct(A,B)  %#codegen
    if coder.target('MATLAB')
    else
        coder.updateBuildInfo('addSourceFiles','addstruct.c');
        L=1000;
        Sx=zeros(1,L); Sy=zeros(1,L);
        StructC=struct('x',{Sx}, 'y',{Sy});
        coder.cstructname(StructC, 'StructC', 'extern', 'HeaderFile', 'addstruct.h');
        coder.ceval('addstruct', coder.rref(A), coder.rref(B), coder.ref(StructC), int32(numel(Sx)));
        S=sum(StructC.x);
        sprintf('sumx: %s', char( num2ascii(S,0) ))
        S=sum(StructC.y);
        sprintf('sumy: %s', char( num2ascii(S,0) ))
    end
end
</code>```

And main.c in Visual Studio:

```<code>#include "calladdstruct.h"
#include "calladdstruct_initialize.h"
#include "calladdstruct_terminate.h"
#include <stdio.h>

int main()
{
   double S;
   double xarr[3]={1,2,3};
   double yarr[3]={1,2,3};
   calladdstruct_initialize();
   S = calladdstruct(xarr, yarr);
   printf("%f\n", S);
   calladdstruct_terminate();
   getchar();
   return 0;
}
</code>```

When I run this in Visual Studio, I get the error

```<code>Exception Thrown at (calladdstruct.dll) in calladdstruct.exe: Access violation writing location
</code>```

Why is this?

答:
The declaration for your struct "StructC" does not match what MATLAB Coder expects.  Try generating code without the "extern" parameter in coder.cstructname to see the expected type.  Then use that in your handwritten definition.

If you need a particular struct format then use coder.opaque and coder.ceval to interact with that exclusively so that you are not baking in assumptions about memory layout that have to match between MATLAB Coder generated data and your handwritten code.

Hope that helps.

Body:
I have the following code:

addstruct.h:

#ifndef ADDSTRUCT_H
#define ADDSTRUCT_H

typedef struct {
    double* x;
    double* y;
} StructC;

void addstruct(double *a, double *b, const StructC *structc, int len);

#endif

addstruct.c:

#include "addstruct.h"

void addstruct(double *a, double *b, StructC *structc, int len)
{
    for (int i=0; i<len; i++)
    {
        structc->x[i]=a[i]+b[i];
        structc->y[i]=-1*(a[i]+b[i]);
    }
}

calladdstruct.m:

function S = calladdstruct(A,B)  %#codegen
    if coder.target('MATLAB')
    else
        coder.updateBuildInfo('addSourceFiles','addstruct.c');
        L=1000;
        Sx=zeros(1,L); Sy=zeros(1,L);
        StructC=struct('x',{Sx}, 'y',{Sy});
        coder.cstructname(StructC, 'StructC', 'extern', 'HeaderFile', 'addstruct.h');
        coder.ceval('addstruct', coder.rref(A), coder.rref(B), coder.ref(StructC), int32(numel(Sx)));
        S=sum(StructC.x);
        sprintf('sumx: %s', char( num2ascii(S,0) ))
        S=sum(StructC.y);
        sprintf('sumy: %s', char( num2ascii(S,0) ))
    end
end

And main.c in Visual Studio:

#include "calladdstruct.h"
#include "calladdstruct_initialize.h"
#include "calladdstruct_terminate.h"
#include <stdio.h>

int main()
{
   double S;
   double xarr[3]={1,2,3};
   double yarr[3]={1,2,3};
   calladdstruct_initialize();
   S = calladdstruct(xarr, yarr);
   printf("%f\n", S);
   calladdstruct_terminate();
   getchar();
   return 0;
}

When I run this in Visual Studio, I get the error

Exception Thrown at (calladdstruct.dll) in calladdstruct.exe: Access violation writing location

Why is this?


问:
Oracle SQL - Using CASE WHEN to select a proper date field
I have a complicated problem and I cannot for the life of me figure out the logic in my head.

I am trying to tackle the issue of building a query reporting the proper dates for a material event. Essentially, my company is trying to track inventory management by seeing when we buy (quantity+) a part, when we manufacture (quantity+) a part, when we sell (quantity-) a part, or when we use that part to build a higher assembly part (quantity-).

The table structures I am working with look like this:

Where there can be 4 types of events, each having their own unique identifier, and each having a date on which that event occurs.

I then have the "Happenings" table, which actually has the list of transactions, that looks like this:

(Note I have eliminated some irrelevant field names).

What I am trying to accomplish is using a CASE...WHEN statement to select the proper date based on if the current line's foreign key.

So something to the effect of:

```<code>CASE
    WHEN Type = "Purchase Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.PO_ID)
    WHEN TYPE = "Make Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.MO_ID)
    WHEN TYPE = "Sale" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.Sale_ID)
    WHEN TYPE = "Create Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.CO_ID)
    ELSE NULL AS Event_Date
</code>```

Unfortunately, I cannot post too much data as it is company proprietary, but that is the gist of what I am trying to accomplish; using CASE...WHEN to properly select a value from another table when my current row contains the unique identifier.

答:
try to use nvl function
for organize Happenings table.
NVL( PO_ID, NVL( MO_ID, NVL(CO_ID, NVL(Sale_ID, 0) ))) AS IDS

then

Events.Number = IDS

hope it helps

Body:
I have a complicated problem and I cannot for the life of me figure out the logic in my head.

I am trying to tackle the issue of building a query reporting the proper dates for a material event. Essentially, my company is trying to track inventory management by seeing when we buy (quantity+) a part, when we manufacture (quantity+) a part, when we sell (quantity-) a part, or when we use that part to build a higher assembly part (quantity-).

The table structures I am working with look like this:

Where there can be 4 types of events, each having their own unique identifier, and each having a date on which that event occurs.

I then have the "Happenings" table, which actually has the list of transactions, that looks like this:

(Note I have eliminated some irrelevant field names).

What I am trying to accomplish is using a CASE...WHEN statement to select the proper date based on if the current line's foreign key.

So something to the effect of:

CASE
    WHEN Type = "Purchase Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.PO_ID)
    WHEN TYPE = "Make Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.MO_ID)
    WHEN TYPE = "Sale" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.Sale_ID)
    WHEN TYPE = "Create Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.CO_ID)
    ELSE NULL AS Event_Date

Unfortunately, I cannot post too much data as it is company proprietary, but that is the gist of what I am trying to accomplish; using CASE...WHEN to properly select a value from another table when my current row contains the unique identifier.


问:
How enable auto-format code for Intellij IDEA?
Is it possible in Intellij IDEA after typing ';' or press 'Enter' happened formatting of this string?

For instance,
to:

```<code>a+b=10;
</code>```

after:

```<code>a + b = 10;
</code>```

Or only possible option: Code > Reformat Code...?

Thank you!

答: I know this question is quite old but there is actually a Save Actions plugin for IntelliJ that can be configured to format the code automatically.</p>

ContentLicense: CC BY-SA 3.0

Body:
Is it possible in Intellij IDEA after typing ';' or press 'Enter' happened formatting of this string?

For instance,
to:

a+b=10;

after:

a + b = 10;

Or only possible option: Code > Reformat Code...?

Thank you!


问:
Index all *except* one item in python
Is there a simple way to index all elements of a list (or array, or whatever) except for a particular index?  E.g.,

mylist[3] will return the item in position 3

milist[~3] will return the whole list except for 3

答:
Use np.delete ! It does not actually delete anything inplace

In your example, "mylist[~3]" would be written like that: mylist.delete(3)

A more complex example:

```<code>import numpy as np
a = np.array([[1,4],[5,7],[3,1]])

# a: array([[1, 4],
#           [5, 7],
#           [3, 1]])

ind = np.array([0,1])

# ind: array([0, 1])

# a[ind]: array([[1, 4],
#                [5, 7]])

all_except_index = np.delete(a, ind, axis=0)
# all_except_index: array([[3, 1]])

# a: (still the same): array([[1, 4],
#                             [5, 7],
#                             [3, 1]])
</code>```

Title: Index all *except* one item in python

Body:
Use np.delete ! It does not actually delete anything inplace

In your example, "mylist[~3]" would be written like that: mylist.delete(3)

A more complex example:

import numpy as np
a = np.array([[1,4],[5,7],[3,1]])

# a: array([[1, 4],
#           [5, 7],
#           [3, 1]])

ind = np.array([0,1])

# ind: array([0, 1])

# a[ind]: array([[1, 4],
#                [5, 7]])

all_except_index = np.delete(a, ind, axis=0)
# all_except_index: array([[3, 1]])

# a: (still the same): array([[1, 4],
#                             [5, 7],
#                             [3, 1]])


问:
My search function doesnt work if we search again because the original array gets changed
```<code><input type="text" [(ngModel)]="searchTerm" (input)="search()">
</code>```

We type something to search the first time it gets searched but again if we search then no records are found because the original array records is changed it would only consist of the records which are searched and not all the records how to deal with this problem.

I could create a second array to keep a copy of all the records and assign it to the original array in the else if condition but that would only work if we empty the search box and not if we search and type again without emptying the search box to the last character.

The records are shown in the table with ngfor. The search function is for that table

```<code> searchTerm : any;
    records: any;  //array of objects

    search(){
 if(this.searchTerm !== ""){
     this.records = this.records.filter((res: any)=>{
            return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
          });
} else if(this.searchTerm === "") {

}
    }
</code>```

答:
Your objects are in this.records and when you do search you assign the result again to the same variable this.records. The next time you search, you won't get it because the items does not exist in the array. Create another array for search results.

```<code>this.filteredRecords = this.records.filter((res: any)=>{
    return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
});
</code>```

And depends how you handle for different user cases. When you search you show fiteredRecords which contains results returned from your filter function, and in normal user case or searchTerm is empty:

```<code>else if(this.searchTerm === "") {
 this.filteredRecords = this.records
}
</code>```

Body:
<input type="text" [(ngModel)]="searchTerm" (input)="search()">

We type something to search the first time it gets searched but again if we search then no records are found because the original array records is changed it would only consist of the records which are searched and not all the records how to deal with this problem.

I could create a second array to keep a copy of all the records and assign it to the original array in the else if condition but that would only work if we empty the search box and not if we search and type again without emptying the search box to the last character.

The records are shown in the table with ngfor. The search function is for that table

 searchTerm : any;
    records: any;  //array of objects

    search(){
 if(this.searchTerm !== ""){
     this.records = this.records.filter((res: any)=>{
            return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
          });
} else if(this.searchTerm === "") {

}
    }

Body:
Your objects are in this.records and when you do search you assign the result again to the same variable this.records. The next time you search, you won't get it because the items does not exist in the array. Create another array for search results.

this.filteredRecords = this.records.filter((res: any)=>{
    return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
});

And depends how you handle for different user cases. When you search you show fiteredRecords which contains results returned from your filter function, and in normal user case or searchTerm is empty:

else if(this.searchTerm === "") {
 this.filteredRecords = this.records
}


问:
How can I query multiple columns from a drop down menu and a count of a certain column
I'm trying to generate a report for a user to select from a drop-down menu. I'd like to be able to pull multiple columns from a selected drop down. And, if possible, get a certain count for a certain column.

So far I've only been able to select one column and get a count from it.

```<code>=QUERY(A2:O20,"SELECT M, count(M) Where E ='" &B23 & "' group by M",0)
</code>```

I'd like to somehow to continue selecting certain columns and have them display when a user selects from the drop-down menu, as well as keeping my current work (The count from M)

答:
I set up a copy of your sheet that stacks the count of each column as a report based on which value is selected from the drop down.  The formula is in cell K1 and I've moved the drop down to cell J1:

https://docs.google.com/spreadsheets/d/1ccFgll7mW2rNs6m9gHUAx7ObsZ8n4GFjMc2cZS0nX68/edit?usp=sharing

The syntax of the formula uses ; to place each QUERY output on top of the next:

={QUERY(ColA);QUERY(ColB);QUERY(ColC);QUERY(ColE) etc...}

Body:
I'm trying to generate a report for a user to select from a drop-down menu. I'd like to be able to pull multiple columns from a selected drop down. And, if possible, get a certain count for a certain column.

So far I've only been able to select one column and get a count from it.

=QUERY(A2:O20,"SELECT M, count(M) Where E ='" &B23 & "' group by M",0)

I'd like to somehow to continue selecting certain columns and have them display when a user selects from the drop-down menu, as well as keeping my current work (The count from M)


答:
Aggregation and join:

```<code>select t2.start, t2.end, array_agg(t1.value)
from table2 t2 left join
     table1 t1
     on t1.timestamp >= t2.start and t1.timestamp < t2.end
group by t2.start, t2.end;
</code>```

Title: Returning an array of values from timestamps between a start and end time

Body:
I have a query that produces a timestamp and a value at that timestamp.

select timestamp, value
from table1;

So, a sample from the data would look like this:

      timestamp      |     value      |
---------------------------------------
 2019-02-28 01:00:00 | 1              |
 2019-02-28 01:10:00 | 1              |
 2019-02-28 01:20:00 | 6              |
 2019-02-28 01:30:00 | 17             |
 2019-02-28 01:40:00 | 4              |
 2019-02-28 01:50:00 | 4              |

I have a second query that produces a start timestamp and an end timestamp.

select start, end
from table2;

A sample from that would look like this:

       start        |         end         |
-------------------------------------------
2019-02-28 01:00:00 | 2019-02-28 01:30:00 |
2019-02-28 01:40:00 | 2019-02-28 01:50:00 |

How would I be able to combine the two queries to produce an output like this?

       start        |         end         |      values     |
-------------------------------------------------------------
2019-02-28 01:00:00 | 2019-02-28 01:30:00 | {1,1,6}         |
2019-02-28 01:40:00 | 2019-02-28 01:50:00 | {4}             |

Body:
Aggregation and join:

select t2.start, t2.end, array_agg(t1.value)
from table2 t2 left join
     table1 t1
     on t1.timestamp >= t2.start and t1.timestamp < t2.end
group by t2.start, t2.end;


问:
Search filter cannot take sort function in react
I am new in React and was trying to make a AutoCompleteText Search Box from a youtube tutorialReact Beginners Tutorial - Build an Autocomplete Text Box for my Web Application(https://github.com/pydevsg/Bank-Filter-App). But it is showing me this error when I am running it through localhost.

But it is showing me this error when I am running it through localhost.

TypeError: Cannot read property 'sort' of undefined

AutoCompleteText.onTextChanged

14 |   let suggestions = [];

15 |   if (value.length > 0) {

16 |     const regex = new RegExp(${value}, i);

17 |     suggestions = this.items.sort().filter(v => regex.test(v));

18 |   }

19 |   this.setState(() => ({ suggestions, text: value }));

20 | };

I expect that the SearchBox should be able to show all the data as per my DataTable.

答:
Alright I see what your problems are, you've got components rendering unessesarily and not rendering the ones that you need.

Firstly:

import App from "./App"; // Import your app

// Make it display the App
var displayDropdown = (

    <App />

);

// Get rid of all other ReactDOM renders
ReactDOM.render(displayDropdown, document.getElementById("root"));```

Then in DataTable.js, get rid of your AutoCompleteText component, it's not doing anything and is what's causing it to blow up since you're not passing any props to it. If you want to keep the one in the DataTable component then you need to pass the bank array to it just like you're doing in App.js.

That should get you closer to where you want to be.

Body:
Alright I see what your problems are, you've got components rendering unessesarily and not rendering the ones that you need.

Firstly:

import App from "./App"; // Import your app

// Make it display the App
var displayDropdown = (
  <div style={{ display: "flex", justifyContent: "center" }}>
    <App />
  </div>
);

// Get rid of all other ReactDOM renders
ReactDOM.render(displayDropdown, document.getElementById("root"));

Then in DataTable.js, get rid of your AutoCompleteText component, it's not doing anything and is what's causing it to blow up since you're not passing any props to it. If you want to keep the one in the DataTable component then you need to pass the bank array to it just like you're doing in App.js.

That should get you closer to where you want to be.


问:
calling variables for rule individually and adding an independent environment for a specific rule
I need to run a snakemake rule in the cluster, therefore for some rules, I need some tools and library needed to e loaded whereas, these tools are independent/ exclusive to other rules. I this case how can I specify these in my snakemake rule. For example, for rule score I need to module load r/3.5.1 and export R_lib =/user/tools/software currently, I am running these lines separately in the command line before running snakemake. But it would be great if there is a way to do it within the rule as env.

Question,

I have a rule as following,

```<code>rule score:
    input:
        count=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.tsv'),
        libsize=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.size_tsv')
    params:
        result_dir=os.path.join(config['general']['paths']['outdir'], 'score'),
        cancertype=config['general']['paths']['cancertype'],
        sample_id=expand('{sample}',sample=samples['sample'].unique())
    output:
        files=os.path.join(config['general']['paths']['outdir'], 'score', '{sample}_bg_scores.tsv', '{sample}_tp_scores.tsv')
    shell:
        'mkdir -p {params.result_dir};Rscript {config[general][paths][tool]} {params.result_dir} {params.cancertype} {params.sample_id} {input.count} {input.libsize}'
</code>```

My actual behavior for the above code snippet is:

```<code>shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv
</code>```

Whereas, the expected behavior is:

```<code>shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv
</code>```

and for the second sample,

```<code>shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 /cluster/projects/test/results/exp/GNMS4.tsv /cluster/projects/test/results/Exp/GNMS4.ize.tsv
</code>```

I need the variable  sample_d ['GNMS4', 'MRT5T'] should be taken separately, not together in one shell command line.

答:
Regarding your first question: You can put whatever module load or export commands you like in the shell section of a rule.

Regarding your second question, you should probably not use expand in the params section of your rule. In expand('{sample}',sample=samples['sample'].unique()) you are actually not using the value of the sample wildcard, but generating a list of all unique values in sample['sample']. You probably just need to use wildcards.sample in the definition of your shell command instead of using a params element.

If you want to run several instances of the score rule based on possible values for sample, you need to "drive" this using another rule that wants the output of score as its input.

Note  that to improve readability, you can use python's multi-line strings (triple-quoted).

To sum up, you might try something like this:

```<code>rule all:
    input:
        expand(
            os.path.join(
                config['general']['paths']['outdir'],
                'score',
                '{sample}_bg_scores.tsv',
                '{sample}_tp_scores.tsv'),
            sample=samples['sample'].unique())

rule score:
    input:
        count = os.path.join(
             config['general']['paths']['outdir'],
             'count_expression', '{sample}.tsv'),
        libsize = os.path.join(
             config['general']['paths']['outdir'],
             'count_expression', '{sample}.size_tsv')
    params:
        result_dir = os.path.join(config['general']['paths']['outdir'], 'score'),
        cancertype = config['general']['paths']['cancertype'],
    output:
        files = os.path.join(
            config['general']['paths']['outdir'],
            'score', '{sample}_bg_scores.tsv', '{sample}_tp_scores.tsv')
    shell:
        """
        module load r/3.5.1
        export R_lib =/user/tools/software
        mkdir -p {params.result_dir}
        Rscript {config[general][paths][tool]} {params.result_dir} {params.cancertype} {wildcards.sample} {input.count} {input.libsize}
        """
</code>```

Body:
I need to run a snakemake rule in the cluster, therefore for some rules, I need some tools and library needed to e loaded whereas, these tools are independent/ exclusive to other rules. I this case how can I specify these in my snakemake rule. For example, for rule score I need to module load r/3.5.1 and export R_lib =/user/tools/software currently, I am running these lines separately in the command line before running snakemake. But it would be great if there is a way to do it within the rule as env.

Question,

I have a rule as following,

rule score:
    input:
        count=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.tsv'),
        libsize=os.path.join(config['general']['paths']['outdir'], 'count_expression', '{sample}.size_tsv')
    params:
        result_dir=os.path.join(config['general']['paths']['outdir'], 'score'),
        cancertype=config['general']['paths']['cancertype'],
        sample_id=expand('{sample}',sample=samples['sample'].unique())
    output:
        files=os.path.join(config['general']['paths']['outdir'], 'score', '{sample}_bg_scores.tsv', '{sample}_tp_scores.tsv')
    shell:
        'mkdir -p {params.result_dir};Rscript {config[general][paths][tool]} {params.result_dir} {params.cancertype} {params.sample_id} {input.count} {input.libsize}'

My actual behavior for the above code snippet is:

shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv

Whereas, the expected behavior is:

shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC MRT5T /cluster/projects/test/results/exp/MRT5T.tsv /cluster/projects/test/results/Exp/MRT5T.size.tsv

and for the second sample,

shell:
        mkdir -p /cluster/user/snakemake_test/results_april30/score;Rscript /cluster/home/user/Projects/R_scripts/scoretool.R /cluster/user/snakemake_test/results_april30/score DMC GNMS4 /cluster/projects/test/results/exp/GNMS4.tsv /cluster/projects/test/results/Exp/GNMS4.ize.tsv

I need the variable  sample_d ['GNMS4', 'MRT5T'] should be taken separately, not together in one shell command line.

Body:
Regarding your first question: You can put whatever module load or export commands you like in the shell section of a rule.

Regarding your second question, you should probably not use expand in the params section of your rule. In expand('{sample}',sample=samples['sample'].unique()) you are actually not using the value of the sample wildcard, but generating a list of all unique values in sample['sample']. You probably just need to use wildcards.sample in the definition of your shell command instead of using a params element.

If you want to run several instances of the score rule based on possible values for sample, you need to "drive" this using another rule that wants the output of score as its input.

Note  that to improve readability, you can use python's multi-line strings (triple-quoted).

To sum up, you might try something like this:

rule all:
    input:
        expand(
            os.path.join(
                config['general']['paths']['outdir'],
                'score',
                '{sample}_bg_scores.tsv',
                '{sample}_tp_scores.tsv'),
            sample=samples['sample'].unique())

rule score:
    input:
        count = os.path.join(
             config['general']['paths']['outdir'],
             'count_expression', '{sample}.tsv'),
        libsize = os.path.join(
             config['general']['paths']['outdir'],
             'count_expression', '{sample}.size_tsv')
    params:
        result_dir = os.path.join(config['general']['paths']['outdir'], 'score'),
        cancertype = config['general']['paths']['cancertype'],
    output:
        files = os.path.join(
            config['general']['paths']['outdir'],
            'score', '{sample}_bg_scores.tsv', '{sample}_tp_scores.tsv')
    shell:
        """
        module load r/3.5.1
        export R_lib =/user/tools/software
        mkdir -p {params.result_dir}
        Rscript {config[general][paths][tool]} {params.result_dir} {params.cancertype} {wildcards.sample} {input.count} {input.libsize}
        """


问:
Iron-list row vertical responsiveness breaks
Using Polymer 1.* with iron list. I am having a issue with the rows of iron-list being responsive vertically.

For instance, in the below example when the text collapses in the first row the row line above Charlie Brown overlaps Charlie Brown row/text.

I see that each row is position: absolute by iron-list, so not sure if there is anything I can do about this.

Any suggestions?

答:
I had this issue some times ago (well not exactly the same, but it look like this is the same root cause) and the solution I found was to force the element to re-render when the window was resized.

Polymer is fixing some absolute position values at render, and some elements break when viewport is changed without triggering a re-render.

I you need it, i will try to find the exact code snippet, but just listen for resize, and call this.render on the iron list should do.


问:
java collection without null object
Is there any collection in java that won't add null object? Given a list of item, query DB for those items, when the result returned from DB, i'll add the item to result list if it does exist in DB, if it doesn't DB return null, then I'll discard it.

I have following code does this:

```<code>reqIds.forEach(
        reqId -> {
          columnValueMap.clear();
          columnValueMap.put("request_id", reqId);
          EventAudit auditRecord =
              pollDatabaseFindByIdAndKey(
                  EventAudit.class, columnValueMap);

          if (auditRecord != null) {
            auditMap.put(auditRecord.getRequestId(), auditRecord);
          }
        });
</code>```

i know i can use Java stream filter to filter out null but just wonder if there is any smart collection that will reject null object automatically so i don't need to do extra Null checking

答:
Look at the java-doc of Collection and it's definition of add:

If a collection refuses to add a particular element for any reason
  other than that it already contains the element, it must throw an
  exception (rather than returning false). This preserves the invariant
  that a collection always contains the specified element after this
  call returns.

and

NullPointerException - if the specified element is null and this
  collection does not permit null elements

As you can see such a Collection would break the contract defined in the Collection interface. You will have to look for third party libraries to accomplish what you want but I highly recommend you to not use such a collection as it breaks several assumption an the principle of least astonishment when a user comfortable with other collections gets unexpected behaviour.

Title: java collection without null object

Body:
Is there any collection in java that won't add null object? Given a list of item, query DB for those items, when the result returned from DB, i'll add the item to result list if it does exist in DB, if it doesn't DB return null, then I'll discard it.

I have following code does this:

reqIds.forEach(
        reqId -> {
          columnValueMap.clear();
          columnValueMap.put("request_id", reqId);
          EventAudit auditRecord =
              pollDatabaseFindByIdAndKey(
                  EventAudit.class, columnValueMap);

          if (auditRecord != null) {
            auditMap.put(auditRecord.getRequestId(), auditRecord);
          }
        });

i know i can use Java stream filter to filter out null but just wonder if there is any smart collection that will reject null object automatically so i don't need to do extra Null checking


问:
JButton is drawing behind an image
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:

```<code>    public void drawStartScreen(){
    startScreenOn = true;
    Graphics2D b = buffer.createGraphics();
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start,0,0,null);

    setLayout( null );
    button = new JButton("Start Game");
    button.setBounds(10,10,100,100);
    button.setVisible( true );
    add(button);
}
</code>```

It draws the image first, and then the Button, but the button still draws behind the image.

答:
I recommend you'd use a JLayeredPane (I go for custom painting only as a last resort).

If you're still interested in mixing the 'low-level' painting with 'higher-level' JComponent hierarchy, look at a question about a JFrame that has multiple layers.

Title: JButton is drawing behind an image

Body:
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:

    public void drawStartScreen(){
    startScreenOn = true;
    Graphics2D b = buffer.createGraphics();
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start,0,0,null);

    setLayout( null );
    button = new JButton("Start Game");
    button.setBounds(10,10,100,100);
    button.setVisible( true );
    add(button);
}

It draws the image first, and then the Button, but the button still draws behind the image.


问:
Write to csv file
I need some contents to be written in csv format to a file using ansible

```<code>shell: ps -ef | grep java | awk '{print $1}'
register: username

shell: ps -ef | grep java | awk '{print $2}'
register: id
</code>```

The output for username will be similar to :

```<code>root
admin
test_admin
</code>```

The output for id will be similar to:

```<code>1232
4343
2233
</code>```

so I want this to be written to a csv file as

```<code>root,1232
admin,4343
test_admin,2233
</code>```

Please suggest.

答:
You can use a combination of the zip, map and join filters to achieve your desired result:

```<code>- hosts: all
  tasks:
    - name: combination of two lists
      set_fact:
        lines: "{{ [1,2,3]|zip(['a','b','c'])|list }}"
    - debug:
        msg: "{{ lines }}"
    - name: transform each line into a string
      set_fact:
        lines: "{{ lines | map('join', ', ') | list }}"
    - debug:
        msg: "{{ lines }}"
    - name: combine lines
      set_fact:
        lines: "{{ lines | join('\n') }}"
    - debug:
        msg: "{{ lines }}"
    - name: write lines to file
      copy:
        content: "{{ lines }}"
        dest: "output.csv"
</code>```

Or when you combine the filters together:

```<code>- name: write lines to file
  copy:
    content: "{{ [1,2,3] | zip(['a','b','c']) | map('join', ', ')  | join('\n') }}"
    dest: "output.csv"
</code>```

The content of output.csv will be:

```<code>1, a
2, b
3, c
</code>```

Title: Write to csv file

Body:
I need some contents to be written in csv format to a file using ansible

shell: ps -ef | grep java | awk '{print $1}'
register: username

shell: ps -ef | grep java | awk '{print $2}'
register: id

The output for username will be similar to :

root
admin
test_admin

The output for id will be similar to:

1232
4343
2233

so I want this to be written to a csv file as

root,1232
admin,4343
test_admin,2233

Please suggest.

Body:
You can use a combination of the zip, map and join filters to achieve your desired result:

- hosts: all
  tasks:
    - name: combination of two lists
      set_fact:
        lines: "{{ [1,2,3]|zip(['a','b','c'])|list }}"
    - debug:
        msg: "{{ lines }}"
    - name: transform each line into a string
      set_fact:
        lines: "{{ lines | map('join', ', ') | list }}"
    - debug:
        msg: "{{ lines }}"
    - name: combine lines
      set_fact:
        lines: "{{ lines | join('\n') }}"
    - debug:
        msg: "{{ lines }}"
    - name: write lines to file
      copy:
        content: "{{ lines }}"
        dest: "output.csv"

Or when you combine the filters together:

- name: write lines to file
  copy:
    content: "{{ [1,2,3] | zip(['a','b','c']) | map('join', ', ')  | join('\n') }}"
    dest: "output.csv"

The content of output.csv will be:

1, a
2, b
3, c


问:
RxJS 1 array item into sequence of single items - operator
Given such observable

```<code>Rx.Observable.of([1,2,3,4,5])
</code>```

which emits a single item (that is an array), what is the operator that will transform this observable to a one that emits 5 single items (or whatever the array consists of)?

The example is on .of, but it would be the same for fetching arrays via promises, there might be many other examples. Don't suggest to replace of with from

答:
You can use from now to convert an array into a sequence.

https://www.learnrxjs.io/operators/creation/from.html

from([4,5,6])

Body:
Given such observable

Rx.Observable.of([1,2,3,4,5])

which emits a single item (that is an array), what is the operator that will transform this observable to a one that emits 5 single items (or whatever the array consists of)?

The example is on .of, but it would be the same for fetching arrays via promises, there might be many other examples. Don't suggest to replace of with from


问:
How to use a Keras trained Embedded layer?
My model is:

```<code>        model = Sequential()
        model.add(Embedding(input_dim=vocab_size,
                            output_dim=1024, input_length=self.SEQ_LENGTH))

        model.add(LSTM(vocab_size))

        model.add(Dropout(rate=0.5))
        model.add(Dense(vocab_size - 1, activation='softmax'))
</code>```

And I have it trained. But now during inference time, how can I use that embedding?

答:
Your question is solved here. As skeleton you can use this code:</p>

```<code>from tensorflow.python.keras.preprocessing.text import Tokenizer

tokenizer_obj = Tokenizer()
tokenizer_obj.fit_on_texts(your_dataset)

...

max_length = max_number_words
X_test_tokens = tokenizer_obj.texts_to_sequences(X_test)
X_test_pad = pad_sequences(X_test_tokens, maxlen=max_length, padding='post')

score, acc = model.evaluate(X_test_pad, y_test, batch_size=128)
</code>```

Body:
My model is:

        model = Sequential()
        model.add(Embedding(input_dim=vocab_size,
                            output_dim=1024, input_length=self.SEQ_LENGTH))

        model.add(LSTM(vocab_size))

        model.add(Dropout(rate=0.5))
        model.add(Dense(vocab_size - 1, activation='softmax'))

And I have it trained. But now during inference time, how can I use that embedding?

Body:
Your question is solved here. As skeleton you can use this code:

from tensorflow.python.keras.preprocessing.text import Tokenizer

tokenizer_obj = Tokenizer()
tokenizer_obj.fit_on_texts(your_dataset)

...

max_length = max_number_words
X_test_tokens = tokenizer_obj.texts_to_sequences(X_test)
X_test_pad = pad_sequences(X_test_tokens, maxlen=max_length, padding='post')

score, acc = model.evaluate(X_test_pad, y_test, batch_size=128)


问:
Turn off autocomplete in PhpStorm
Right now if I type in $ into Jetbrains PhpStorm IDE, it will display a whole bunch of suggestions (e.g. variables that have already been declared) which slows down my typing.

Is there a way to configure PhpStorm to NOT do this? In other words, turn off auto-complete or only do auto-complete if I press Ctrl+Space and not when I just type in $?

答: My auto-completion was not working, I had to execute in menu File->Invalidate cache... (and disable Nette tester plugin in my case)

Title: Turn off autocomplete in PhpStorm


问:
Is there a way to automate xml.version?
Imagine that I have the following XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<colors>
    <color1> Blue</color1>
    <color2> Red</color2>
</colors>
</code>```

is there a way to auto set version with the version of my pom.xml project?

Suppose my pom.xml is like:

```<code><groupId>br.com.colors/groupId>
<artifactId>colors</artifactId>
<version>1.0.2</version>
</code>```

xml verision shoud be like:

```<code><?xml version="1.0.2" encoding="UTF-8"?>
<colors>
     <color1> Blue</color1>
     <color2> Red</color2>
</colors>
</code>```

答:
That version is not what you imagine it means.

Versioning should be in your XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<colors version="1.0.2">
     <color1>Blue</color1>
     <color2>Red</color2>
</colors>
</code>```

You'll need a Maven task or plug in that can modify the files for you.

Personally, I'd advise against it.  Let your GitHub or source code management tool handle versioning.

You seem to want the object that is parsing your XML into a DOM tree to validate the version.  Can you describe what that looks like?  What do valid and invalid version scenarios look like?  What does the XML process do with that attribute?

Title: Is there a way to automate xml.version?

Body:
Imagine that I have the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<colors>
    <color1> Blue</color1>
    <color2> Red</color2>
</colors>

is there a way to auto set version with the version of my pom.xml project?

Suppose my pom.xml is like:

<groupId>br.com.colors/groupId>
<artifactId>colors</artifactId>
<version>1.0.2</version>

xml verision shoud be like:

<?xml version="1.0.2" encoding="UTF-8"?>
<colors>
     <color1> Blue</color1>
     <color2> Red</color2>
</colors>

Body:
That version is not what you imagine it means.

Versioning should be in your XML:

<?xml version="1.0" encoding="UTF-8"?>
<colors version="1.0.2">
     <color1>Blue</color1>
     <color2>Red</color2>
</colors>

You'll need a Maven task or plug in that can modify the files for you.

Personally, I'd advise against it.  Let your GitHub or source code management tool handle versioning.

You seem to want the object that is parsing your XML into a DOM tree to validate the version.  Can you describe what that looks like?  What do valid and invalid version scenarios look like?  What does the XML process do with that attribute?


问:
If a bash command accepts a filename as the last arg, can piping be used to provide file content?
Say a command takes a filename as its last argument:

```<code>count-words "$word" file.txt
</code>```

Is there a way to use pipe in order to provide file content rather than writing to a temp file?

答:
Many programs will accept a single hyphen (-) as an instruction to use standard input. Consider, given how you're invoking your example command, the following:

```<code>cat file.txt | grep -Fow "$word" - | wc -l
</code>```

This counts instances of $word in the given file. The -F option speeds up the search by disabling regular expressions (so . actually means .), -o sets the output to show just the matches (one per line), and the -w option requires a word boundary on both sides of the word (so foo will not match food; remove this flag to change that). wc -l will give you the count of the lines outputted by grep, which is the number of instances of $word. (I didn't use grep -c because that counts the lines with matches, which means foo bar foo baz on a line would be counted just once.)

If count-words is your script, consider one of these options:

```<code># imply standard input when given insufficient arguments
# or when the only argument is a hyphen
# (requires you to `shift` your options and the query term)
if [ "$#" = "0" ] || [ "$*" = "-" ]; then
  set -- /dev/stdin
fi

# convert hyphen(s) to /dev/stdin within the argument list
FIRST=1
for OPT in "$@"; do
  if [ "$FIRST" = 1 ]; then
    unset FIRST
    set --
  fi
  if [ "$OPT" = "-" ]; then
    OPT="/dev/stdin"
  fi
  set -- "$@" "$OPT"
done
</code>```

This will let you run as any of

count-words "$word" < file.txt

get-input | count-words "$word"

get-input | count-words "$word" -

get-input | count-words "$word" /dev/stdin

echo "$(get-input)" | count-words "$word"

count-words "$word" <<<"list of words as if echoed"

count-words "$word" <(get-input)

The last three are bashisms and will not work in dash or other simpler /bin/sh programs. The very last command tells count-words to use process substitution to supply a named pipe as a temporary filehandle that stores the output of get-input.

Body:
Say a command takes a filename as its last argument:

count-words "$word" file.txt

Is there a way to use pipe in order to provide file content rather than writing to a temp file?

Body:
Many programs will accept a single hyphen (-) as an instruction to use standard input. Consider, given how you're invoking your example command, the following:

cat file.txt | grep -Fow "$word" - | wc -l

This counts instances of $word in the given file. The -F option speeds up the search by disabling regular expressions (so . actually means .), -o sets the output to show just the matches (one per line), and the -w option requires a word boundary on both sides of the word (so foo will not match food; remove this flag to change that). wc -l will give you the count of the lines outputted by grep, which is the number of instances of $word. (I didn't use grep -c because that counts the lines with matches, which means foo bar foo baz on a line would be counted just once.)

If count-words is your script, consider one of these options:

# imply standard input when given insufficient arguments
# or when the only argument is a hyphen
# (requires you to `shift` your options and the query term)
if [ "$#" = "0" ] || [ "$*" = "-" ]; then
  set -- /dev/stdin
fi

# convert hyphen(s) to /dev/stdin within the argument list
FIRST=1
for OPT in "$@"; do
  if [ "$FIRST" = 1 ]; then
    unset FIRST
    set --
  fi
  if [ "$OPT" = "-" ]; then
    OPT="/dev/stdin"
  fi
  set -- "$@" "$OPT"
done

This will let you run as any of

count-words "$word" < file.txt

get-input | count-words "$word"

get-input | count-words "$word" -

get-input | count-words "$word" /dev/stdin

echo "$(get-input)" | count-words "$word"

count-words "$word" <<<"list of words as if echoed"

count-words "$word" <(get-input)

The last three are bashisms and will not work in dash or other simpler /bin/sh programs. The very last command tells count-words to use process substitution to supply a named pipe as a temporary filehandle that stores the output of get-input.


问:
How could I get [a,0,b,0,c,0] when I give [a,b,c]?
I've made this code:

```<code>ceros([A|B],[C|D]):-
C is [A,0],
ceros(B,D).
</code>```

and when I try this consult:

```<code>?- ceros([a,b,c],X)
</code>```

I'm supposed to get:
X=[a,0,b,0,c,0]

but I get an error:

```<code>Arithmetic: `[_2554,0]' is not a function
</code>```

I've no idea why I'm getting this error so I'd be so grateful if someone can explain it for me. Thanks

Body:
I've made this code:

ceros([A|B],[C|D]):-
C is [A,0],
ceros(B,D).

and when I try this consult:

?- ceros([a,b,c],X)

I'm supposed to get:
X=[a,0,b,0,c,0]

but I get an error:

Arithmetic: `[_2554,0]' is not a function

I've no idea why I'm getting this error so I'd be so grateful if someone can explain it for me. Thanks

Body:
Got it

ceros([],[]).
ceros([A|B],[A,0|D]):-
ceros(B,D).


问:
`python: not found` error when fetching Chromium source with `depot_tools`
I'm recently following the Chromium build instructions for Windows but fetch yields the following error:

```<code>$ fetch chromium
/c/src/depot_tools/fetch: line 8: exec: python: not found
</code>```

NB: Python 3.6 is already installed on my PC.

答:
The Windows build instructions fail to specify the required Python version, but the Linux ones are clear:

System requirements

A 64-bit Intel machine with at least 8GB of RAM. More than 16GB is highly recommended.

At least 100GB of free disk space.

You must have Git and Python v2 installed already.

The executable for Python 3.x is python3, and the one for Python 2.x is python, therefore you need to install Python 2.x.

Body:
I'm recently following the Chromium build instructions for Windows but fetch yields the following error:

$ fetch chromium
/c/src/depot_tools/fetch: line 8: exec: python: not found

NB: Python 3.6 is already installed on my PC.


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答: I currently do it by making use of unemployment benefit.</p>

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: anon


问:
To convert a data coming in 2x to 1x clock in verilog or systemverilog
I am working on validation. I current face a problem of converting a data that is coming to a unit in 2x clock.

For a signal of 132 bits it travels as 66 bit bus in 2x clock.

At receiving again all the clock conversion is to be done from 2x to 1x getting back all 132 bits of the signal.

Can somebody help me on how to do this ?

Thanks a lot in advance.

答:
The usual way is that you have a 132 bit dual ported register. With one port in your 1x clock domain and and the other port in your 2x clock domain. As one is read only and one write only, you can just describe it like a normal register. But migrating between different clock domains is very tricky, esp. because of metastability. Do workaround this you have to add another level(s) of flip flops (i.e. another register).

My answer is not very specific and detailed, but this due to the fact, that your question is very unspecific/broad.


问:
Create new columns with quantiles from a group in r
I want to include new columns with quantile 1 y 3 by group

I have this dataframe:

```<code>d <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-23", "2017-02-23","2018-02-22", "2018-02-22"),
var1 = c(1,3,6,7,8,5),
var2 = c(1,3,18,15,25,5))
</code>```

and I would like to have two new columns Q1var1, Q1var2, Q1var1 and Q1var2 like:

```<code>d = d %>% group_by(date) %>% mutate(Q1var1 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q1var2 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var1 = quantile(var1,prob = 0.75,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var2 = quantile(var1,prob = 0.75,na.rm = TRUE))
</code>```

but in a faster way

Body:
I want to include new columns with quantile 1 y 3 by group

I have this dataframe:

d <- data.frame(date = c("2017-02-23", "2017-02-22", "2017-02-23", "2017-02-23","2018-02-22", "2018-02-22"),
var1 = c(1,3,6,7,8,5),
var2 = c(1,3,18,15,25,5))

and I would like to have two new columns Q1var1, Q1var2, Q1var1 and Q1var2 like:

d = d %>% group_by(date) %>% mutate(Q1var1 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q1var2 = quantile(var1,prob = 0.25,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var1 = quantile(var1,prob = 0.75,na.rm = TRUE))
d = d %>% group_by(date) %>% mutate(Q3var2 = quantile(var1,prob = 0.75,na.rm = TRUE))

but in a faster way

Body:
An option would be to group by 'date', then use mutate_at for applying functions on multiple columns, convert the quantile output to a tibble wrapped in a list and then unnest

library(tidyverse)
d %>%
  group_by(date) %>%
  mutate_at(vars(var1, var2), list(Qs = ~
     list(as_tibble(as.list(quantile(., prob = c(0.25, 0.75),
         na.rm = TRUE )))))) %>%
  unnest
# A tibble: 6 x 7
# Groups:   date [3]
#  date        var1  var2 `25%` `75%` `25%1` `75%1`
#  <fct>      <dbl> <dbl> <dbl> <dbl>  <dbl>  <dbl>
#1 2017-02-23     1     1  3.5   6.5       8   16.5
#2 2017-02-22     3     3  3     3         3    3
#3 2017-02-23     6    18  3.5   6.5       8   16.5
#4 2017-02-23     7    15  3.5   6.5       8   16.5
#5 2018-02-22     8    25  5.75  7.25     10   20
#6 2018-02-22     5     5  5.75  7.25     10   20

Or with data.table

library(data.table)
nm1 <-  paste0("Q_", rep(c("var1", "var2"), each = 2), c(".Q25", ".Q75"))
setDT(d)[, (nm1) := unlist(lapply(.SD, function(x)
   as.list(quantile(x, prob = c(0.25, 0.75)))), recursive = FALSE),
          date, .SDcols = var1:var2]
d
#         date var1 var2 Q_var1.Q25 Q_var1.Q75 Q_var2.Q25 Q_var2.Q75
#1: 2017-02-23    1    1       3.50       6.50          8       16.5
#2: 2017-02-22    3    3       3.00       3.00          3        3.0
#3: 2017-02-23    6   18       3.50       6.50          8       16.5
#4: 2017-02-23    7   15       3.50       6.50          8       16.5
#5: 2018-02-22    8   25       5.75       7.25         10       20.0
#6: 2018-02-22    5    5       5.75       7.25         10       20.0


问:
vba listobject CopyFromRecordset
How to populate data from a recordset into a listobject?
The code below is not completely working:</p>

```<code>oCN.ConnectionString = "DRIVER={SQL Server};Server=SRVSQL;Database=TEST;"
oCN.Open
Dim sqlString As String
sqlString = "SELECT * FROM MYTABLE"
oRS.Open sqlString, oCN

With Feuil3.ListObjects("TableArticles")
    If Not .DataBodyRange Is Nothing Then
        .DataBodyRange.Delete
    End If

    ' This make a 91 error
    Call .DataBodyRange.CopyFromRecordset(oRS)
    ' This copy data into sheet, not into listobject
    Call Feuil3.Range("A2").CopyFromRecordset(oRS)
End With
</code>```

答:
If you are always deleting the .DataBodyRange first, you can use the `.InsertRowRange'.

```<code>With Feuil3.ListObjects("TableArticles")
    If Not .DataBodyRange Is Nothing Then .DataBodyRange.Delete
    .InsertRowRange.CopyFromRecordset(oRS)
End With
</code>```

Title: vba listobject CopyFromRecordset

Body:
How to populate data from a recordset into a listobject?
The code below is not completely working:

oCN.ConnectionString = "DRIVER={SQL Server};Server=SRVSQL;Database=TEST;"
oCN.Open
Dim sqlString As String
sqlString = "SELECT * FROM MYTABLE"
oRS.Open sqlString, oCN

With Feuil3.ListObjects("TableArticles")
    If Not .DataBodyRange Is Nothing Then
        .DataBodyRange.Delete
    End If

    ' This make a 91 error
    Call .DataBodyRange.CopyFromRecordset(oRS)
    ' This copy data into sheet, not into listobject
    Call Feuil3.Range("A2").CopyFromRecordset(oRS)
End With

Body:
If you are always deleting the .DataBodyRange first, you can use the `.InsertRowRange'.

With Feuil3.ListObjects("TableArticles")
    If Not .DataBodyRange Is Nothing Then .DataBodyRange.Delete
    .InsertRowRange.CopyFromRecordset(oRS)
End With


问:
"Error Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time"
I'm creating a ASP .NET Core Web API using  VS 2019 preview and .NET Core 3.0.
When I try execute : add-migration, I'm getting the error :
"Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time,..."

Below is my context file:

```<code>  public class AppDbContext : DbContext
  {
     public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        { }
     public DbSet<Categoria> Categorias { get; set; }
     public DbSet<Produto> Produtos { get; set; }
  }
</code>```

My ConfigureServices method:

```<code>public void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<AppDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

  services.AddControllers().AddNewtonsoftJson();
}
</code>```

My appsettings.json

```<code>{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;DataBase....."
  },
...
}
</code>```

I always using this approach and it works.

I also tried create a empty constructor in context class and the I got this error :
"System.InvalidOperationException: No database provider has been configured for this DbContext..."

Am I forgetting some detail ?

note: This works fine in ASP .NET Core 2.2

答:
You can tell the migration how to create your DbContext by implementing the IDesignTimeDbContextFactory<TContext> interface: If a class implementing this interface is found in either the same project as the derived DbContext or in the application's startup project, the tools bypass the other ways of creating the DbContext and use the design-time factory instead.

for more information see this link

```<code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace MyProject
{
    public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
            optionsBuilder.UseMySql("Server=localhost;DataBase.....");

            return new AppDbContext(optionsBuilder.Options);
        }
    }
}
</code>```

Body:
I'm creating a ASP .NET Core Web API using  VS 2019 preview and .NET Core 3.0.
When I try execute : add-migration, I'm getting the error :
"Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time,..."

Below is my context file:

  public class AppDbContext : DbContext
  {
     public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        { }
     public DbSet<Categoria> Categorias { get; set; }
     public DbSet<Produto> Produtos { get; set; }
  }

My ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<AppDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

  services.AddControllers().AddNewtonsoftJson();
}

My appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;DataBase....."
  },
...
}

I always using this approach and it works.

I also tried create a empty constructor in context class and the I got this error :
"System.InvalidOperationException: No database provider has been configured for this DbContext..."

Am I forgetting some detail ?

note: This works fine in ASP .NET Core 2.2

Body:
You can tell the migration how to create your DbContext by implementing the IDesignTimeDbContextFactory<TContext> interface: If a class implementing this interface is found in either the same project as the derived DbContext or in the application's startup project, the tools bypass the other ways of creating the DbContext and use the design-time factory instead.

for more information see this link

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace MyProject
{
    public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
            optionsBuilder.UseMySql("Server=localhost;DataBase.....");

            return new AppDbContext(optionsBuilder.Options);
        }
    }
}


问:
Implementing MATLAB Code in Java- Illumination Invariant
I have the following code written in MATLAB, taken from this paper on page 3:

```<code>function [ ii_image ] = RGB2IlluminationInvariant( image, alpha )
ii_image = 0.5 + log(image(:,:,2)) - alpha*log(image(:,:,3)) - (1-alpha)*log(image(:,:,1));
</code>```

This code should convert a 3-channel RGB image into its illumination invariant. I would like to know what the code is doing so that I can implement it in Java.

From what I can gather, it's calculating the logarithm of each red/green/blue pixel, and subtracting the values from each other, but the result isn't be an integer, so I can't apply it to Java's BufferedImage class when changing the RGB values. How can I emulate this function in Java?

答: You can find a lot of matrix library in Java according to here.  I suggest you can choose EJML to convert your logic into Java.</p>

Body:
I have the following code written in MATLAB, taken from this paper on page 3:

function [ ii_image ] = RGB2IlluminationInvariant( image, alpha )
ii_image = 0.5 + log(image(:,:,2)) - alpha*log(image(:,:,3)) - (1-alpha)*log(image(:,:,1));

This code should convert a 3-channel RGB image into its illumination invariant. I would like to know what the code is doing so that I can implement it in Java.

From what I can gather, it's calculating the logarithm of each red/green/blue pixel, and subtracting the values from each other, but the result isn't be an integer, so I can't apply it to Java's BufferedImage class when changing the RGB values. How can I emulate this function in Java?


问:
How to get current window pageYOffset in styled component?
Im struggling with translate animation which depends on scrollYOffset of a window.

I've got something like this :

```<code>const StyledHeading = styled.h1`
  font-size: ${({ theme }) => theme.fontSize.l};
  letter-spacing: 1px;
  font-family: ${({ theme }) => theme.font.firaSans};
  margin: 0;
  transition: 0.25s ease-in-out;
  transform: translateX(${({ offset }) => (offset > 100 ? '-50px' : '0px')});
`;

export default function Navbar() {
  const [offset, setOffset] = useState(window.pageYOffset);

  useEffect(() => {
    window.addEventListener('scroll', () => {
      setOffset(window.pageYOffset);
    });
  });

  return (
    <StyledHeader >
      <StyledWrapper>
        <StyledHeading offset={offset}>
          Bookphiles <i className="fas fa-book-open" />
        </StyledHeading>
        <nav>
          <NavLinks  />
        </nav>
      </StyledWrapper>
    </StyledHeader>
  );
}
</code>```

But its seems to be done in very inefficient way, because every scroll causes DOM rerender. Can this be done in some better way?

答:
IMHO, if you want to avoid choppy animation, you should rely on refs DOM management instead of React render():

```<code>import React, { useState, useEffect, createRef } from 'react';

export default function Navbar() {
  const ref = createRef();

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
  });

  handleScroll = (e) => {
      const offset = window.pageYOffset;
      ref.current.style.transform = `translateX(${({ offset }) => (offset > 100 ? '-50px' : '0px')})`;
  }

  return (
    //...code
        <StyledHeading ref={ref}>
          Bookphiles <i className="fas fa-book-open" />
        </StyledHeading>
    //..code
  );
}
</code>```

Notice that there could be some typo in my code but the concept is to not involve re-rendering in scroll management.
Remember to remove the listener before unmounting your component.

Body:
Im struggling with translate animation which depends on scrollYOffset of a window.

I've got something like this :

const StyledHeading = styled.h1`
  font-size: ${({ theme }) => theme.fontSize.l};
  letter-spacing: 1px;
  font-family: ${({ theme }) => theme.font.firaSans};
  margin: 0;
  transition: 0.25s ease-in-out;
  transform: translateX(${({ offset }) => (offset > 100 ? '-50px' : '0px')});
`;

export default function Navbar() {
  const [offset, setOffset] = useState(window.pageYOffset);

  useEffect(() => {
    window.addEventListener('scroll', () => {
      setOffset(window.pageYOffset);
    });
  });

  return (

          <NavLinks  />

      </StyledWrapper>
    </StyledHeader>
  );
}

But its seems to be done in very inefficient way, because every scroll causes DOM rerender. Can this be done in some better way?

Body:
IMHO, if you want to avoid choppy animation, you should rely on refs DOM management instead of React render():

import React, { useState, useEffect, createRef } from 'react';

export default function Navbar() {
  const ref = createRef();

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
  });

  handleScroll = (e) => {
      const offset = window.pageYOffset;
      ref.current.style.transform = `translateX(${({ offset }) => (offset > 100 ? '-50px' : '0px')})`;
  }

  return (
    //...code
        <StyledHeading ref={ref}>
          Bookphiles <i className="fas fa-book-open" />
        </StyledHeading>
    //..code
  );
}

Notice that there could be some typo in my code but the concept is to not involve re-rendering in scroll management.
Remember to remove the listener before unmounting your component.


问:
Does aria-haspopup require a true/false value?
According to the spec, the value should be a boolean. However, one of the spec examples of proper implementation uses a string value other than true/false - "listbox", which is the value of another element's role attribute. Is this a flaw in the implementation example or do screen readers, in practice, gain additional information from values other than true?

Relevant code from linked example:

```<code><div role="combobox" aria-expanded="false" aria-owns="ex1-listbox" aria-haspopup="listbox" id="ex1-combobox">
    <input type="text" aria-autocomplete="list" aria-controls="ex1-listbox" id="ex1-input" aria-activedescendant="">
</div>
</code>```

答: It looks like I found myself reading an older version of the spec. This version was the correct one, and it contains the newer options.</p>

Body:
According to the spec, the value should be a boolean. However, one of the spec examples of proper implementation uses a string value other than true/false - "listbox", which is the value of another element's role attribute. Is this a flaw in the implementation example or do screen readers, in practice, gain additional information from values other than true?

Relevant code from linked example:

    <input type="text" aria-autocomplete="list" aria-controls="ex1-listbox" id="ex1-input" aria-activedescendant="">


问:
Theming Drupal 8 - Loop through all posted articles and print specific section
I am trying to create my first Drupal 8 theme. On the frontpage, I want to list all articles with the title, summary, date posted, etc.

I more or less achieved this using views. Basically {{ page.content }} in twig, but found it to be really inflexible and I didn't really get the results that I wanted. What I want to do is just to iterate through all the articles and print each section of that article "manually". For instance:

```<code>{% for page in pages %}
  {{ page.content.title }}
  {{ page.content.datePosted }}
  {{ page.content.body }}
{% endfor %}
</code>```

So that I can have more control of what is happening and not making a lot of configuration in the views module when deploying. What is the best soltuion to achieve this? Thanks!

答:
I recommend to use Views. Configure you view (filter by content type, etc.), you have a lot of parameters to achieve what you need.

Set the view to show "Content" and give it a view mode (you can use the default teaser, full, or create your own view mode). Then you can create a custom template for this :

```<code>node--xxxx--teaser.html.twig
</code>```

In order to know how to name your custom template file, enable Twig Debugging in sites/default/services.yml. Set the debug variable to true. And clear cache. Then, you will see in source code the template name suggestion like this :

```<code>    <!-- FILE NAME SUGGESTIONS:
   * node--1--full.html.twig
   * node--1.html.twig
   x node--oeuvre--full.html.twig
   * node--oeuvre.html.twig
   * node--full.html.twig
   * node.html.twig
   -->
</code>```

In your twig, you can do that kind of templating :

```<code><a href="{{ url }}">{{ content.my_field_image[0] }}</a>

<h2><a href="{{ url }}">{{ node.title.value }}</a></h2>

<p>{{ content.body }}</p>
</code>```

Body:
I am trying to create my first Drupal 8 theme. On the frontpage, I want to list all articles with the title, summary, date posted, etc.

I more or less achieved this using views. Basically {{ page.content }} in twig, but found it to be really inflexible and I didn't really get the results that I wanted. What I want to do is just to iterate through all the articles and print each section of that article "manually". For instance:

{% for page in pages %}
  {{ page.content.title }}
  {{ page.content.datePosted }}
  {{ page.content.body }}
{% endfor %}

So that I can have more control of what is happening and not making a lot of configuration in the views module when deploying. What is the best soltuion to achieve this? Thanks!

Body:
I recommend to use Views. Configure you view (filter by content type, etc.), you have a lot of parameters to achieve what you need.

Set the view to show "Content" and give it a view mode (you can use the default teaser, full, or create your own view mode). Then you can create a custom template for this :

node--xxxx--teaser.html.twig

In order to know how to name your custom template file, enable Twig Debugging in sites/default/services.yml. Set the debug variable to true. And clear cache. Then, you will see in source code the template name suggestion like this :

    <!-- FILE NAME SUGGESTIONS:
   * node--1--full.html.twig
   * node--1.html.twig
   x node--oeuvre--full.html.twig
   * node--oeuvre.html.twig
   * node--full.html.twig
   * node.html.twig
   -->

In your twig, you can do that kind of templating :

<a href="{{ url }}">{{ content.my_field_image[0] }}</a>

<h2><a href="{{ url }}">{{ node.title.value }}</a></h2>

<p>{{ content.body }}</p>


问:
Stubbing / mocking a database in .Net
I have a webservice which basically just executes some stored procedures, transforms the data and sends it to the browser. No fancy ORM mapper or something like that involved. To be able to write test without accessing the database, I have done the following:

I have extracted all calls to the DB into one class. The methods return just the DataSet and DataTable objects.

Executed a sample call for each method and serialized the DataSet/DataTable to disk.

Extracted an interface exposing all available methods.

Implemented a fake database class which just loads the serialized data and returns it.

Now I have serialized sample results which I can check in with my project, and I can use the fake database in my tests.

This works quite well for me. Is there some framework which makes creating and loading the sample data easier? My current project is small, but I would use the same schema in larger projects.

Update:

Obviously all answers are not wrong, but miss the point. I'm aware of the basics of unit testing. But my code is working with DataTables, so I would have to somehow fake my DataTables. Building a DataTable from scratch is not an easy task, and it would bloat my tests and reduce readability. In my case, it would be quite impossible to generate useful sample data by hand.

Therefore, I executed some sample calls against a sample database to get some DataTables. I have serialized these tables to disk and use the serialized versions to create my fake DataTables when testing. That way the tests are independent of the database.

There are different options regarding how to structure the code, to make deserialization of the tables easier. But those are implementation details which don't need a discussion at this point. My problem is the following:

Managing the sample calls and (de)serializing the tables is tedious work. I was looking for some tools to make this easier.

答:
You could mock your DataAccess class with Rhinomocks and return a fake datatable. So you can test the code that uses this DataTable.

```<code>var mockedDatatable= GetMockdt();

var mocks = new MockRepository();
var dal = mocks.StrictMock<DataAccess>();

using (mocks.Record())
{
  Expect.Call(dal.GetDataTableFromDatabase("", null)).Return(mockedDatatable).IgnoreArguments();
}

using (mocks.Playback())
{
  new SomeClass(dal);
}
</code>```

UPDATE the mockdt message

```<code>private static DataTable GetMockdt()
{
  var dt = new DataTable();

  dt.Columns.Add("pageHeader");
  dt.Columns.Add("templatename");
  dt.Columns.Add("pageText");
  dt.Columns.Add("pageTitleBar");
  dt.Columns.Add("metaDescription");
  dt.Columns.Add("pageStartCode");
  dt.Columns.Add("pageEndCode");
  dt.Columns.Add("templateStartCode");
  dt.Columns.Add("templateEndCode");
  dt.Columns.Add("Author");
  dt.Columns.Add("version_date");
  dt.Columns.Add("pageurl");
  dt.Columns.Add("type");
  dt.Columns.Add("isparent");
  dt.Columns.Add("pagename");
  dt.Columns.Add("parentname");
  dt.Columns.Add("url");

  var mockRow = dt.NewRow();

  mockRow["pageHeader"] = "homepage";
  mockRow["pageText"] = "<p>home</p>";
  mockRow["templatename"] = "home";
  mockRow["pageTitleBar"] = "homepages";
  mockRow["metaDescription"] = "homepages";
  mockRow["pageStartCode"] = "homepages";
  mockRow["pageEndCode"] = "homepages";
  mockRow["templateStartCode"] = "homepages";
  mockRow["templateEndCode"] = "homepages";
  mockRow["Author"] = "someone";
  mockRow["version_date"] = "";
  mockRow["pageurl"] = "home";
  mockRow["type"] = "internal";
  mockRow["isparent"] = "true";
  mockRow["pagename"] = "homepage";
  mockRow["parentname"] = "root";
  mockRow["url"] = "homepage";

  dt.Rows.Add(mockRow);

  return dt;
}
</code>```

Title: Stubbing / mocking a database in .Net

Body:
You could mock your DataAccess class with Rhinomocks and return a fake datatable. So you can test the code that uses this DataTable.

var mockedDatatable= GetMockdt();

var mocks = new MockRepository();
var dal = mocks.StrictMock<DataAccess>();

using (mocks.Record())
{
  Expect.Call(dal.GetDataTableFromDatabase("", null)).Return(mockedDatatable).IgnoreArguments();
}

using (mocks.Playback())
{
  new SomeClass(dal);
}

UPDATE the mockdt message

private static DataTable GetMockdt()
{
  var dt = new DataTable();

  dt.Columns.Add("pageHeader");
  dt.Columns.Add("templatename");
  dt.Columns.Add("pageText");
  dt.Columns.Add("pageTitleBar");
  dt.Columns.Add("metaDescription");
  dt.Columns.Add("pageStartCode");
  dt.Columns.Add("pageEndCode");
  dt.Columns.Add("templateStartCode");
  dt.Columns.Add("templateEndCode");
  dt.Columns.Add("Author");
  dt.Columns.Add("version_date");
  dt.Columns.Add("pageurl");
  dt.Columns.Add("type");
  dt.Columns.Add("isparent");
  dt.Columns.Add("pagename");
  dt.Columns.Add("parentname");
  dt.Columns.Add("url");

  var mockRow = dt.NewRow();

  mockRow["pageHeader"] = "homepage";
  mockRow["pageText"] = "<p>home</p>";
  mockRow["templatename"] = "home";
  mockRow["pageTitleBar"] = "homepages";
  mockRow["metaDescription"] = "homepages";
  mockRow["pageStartCode"] = "homepages";
  mockRow["pageEndCode"] = "homepages";
  mockRow["templateStartCode"] = "homepages";
  mockRow["templateEndCode"] = "homepages";
  mockRow["Author"] = "someone";
  mockRow["version_date"] = "";
  mockRow["pageurl"] = "home";
  mockRow["type"] = "internal";
  mockRow["isparent"] = "true";
  mockRow["pagename"] = "homepage";
  mockRow["parentname"] = "root";
  mockRow["url"] = "homepage";

  dt.Rows.Add(mockRow);

  return dt;
}