问:
Performance of SUM Columns using CASE COUNT
I have a query that summarizes the total of a new buyer and returning buyer.

t_so_salesorder table looks like this

```<code>create_time |  code  | member_name | financial_status
2019-01-01    190001      Qwerty            3
2019-01-01    190002      Ytrewq            3
2019-01-01    190003      Poiuyt            1
2019-01-01    190004      Zxcvbn            3
</code>```

My query looks like this.

```<code>SELECT
    T1.YC
    , T1.MC
    , SUM(T1.NewBuyer)
    , SUM(T1.RetBuyer)
FROM
(SELECT
    YEAR(A.create_time) AS YC
    , DATE_FORMAT(A.create_time, '%M') AS MC
    , CASE
        WHEN COUNT(t1.create_time) = 1 THEN 1
        ELSE 0
    END AS NewBuyer
    , CASE
        WHEN COUNT(t1.create_time) > 1 THEN 1
        ELSE 0
    END AS RetBuyer
FROM
    db_bb_mall_trade1_prod.t_so_salesorder a
JOIN
    db_bb_mall_trade1_prod.t_so_salesorder t1 ON a.member_name = t1.member_name AND a.create_time >= t1.create_time and t1.financial_status = 3
WHERE YEAR(A.create_time) BETWEEN YEAR(CURDATE() - INTERVAL 1 YEAR) AND YEAR(CURDATE()) AND a.financial_status = 3
GROUP BY a.create_time, a.member_name, a.code) T1
GROUP BY T1.YC, T1.MC
ORDER BY T1.YC ASC, T1.MC ASC;
</code>```

and the output looks like this

```<code>YC   |    MC  | NewBuyer | RetBuyer
2019   January    300        400
2019   February   130        500
2019    March     210        110
.
.
.
</code>```

The output is exactly like I wanted but the problem is, my query is taking way too long to generate. It's taking about 2 minutes for only 14 rows. Can you suggesting a more simple and efficient query for me. Thank you.

EDIT: This is the explain result

```<code>id | select_type |  table  | type |         possible_keys      | key | key_len | ref |    rows    | Extra
1      PRIMARY    <derived2>  ALL               null             null   null     null  11720877169  Using temporary; Using filesort
2      DERIVED        t1      ALL  IDX_SALESORDERSUM_CREATETIME  null   null     null     108263    Using where; Using temporary; Using filesort
2      DERIVED        a       ALL  IDX_SALESORDERSUM_CREATETIME  null   null     null     108263    Range checked for each record (index map: 0x10)
</code>```

答:
Look at that 11720877169.  It is probably 108263*108263.  Smells like a "cross join", as if there is no ON clause, or it involves un-indexed columns.  Add this to t_so_salesorder

```<code>ADD INDEX(member_name)
</code>```

That will make the query run orders of magnitude faster.

But, you can still do better.  Let's change

```<code>            FROM  db_bb_mall_trade1_prod.t_so_salesorder a
            JOIN  db_bb_mall_trade1_prod.t_so_salesorder t1
                          ON a.member_name = t1.member_name
              AND  a.create_time >= t1.create_time
              and  t1.financial_status = 3
            WHERE  YEAR(A.create_time) BETWEEN YEAR(CURDATE() - INTERVAL 1 YEAR)
                                           AND YEAR(CURDATE())
              AND  a.financial_status = 3
</code>```

to

```<code>            FROM  db_bb_mall_trade1_prod.t_so_salesorder a
            JOIN  db_bb_mall_trade1_prod.t_so_salesorder t1
                   ON a.member_name = t1.member_name
                  AND a.financial_status = t1.financial_status
                  AND  a.create_time >= t1.create_time
            WHERE  A.create_time >= CONCAT(YEAR(CURDATE()), '-01-01')
              AND  A.create_time <= CONCAT(YEAR(CURDATE()), '-12-31')
              AND  a.financial_status = 3

ADD INDEX(financial_status, member_name, create_time)
</code>```

That will

Make the test on create_time "sargable".

Get rid of the bug with New Year's Day.  (BETWEEN is inclusive.)

Run faster than with the single-column INDEX previously mentioned.

Since you seem to be doing a "groupwise-max", there are even faster ways.  But I will let you digest these improvements first.

Also, I doubt if you need a subquery.  (Again, I would rather see you rewrite before tackling any further rewrites.)

Body:
I have a query that summarizes the total of a new buyer and returning buyer.

t_so_salesorder table looks like this

create_time |  code  | member_name | financial_status
2019-01-01    190001      Qwerty            3
2019-01-01    190002      Ytrewq            3
2019-01-01    190003      Poiuyt            1
2019-01-01    190004      Zxcvbn            3

My query looks like this.

SELECT
    T1.YC
    , T1.MC
    , SUM(T1.NewBuyer)
    , SUM(T1.RetBuyer)
FROM
(SELECT
    YEAR(A.create_time) AS YC
    , DATE_FORMAT(A.create_time, '%M') AS MC
    , CASE
        WHEN COUNT(t1.create_time) = 1 THEN 1
        ELSE 0
    END AS NewBuyer
    , CASE
        WHEN COUNT(t1.create_time) > 1 THEN 1
        ELSE 0
    END AS RetBuyer
FROM
    db_bb_mall_trade1_prod.t_so_salesorder a
JOIN
    db_bb_mall_trade1_prod.t_so_salesorder t1 ON a.member_name = t1.member_name AND a.create_time >= t1.create_time and t1.financial_status = 3
WHERE YEAR(A.create_time) BETWEEN YEAR(CURDATE() - INTERVAL 1 YEAR) AND YEAR(CURDATE()) AND a.financial_status = 3
GROUP BY a.create_time, a.member_name, a.code) T1
GROUP BY T1.YC, T1.MC
ORDER BY T1.YC ASC, T1.MC ASC;

and the output looks like this

YC   |    MC  | NewBuyer | RetBuyer
2019   January    300        400
2019   February   130        500
2019    March     210        110
.
.
.

The output is exactly like I wanted but the problem is, my query is taking way too long to generate. It's taking about 2 minutes for only 14 rows. Can you suggesting a more simple and efficient query for me. Thank you.

EDIT: This is the explain result

id | select_type |  table  | type |         possible_keys      | key | key_len | ref |    rows    | Extra
1      PRIMARY    <derived2>  ALL               null             null   null     null  11720877169  Using temporary; Using filesort
2      DERIVED        t1      ALL  IDX_SALESORDERSUM_CREATETIME  null   null     null     108263    Using where; Using temporary; Using filesort
2      DERIVED        a       ALL  IDX_SALESORDERSUM_CREATETIME  null   null     null     108263    Range checked for each record (index map: 0x10)

Body:
Look at that 11720877169.  It is probably 108263*108263.  Smells like a "cross join", as if there is no ON clause, or it involves un-indexed columns.  Add this to t_so_salesorder

ADD INDEX(member_name)

That will make the query run orders of magnitude faster.

But, you can still do better.  Let's change

            FROM  db_bb_mall_trade1_prod.t_so_salesorder a
            JOIN  db_bb_mall_trade1_prod.t_so_salesorder t1
                          ON a.member_name = t1.member_name
              AND  a.create_time >= t1.create_time
              and  t1.financial_status = 3
            WHERE  YEAR(A.create_time) BETWEEN YEAR(CURDATE() - INTERVAL 1 YEAR)
                                           AND YEAR(CURDATE())
              AND  a.financial_status = 3

to

            FROM  db_bb_mall_trade1_prod.t_so_salesorder a
            JOIN  db_bb_mall_trade1_prod.t_so_salesorder t1
                   ON a.member_name = t1.member_name
                  AND a.financial_status = t1.financial_status
                  AND  a.create_time >= t1.create_time
            WHERE  A.create_time >= CONCAT(YEAR(CURDATE()), '-01-01')
              AND  A.create_time <= CONCAT(YEAR(CURDATE()), '-12-31')
              AND  a.financial_status = 3

ADD INDEX(financial_status, member_name, create_time)

That will

Make the test on create_time "sargable".

Get rid of the bug with New Year's Day.  (BETWEEN is inclusive.)

Run faster than with the single-column INDEX previously mentioned.

Since you seem to be doing a "groupwise-max", there are even faster ways.  But I will let you digest these improvements first.

Also, I doubt if you need a subquery.  (Again, I would rather see you rewrite before tackling any further rewrites.)


来源: stackexchange

问:
Conflicting types for method
I'm getting this error that says "Conflicting type for method compress"

Here is my code:

```<code>int main(int argc, char **argv){

char* ptr = argv[1];
printf("%c\n", compress(ptr, 'j', 1));
}

const char* compress(char* ptr, char c, int i){
    return "Hi";
}
</code>```

Does anyone know what the issue is? Thanks so much for your help!

答:
You attempted to use compress before it was declared.  As a result, the default function declaration of int compress() was assumed.  That implicit declaration doesn't match the actual definition.

Move compress above main.  That way the function is defined before it is used.

Also, in your call to printf, you use the %c format specifier which expects a char but you pass in a char *.  Change the format specifier to %s to match so that the entire string is printed.

ContentLicense: CC BY-SA 4.0

Title: Conflicting types for method

Body:
I'm getting this error that says "Conflicting type for method compress"

Here is my code:

int main(int argc, char **argv){

char* ptr = argv[1];
printf("%c\n", compress(ptr, 'j', 1));
}

const char* compress(char* ptr, char c, int i){
    return "Hi";
}

Does anyone know what the issue is? Thanks so much for your help!


问:
Fix issue with regex expression getting first word in string in Java?
I am running a simple Java application and I want to grab the very first word in each string that I pass. So I did a str.split(" "); but I realized that my string that I have is very dynamic and it is constantly changing. So I pick up a , tagged on to the string which once I pass as a parameter crashes my code. So I am trying to find a particualry regex expression to just grab the very first words up until either a space, coma, period, or etc.

Example String:

```<code>WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')
</code>```

My goal would to be to just grab WebServer.

答:
If you want to find() first word which is NOT comma, whitespace, etc. you can use negated character class [^ ] and place inside all characters which you don't want. This will result in creating character class which will accept all other characters.

In your case you can use code like:

```<code>String yourText = "WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')";
Pattern p = Pattern.compile("[^,\\s]+");
Matcher m = p.matcher(yourText);
if (m.find()){
    String firstMatch = m.group();
    System.out.println(firstMatch);
}else{
    //handle case where there is no match found.
}
</code>```

Output: WebServer

NOTE: Using find() will also allow you to find word even when your text starts with characters you want to skip like when String yourText = ",,,foo,,"; result would be foo.

Body:
I am running a simple Java application and I want to grab the very first word in each string that I pass. So I did a str.split(" "); but I realized that my string that I have is very dynamic and it is constantly changing. So I pick up a , tagged on to the string which once I pass as a parameter crashes my code. So I am trying to find a particualry regex expression to just grab the very first words up until either a space, coma, period, or etc.

Example String:

WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')

My goal would to be to just grab WebServer.

Body:
If you want to find() first word which is NOT comma, whitespace, etc. you can use negated character class [^ ] and place inside all characters which you don't want. This will result in creating character class which will accept all other characters.

In your case you can use code like:

String yourText = "WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')";
Pattern p = Pattern.compile("[^,\\s]+");
Matcher m = p.matcher(yourText);
if (m.find()){
    String firstMatch = m.group();
    System.out.println(firstMatch);
}else{
    //handle case where there is no match found.
}

Output: WebServer

NOTE: Using find() will also allow you to find word even when your text starts with characters you want to skip like when String yourText = ",,,foo,,"; result would be foo.


问:
copy 'has_many' objects with one SQL INSERT
I have the following (this has been simplified to make the question at
hand more obvious):

```<code>user model has_many favorites
favorite model belongs_to user
</code>```

After a new user is created, I want to copy all the favorites from an
existing user to the new user. Right now I have the following code:

```<code># bob is the existing user and sam is the new user
bob.favorites.each do | f |
  u = Favorite.new(f.attributes)
  u.user_id = sam.user_id
  u.save!
end
</code>```

This creates an SQL INSERT for every favorite that bob has.

I know SQL could do this in one command with something like:

```<code>INSERT INTO favorites SELECT url, sam.user_id AS user_id FROM
favorites WHERE user_id = bob.user_id
</code>```

Does ActiveRecord have something in place for me to do this? I would
be nice to keep the code in Ruby rather than SQL.

Thanks in advance.

答:
A gem called ar-extensions supports INSERT SELECT SQL satements.

```<code>Favorite.insert_select(
  :from => :favorites,
  :conditions => ['favorites.user_id = ?', bob.user_id],
  :select => ['favorites.url, ?', sam.user_id],
  :into => [:url, :user_id]
)
</code>```

I'm not 100% sure this will work exactly how it is but it should be possible if you dig into the documentation.

ContentLicense: CC BY-SA 3.0

Body:
I have the following (this has been simplified to make the question at
hand more obvious):

user model has_many favorites
favorite model belongs_to user

After a new user is created, I want to copy all the favorites from an
existing user to the new user. Right now I have the following code:

# bob is the existing user and sam is the new user
bob.favorites.each do | f |
  u = Favorite.new(f.attributes)
  u.user_id = sam.user_id
  u.save!
end

This creates an SQL INSERT for every favorite that bob has.

I know SQL could do this in one command with something like:

INSERT INTO favorites SELECT url, sam.user_id AS user_id FROM
favorites WHERE user_id = bob.user_id

Does ActiveRecord have something in place for me to do this? I would
be nice to keep the code in Ruby rather than SQL.

Thanks in advance.

Body:
A gem called ar-extensions supports INSERT SELECT SQL satements.

Favorite.insert_select(
  :from => :favorites,
  :conditions => ['favorites.user_id = ?', bob.user_id],
  :select => ['favorites.url, ?', sam.user_id],
  :into => [:url, :user_id]
)

I'm not 100% sure this will work exactly how it is but it should be possible if you dig into the documentation.


问:
Solving a simple system of differential equations
How would I numerically solve for the following simple system of differential equations using Octave?

Note:

I use the qualifier "simple" as, from my understanding, the system is
first order and is not coupled.

I have tried every
method and script online to try solve    this including here,
here and here. In all options, I    either get a hanging,
non-responsive Octave, a prompt stating    "repeated convergence
failures", an error with recommendation that    I manually adjust
the initial and maximum step size (which I did try    and do, to no
avail), or something that initially seems like a solution on account of no errors but plotting the solution shows a blank graph

Where Octave provided for equivalent Matlab routines, I tried the various routines ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb, ode15i and of course, Octaves own lsode command, all giving the same errors described above.

答:
Let's first replicate the vanilla solution

```<code>% z = [x,y]
f = @(t,z) [ z(1).^2+t; z(1).*z(2)-2 ];
z0 = [ 2; 1];

[ T, Z ] = ode45(f, [0, 10], z0);

plot(T,Z); legend(["x";"y"]);
</code>```

The integrator fails as reported with the warning

warning:  Solving was not successful.  The iterative integration loop exited at time t = 0.494898 before the endpoint at tend = 10.000000 was reached.  This may happen if the stepsize becomes too small.  Try to reduce the value of 'InitialStep' and/or 'MaxStep' with the command 'odeset'.

Repeating the integration up to shortly before the critical time

```<code>opt = odeset('MaxStep',0.01);
[ T, Z ] = ode45(f, [0, 0.49], z0, opt);
clf; plot(T,Z); legend(["x";"y"]);
</code>```

results in the graph

where one can see that the quadratic term in the first equation leads to run-away growth. For some reason the solver does only recognize the ever reducing step size, but not the run-away values of the solution.

Indeed the first is a Riccati equation which are known to have poles at finite times. Using the typical parametrization x(t)=-u'(t)/u(t) has by the product/quotient rule the derivative

```<code>x' = -u''(t)/u(t) - u'(t)* (-u'(t)/u(t)^2) = -u''(t)/u(t) + x(t)^2
</code>```

which then results in the ODE for u

```<code>u''(t)+t*u(t)=0, u(0)=-1, u'(0)=x(0)=2,
</code>```

which is an Airy equation with the oscillating branch for t>0. The first root of u is a pole for x, there is no way to extend the solution beyond this point.

```<code>g=@(t,u) [u(2); -t.*u(1)]
u0 = [ 1; -2];

function [val,term, dir] = event(t,u)
   val = u(1);
   term = 0;
   dir = 0;
end
opt = odeset('MaxStep',0.1, 'Events', @(t,u) event(t,u));
[T,U,Te,Ue,Ie] = ode45(g,[0,4],u0,opt);
disp(Te)
clf; plot(T,U); legend(["u";"u'"]);
</code>```

which lists the zeros of u as 0.4949319379979706, 2.886092605590324, again confirming the reason for the warning, and gives the plot

Body:
Let's first replicate the vanilla solution

% z = [x,y]
f = @(t,z) [ z(1).^2+t; z(1).*z(2)-2 ];
z0 = [ 2; 1];

[ T, Z ] = ode45(f, [0, 10], z0);

plot(T,Z); legend(["x";"y"]);

The integrator fails as reported with the warning

warning:  Solving was not successful.  The iterative integration loop exited at time t = 0.494898 before the endpoint at tend = 10.000000 was reached.  This may happen if the stepsize becomes too small.  Try to reduce the value of 'InitialStep' and/or 'MaxStep' with the command 'odeset'.

Repeating the integration up to shortly before the critical time

opt = odeset('MaxStep',0.01);
[ T, Z ] = ode45(f, [0, 0.49], z0, opt);
clf; plot(T,Z); legend(["x";"y"]);

results in the graph

where one can see that the quadratic term in the first equation leads to run-away growth. For some reason the solver does only recognize the ever reducing step size, but not the run-away values of the solution.

Indeed the first is a Riccati equation which are known to have poles at finite times. Using the typical parametrization x(t)=-u'(t)/u(t) has by the product/quotient rule the derivative

x' = -u''(t)/u(t) - u'(t)* (-u'(t)/u(t)^2) = -u''(t)/u(t) + x(t)^2

which then results in the ODE for u

u''(t)+t*u(t)=0, u(0)=-1, u'(0)=x(0)=2,

which is an Airy equation with the oscillating branch for t>0. The first root of u is a pole for x, there is no way to extend the solution beyond this point.

g=@(t,u) [u(2); -t.*u(1)]
u0 = [ 1; -2];

function [val,term, dir] = event(t,u)
   val = u(1);
   term = 0;
   dir = 0;
end
opt = odeset('MaxStep',0.1, 'Events', @(t,u) event(t,u));
[T,U,Te,Ue,Ie] = ode45(g,[0,4],u0,opt);
disp(Te)
clf; plot(T,U); legend(["u";"u'"]);

which lists the zeros of u as 0.4949319379979706, 2.886092605590324, again confirming the reason for the warning, and gives the plot


问:
React dropdown issue - how to stop dynamically created dropdowns from all updating at once
I am dynamically rendering a large list of cards using React hooks, and each component has its drop-down list. If I select one option, which updates the component state, every drop-down update to the same value. I have tried implementing select an option of React, and separately React-dropdown, and none of my approaches work. I recognize the problem is that when any dropdown is updated, they all refer to the same value in state and if I comment out the state update the dropdowns work.

I just don’t capture the state update. I am unsure what is the best way to capture these selection(s) while the user picks between the dropdowns and then showing the rendered selection.

A lot of the approaches I have seen don’t address having multiple dynamically created dropdowns on one page, so if there are any thoughts on how to resolve the issue, that would be helpful. Below is part of the code:

<select onChange(event=> selectedDropdownItem(selection)
  value={event.target.value}
  >
  dropdownList.map(name =>
  <option key={name.id} value={name.id} label={name.name} />
</select>
```

<pre class="lang-js prettyprint-override"><code>const [header, setHeader] = useState({ name: “select name”, id: null })

selectedDropdownItem = selection => {
  setHeader({
    name: selection.name,
    id: selection.id
  })
}
</code>```

答:
As i am not much clear about your question for the multiple selection in single component. I just created one which will do the dynamic dropdown based on that, and update the name based on selection using useState. Whenever you do the selection , it will come to parent component and do the update and return the value to the child component.
Hope i explained as you expected.

Here is the working code link.

If you have any queries, give a comment :)

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

    const DropDownCard = ({name, list, selectedValue, onChange}) => {

      const onSelectChange = event => {
        const { value } = event.target;
        const { name } = list.find(val => val.id == value);
        onChange({id: value, name});
      };

        return (
          <div>
            <h1>Card {name}</h1>
            <select onChange={onSelectChange} value={selectedValue}>
             {
               list.map(name => <option
                key={name.id}
                value={name.id}
                label={name.name}
              />)
             }

            </select>
          </div>
        )
    }

    const cardList = [
      {name:'', selectedValue: null},
      {name:'', selectedValue: null},
      {name:'', selectedValue: null},
    ];

    const Home = () => {
      const [hea, setHea] = useState(cardList);
      const list = [
        {name: "select name", id: ''},
        {name: "Name 1", id: 1},
        {name: "Name 2", id: 2}
      ];

      const onCardNameSelect = (info, index) => {
        setHea(prevState => {
          const {id, name} = info;
          prevState[index].selectedValue = id;
          prevState[index].name = name;
          return [...prevState];
        });
      };

      return(
        <>
          <div>Hello</div>
          {hea.map((val,i) => <DropDownCard  key={"dropDown"+Math.random()}
            name={val.name}
            selectedValue={val.selectedValue}
            list = {list}
            onChange = {event => onCardNameSelect(event, i)}
          />)}
        </>

      )
    };
    export default Home;
</code>```

Body:
I am dynamically rendering a large list of cards using React hooks, and each component has its drop-down list. If I select one option, which updates the component state, every drop-down update to the same value. I have tried implementing select an option of React, and separately React-dropdown, and none of my approaches work. I recognize the problem is that when any dropdown is updated, they all refer to the same value in state and if I comment out the state update the dropdowns work.

I just don’t capture the state update. I am unsure what is the best way to capture these selection(s) while the user picks between the dropdowns and then showing the rendered selection.

A lot of the approaches I have seen don’t address having multiple dynamically created dropdowns on one page, so if there are any thoughts on how to resolve the issue, that would be helpful. Below is part of the code:

<select onChange(event=> selectedDropdownItem(selection)
  value={event.target.value}
  >
  dropdownList.map(name =>
  <option key={name.id} value={name.id} label={name.name} />
</select>

const [header, setHeader] = useState({ name: “select name”, id: null })

selectedDropdownItem = selection => {
  setHeader({
    name: selection.name,
    id: selection.id
  })
}

Body:
As i am not much clear about your question for the multiple selection in single component. I just created one which will do the dynamic dropdown based on that, and update the name based on selection using useState. Whenever you do the selection , it will come to parent component and do the update and return the value to the child component.
Hope i explained as you expected.

Here is the working code link.

If you have any queries, give a comment :)

    import React, {useState} from 'react';

    const DropDownCard = ({name, list, selectedValue, onChange}) => {

      const onSelectChange = event => {
        const { value } = event.target;
        const { name } = list.find(val => val.id == value);
        onChange({id: value, name});
      };

        return (
          <div>
            <h1>Card {name}</h1>
            <select onChange={onSelectChange} value={selectedValue}>
             {
               list.map(name => <option
                key={name.id}
                value={name.id}
                label={name.name}
              />)
             }

            </select>
          </div>
        )
    }

    const cardList = [
      {name:'', selectedValue: null},
      {name:'', selectedValue: null},
      {name:'', selectedValue: null},
    ];

    const Home = () => {
      const [hea, setHea] = useState(cardList);
      const list = [
        {name: "select name", id: ''},
        {name: "Name 1", id: 1},
        {name: "Name 2", id: 2}
      ];

      const onCardNameSelect = (info, index) => {
        setHea(prevState => {
          const {id, name} = info;
          prevState[index].selectedValue = id;
          prevState[index].name = name;
          return [...prevState];
        });
      };

      return(
        <>
          <div>Hello</div>
          {hea.map((val,i) => <DropDownCard  key={"dropDown"+Math.random()}
            name={val.name}
            selectedValue={val.selectedValue}
            list = {list}
            onChange = {event => onCardNameSelect(event, i)}
          />)}
        </>

      )
    };
    export default Home;


问:
Is there any way to make this code simpler? I feel like there should be but I am very new to Python
```<code>def life():
    print("You wake up")
    eat = input("are you hungry? Please Enter y or n.")
    if eat.upper() == "Y":
        print("I predict you will eat breakfast")
    elif eat.upper() == "N":
        print("I predict you will skip breakfast")
    while eat.upper() not in ("Y","N"):
        print("input not accepted")
        eat = input("are you hungry? Please Enter y or n.")
        if eat.upper() == "Y":
            print("I predict you will eat breakfast")
        elif eat.upper() == "N":
            print("I predict you will skip breakfast")
    print("You leave the house")
    day = input("is it cloudy? please enter y or n")
    if day.upper() == "Y":
        print("I predict you will bring an umbrella")
    elif day.upper() == "N":
        print("I predict you will wear sunglasses")
    while day.upper() not in ("Y","N"):
        print("input not accepted")
        day = input("is it cloudy? please enter y or n")
        if day.upper() == "Y":
            print("I predict you will bring an umbrella")
        elif day.upper() == "N":
            print("I predict you will wear sunglasses")
    print("You go out for dinner")
    food = input("Do you want meat? please enter y or n")
    if food.upper() == "Y":
        print("I predict you will order steak!")
    elif food.upper() == "N":
        pass
    while food.upper() not in ("Y", "N"):
        print("input not accepted")
        food = input("Do you want meat? please enter y or n")
        if food.upper() == "Y":
            print("I predict you will order steak!")
        elif food.upper() == "N":
            pass
    pasta = input("Do you want Pasta: please enter y or n")
    if pasta.upper() == "Y":
        print("I predict you will order spaghetti and meatballs!!")
    elif pasta.upper() == "N":
        print("I predict you will order salad.")
    while pasta.upper() not in ("Y", "N"):
        print("input not accepted")
        pasta = input("Do you want Pasta: please enter y or n")
        if pasta.upper() == "Y":
            print("I predict you will order spaghetti and meatballs!!")
        elif pasta.upper() == "N":
            print("I predict you will order salad.")
life()
</code>```

<p>I feel like it is unnecessary to repeat multiple lines of code in the while statement. Is there any way to make the while statement go to a previous line of code and run it from there instead of re-entering the same code back into the while statement. The code seems to run fine but I would like it to be less clunky if possible.
Thanks! </p>

答:
There are several modifications I would suggest.

Use inline conditional statements <expression1> if <condition> else <expression2>

Use string formatting "Today is {}".format(date)

So you can write

s = "eat" if eat.upper() == "Y" else "skip" if eat.upper() == "N" else ""
print("I predict you will {} breakfast".format(s))
```

Be sure to check that eat.upper() is "Y" or "N" first, or the code would fail.

Since your code for eat and day are similar, you could also use a function to simplify your code.

Body:
def life():
    print("You wake up")
    eat = input("are you hungry? Please Enter y or n.")
    if eat.upper() == "Y":
        print("I predict you will eat breakfast")
    elif eat.upper() == "N":
        print("I predict you will skip breakfast")
    while eat.upper() not in ("Y","N"):
        print("input not accepted")
        eat = input("are you hungry? Please Enter y or n.")
        if eat.upper() == "Y":
            print("I predict you will eat breakfast")
        elif eat.upper() == "N":
            print("I predict you will skip breakfast")
    print("You leave the house")
    day = input("is it cloudy? please enter y or n")
    if day.upper() == "Y":
        print("I predict you will bring an umbrella")
    elif day.upper() == "N":
        print("I predict you will wear sunglasses")
    while day.upper() not in ("Y","N"):
        print("input not accepted")
        day = input("is it cloudy? please enter y or n")
        if day.upper() == "Y":
            print("I predict you will bring an umbrella")
        elif day.upper() == "N":
            print("I predict you will wear sunglasses")
    print("You go out for dinner")
    food = input("Do you want meat? please enter y or n")
    if food.upper() == "Y":
        print("I predict you will order steak!")
    elif food.upper() == "N":
        pass
    while food.upper() not in ("Y", "N"):
        print("input not accepted")
        food = input("Do you want meat? please enter y or n")
        if food.upper() == "Y":
            print("I predict you will order steak!")
        elif food.upper() == "N":
            pass
    pasta = input("Do you want Pasta: please enter y or n")
    if pasta.upper() == "Y":
        print("I predict you will order spaghetti and meatballs!!")
    elif pasta.upper() == "N":
        print("I predict you will order salad.")
    while pasta.upper() not in ("Y", "N"):
        print("input not accepted")
        pasta = input("Do you want Pasta: please enter y or n")
        if pasta.upper() == "Y":
            print("I predict you will order spaghetti and meatballs!!")
        elif pasta.upper() == "N":
            print("I predict you will order salad.")
life()

I feel like it is unnecessary to repeat multiple lines of code in the while statement. Is there any way to make the while statement go to a previous line of code and run it from there instead of re-entering the same code back into the while statement. The code seems to run fine but I would like it to be less clunky if possible.
Thanks!

Body:
There are several modifications I would suggest.

Use inline conditional statements <expression1> if <condition> else <expression2>

Use string formatting "Today is {}".format(date)

So you can write

s = "eat" if eat.upper() == "Y" else "skip" if eat.upper() == "N" else ""
print("I predict you will {} breakfast".format(s))

Be sure to check that eat.upper() is "Y" or "N" first, or the code would fail.

Since your code for eat and day are similar, you could also use a function to simplify your code.


问:
Finding ALL matches after a certain character(s)
I'd like to think I'm ok at writing RegEx's, but there's one thing I can't seem to crack:

I want to start looking for multiple, identical matches after a certain set of characters and capture all of them. Here's an example string:

```<code>Dialogue: 0,0:05:47.99,0:05:50.74,JoJo-main,Koichi,0000,0000,0000,,What are you doing, Giorno Giovanna?!
</code>```

For this example, I want to start looking for matches after ,,. I want to find all instances of Gio i.e.

```<code>Dialogue: 0,0:05:47.99,0:05:50.74,JoJo-main,Koichi,0000,0000,0000,,What are you doing, {Gio}rno {Gio}vanna?!
</code>```

I've tried first using non-capturing groups like /(?:,,.*?)(Gio)/g then lookbehinds like /(?<=,,.*?)(Gio)/g, /(?<=,,)(?:.*?)(Gio)/g and /(?<=,,)((?:.*?)(Gio))+/g to avoid consuming the ,,

None of these give me the behaviour I want, as I want individual matches as if I just used Gio, but without the chance of accidentally capturing stuff before the ,,

I could, of course, run one RegEx to find the ,, then feed that position to another RegEx to look for Gios after that point.
However I have thousands of lines like these to parse and thousands of words to look for on each line (I separate them with |), so I'd ideally like to do it with one RegEx and without a loop.

答:
You may consider the following option for the .NET or modern ECMAScript 2018+ compliant JS environments:

```<code>/(?<=,,.*?)Gio/g
</code>```

See the regex demo.

The (?<=,,.*?)Gio pattern matches Gio when it is preceded with ,, and any 0+ chars other  than line break chars, as few as possible.

The following variant will work with PCRE/Onigmo regex engines:

```<code>/(?:\G(?!^)|,,).*?\KGio/
</code>```

See another regex demo. Here, (?:\G(?!^)|,,) matches either the end of the previous successful match or ,, and then .*? matches and consumes any 0+ chars other  than line break chars, as few as possible, then \K will reset the match buffer and Gio will land right there.

Body:
I'd like to think I'm ok at writing RegEx's, but there's one thing I can't seem to crack:

I want to start looking for multiple, identical matches after a certain set of characters and capture all of them. Here's an example string:

Dialogue: 0,0:05:47.99,0:05:50.74,JoJo-main,Koichi,0000,0000,0000,,What are you doing, Giorno Giovanna?!

For this example, I want to start looking for matches after ,,. I want to find all instances of Gio i.e.

Dialogue: 0,0:05:47.99,0:05:50.74,JoJo-main,Koichi,0000,0000,0000,,What are you doing, {Gio}rno {Gio}vanna?!

I've tried first using non-capturing groups like /(?:,,.*?)(Gio)/g then lookbehinds like /(?<=,,.*?)(Gio)/g, /(?<=,,)(?:.*?)(Gio)/g and /(?<=,,)((?:.*?)(Gio))+/g to avoid consuming the ,,

None of these give me the behaviour I want, as I want individual matches as if I just used Gio, but without the chance of accidentally capturing stuff before the ,,

I could, of course, run one RegEx to find the ,, then feed that position to another RegEx to look for Gios after that point.
However I have thousands of lines like these to parse and thousands of words to look for on each line (I separate them with |), so I'd ideally like to do it with one RegEx and without a loop.

Body:
You may consider the following option for the .NET or modern ECMAScript 2018+ compliant JS environments:

/(?<=,,.*?)Gio/g

See the regex demo.

The (?<=,,.*?)Gio pattern matches Gio when it is preceded with ,, and any 0+ chars other  than line break chars, as few as possible.

The following variant will work with PCRE/Onigmo regex engines:

/(?:\G(?!^)|,,).*?\KGio/

See another regex demo. Here, (?:\G(?!^)|,,) matches either the end of the previous successful match or ,, and then .*? matches and consumes any 0+ chars other  than line break chars, as few as possible, then \K will reset the match buffer and Gio will land right there.


问:
How to implement a neural network to play an endless runner game?
After learning the basics of neural networks I want to create a small but an unique project (something more difficult than handwritten digits etc).
I chose to implement an endless runner game, record my moves and train a neural network with the collected data.

Game looks like this:

Player can move to right and to left (arrows) , the goal is to avoid asteroids.
When player presses left arrow, coordinates of all asteroids, player position and left move are recorded.
When player presses right arrow, the same thing happens but "move" is set to right.
I had a problem with figuring out how to record no movement so I coded it to record no movement (straight) when i press up arrow. So when I wasn't moving, i was pressing up arrow (at a medium pace)

There can be maximum of 20 asteroids but I collected data for a smaller data set, to see how it works.

Collected data looks like this:

As you can see in the first row, there are 42 columns.
20 columns for x-coordinates of all asteroids on the board.
20 columns for y-coordinates of all asteroids on the board.
1 column for x-coordinate of a player
1 column for a move (0 - left; 1 - right; 2 - straight, no movement)

I collected 4042 samples:
1140 left
1122 right
1780 straight

As I said before, I prepared it to handle 20 asteroids but I collected data for a only of few of them so the rest of the columns are filled with zeros.

I used tensorflow to train a neural network

```<code>data = pd.read_csv('collected_data.csv')
y = data['move']
x = data.drop('move', axis=1)
x_train = x.to_numpy()
y_train = y.to_numpy()

x_train = tf.keras.utils.normalize(x_train, axis=1)

model = tf.keras.Sequential([
    tf.keras.layers.Dense(41,activation='hard_sigmoid',input_shape=x_train[0].shape),
    tf.keras.layers.Dense(41, activation='hard_sigmoid'),
    tf.keras.layers.Dense(41, activation='hard_sigmoid'),
    tf.keras.layers.Dense(3,activation='hard_sigmoid')
])
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10)

model.save('model.h5')
</code>```

Result:

My model doesn't fit at all. When i run the game, spaceship is not moving at all, always chosing to go straight. I tried different neural network architectures, more layers, fewer layers etc. but it almost doesn't change the result. Do I have not enough data ? Data is too complex? Did I choose the wrong model?
I will be grateful for any advice. Thanks!

答: Ok, thank you. I will try to do this with reinforcment learning. </p>

Body:
After learning the basics of neural networks I want to create a small but an unique project (something more difficult than handwritten digits etc).
I chose to implement an endless runner game, record my moves and train a neural network with the collected data.

Game looks like this:

Player can move to right and to left (arrows) , the goal is to avoid asteroids.
When player presses left arrow, coordinates of all asteroids, player position and left move are recorded.
When player presses right arrow, the same thing happens but "move" is set to right.
I had a problem with figuring out how to record no movement so I coded it to record no movement (straight) when i press up arrow. So when I wasn't moving, i was pressing up arrow (at a medium pace)

There can be maximum of 20 asteroids but I collected data for a smaller data set, to see how it works.

Collected data looks like this:

As you can see in the first row, there are 42 columns.
20 columns for x-coordinates of all asteroids on the board.
20 columns for y-coordinates of all asteroids on the board.
1 column for x-coordinate of a player
1 column for a move (0 - left; 1 - right; 2 - straight, no movement)

I collected 4042 samples:
1140 left
1122 right
1780 straight

As I said before, I prepared it to handle 20 asteroids but I collected data for a only of few of them so the rest of the columns are filled with zeros.

I used tensorflow to train a neural network

data = pd.read_csv('collected_data.csv')
y = data['move']
x = data.drop('move', axis=1)
x_train = x.to_numpy()
y_train = y.to_numpy()

x_train = tf.keras.utils.normalize(x_train, axis=1)

model = tf.keras.Sequential([
    tf.keras.layers.Dense(41,activation='hard_sigmoid',input_shape=x_train[0].shape),
    tf.keras.layers.Dense(41, activation='hard_sigmoid'),
    tf.keras.layers.Dense(41, activation='hard_sigmoid'),
    tf.keras.layers.Dense(3,activation='hard_sigmoid')
])
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10)

model.save('model.h5')

Result:

My model doesn't fit at all. When i run the game, spaceship is not moving at all, always chosing to go straight. I tried different neural network architectures, more layers, fewer layers etc. but it almost doesn't change the result. Do I have not enough data ? Data is too complex? Did I choose the wrong model?
I will be grateful for any advice. Thanks!


问:
Using Data Annotation Validators with the Entity Framework
I am working on WPF application which uses Entity Framework alongwith POCO classes. I would like to use data annotations with POCO classes for Client side validations in UI (WPF). Since, I can't modify the POCO classes (it will be regenerated after updating the entity model), therefore, I have implemented the data annotations using partial class as per approach mentioned in the article: http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs under section "Using Data Annotation Validators with the Entity Framework". Somehow this approach is not working in my case. Can anybody suggest something as to how can I use data annotation with Entity Framework?</p>

答: There is no need to registered the Data Annotations. Just followed the steps mentioned in the article & its working now.</p>

ContentLicense: CC BY-SA 2.5


问:
Javascript node-fetch usage
I can get the data by request from this code.

```<code>let request = require('request');
let options = {
   'method': 'POST',
   'url': 'https://example.com/api',
   'headers': {
       'Content-Type': 'application/x-www-form-urlencoded'
   },
   form: {
       'client_id': '12345678',
       'client_secret': 'abcdefg'
   }
};
request(options, function (error, response) {
   if (error) throw new Error(error);
   console.log(response.body);
});
</code>```

However, I got '404.00.001' when I use "fetch" to access the same API. Is there any thing wrong in this code?

```<code>const fetch = require("node-fetch");

const url = "https://example.com/api";

var headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

var data = JSON.stringify( {
  'client_id': '12345678',
  'client_secret': 'abcdefg'
});

fetch(url, {method: 'POST', headers: headers, body: data})
  .then(response => response.json())
  .then((resp) => {
     console.log(resp);
  })
  .catch(error => console.error('Unable to fetch token.', error));
</code>```

答:
'Content-Type': 'application/x-www-form-urlencoded' does not say JSON so why do you have var data = JSON.stringify?

The documentation tells you how to encode data as form parameters.

```<code>const { URLSearchParams } = require('url');

const params = new URLSearchParams();
params.append('a', 1);
</code>```

Title: Javascript node-fetch usage

Body:
I can get the data by request from this code.

let request = require('request');
let options = {
   'method': 'POST',
   'url': 'https://example.com/api',
   'headers': {
       'Content-Type': 'application/x-www-form-urlencoded'
   },
   form: {
       'client_id': '12345678',
       'client_secret': 'abcdefg'
   }
};
request(options, function (error, response) {
   if (error) throw new Error(error);
   console.log(response.body);
});

However, I got '404.00.001' when I use "fetch" to access the same API. Is there any thing wrong in this code?

const fetch = require("node-fetch");

const url = "https://example.com/api";

var headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

var data = JSON.stringify( {
  'client_id': '12345678',
  'client_secret': 'abcdefg'
});

fetch(url, {method: 'POST', headers: headers, body: data})
  .then(response => response.json())
  .then((resp) => {
     console.log(resp);
  })
  .catch(error => console.error('Unable to fetch token.', error));

Body:
'Content-Type': 'application/x-www-form-urlencoded' does not say JSON so why do you have var data = JSON.stringify?

The documentation tells you how to encode data as form parameters.

const { URLSearchParams } = require('url');

const params = new URLSearchParams();
params.append('a', 1);


问:
The type or namespace name 'BundleCollection' could not be found (are you missing a using directive or an assembly reference?)
So, I have a MVC 4 project in C# and I am using Visual Studio For Web 2012 Express.

I cannot compile the projecto due to the error:
The type or namespace name 'BundleCollection' could not be found (are you missing a using directive or an assembly reference?)

Normally, this would mean that a library is missing. Thus after making a quick search on the internet I used NuGet to install Microsoft.AspNet.Web.Optimization, but that still did not work.

What makes this intriguing to me is that BundleCollections should be known to the application by deafult. I can only imagine that I have added a dependency that messed everything up, but I really can't know for sure.

How can I fix this problem? What am I missing here?

Code:

```<code>using System;
using System.Web;
using System.Web.Optimization;

namespace Dockis
{

    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            IItemTransform cssFixer = new CssRewriteUrlTransform();

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

           //...
        }
    }
}
</code>```

EDIT

After checking my references folder I tried running the command Install-Package System.Web.Optimization, however I cannot install this package. I get the following error:

```<code>Install-Package : One or more errors occurred.
At line:1 char:16
+ Install-Package <<<<  System.Web.Optimization
    + CategoryInfo          : NotSpecified: (:) [Install-Package], AggregateException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
</code>```

What is odd, is the fact that running Install-Package System.Web.Optimization.Less works, and fixes some depencie problems, but not all of them. Thus I believe I really need the first command to work.

What am I doing wrong?

答:
This is just an addition to the solutions already identified for this issue. In my case, none of the above solutions worked. In the end, I had to manually locate the DLL in my .NET folders on my local drive and add the System.Web.Optimization.dll to my project manually.

Visual Studio 2017 indicated sucessful installation of the Microsoft.AspNet.Web.Optimization.1.1.3 package, however, did not allow the DLL to be added to the project. So even though the Nuget install was successful, the app would not compile. Manually adding the DLL to the project fixed it.

Body:
So, I have a MVC 4 project in C# and I am using Visual Studio For Web 2012 Express.

I cannot compile the projecto due to the error:
The type or namespace name 'BundleCollection' could not be found (are you missing a using directive or an assembly reference?)

Normally, this would mean that a library is missing. Thus after making a quick search on the internet I used NuGet to install Microsoft.AspNet.Web.Optimization, but that still did not work.

What makes this intriguing to me is that BundleCollections should be known to the application by deafult. I can only imagine that I have added a dependency that messed everything up, but I really can't know for sure.

How can I fix this problem? What am I missing here?

Code:

using System;
using System.Web;
using System.Web.Optimization;

namespace Dockis
{

    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            IItemTransform cssFixer = new CssRewriteUrlTransform();

            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

           //...
        }
    }
}

EDIT

After checking my references folder I tried running the command Install-Package System.Web.Optimization, however I cannot install this package. I get the following error:

Install-Package : One or more errors occurred.
At line:1 char:16
+ Install-Package <<<<  System.Web.Optimization
    + CategoryInfo          : NotSpecified: (:) [Install-Package], AggregateException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

What is odd, is the fact that running Install-Package System.Web.Optimization.Less works, and fixes some depencie problems, but not all of them. Thus I believe I really need the first command to work.

What am I doing wrong?


问:
Return a requests.Response object from Flask
I'm trying to build a simple proxy using Flask and requests. The code is as follows:

```<code>@app.route('/es/<string:index>/<string:type>/<string:id>',
           methods=['GET', 'POST', 'PUT']):
def es(index, type, id):
    elasticsearch = find_out_where_elasticsearch_lives()
    # also handle some authentication
    url = '%s%s%s%s' % (elasticsearch, index, type, id)

    esreq = requests.Request(method=request.method, url=url,
                             headers=request.headers, data=request.data)
    resp = requests.Session().send(esreq.prepare())
    return resp.text
</code>```

This works, except that it loses the status code from Elasticsearch. I tried returning resp (a requests.models.Response) directly, but this fails with

```<code>TypeError: 'Response' object is not callable
</code>```

Is there another, simple, way to return a requests.models.Response from Flask?

答:
My use case is to call another API in my own Flask API. I'm just propagating unsuccessful requests.get calls through my Flask response. Here's my successful approach:

headers = {
    'Authorization': 'Bearer Muh Token'
}
try:
    response = requests.get(
        '{domain}/users/{id}'\
            .format(domain=USERS_API_URL, id=hit['id']),
        headers=headers)
    response.raise_for_status()
except HTTPError as err:
    logging.error(err)
    flask.abort(flask.Response(response=response.content, status=response.status_code, headers=response.headers.items()))
```

Body:
I'm trying to build a simple proxy using Flask and requests. The code is as follows:

@app.route('/es/<string:index>/<string:type>/<string:id>',
           methods=['GET', 'POST', 'PUT']):
def es(index, type, id):
    elasticsearch = find_out_where_elasticsearch_lives()
    # also handle some authentication
    url = '%s%s%s%s' % (elasticsearch, index, type, id)

    esreq = requests.Request(method=request.method, url=url,
                             headers=request.headers, data=request.data)
    resp = requests.Session().send(esreq.prepare())
    return resp.text

This works, except that it loses the status code from Elasticsearch. I tried returning resp (a requests.models.Response) directly, but this fails with

TypeError: 'Response' object is not callable

Is there another, simple, way to return a requests.models.Response from Flask?


问:
Whats the best/simplest way to protect API keys in Xcode?
I am working on a simple iOS app in Swift that uses an API that I pay for. I do not have a ton of resources and have yet to find a simple/up to date solution to this issue. I want to protect my API key and not put the key directly in my code where I make requests (I have heard this is best practice).
What would be the simplest way to protect my API key from someone taking apart my code and using it.

I've heard something about using Keychain but I'm unsure if this is the best route.

```<code>class APIService {

    static let shared = APIService()
    private let token = "(my token goes here)"

    //...various API request functions
}
</code>```

答:
NSUserDefaults:
NSUserDefaults is simple and effective for saving small datas like NSNumbers or NSStrings, or even saving remember me option for saving ur state of UserName. NSUserDefaults is no way stored securely as it's easily gets Hacked.

KeyChain:
Best place to save tokens, api keys. Find the below apple documentation which describes more,

**“An encrypted container that securely stores small chunks of data on behalf of apps and secure services.” "Simply a database stored in the file system.”**

KeyChain Documentation

And here is the example of Swift Version with simple way to store and retrieve data using KeyChain

https://stackoverflow.com/a/37539998/1244403

Body:
I am working on a simple iOS app in Swift that uses an API that I pay for. I do not have a ton of resources and have yet to find a simple/up to date solution to this issue. I want to protect my API key and not put the key directly in my code where I make requests (I have heard this is best practice).
What would be the simplest way to protect my API key from someone taking apart my code and using it.

I've heard something about using Keychain but I'm unsure if this is the best route.

class APIService {

    static let shared = APIService()
    private let token = "(my token goes here)"

    //...various API request functions
}


问:
Taking two cells as arguments, and return a specific value depending on the string value of the cells
I need to make a VBA function that uses the values of two cells as arguments, and then return something depending on the values of the cells. I was thinking something like this

```<code>   Function returnNewString (cell1,cell2):
    if cell1 == 'somestring' && cell2 == "someotherstring" then
    return "something"
    else if cell1 == 'somestring2' && cell2 == "someotherstring2" then
    return "something else"
   end function
</code>```

A function call of returnNewString(A1,B1) should therefore return 'something' in relation to the conditions.

答:
Just for completness, the implementation of your pseudo code as written would be (which would be case senstitive)</p>

```<code>Function returnNewString (cell1 As Variant, cell2 As Variant) As Variant
    If cell1 = "somestring" And cell2 = "someotherstring" Then
        returnNewString = "something"
    ElseIf cell1 = "somestring2" And cell2 = "someotherstring2" Then
        returnNewString = "something else"
    End If
End Function
</code>```

Body:
I need to make a VBA function that uses the values of two cells as arguments, and then return something depending on the values of the cells. I was thinking something like this

   Function returnNewString (cell1,cell2):
    if cell1 == 'somestring' && cell2 == "someotherstring" then
    return "something"
    else if cell1 == 'somestring2' && cell2 == "someotherstring2" then
    return "something else"
   end function

A function call of returnNewString(A1,B1) should therefore return 'something' in relation to the conditions.

Body:
Just for completness, the implementation of your pseudo code as written would be (which would be case senstitive)

Function returnNewString (cell1 As Variant, cell2 As Variant) As Variant
    If cell1 = "somestring" And cell2 = "someotherstring" Then
        returnNewString = "something"
    ElseIf cell1 = "somestring2" And cell2 = "someotherstring2" Then
        returnNewString = "something else"
    End If
End Function


问:
cuda driver mismatch, can not use tensorflow gpu mode although gpu is installed
I installed cuda 10.2 to ubuntu 18.04 according to the official documentation, where I used the debian package for the installation

running

```<code>cat /proc/driver/nvidia/version
</code>```

I got

```<code>NVRM version: NVIDIA UNIX x86_64 Kernel Module  435.21  Sun Aug 25 08:17:57 CDT 2019
GCC version:  gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
</code>```

nvcc -V

```<code>nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_19:24:38_PDT_2019
Cuda compilation tools, release 10.2, V10.2.89
</code>```

when I run tensorflow 1.13.1 or 1.14.1,

```<code>import tensorflow as tf
tf.Session(config = tf.ConfigProto(log_device_placement = True))
</code>```

I got

```<code>    tensorflow/stream_executor/cuda/cuda_driver.cc:300] failed call to cuInit: CUDA_ERROR_SYSTEM_DRIVER_MISMATCH: system has unsupported display driver / cuda driver combination

2020-02-17 23:27:09.218431: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcuda.so.1
2020-02-17 23:27:09.219872: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: CUDA_ERROR_SYSTEM_DRIVER_MISMATCH: system has unsupported display driver / cuda driver combination
2020-02-17 23:27:09.219940: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: devbox_ailab
2020-02-17 23:27:09.219953: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: devbox_ailab
2020-02-17 23:27:09.220013: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:200] libcuda reported version is: 440.33.1
2020-02-17 23:27:09.220051: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:204] kernel reported version is: 435.21.0
2020-02-17 23:27:09.220062: E tensorflow/stream_executor/cuda/cuda_diagnostics.cc:313] kernel version 435.21.0 does not match DSO version 440.33.1 -- cannot find working devices in this configuration
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 13236727771426211181
, name: "/device:XLA_CPU:0"
device_type: "XLA_CPU"
memory_limit: 17179869184
locality {
}
incarnation: 8110659726839847577
physical_device_desc: "device: XLA_CPU device"
]
</code>```

答:
As described in tensorflow's documentation versions below 1.15 should be installed with specification of gpu explicitly, e.g.:

```<code>pip install tensorflow-gpu==1.14.1
</code>```

Furthermore your cuda version is 10.2 which is not supported by Tensorflow (either tf2.x or tf1.x AFAIK). 1.13.1 and 1.14.1 was compiled against cuda 10.0.

Your only solution is to compile tensorflow with version of your choice against your cuda version (see some info here) or rollback to 10.0 (some options described here).

Body:
I installed cuda 10.2 to ubuntu 18.04 according to the official documentation, where I used the debian package for the installation

running

cat /proc/driver/nvidia/version

I got

NVRM version: NVIDIA UNIX x86_64 Kernel Module  435.21  Sun Aug 25 08:17:57 CDT 2019
GCC version:  gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)

nvcc -V

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_19:24:38_PDT_2019
Cuda compilation tools, release 10.2, V10.2.89

when I run tensorflow 1.13.1 or 1.14.1,

import tensorflow as tf
tf.Session(config = tf.ConfigProto(log_device_placement = True))

I got

    tensorflow/stream_executor/cuda/cuda_driver.cc:300] failed call to cuInit: CUDA_ERROR_SYSTEM_DRIVER_MISMATCH: system has unsupported display driver / cuda driver combination

2020-02-17 23:27:09.218431: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcuda.so.1
2020-02-17 23:27:09.219872: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: CUDA_ERROR_SYSTEM_DRIVER_MISMATCH: system has unsupported display driver / cuda driver combination
2020-02-17 23:27:09.219940: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: devbox_ailab
2020-02-17 23:27:09.219953: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: devbox_ailab
2020-02-17 23:27:09.220013: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:200] libcuda reported version is: 440.33.1
2020-02-17 23:27:09.220051: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:204] kernel reported version is: 435.21.0
2020-02-17 23:27:09.220062: E tensorflow/stream_executor/cuda/cuda_diagnostics.cc:313] kernel version 435.21.0 does not match DSO version 440.33.1 -- cannot find working devices in this configuration
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 13236727771426211181
, name: "/device:XLA_CPU:0"
device_type: "XLA_CPU"
memory_limit: 17179869184
locality {
}
incarnation: 8110659726839847577
physical_device_desc: "device: XLA_CPU device"
]

Body:
As described in tensorflow's documentation versions below 1.15 should be installed with specification of gpu explicitly, e.g.:

pip install tensorflow-gpu==1.14.1

Furthermore your cuda version is 10.2 which is not supported by Tensorflow (either tf2.x or tf1.x AFAIK). 1.13.1 and 1.14.1 was compiled against cuda 10.0.

Your only solution is to compile tensorflow with version of your choice against your cuda version (see some info here) or rollback to 10.0 (some options described here).


问:
Sticky header causes page "jumps" when short page
I've managed to do a sticky header which works fine, apart from the fact, that when page isn't long enough it keeps "jumping". How to make it working properly?
Here is some code, jsfiddle and the most important: A VIDEO - which presents what the problem is. JS fiddle may not show if you have smaller resolution screens. Please see the video. How to fix this issue? I ran out of ideas.

Please see this video: video here

also code here:

```<code><div id="ontop">floating heading</div>
<header>sticky heading</header>
<div id="wrapper">
    1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>10<br/>
</div>

#ontop {width:100%; height:80px; background-color:yellow;}
header {width:100%; height:400px; background-color:lightgrey; }
#wrapper {background-color:lightblue; height:200px;}

.navfixed {position: fixed; top: 0px; z-index: 100; width:100%; display:block; margin-bottom:120px; }
.wrapperBelow{margin-top:22px;}

$(function () {
    var elem = $('header'),
        wrapperElem = $('#wrapper'),
        elemTop = elem.offset().top;
    $(window).scroll(function () {
        elem.toggleClass('navfixed', $(window).scrollTop() > elemTop);
         wrapperElem.toggleClass('wrapperBelow', $(window).scrollTop() > elemTop);
    }).scroll();
});
</code>```

and fiddle: fiddle

答:
If you don't want to set min-heights on your content areas try this.

body {min-height: 75rem;}

Body:
I've managed to do a sticky header which works fine, apart from the fact, that when page isn't long enough it keeps "jumping". How to make it working properly?
Here is some code, jsfiddle and the most important: A VIDEO - which presents what the problem is. JS fiddle may not show if you have smaller resolution screens. Please see the video. How to fix this issue? I ran out of ideas.

Please see this video: video here

also code here:

floating heading

sticky heading

    1
2
3
4
5
6
7
8
9
10

#ontop {width:100%; height:80px; background-color:yellow;}
header {width:100%; height:400px; background-color:lightgrey; }
#wrapper {background-color:lightblue; height:200px;}

.navfixed {position: fixed; top: 0px; z-index: 100; width:100%; display:block; margin-bottom:120px; }
.wrapperBelow{margin-top:22px;}

$(function () {
    var elem = $('header'),
        wrapperElem = $('#wrapper'),
        elemTop = elem.offset().top;
    $(window).scroll(function () {
        elem.toggleClass('navfixed', $(window).scrollTop() > elemTop);
         wrapperElem.toggleClass('wrapperBelow', $(window).scrollTop() > elemTop);
    }).scroll();
});

and fiddle: fiddle


问:
Java Sort after GroupBy
How can I sort these into a SortedMap instead of just a Map?</p>

```<code>    class Person {
        String name;
        double weight;

        public Person(String name, double weight) {
            this.name = name;
            this.weight = weight;
        }

        public double getWeight() {
            return this.weight;
        }
    }
    List<Person> people = Arrays.asList(
            new Person("Alex", 150.0),
            new Person("Courtney", 120.0),
            new Person("Billy", 180.0)
            );

    Map<Double, List<Person>> grouped = people.stream()
            .collect(Collectors.groupingBy(Person::getWeight));
</code>```

答:
You could feed the result in a SortedMap like so:

final Map<Double, List<Person>> grouped = new TreeMap<>(
    people.stream().collect(Collectors.groupingBy(Person::getWeight)));
```

Title: Java Sort after GroupBy

Body:
How can I sort these into a SortedMap instead of just a Map?

    class Person {
        String name;
        double weight;

        public Person(String name, double weight) {
            this.name = name;
            this.weight = weight;
        }

        public double getWeight() {
            return this.weight;
        }
    }
    List<Person> people = Arrays.asList(
            new Person("Alex", 150.0),
            new Person("Courtney", 120.0),
            new Person("Billy", 180.0)
            );

    Map<Double, List<Person>> grouped = people.stream()
            .collect(Collectors.groupingBy(Person::getWeight));


问:
partition function in SQL Server 2005
In MSDN about partition function from here, $PARTITION(Transact-SQL).

I am confused about what the below sample is doing underlying. My understanding is, this SQL statement will iterate all rows in table Production.TransactionHistory, and since for all the rows which will mapping to the same partition, $PARTITION.TransactionRangePF1(TransactionDate) will return the same value, i.e. the partition number for all such rows. So, for example, all rows in partition 1 will result in one row in returning result since they all of the same value of $PARTITION.TransactionRangePF1(TransactionDate). My understanding correct?

```<code>USE AdventureWorks ;
GO
SELECT $PARTITION.TransactionRangePF1(TransactionDate) AS Partition,
COUNT(*) AS [COUNT] FROM Production.TransactionHistory
GROUP BY $PARTITION.TransactionRangePF1(TransactionDate)
ORDER BY Partition ;
GO
</code>```

答:
If your parition function is defined like

```<code>CREATE PARTITION FUNCTION TransactionRangePF1(DATETIME)
AS RANGE RIGHT FOR VALUES ('2007-01-01', '2008-01-01', '2009-01-01')
</code>```

, then this clause:

```<code>$PARTITION.TransactionRangePF1(TransactionDate)
</code>```

is equivalent to:

```<code>CASE
  WHEN TransactionDate < '2007-01-01' THEN 1
  WHEN TransactionDate < '2008-01-01' THEN 2
  WHEN TransactionDate < '2009-01-01' THEN 3
  ELSE 4
END
</code>```

If all your dates fall before '2007-01-01', then the first WHEN clause will always fire and it will always return 1.

The query you posted will return at most 1 row for each partition, as it will group all the rows from the partition (if any) into one group.

If there are no rows for any partition, no rows for it will be returned in the resultset.

Title: partition function in SQL Server 2005

Body:
In MSDN about partition function from here, $PARTITION(Transact-SQL).

I am confused about what the below sample is doing underlying. My understanding is, this SQL statement will iterate all rows in table Production.TransactionHistory, and since for all the rows which will mapping to the same partition, $PARTITION.TransactionRangePF1(TransactionDate) will return the same value, i.e. the partition number for all such rows. So, for example, all rows in partition 1 will result in one row in returning result since they all of the same value of $PARTITION.TransactionRangePF1(TransactionDate). My understanding correct?

USE AdventureWorks ;
GO
SELECT $PARTITION.TransactionRangePF1(TransactionDate) AS Partition,
COUNT(*) AS [COUNT] FROM Production.TransactionHistory
GROUP BY $PARTITION.TransactionRangePF1(TransactionDate)
ORDER BY Partition ;
GO

LastEditorDisplayName: gbn

Body:
If your parition function is defined like

CREATE PARTITION FUNCTION TransactionRangePF1(DATETIME)
AS RANGE RIGHT FOR VALUES ('2007-01-01', '2008-01-01', '2009-01-01')

, then this clause:

$PARTITION.TransactionRangePF1(TransactionDate)

is equivalent to:

CASE
  WHEN TransactionDate < '2007-01-01' THEN 1
  WHEN TransactionDate < '2008-01-01' THEN 2
  WHEN TransactionDate < '2009-01-01' THEN 3
  ELSE 4
END

If all your dates fall before '2007-01-01', then the first WHEN clause will always fire and it will always return 1.

The query you posted will return at most 1 row for each partition, as it will group all the rows from the partition (if any) into one group.

If there are no rows for any partition, no rows for it will be returned in the resultset.

OwnerDisplayName: Quassnoi

LastEditorDisplayName: Quassnoi


问:
selecting the Row of table Except the First one
i want to select all the row except the Top One so can anybody help me on this Query.</p>

答:
```<code>with cte as
(
    select *, row_number() over (order by CustomerId) RowNumber
    from Sales.Customer
)
select *
from cte
where RowNumber != 1
</code>```

OR

```<code>select *
from
(
    select *, row_number() over (order by CustomerId) RowNumber
    from Sales.Customer
) tt
where RowNumber != 1
</code>```

Body:
with cte as
(
    select *, row_number() over (order by CustomerId) RowNumber
    from Sales.Customer
)
select *
from cte
where RowNumber != 1

OR

select *
from
(
    select *, row_number() over (order by CustomerId) RowNumber
    from Sales.Customer
) tt
where RowNumber != 1


问:
predict with kernlab package error Error in .local(object, ...) : test vector does not match model R
I'm testing the kernlab package in a regression problem. It seems it's a common issue to get 'Error in .local(object, ...) : test vector does not match model ! when passing the ksvm object to the predict function. However I just found answers to classification problems or custom kernels that are not applicable to my problem (I'm using a built-in one for regression). I'm running out of ideas here, my sample code is:

```<code>data <- matrix(rnorm(200*10),200,10)
tr <- data[1:150,]
ts <- data[151:200,]

mod <- ksvm(x = tr[,-1],
            y = tr[,1],
            kernel = "rbfdot", type = 'nu-svr',
            kpar = "automatic", C = 60, cross = 3)

pred <- predict(mod,
                ts
                )
</code>```

答:
You can use pred <- predict(mod, ts) if ts is a dataframe.

It would be

```<code>    data <- setNames(data.frame(matrix(rnorm(200*10),200,10)),
                     c("Y",paste("X", 1:9, sep = "")))
    tr <- data[1:150,]
    ts <- data[151:200,]

    mod <- ksvm(as.formula("Y ~ ."), data = tr,
        kernel = "rbfdot", type = 'nu-svr',
        kpar = "automatic", C = 60, cross = 3)

    pred <- predict(mod, ts)
</code>```

Body:
I'm testing the kernlab package in a regression problem. It seems it's a common issue to get 'Error in .local(object, ...) : test vector does not match model ! when passing the ksvm object to the predict function. However I just found answers to classification problems or custom kernels that are not applicable to my problem (I'm using a built-in one for regression). I'm running out of ideas here, my sample code is:

data <- matrix(rnorm(200*10),200,10)
tr <- data[1:150,]
ts <- data[151:200,]

mod <- ksvm(x = tr[,-1],
            y = tr[,1],
            kernel = "rbfdot", type = 'nu-svr',
            kpar = "automatic", C = 60, cross = 3)

pred <- predict(mod,
                ts
                )

Body:
You can use pred <- predict(mod, ts) if ts is a dataframe.

It would be

    data <- setNames(data.frame(matrix(rnorm(200*10),200,10)),
                     c("Y",paste("X", 1:9, sep = "")))
    tr <- data[1:150,]
    ts <- data[151:200,]

    mod <- ksvm(as.formula("Y ~ ."), data = tr,
        kernel = "rbfdot", type = 'nu-svr',
        kpar = "automatic", C = 60, cross = 3)

    pred <- predict(mod, ts)


问:
My C# DotNet DLL being detected as Ransomware by Windows Defender
This is a real shot in the dark. I have a C# DotNet solution (Visual Studio 2010) that consists of the EXE and several class library support DLLs. The Solution uses SMO (SQL Management Objects) to connect to and browse a database.

One of the DLLs is being flagged as Ransomware by Windows Defender (Windows 10 Pro x64). Specifically Ransom:MSIL/Hasadcrypt.A. I ran the DLL through VirusTotal and nothing else is flagging it except Microsoft. It is without question not RansomWare. I don't even know where to begin to figure out what is causing it to be flagged. Any suggestions as to where to start would be greatly appreciated.

答:
Some viruses encrypt themselves.  I don't know what you may be doing to set off the alarms, but that's what I would look into.  You didn't actually tell us what the file does, but you did leave that word "crypt" in the file name.

Did you create it yourself?  How do you know for certain that "It is without question not RansomWare."  And if it is self-modifying code, that is one thing that virus software looks at -- it allows the virus or malware to mutate, so as to avoid detection.


问:
Excel VBA insert row plus copy last row formula
Formula below just inserts the row and changing color for certain offset. I need to copy formula from previuos cells H, M, N. Any ideas?</p>

```<code>Sub button()
LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
Range("D" & LastRow + 1).EntireRow.Insert
With Range("D" & Rows.Count).End(xlUp).Offset(1)
    .Value = .Offset(-1).Value + 1
    .Offset(, -1).Interior.ColorIndex = 0
    .Offset(, -2).Interior.ColorIndex = 0
    .Offset(, -3).Interior.ColorIndex = 0
End With
End Sub
</code>```

答:
So now it's working

Sub Prideti_produkta()

```<code>LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
Range("D" & LastRow + 1).EntireRow.Insert
Range("H" & LastRow + 1).FillDown
Range("K" & LastRow + 1).FillDown
Range("M" & LastRow + 1).FillDown
Range("N" & LastRow + 1).FillDown

With Range("D" & Rows.Count).End(xlUp).Offset(1)
    .Value = .Offset(-1).Value + 1
    .Offset(, -1).Interior.ColorIndex = 0
    .Offset(, -2).Interior.ColorIndex = 0
    .Offset(, -3).Interior.ColorIndex = 0
End With

End Sub
</code>```

Body:
Formula below just inserts the row and changing color for certain offset. I need to copy formula from previuos cells H, M, N. Any ideas?

Sub button()
LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
Range("D" & LastRow + 1).EntireRow.Insert
With Range("D" & Rows.Count).End(xlUp).Offset(1)
    .Value = .Offset(-1).Value + 1
    .Offset(, -1).Interior.ColorIndex = 0
    .Offset(, -2).Interior.ColorIndex = 0
    .Offset(, -3).Interior.ColorIndex = 0
End With
End Sub

Body:
So now it's working

Sub Prideti_produkta()

LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
Range("D" & LastRow + 1).EntireRow.Insert
Range("H" & LastRow + 1).FillDown
Range("K" & LastRow + 1).FillDown
Range("M" & LastRow + 1).FillDown
Range("N" & LastRow + 1).FillDown

With Range("D" & Rows.Count).End(xlUp).Offset(1)
    .Value = .Offset(-1).Value + 1
    .Offset(, -1).Interior.ColorIndex = 0
    .Offset(, -2).Interior.ColorIndex = 0
    .Offset(, -3).Interior.ColorIndex = 0
End With

End Sub


问:
Node - Receiving ECONNRESET error when doing an http request with axios
I have a function in Node that needs to fetch all of the Users from Azure AD (I'm utilizing Microsoft Graph and Axios).

This function queries Microsoft Graph, the response includes an array of users. The max number of objects in this array is capped at 999. If there are more users, this response will also include an @odata.nextLink. My plan was to query, and if there is an @odata.nextLink in the response, query again until there is no @odata.nextLink. Not entirely sure if there is another way to do this better.

```<code>async function fetchUsers(tokenEndpoint, client_id, client_secret, query) {
  try {
    let allUsers = [];
    let bearer = `Bearer ${await fetchToken(
      tokenEndpoint,
      client_id,
      client_secret
    )}`;
    let res = await fetchData(bearer, `${msAPI}${query}`);
    if (res.status === 200) {
      allUsers.push(...res.data.value);
      console.log(allUsers.length);
      let nextURL = res.data["@odata.nextLink"];
      while (nextURL != undefined) {
        bearer = `Bearer ${await fetchToken(
          tokenEndpoint,
          client_id,
          client_secret
        )}`;
        res = await fetchData(bearer, nextURL);
        allUsers.push(...res.data.value);
        nextURL = res.data["@odata.nextLink"];
        console.log(allUsers.length);
      }
    }
    return allUsers;
  } catch (err) {
    handleError(err);
  }
}

async function fetchToken(tokenEndpoint, client_id, client_secret) {
  try {
    const res = await axios.post(
      tokenEndpoint,
      qs.stringify({
        client_id,
        client_secret,
        grant_type: "client_credentials",
        scope
      })
    );
    return res.data.access_token;
  } catch (err) {
    handleError(err);
  }
}

async function fetchData(bearer, url) {
  try {
    const res = await axios.get(url, {
      headers: {
        Authorization: bearer
      }
    });
    return res;
  } catch (err) {
    handleError(err);
  }
}

I have this statement in another async function
const allUsers = await fetchUsers(tokenEndpoint,clientId,clientSecret,query);

</code>```

Sometimes this runs perfectly and I get all my Azure AD users and sometimes I receive an ECONNRESET error in the middle of the function being run and it won't finish. This error seemed to happen a few times on one network, then I tested on a different network and didn't get the error once. Swapped back to the original network and got the errors again. Not sure if this is a network issue or the way I am doing the Axios requests in my loop.

Regardless, how would I go about resolving this ECONNRESET issue?

答:
An ECONNRESET occurs when a TCP abruptly closed. This could be caused by a failure in your local network, the remote service, or anywhere in between the two.

The most likely cause here is requesting $top=999. That is an excessively large (and therefore long) page size. You should be setting this to a smaller value or, ideally, leaving it to the default. This ensures the page sizes are reasonable, requests complete quickly, and helps avoid potential getting throttled by AAD.

Your "follow each @odata.nextLink plan is the correct pattern to use. This allows you to pull a page of data and process it prior to making subsequent requests for additional pages. In between requests you'll want to store the current @odata.nextLink so if anything goes wrong, you can pick up where you left off.

Body:
I have a function in Node that needs to fetch all of the Users from Azure AD (I'm utilizing Microsoft Graph and Axios).

This function queries Microsoft Graph, the response includes an array of users. The max number of objects in this array is capped at 999. If there are more users, this response will also include an @odata.nextLink. My plan was to query, and if there is an @odata.nextLink in the response, query again until there is no @odata.nextLink. Not entirely sure if there is another way to do this better.

async function fetchUsers(tokenEndpoint, client_id, client_secret, query) {
  try {
    let allUsers = [];
    let bearer = `Bearer ${await fetchToken(
      tokenEndpoint,
      client_id,
      client_secret
    )}`;
    let res = await fetchData(bearer, `${msAPI}${query}`);
    if (res.status === 200) {
      allUsers.push(...res.data.value);
      console.log(allUsers.length);
      let nextURL = res.data["@odata.nextLink"];
      while (nextURL != undefined) {
        bearer = `Bearer ${await fetchToken(
          tokenEndpoint,
          client_id,
          client_secret
        )}`;
        res = await fetchData(bearer, nextURL);
        allUsers.push(...res.data.value);
        nextURL = res.data["@odata.nextLink"];
        console.log(allUsers.length);
      }
    }
    return allUsers;
  } catch (err) {
    handleError(err);
  }
}

async function fetchToken(tokenEndpoint, client_id, client_secret) {
  try {
    const res = await axios.post(
      tokenEndpoint,
      qs.stringify({
        client_id,
        client_secret,
        grant_type: "client_credentials",
        scope
      })
    );
    return res.data.access_token;
  } catch (err) {
    handleError(err);
  }
}

async function fetchData(bearer, url) {
  try {
    const res = await axios.get(url, {
      headers: {
        Authorization: bearer
      }
    });
    return res;
  } catch (err) {
    handleError(err);
  }
}

I have this statement in another async function
const allUsers = await fetchUsers(tokenEndpoint,clientId,clientSecret,query);

Sometimes this runs perfectly and I get all my Azure AD users and sometimes I receive an ECONNRESET error in the middle of the function being run and it won't finish. This error seemed to happen a few times on one network, then I tested on a different network and didn't get the error once. Swapped back to the original network and got the errors again. Not sure if this is a network issue or the way I am doing the Axios requests in my loop.

Regardless, how would I go about resolving this ECONNRESET issue?


问:
VueJS Store pattern with get & set
I have a small store (following the state pattern on VueJS (not VUEX)).

It essentially looks like this

```<code>export default {
    get selectedPartner() {
        return localStorage.getItem('selectedPartner');
    },

    set selectedPartner(item) {

        localStorage.setItem('selectedPartner', item);
    },

    clearFilters() {
        localStorage.removeItem('selectedPartner');
    }
}
</code>```

In my .vue component I am now trying to bind to it like so

```<code>    data: function() {
      return {
        // Other stuff here...
        selectedPartner: filterStore.selectedPartner,
      }
    },
</code>```

Now, when it draws the component, the getter is actually properly called.
When i change the value in the component, it does not update the store...

I do realise that doing it like this (in localStorage) is awfully close to VUEX.
But chose for this approach to grasp state in its most simple form first, before getting into VUEX.

Many thanks

答:
Use computed instead of data:

```<code>computed: {
  selectedPartner: {
    get() { return filterStore.selectedPartner; },
    set(item) { filterStore.selectedPartner = item; }
  }
}
</code>```

Title: VueJS Store pattern with get & set

Body:
I have a small store (following the state pattern on VueJS (not VUEX)).

It essentially looks like this

export default {
    get selectedPartner() {
        return localStorage.getItem('selectedPartner');
    },

    set selectedPartner(item) {

        localStorage.setItem('selectedPartner', item);
    },

    clearFilters() {
        localStorage.removeItem('selectedPartner');
    }
}

In my .vue component I am now trying to bind to it like so

    data: function() {
      return {
        // Other stuff here...
        selectedPartner: filterStore.selectedPartner,
      }
    },

Now, when it draws the component, the getter is actually properly called.
When i change the value in the component, it does not update the store...

I do realise that doing it like this (in localStorage) is awfully close to VUEX.
But chose for this approach to grasp state in its most simple form first, before getting into VUEX.

Many thanks

Body:
Use computed instead of data:

computed: {
  selectedPartner: {
    get() { return filterStore.selectedPartner; },
    set(item) { filterStore.selectedPartner = item; }
  }
}


问:
How to produce JSON output with Jersey 1.6 using JAXB
```<code>@XmlRootElement
public class Todo {
    private String s = "test";

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

}
</code>```

and service:

```<code>@Path("/test")
public class Service {

    @GET
    @Produces({MediaType.APPLICATION_JSON })
    public List<Todo> getAllGadgets() {
        return Arrays.asList(new Todo[] { new Todo() });
    }

}
</code>```

my web.xml:

```<code><servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.test</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</code>```

All this work if I set  MediaType.APPLICATION_XML for Produces annotation. But for JSON I get the following exception:

SEVERE: Mapped exception to response:
  500 (Internal Server Error)
  javax.ws.rs.WebApplicationException:
  com.sun.jersey.api.MessageException: A
  message body writer for Java class
  java.util.Arrays$ArrayList, and Java
  type java.util.List,
  and MIME media type application/json
  was not found

I use Jersey 1.6 and, according to the tutorial, JSON format should work with JAXB without any additional programming. What's wrong?

答: I solved this. All I needed to do was to add jersey-json-1.6.jar library to the project (this is not required part of jersey)</p>

Body:
@XmlRootElement
public class Todo {
    private String s = "test";

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

}

and service:

@Path("/test")
public class Service {

    @GET
    @Produces({MediaType.APPLICATION_JSON })
    public List<Todo> getAllGadgets() {
        return Arrays.asList(new Todo[] { new Todo() });
    }

}

my web.xml:

<servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.test</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

All this work if I set  MediaType.APPLICATION_XML for Produces annotation. But for JSON I get the following exception:

SEVERE: Mapped exception to response:
  500 (Internal Server Error)
  javax.ws.rs.WebApplicationException:
  com.sun.jersey.api.MessageException: A
  message body writer for Java class
  java.util.Arrays$ArrayList, and Java
  type java.util.List,
  and MIME media type application/json
  was not found

I use Jersey 1.6 and, according to the tutorial, JSON format should work with JAXB without any additional programming. What's wrong?


问:
Accessing DOM object in Node JS
I am using a code snippet from a Github repository by Microsoft (https://github.com/microsoft/customvision-tfjs) for using a Tensorflow.js model in Node JS.

Here they are using document.getElementById() to access an image element and then passing it to a function for predication, but it's written between Node.js code where DOM is not available. is this code incorrect? or is there a way to access HTML elements in Node JS

```<code>const cvstfjs = require('@microsoft/customvision-tfjs');

async function doThings() {
  let model = new cvstfjs.ObjectDetectionModel();
  await model.loadModelAsync('model.json');
  const image = document.getElementById('image');
  const result = await model.executeAsync(image);
  return result;
}

doThings().then((result) => {
  console.log(result);
});
</code>```

答:
Either use TF in the browser via webpack and operate DOM as usual

or if you want a server-side fun use cheerio library.

```<code>npm i cheerio

const cheerio = require('cheerio')

var html = await fs.readFile('./dong.html')

const $ = cheerio.load(html.toString())

$('#element').text()
</code>```

Title: Accessing DOM object in Node JS

Body:
I am using a code snippet from a Github repository by Microsoft (https://github.com/microsoft/customvision-tfjs) for using a Tensorflow.js model in Node JS.

Here they are using document.getElementById() to access an image element and then passing it to a function for predication, but it's written between Node.js code where DOM is not available. is this code incorrect? or is there a way to access HTML elements in Node JS

const cvstfjs = require('@microsoft/customvision-tfjs');

async function doThings() {
  let model = new cvstfjs.ObjectDetectionModel();
  await model.loadModelAsync('model.json');
  const image = document.getElementById('image');
  const result = await model.executeAsync(image);
  return result;
}

doThings().then((result) => {
  console.log(result);
});

Body:
Either use TF in the browser via webpack and operate DOM as usual

or if you want a server-side fun use cheerio library.

npm i cheerio

const cheerio = require('cheerio')

var html = await fs.readFile('./dong.html')

const $ = cheerio.load(html.toString())

$('#element').text()


问:
CORS error when posting data to my DRF API from a template within the project itself
I have a Django project that has an end-point created using DRF. I am posting data to it from a template within the project itself (another rendered view). However, I get the following error code:

```<code>403 Unauthorized. CSRF token not provided.
</code>```

This makes no sense because both the end-point and the view shares the same origin. So why am I getting this error? And how can I solve this issue? Thanks for any help.

答:
You simply need to do what it says: provide csrf token.
Use this function to get it from cookies:

```<code>export function getCookie(name){
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
          var cookie = cookies[i].trim();
          if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
          }
      }
  }
  return cookieValue;
}
</code>```

Then modify your ajax function like so:

```<code>const csrf_token = this.getCookie('csrftoken')
const postData = async() => {
              ...
      headers: {
          'Content-Type': 'application/json',
          'x-csrftoken': csrf_token
      }
              ...
}
</code>```

Body:
I have a Django project that has an end-point created using DRF. I am posting data to it from a template within the project itself (another rendered view). However, I get the following error code:

403 Unauthorized. CSRF token not provided.

This makes no sense because both the end-point and the view shares the same origin. So why am I getting this error? And how can I solve this issue? Thanks for any help.

Body:
You simply need to do what it says: provide csrf token.
Use this function to get it from cookies:

export function getCookie(name){
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
          var cookie = cookies[i].trim();
          if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
          }
      }
  }
  return cookieValue;
}

Then modify your ajax function like so:

const csrf_token = this.getCookie('csrftoken')
const postData = async() => {
              ...
      headers: {
          'Content-Type': 'application/json',
          'x-csrftoken': csrf_token
      }
              ...
}


问:
Generics for data structure that stores key value pair
Given I wanted to write my own data structure, as far as I understand, if I wanted to use generics I would do public class myDataStructure<E>. However, If I wanted to write a data structure that stored data in a key value pair, how would I use generics? Could I do public class myOtherDataStructure<E, Integer> for example, and use <E> the same way it was used with myDataStructure?

Also, I don't want to use HashMap or anything similar. The point here is that I want to understand what I would do if I wanted to define my own data structure.

答:
If you know your values are only going to be integers, then the value type should not be a generic type. Your data structure can look like this:</p>

```<code>public class MyOtherDataStructure<K> {

    public void put(K key, Integer value) {...}

    public Integer get(K key) {...}

}
</code>```

Body:
If you know your values are only going to be integers, then the value type should not be a generic type. Your data structure can look like this:

public class MyOtherDataStructure<K> {

    public void put(K key, Integer value) {...}

    public Integer get(K key) {...}

}


问:
What is a UML profile diagram and when is it used?
I have been reading about the UML Profile Diagram but I don't understand it. I want to mainly understand when it can used.

答:
Actually there is no special UML diagram. All UML diagrams are equal - but some are more equal than others. UML diagram categories were introduced to contain mainly (but not forcibly) elements of a certain area. Well known are use case and class diagram (and a couple more).

Now, a profile in UML is used to define stereotypes and possibly stereotype properties going along with them. A stereotype  "extends" meta elements defined in UML (like classes, use cases, etc.) or other profiles, this way building new meta types.

You do that to model certain domains and give the modeler specific new elements. E.g. you can define a profile for a car manufacturer and introduce stereotypes like <<motor>>, <<chasis>> and so on. So these are business objects with a well know semantic in that domain. A motor could go with stereotype properties like type being an enumeration of gas, electric, etc. There are a couple of pre-defined profiles published by OMG (and other authorities) like SysML, BPMN, etc.

A profile diagram (from a tool perspective) would offer you meta classes, handles for stereotype properties and specific connectors like Extends to ease creation of new profiles.


问:
Error sending temperature data from Arduino to Matlab
I am trying to send temperature sensor data from arduino to matlab using serial communication. The temperature data are displayed on the Arduino serial monitor but I couldn't get the data in Matlab. The following error occurs. I've tried every possible ways to get the data by putting a pause(3) before fscanf but it still doesn't work.

Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.
  'serial' unable to read any data. For more information on possible reasons, see Serial Read Warnings.
     NaN

My matlab code as follows

```<code>if ~isempty(instrfind)
    fclose(instrfind);
    delete (instrfind);
end

waitTime = 10;

s = serial('COM4','BAUD',9600);

waitTime = duration(0,waitTime,0);
t = datetime('now') - startTime;

while t < waitTime
    fopen(s);
    pause(3);
    idn = fscanf(s);
    fclose(s);

    serialData = str2double(idn);
    corrData = serialData;
    disp(corrData);
end

clear a;
clear s;
</code>```

答: fscanf will return when the first terminator is found. This is usually carriage return (CR). Since you are using Serial.print(bme.readTemperature()); there is never a CR sent by the Arduino. Try Serial.println(bme.readTemperature());

Body:
I am trying to send temperature sensor data from arduino to matlab using serial communication. The temperature data are displayed on the Arduino serial monitor but I couldn't get the data in Matlab. The following error occurs. I've tried every possible ways to get the data by putting a pause(3) before fscanf but it still doesn't work.

Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.
  'serial' unable to read any data. For more information on possible reasons, see Serial Read Warnings.
     NaN

My matlab code as follows

if ~isempty(instrfind)
    fclose(instrfind);
    delete (instrfind);
end

waitTime = 10;

s = serial('COM4','BAUD',9600);

waitTime = duration(0,waitTime,0);
t = datetime('now') - startTime;

while t < waitTime
    fopen(s);
    pause(3);
    idn = fscanf(s);
    fclose(s);

    serialData = str2double(idn);
    corrData = serialData;
    disp(corrData);
end

clear a;
clear s;