问:
Eclipse - Glassfish 5 - Error in glassfish-web.xml
I try to create a new j2e project running on a glassfish server.
I created the server and am able to run it from eclipse but the project itself has an issue with the glassfish-web.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <context-root>/test-glassfish</context-root>
</glassfish-web-app>
</code>```

I really don't get what is wrong and I didn't find much in my search.

答:
This is not a JDK issue, and not required to install a new eclipse.

The root cause is the internet not connecting inside eclipse.

Here are the steps for modifying network inside eclipse:

In eclipse - GoTo --> Preferences --> Network Connections

Inside "Network Connections" -->  select ActiveProvider = manual

Click on "Apply & Close".

Restart eclipse.

you will get access to Marketplace.

eclipse Preferences screenshot for reference :
https://i.stack.imgur.com/Flljz.png

Body:
I try to create a new j2e project running on a glassfish server.
I created the server and am able to run it from eclipse but the project itself has an issue with the glassfish-web.xml :

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <context-root>/test-glassfish</context-root>
</glassfish-web-app>

I really don't get what is wrong and I didn't find much in my search.


来源: stackexchange

问:
Google sheets query inside select string in a where clause how to use reference cells with dates in them as filters
```<code>=QUERY(customers,"SELECT B, G, F, E, M WHERE F >= DATE '2020-6-1' AND F <= DATE '2020-6-7',0)
</code>```

I have this string inside a Google Sheets Query.

I want to replace the two dates with a cell for each to simplify adjusting the dates every week at the cell and not the actual function.

How can I do that?

答:
See if this helps

```<code>=QUERY(customers,"SELECT B, G, F, E, M WHERE F >= DATE '"&TEXT(A1, "yyyy-MM-dd")&"'  AND F <= DATE '"&TEXT(B1, "yyyy-MMM-dd")&"'",0)
</code>```

Change the cell references as needed. Depending on your locale you may have to change the commas in the formula to semi-colons.

ContentLicense: CC BY-SA 4.0

Body:
=QUERY(customers,"SELECT B, G, F, E, M WHERE F >= DATE '2020-6-1' AND F <= DATE '2020-6-7',0)

I have this string inside a Google Sheets Query.

I want to replace the two dates with a cell for each to simplify adjusting the dates every week at the cell and not the actual function.

How can I do that?

Body:
See if this helps

=QUERY(customers,"SELECT B, G, F, E, M WHERE F >= DATE '"&TEXT(A1, "yyyy-MM-dd")&"'  AND F <= DATE '"&TEXT(B1, "yyyy-MMM-dd")&"'",0)

Change the cell references as needed. Depending on your locale you may have to change the commas in the formula to semi-colons.


问:
Freeze Time test cases fail when a variable is used to reference the time
I'm using freeze-time to run my python unittest Test cases.

A dummy test case:

@freeze_time('2020-01-01')
def test_something(self):
  expected_output = {'time': '2020-01-01'}

  output = call_tested_code()

  self.assertEqual(expected_output, output)
```

<p>Main code / Code that is being tested:</p>

<pre class="lang-py prettyprint-override"><code>GET_CURRENT_TIME = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

def call_tested_code():
  return {'time': GET_CURRENT_TIME}
</code>```

This is failing, as the output is giving current_date instead of frozen date.
It was working when the GET_CURRENT_TIME was a lambda, but that results in different timestamps for my code, which I don't want.

Feel free to comment if any additional Information is required. Thanks

答:
Your tested code is being imported before your test function, so GET_CURRENT_TIME is evaluated before your freeze_time so that's the problem.

To solve if either import call_tested_code inside the test function or put it inside a lambda or another callable, as mentioned by you.

```<code>@freeze_time('2020-01-01')
def test_something(self):
    from package import call_tested_code # edit here with your correct import
    expected_output = {'time': '2020-01-01'}
    output = call_tested_code()
    self.assertEqual(expected_output, output)
</code>```

Also, I think you should change the expected output to be a datetime string not only date as your GET_CURRENT_TIME uses this format '%Y-%m-%d %H:%M:%S'.

Body:
I'm using freeze-time to run my python unittest Test cases.

A dummy test case:

@freeze_time('2020-01-01')
def test_something(self):
  expected_output = {'time': '2020-01-01'}

  output = call_tested_code()

  self.assertEqual(expected_output, output)

Main code / Code that is being tested:

GET_CURRENT_TIME = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

def call_tested_code():
  return {'time': GET_CURRENT_TIME}

This is failing, as the output is giving current_date instead of frozen date.
It was working when the GET_CURRENT_TIME was a lambda, but that results in different timestamps for my code, which I don't want.

Feel free to comment if any additional Information is required. Thanks

Body:
Your tested code is being imported before your test function, so GET_CURRENT_TIME is evaluated before your freeze_time so that's the problem.

To solve if either import call_tested_code inside the test function or put it inside a lambda or another callable, as mentioned by you.

@freeze_time('2020-01-01')
def test_something(self):
    from package import call_tested_code # edit here with your correct import
    expected_output = {'time': '2020-01-01'}
    output = call_tested_code()
    self.assertEqual(expected_output, output)

Also, I think you should change the expected output to be a datetime string not only date as your GET_CURRENT_TIME uses this format '%Y-%m-%d %H:%M:%S'.


问:
Space in Batch File
I'm fairly new to batches. Starting to learn the basics but already run into a problem.

So my Code looks something like this:

```<code>findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\*.* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause
</code>```

The Problem here is, that I also receive Files with spaces. For Example "File with Spacer.pdf".
I already tried to use quotation marks. But these didnt work out for me.

Maybe you can give me a hint how to solve this one.

Thanks!

Edit:

Tried to use the quotation marks direct at the file name ("* ".*).

```<code>findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\"*".* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause
</code>```

And I tried to use it for the whole path ("C:\Users\XY\Desktop\Start*.*")

```<code>findstr /i /m Findthisstring "C:\Users\XY\Desktop\Start\*.*" > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause
</code>```

答:
So i managed to get it working with the "DELIMS=" command. Also thanks @mark for the Hint with the Quoted "%%I".

My final Code:

```<code>findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\"*".* > test.lst
for /f "DELIMS=" %%I in (C:\Users\XY\Desktop\test.lst) do @move "%%I" C:\Users\XY\Desktop\Target\

pause
</code>```

Title: Space in Batch File

Body:
I'm fairly new to batches. Starting to learn the basics but already run into a problem.

So my Code looks something like this:

findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\*.* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause

The Problem here is, that I also receive Files with spaces. For Example "File with Spacer.pdf".
I already tried to use quotation marks. But these didnt work out for me.

Maybe you can give me a hint how to solve this one.

Thanks!

Edit:

Tried to use the quotation marks direct at the file name ("* ".*).

findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\"*".* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause

And I tried to use it for the whole path ("C:\Users\XY\Desktop\Start*.*")

findstr /i /m Findthisstring "C:\Users\XY\Desktop\Start\*.*" > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause

Body:
So i managed to get it working with the "DELIMS=" command. Also thanks @mark for the Hint with the Quoted "%%I".

My final Code:

findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\"*".* > test.lst
for /f "DELIMS=" %%I in (C:\Users\XY\Desktop\test.lst) do @move "%%I" C:\Users\XY\Desktop\Target\

pause


问:
iterate 2 dicts and compare values then append inner list
I am faced with a situation where I need to iterate nested dicts with same outermost keys, compare inner key value to inner key value of other dict then append. Below will help to understand:

```<code>{AD:{(62,'VMX','Barcelona','ES'): ['123','567','666'}} #dict1  many more rows

{AD:{(151,'CMXS','','ES','62'): ['345','6754']}}       #dict 2 many more rows

</code>```

So I need to iterate both dicts, compare tuple key[0] of dict1 == tuple key[4] of dict2, if they match append inner list in dict1 with inner list in dict2.

after this dict1 looks like

```<code>{AD:{(62,'VMX','Barcelona','ES'): ['123','567','666','345','6754'}}

</code>```

Wrote this code but it not working as expected

```<code>for k,v in dict1.items():
    if len(v)!= 0:
        for c,a in dict2.items():
            if len(a)!= 0:
                for k2,v2 in v.items():
                    for c2,a2 in a.items():
                        if str(k2[0]) == c2[4]:
                            v2.append(a2)

</code>```

答:
The for loops are placed correctly as long as the example goes.

What do you mean by unexpectedly?
Do you mean this?

```<code>{'AD': {(62, 'VMX', 'Barcelona', 'ES'): ['123', '567', '666', ['345', '6754']]}}
</code>```

That extra array within the array?

Because if so, the answer would be to switch the .append() with a .extend()

Body:
I am faced with a situation where I need to iterate nested dicts with same outermost keys, compare inner key value to inner key value of other dict then append. Below will help to understand:

{AD:{(62,'VMX','Barcelona','ES'): ['123','567','666'}} #dict1  many more rows

{AD:{(151,'CMXS','','ES','62'): ['345','6754']}}       #dict 2 many more rows

So I need to iterate both dicts, compare tuple key[0] of dict1 == tuple key[4] of dict2, if they match append inner list in dict1 with inner list in dict2.

after this dict1 looks like

{AD:{(62,'VMX','Barcelona','ES'): ['123','567','666','345','6754'}}

Wrote this code but it not working as expected

for k,v in dict1.items():
    if len(v)!= 0:
        for c,a in dict2.items():
            if len(a)!= 0:
                for k2,v2 in v.items():
                    for c2,a2 in a.items():
                        if str(k2[0]) == c2[4]:
                            v2.append(a2)

Body:
The for loops are placed correctly as long as the example goes.

What do you mean by unexpectedly?
Do you mean this?

{'AD': {(62, 'VMX', 'Barcelona', 'ES'): ['123', '567', '666', ['345', '6754']]}}

That extra array within the array?

Because if so, the answer would be to switch the .append() with a .extend()


问:
How to add column with specific condition for oracle DB
How do add a field – DOC with Date type to the Registration table.
Also DOC (Date of Completion) should be greater than DOJ (Date of joining).

I wrote this query but it is showing error : Column check constraint cannot reference other column

```<code>ALTER TABLE Registration add DOC date CHECK(DOC > DOJ);
</code>```

答:
Add both the DOC column and the CHECK constraint with a single ALTER TABLE statement (see DBfiddle here) :</p>

```<code>-- table for testing
create table atable( doj date ) ;

alter table atable
add (
  doc date
, constraint checkdoc check( doc > doj ) -- cannot be coded *inline*
);

-- testing -----------------------------------------------------
-- this insert must succeed
insert into atable( doj, doc ) values ( sysdate, sysdate + 1 );

-- this insert must fail due to the CHECK constraint
insert into atable( doj, doc ) values ( sysdate + 1, sysdate ) ;
-- ORA-02290: check constraint (...CHECKDOC) violated

-- table/data --------------------------------------------------
select * from atable ;
DOJ         DOC
03-JUN-20   04-JUN-20
</code>```

Body:
How do add a field – DOC with Date type to the Registration table.
Also DOC (Date of Completion) should be greater than DOJ (Date of joining).

I wrote this query but it is showing error : Column check constraint cannot reference other column

ALTER TABLE Registration add DOC date CHECK(DOC > DOJ);

Body:
Add both the DOC column and the CHECK constraint with a single ALTER TABLE statement (see DBfiddle here) :

-- table for testing
create table atable( doj date ) ;

alter table atable
add (
  doc date
, constraint checkdoc check( doc > doj ) -- cannot be coded *inline*
);

-- testing -----------------------------------------------------
-- this insert must succeed
insert into atable( doj, doc ) values ( sysdate, sysdate + 1 );

-- this insert must fail due to the CHECK constraint
insert into atable( doj, doc ) values ( sysdate + 1, sysdate ) ;
-- ORA-02290: check constraint (...CHECKDOC) violated

-- table/data --------------------------------------------------
select * from atable ;
DOJ         DOC
03-JUN-20   04-JUN-20


问:
What is the right API to use to remap keys in OSX?
I'm looking at Karabiner, the OSX keyboard remapper for Parallels development.  According to this issue this is best fixed by filing a bug with Apple.

What is the alternative (if any) supported API to create such a functionality?

答: Karabiner-Elements is solid and versatile despite the sketchy documentation and user interface, excusable for a work in progress.  There are many useful examples, e.g., this one which required dedicated tools and the Karabiner error log to generate the tricky JSON rules.  Any key can be both a modifier and regular key, run a program, etc., all at once.  Public domain on GitHub.</p>

ContentLicense: CC BY-SA 3.0


问:
NaN resulting from sum of values in nodeJS
I'm fairly new to Javascript. But I created an HTML code that takes input and then the NodeJS runs it on the server to calculate the sum. I downloaded both modules properly. But I still seem to get Nan as the sum of numbers.

The code seems to work properly for a friend. And I copy pasted his JS code to mine, still no luck.

JS

```<code>const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = req.body.num1;
      num2 = req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});
</code>```

HTML

```<code><form action="/" method="POST">
    <input type="text " name="num1 " placeholder="First Number " />
    <input type="text " name="num2 " placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>
</code>```

答:
Remove the trailing space in the name attribute, also if you're passing numbers why don't you set the type as number

And either one of the values or maybe both is getting passed as undefined hence you get NaN

Body:
I'm fairly new to Javascript. But I created an HTML code that takes input and then the NodeJS runs it on the server to calculate the sum. I downloaded both modules properly. But I still seem to get Nan as the sum of numbers.

The code seems to work properly for a friend. And I copy pasted his JS code to mine, still no luck.

JS

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = req.body.num1;
      num2 = req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});

HTML

<form action="/" method="POST">
    <input type="text " name="num1 " placeholder="First Number " />
    <input type="text " name="num2 " placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>


问:
SAS-Append data to a table and increment a flag on the resultant table
I have two tables on SAS "Table_A" and "Table_A_Archive", as part my ETL process "Table_A" is created on a daily basis and the data should be archived on "Table_A_Archive". When the data is archived on "Table_A_Archive" a a flag will be created/updated "DT_FLAG".

On the first day this is how the table would look like

```<code> "Table_A"
 | ID  | Load_Date
 ------ -------------
 | 100 | 01JUN2020:12:13:56

 "Table_A_Archive"
  | ID  | Load_Date           | DT_FLAG
  ------ --------------------- ---------
  | 100 | 01JUN2020:12:13:56  | 1
</code>```

On Day 2

```<code> "Table_A"
 | ID  | Load_Date
 ------ ------------
 | 101 | 02JUN2020:12:13:56

 "Table_A_Archive"
 | ID  | Load_Date           | DT_FLAG
 ------ --------------------- ---------
 | 100 | 01JUN2020:12:13:56  | 2
 | 101 | 02JUN2020:12:13:56  | 1
</code>```

The new data should be loaded with the DT_FLAG of 1 and old records DT_FLAG should be incremented by 1. Load_Date is the pivotal point. I have written a SAS code but it seems a bit messy, can someone please help me with a SAS Datastep

```<code> %macro Cntl_archive(table_name=,arch_table_name=);
 %GLOBAL WRK;

 %if %sysfunc(exist(&arch_table_name.))  %then %do;

 proc append base=&arch_table_name. data=&table_name. force;
 run;

 proc sql;
 Create table TEMP as
 Select distinct Load_Date,Load_Date as WRK from &arch_table_name.
 order by Load_Date desc
 ;quit;

 proc rank data=TEMP descending out=TEMP;
 var WRK;
 ranks count;
 run;

 data &arch_table_name. (drop=DT_FLAG);
 set    &arch_table_name.;
 run;

 proc sql;
 Create table &arch_table_name. as
 Select T0.*,T1.count as DT_FLAG from &arch_table_name. T0
 inner join TEMP T1 on T0.Load_Date=T1.Load_Date
 ;quit
 %end;
 %else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;
</code>```

答:
I tried solving it by this method.</p>

```<code>%macro Cntl_archive(table_name=,arch_table_name=);

%if %sysfunc(exist(&arch_table_name.))  %then %do;

data Data_append;
set &table_name.;
if _n_ = 1
then do;
  set &arch_table_name.(keep=dt_flag) point=nobs nobs=nobs;
dt_flag + 1;
end;
run;

proc append base=&arch_table_name. data=Data_append force;
run;

%end;
%else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;
</code>```

Body:
I have two tables on SAS "Table_A" and "Table_A_Archive", as part my ETL process "Table_A" is created on a daily basis and the data should be archived on "Table_A_Archive". When the data is archived on "Table_A_Archive" a a flag will be created/updated "DT_FLAG".

On the first day this is how the table would look like

 "Table_A"
 | ID  | Load_Date
 ------ -------------
 | 100 | 01JUN2020:12:13:56

 "Table_A_Archive"
  | ID  | Load_Date           | DT_FLAG
  ------ --------------------- ---------
  | 100 | 01JUN2020:12:13:56  | 1

On Day 2

 "Table_A"
 | ID  | Load_Date
 ------ ------------
 | 101 | 02JUN2020:12:13:56

 "Table_A_Archive"
 | ID  | Load_Date           | DT_FLAG
 ------ --------------------- ---------
 | 100 | 01JUN2020:12:13:56  | 2
 | 101 | 02JUN2020:12:13:56  | 1

The new data should be loaded with the DT_FLAG of 1 and old records DT_FLAG should be incremented by 1. Load_Date is the pivotal point. I have written a SAS code but it seems a bit messy, can someone please help me with a SAS Datastep

 %macro Cntl_archive(table_name=,arch_table_name=);
 %GLOBAL WRK;

 %if %sysfunc(exist(&arch_table_name.))  %then %do;

 proc append base=&arch_table_name. data=&table_name. force;
 run;

 proc sql;
 Create table TEMP as
 Select distinct Load_Date,Load_Date as WRK from &arch_table_name.
 order by Load_Date desc
 ;quit;

 proc rank data=TEMP descending out=TEMP;
 var WRK;
 ranks count;
 run;

 data &arch_table_name. (drop=DT_FLAG);
 set    &arch_table_name.;
 run;

 proc sql;
 Create table &arch_table_name. as
 Select T0.*,T1.count as DT_FLAG from &arch_table_name. T0
 inner join TEMP T1 on T0.Load_Date=T1.Load_Date
 ;quit
 %end;
 %else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;

Body:
I tried solving it by this method.

%macro Cntl_archive(table_name=,arch_table_name=);

%if %sysfunc(exist(&arch_table_name.))  %then %do;

data Data_append;
set &table_name.;
if _n_ = 1
then do;
  set &arch_table_name.(keep=dt_flag) point=nobs nobs=nobs;
dt_flag + 1;
end;
run;

proc append base=&arch_table_name. data=Data_append force;
run;

%end;
%else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;


问:
React/Redux question about dispatching an action to add an item to an array
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

```<code>addSeenCard(this.props.randomCard)
</code>```

Here is my portable action creator function for addSeenCard:

```<code>export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}
</code>```

Here is my reducer function:

```<code> case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }
</code>```

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

答:
Thats what I was missing in my reducer, the spread operator. Thank you very much, all your answers work. Because I am storing the random card in the state I have decided to dispatch the ADD_SEEN_CARD function with an empty payload and do this instead:

```<code>  case 'ADD_SEEN_CARD':
  return {
    ...state,
    seenCard: state.seenCard.concat(state.randomCard[0].id)
    //  seenCard: [...state.seenCard, state.randomCard[0].id]
    }
</code>```

Thank you again for all your answers.

Body:
I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

addSeenCard(this.props.randomCard)

Here is my portable action creator function for addSeenCard:

export function addSeenCard(randomCard) {

 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}

Here is my reducer function:

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null.  I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

Body:
Thats what I was missing in my reducer, the spread operator. Thank you very much, all your answers work. Because I am storing the random card in the state I have decided to dispatch the ADD_SEEN_CARD function with an empty payload and do this instead:

  case 'ADD_SEEN_CARD':
  return {
    ...state,
    seenCard: state.seenCard.concat(state.randomCard[0].id)
    //  seenCard: [...state.seenCard, state.randomCard[0].id]
    }

Thank you again for all your answers.


问:
How to turn txt file to nice dataframe
I have a txt file containing Track ID, Song ID, Artist Name and Song name. I'd like to convert it into a dataframe in R to do some analysis. What would be a good function to use to separate the data? Below is the top row of the dataset. Thanks!</p>

```<code>TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
</code>```

答:
You may use readLines and strsplit.

```<code>rw <- readLines("X:/foo.txt")
nice.df <- setNames(as.data.frame(do.call(rbind, strsplit(rw, "<SEP>"))),
                    c("Track.ID", "Song.ID", "Artist.Name", "Song.name"))
nice.df
#             Track.ID            Song.ID      Artist.Name   Song.name
# 1 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
# 2 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
# 3 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
# 4 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
</code>```

foo.txt content:

```<code>TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
</code>```

Title: How to turn txt file to nice dataframe

Body:
I have a txt file containing Track ID, Song ID, Artist Name and Song name. I'd like to convert it into a dataframe in R to do some analysis. What would be a good function to use to separate the data? Below is the top row of the dataset. Thanks!

TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan

Body:
You may use readLines and strsplit.

rw <- readLines("X:/foo.txt")
nice.df <- setNames(as.data.frame(do.call(rbind, strsplit(rw, "<SEP>"))),
                    c("Track.ID", "Song.ID", "Artist.Name", "Song.name"))
nice.df
#             Track.ID            Song.ID      Artist.Name   Song.name
# 1 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
# 2 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
# 3 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
# 4 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan

foo.txt content:

TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan


问:
When to use imputer1.fit(X.iloc[:, 0:3]) vs imputer.fit(X[:, 1:3]) 0
I'm new to coding and this might be a silly question. I'm using the data preprocessing tools approach to practice missing data imputing on multiple files. However, I'm not clear when to use X.iloc[] vs x[]

Both the below examples work but I have no idea why

Ex 1:

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
print (X)
</code>```

Ex 2:

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('datasets_596958_1073629_Placement_Data_Full_Class_edited3.csv')
X = dataset.iloc[:, :-1]
Y = dataset.iloc[:, -1]

from sklearn.impute import SimpleImputer
imputer1 = SimpleImputer(missing_values=np.NaN, strategy ="most_frequent")
imputer1.fit(X.iloc[:, 0:3])

X.iloc[:, 0:3]= imputer1.transform(X.iloc[:, 0:3])
imputer2 = SimpleImputer(missing_values=np.NaN, strategy ="mean")
imputer2.fit(X.iloc[:, 3:5])
X.iloc[:, 3:5]= imputer2.transform(X.iloc[:, 3:5])
</code>```

答: You would access a list using x[] and you would access a pandas dataframe using x.iloc[]. You may confirm the datatype by using the type() function in Python.

Body:
I'm new to coding and this might be a silly question. I'm using the data preprocessing tools approach to practice missing data imputing on multiple files. However, I'm not clear when to use X.iloc[] vs x[]

Both the below examples work but I have no idea why

Ex 1:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
print (X)

Ex 2:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('datasets_596958_1073629_Placement_Data_Full_Class_edited3.csv')
X = dataset.iloc[:, :-1]
Y = dataset.iloc[:, -1]

from sklearn.impute import SimpleImputer
imputer1 = SimpleImputer(missing_values=np.NaN, strategy ="most_frequent")
imputer1.fit(X.iloc[:, 0:3])

X.iloc[:, 0:3]= imputer1.transform(X.iloc[:, 0:3])
imputer2 = SimpleImputer(missing_values=np.NaN, strategy ="mean")
imputer2.fit(X.iloc[:, 3:5])
X.iloc[:, 3:5]= imputer2.transform(X.iloc[:, 3:5])


问:
How can I align my text/border to the center of my page with the
 element?

div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div1 style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div1>
</body></code>```

I'm trying to align both my border and text to the center of my page, but somethings not working. If I haven't explained it well enough please ask for more details :). Here is the code:

HTML

```<code><body>
  <div1 style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div1>
</body>
</code>```

CSS

```<code>div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }
</code>```

答:
Please modify div1 to div and check again.

See below codes:

div {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div>
</body></code>```

Title: How can I align my text/border to the center of my page with the <div> element?

Body:
div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }

  <div1 style="font-size: 30px; text-align: center;">
    Text here
  </div1>

I'm trying to align both my border and text to the center of my page, but somethings not working. If I haven't explained it well enough please ask for more details :). Here is the code:

HTML

  <div1 style="font-size: 30px; text-align: center;">
    Text here
  </div1>

CSS

div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }

Body:
Please modify div1 to div and check again.

See below codes:

div {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }

<body>
  <div style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div>
</body>


问:
.click event doesn't seem to fire
I've got the following code inside of a

答: Turned out to be a timing issue. My jQuery code was running before the  element was loaded on the page, due to where I placed them in relation to one another - hence the jQuery was trying to bind to an ID that didn't yet exist.</p>

Title: .click event doesn't seem to fire

Body: I've got the following code inside of a


问:
Django - Spotify API authorisation
I have developed a simple Django app, using Spotify API and Spotipy Authorisation (authorisation flow). This runs a localhost server where I click a simple button which creates a playlist in Spotify.

My issue however is in setting this up for an alternative user to login via their credentials and gain authorisation.

Atm, I have set this app up using a hardcoded cid and client secret within the views.py module (in the backend). This uses the following code to gain auth.

```<code>token = util.prompt_for_user_token(username, scope, client_id= cid, client_secret= secret, redirect_uri=r_uri)
</code>```

My index.html file then links a button to this script so that when clicked, the playlist is created. I expect this index.html needs to be updated to allow the user to login to their own spotify account and to authorise their token. However I am unsure on how to update this or if I am on the right track.

Alternatively, I think I may need to restart the project using java to gain authorisation for another user or using Implicit Grant Auth method, if spotipy authorisation cannot be used.

答:
I am not very familiar with Spottily API , but what i would try to do it to get the user id as describe below:

https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids

from the client to the server using Ajax ,and then in the client

use the the Playlist API:

https://developer.spotify.com/documentation/web-api/reference-beta/#category-playlists

Title: Django - Spotify API authorisation

Body:
I have developed a simple Django app, using Spotify API and Spotipy Authorisation (authorisation flow). This runs a localhost server where I click a simple button which creates a playlist in Spotify.

My issue however is in setting this up for an alternative user to login via their credentials and gain authorisation.

Atm, I have set this app up using a hardcoded cid and client secret within the views.py module (in the backend). This uses the following code to gain auth.

token = util.prompt_for_user_token(username, scope, client_id= cid, client_secret= secret, redirect_uri=r_uri)

My index.html file then links a button to this script so that when clicked, the playlist is created. I expect this index.html needs to be updated to allow the user to login to their own spotify account and to authorise their token. However I am unsure on how to update this or if I am on the right track.

Alternatively, I think I may need to restart the project using java to gain authorisation for another user or using Implicit Grant Auth method, if spotipy authorisation cannot be used.


问:
How to display lines with Chinese letters on DevC++?
What I want is to display a line with a Chinese letter, entered by the user. Though the program DevC++.

This is my code:

```<code>#define UNICODE
#include <iostream>
#include <string>
    using namespace std;
    extern wostream wcout;
int main(int argc, char** argv) {
    std::wstring kanji = L"?";
    //std::wchar_t stop = L"0";
    std::wcout << L"\n\nWelcome to the Chinese letter program\n";
    std::wcout << L"The program will ask you for one Chinese letter\n";
    std::wcout << L"Then press enter, and a message will display.\n";
    std::wcout << L"Once you are done,you can enter another Chinese letter\n";
    std::wcout << L"To exit just close the Ubuntu's terminal'\n\n";
        for(int x = 0; x < 80; x++){
            std::wcout << L"Give me one Chinese letter...";
                wcin >> kanji;
                std::wcout << L"The Chinese letter is \"" << kanji << "\".\n\n";
        }
    return 0;
}
</code>```

What matters to me is the "The Chinese letter is "(kanji)"." line. When I do what the program says I get "The Chinese letter is "?".". So the problem is that DevC++ doesn't show the Chinese letters correctly, even when I using the wcin and wcout things.

Note I am using DevC++ on Ubuntu, through wine.

答:
The problem was solved using html to complement what DevC++ cannot do, which is working with Chinese letters.

The c++ code ended up like this:

```<code>#include <iostream>
#include <string>
    using namespace std;
int main(int argc, char** argv) {
    string kanji = "?";
    int x2=0;
    int x3=1;
    std::cout << "\n\nWelcome to the Chinese letter program\n";
    std::cout << "This program will display a line or lines with Chinese letters\n";
    std::cout << "through a jury-rigged method.\n";
    std::cout << "This will generate an html code, that must be\n";
    std::cout << "transformed into an html file.\n";
    std::cout << "To exit just close the Ubuntu's terminal.\n";
    std::cout << "Note: the only catch is that it must be applied\n";
    std::cout << "a backspace where you gave enter into the html code.\n\n";

    std::cout << "\n\nHow many Chinese letters will be?";
    cin >> x2;

    std::cout << "\n\n<html>\n";
    std::cout << "<header><title>Chinese letters</title></header>\n";
    std::cout << "<body>\n";
        for(int x = 0; x < x2; x++){
            std::cout << "<!-- (Loop " << x3 << "/" << x2 << ") -->\n";
            std::cout << "The Chinese letter is \"";
            cin >> kanji;
            std::cout << "\".\n";
            std::cout << "<br><br>\n";
            x3++;
        }
    std::cout << "</body>\n";
    std::cout << "</html>\n";
    std::cout << "\n\n";
    system("pause");
    return 0;
}
</code>```

Which generates an html code that can display Chinese letters. For example like this:

```<code><html>
<header><title>Chinese letters</title></header>
<body>
<!-- (Loop 1/2) -->
The Chinese letter is "銀".
<br><br>
<!-- (Loop 2/2) -->
The Chinese letter is "囗".
<br><br>
</body>
</html>
</code>```

Ending with what was expected from the c++ program:

```<code>The Chinese letter is "銀".

The Chinese letter is "囗".
</code>```

Body:
What I want is to display a line with a Chinese letter, entered by the user. Though the program DevC++.

This is my code:

#define UNICODE
#include <iostream>
#include <string>
    using namespace std;
    extern wostream wcout;
int main(int argc, char** argv) {
    std::wstring kanji = L"?";
    //std::wchar_t stop = L"0";
    std::wcout << L"\n\nWelcome to the Chinese letter program\n";
    std::wcout << L"The program will ask you for one Chinese letter\n";
    std::wcout << L"Then press enter, and a message will display.\n";
    std::wcout << L"Once you are done,you can enter another Chinese letter\n";
    std::wcout << L"To exit just close the Ubuntu's terminal'\n\n";
        for(int x = 0; x < 80; x++){
            std::wcout << L"Give me one Chinese letter...";
                wcin >> kanji;
                std::wcout << L"The Chinese letter is \"" << kanji << "\".\n\n";
        }
    return 0;
}

What matters to me is the "The Chinese letter is "(kanji)"." line. When I do what the program says I get "The Chinese letter is "?".". So the problem is that DevC++ doesn't show the Chinese letters correctly, even when I using the wcin and wcout things.

Note I am using DevC++ on Ubuntu, through wine.

Body:
The problem was solved using html to complement what DevC++ cannot do, which is working with Chinese letters.

The c++ code ended up like this:

#include <iostream>
#include <string>
    using namespace std;
int main(int argc, char** argv) {
    string kanji = "?";
    int x2=0;
    int x3=1;
    std::cout << "\n\nWelcome to the Chinese letter program\n";
    std::cout << "This program will display a line or lines with Chinese letters\n";
    std::cout << "through a jury-rigged method.\n";
    std::cout << "This will generate an html code, that must be\n";
    std::cout << "transformed into an html file.\n";
    std::cout << "To exit just close the Ubuntu's terminal.\n";
    std::cout << "Note: the only catch is that it must be applied\n";
    std::cout << "a backspace where you gave enter into the html code.\n\n";

    std::cout << "\n\nHow many Chinese letters will be?";
    cin >> x2;

    std::cout << "\n\n<html>\n";
    std::cout << "<header><title>Chinese letters</title></header>\n";
    std::cout << "<body>\n";
        for(int x = 0; x < x2; x++){
            std::cout << "<!-- (Loop " << x3 << "/" << x2 << ") -->\n";
            std::cout << "The Chinese letter is \"";
            cin >> kanji;
            std::cout << "\".\n";
            std::cout << "<br><br>\n";
            x3++;
        }
    std::cout << "</body>\n";
    std::cout << "</html>\n";
    std::cout << "\n\n";
    system("pause");
    return 0;
}

Which generates an html code that can display Chinese letters. For example like this:

<html>
<header><title>Chinese letters</title></header>
<body>
<!-- (Loop 1/2) -->
The Chinese letter is "銀".
<br><br>
<!-- (Loop 2/2) -->
The Chinese letter is "囗".
<br><br>
</body>
</html>

Ending with what was expected from the c++ program:

The Chinese letter is "銀".

The Chinese letter is "囗".


答:
you need to set width to your body tag and horizontal margin to auto to you text
also change your div1 to div

```<code>body{
     width: 100vw;
}
div {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: auto 10px;
     width: fit-content;
 }
</code>```

Body:
you need to set width to your body tag and horizontal margin to auto to you text
also change your div1 to div

body{
     width: 100vw;
}
div {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: auto 10px;
     width: fit-content;
 }


答:
```<code>dict1 = {"AD":{(62,'VMX','Barcelona','ES'): ['123','567','666']}} #dict1  many more rows

dict2 = {"AD":{(151,'CMXS','','ES','62'): ['345','6754']}}       #dict 2 many more rows

# create a simplified map of dict2
dict3 = {}
for outer_key, outer_value_dict in dict2.items():
    for inner_key_tuple, inner_value_list in outer_value_dict.items():
        new_key = (outer_key, inner_key_tuple[4]) # e.g. (AD, 62)
        dict3.setdefault(new_key, []).extend(inner_value_list)

# now modify dict1 using dict3 instead of dict2
for outer_key, outer_value in dict1.items():
    for inner_key_tuple, inner_value_list in outer_value.items():
        lookup_key = (outer_key, str(inner_key_tuple[0]))
        # search dict3 using the lookup_key.
        # if not present, get will return an empty list
        list_to_extend = dict3.get(lookup_key, [])
        inner_value_list.extend(list_to_extend)

print(dict1)
</code>```

Output

```<code>/tmp $ python test.py.py
{'AD': {(62, 'VMX', 'Barcelona', 'ES'): ['123', '567', '666', '345', '6754']}}
</code>```

Based on the comments, since you wanted to know how to avoid one of the loops - here's an updated version

```<code>for k,v in dict1.items():
    a = dict2.get(k)
    if a is None or len(v) == 0:
        continue

    for k2,v2 in v.items():
        for c2,a2 in a.items():
            if str(k2[0]) == c2[4]:
                v2.append(a2)
</code>```

Title: iterate 2 dicts and compare values then append inner list

Body:
I am faced with a situation where I need to iterate nested dicts with same outermost keys, compare inner key value to inner key value of other dict then append. Below will help to understand:

{AD:{(62,'VMX','Barcelona','ES'): ['123','567','666'}} #dict1  many more rows

{AD:{(151,'CMXS','','ES','62'): ['345','6754']}}       #dict 2 many more rows

So I need to iterate both dicts, compare tuple key[0] of dict1 == tuple key[4] of dict2, if they match append inner list in dict1 with inner list in dict2.

after this dict1 looks like

{AD:{(62,'VMX','Barcelona','ES'): ['123','567','666','345','6754'}}

Wrote this code but it not working as expected

for k,v in dict1.items():
    if len(v)!= 0:
        for c,a in dict2.items():
            if len(a)!= 0:
                for k2,v2 in v.items():
                    for c2,a2 in a.items():
                        if str(k2[0]) == c2[4]:
                            v2.append(a2)

Body:
dict1 = {"AD":{(62,'VMX','Barcelona','ES'): ['123','567','666']}} #dict1  many more rows

dict2 = {"AD":{(151,'CMXS','','ES','62'): ['345','6754']}}       #dict 2 many more rows

# create a simplified map of dict2
dict3 = {}
for outer_key, outer_value_dict in dict2.items():
    for inner_key_tuple, inner_value_list in outer_value_dict.items():
        new_key = (outer_key, inner_key_tuple[4]) # e.g. (AD, 62)
        dict3.setdefault(new_key, []).extend(inner_value_list)

# now modify dict1 using dict3 instead of dict2
for outer_key, outer_value in dict1.items():
    for inner_key_tuple, inner_value_list in outer_value.items():
        lookup_key = (outer_key, str(inner_key_tuple[0]))
        # search dict3 using the lookup_key.
        # if not present, get will return an empty list
        list_to_extend = dict3.get(lookup_key, [])
        inner_value_list.extend(list_to_extend)

print(dict1)

Output

/tmp $ python test.py.py
{'AD': {(62, 'VMX', 'Barcelona', 'ES'): ['123', '567', '666', '345', '6754']}}

Based on the comments, since you wanted to know how to avoid one of the loops - here's an updated version

for k,v in dict1.items():
    a = dict2.get(k)
    if a is None or len(v) == 0:
        continue

    for k2,v2 in v.items():
        for c2,a2 in a.items():
            if str(k2[0]) == c2[4]:
                v2.append(a2)


问:
Binary Tree: summation of all nodes between a min and max value
I have an assignment where I am given the root of a randomly generated BST. I am given randomly generated test cases for this assignment.

The assignment description is the following:

You are given the root node of a binary search tree, T, and two
  integers: min, and max. Note that min and max are not necessarily stored in the
  tree. Determine the sum of all keys stored in T that are larger than or
  equal to min, and smaller than or equal to max. Implement your algorithm
  recursively

I am not allowed to have global variables or create helper functions

my current code is this:

```<code>private static int problem2(Node root, int min, int max){

 if(root = null){
    return 0;
 }

 if(root.key < min || root.key > max){
   int lft = problem2(root.left, min, max);
   int rgt = problem2(root.right, min, max);
   int sum = lft + rgt;
   return sum;
 }

}
</code>```

my issue is that if at any point during my recursion, the node trips the base case and causes my function to not complete itself properly.
I believe that my ordering may be to blame.

The node classed is defined as:

```<code>private static class Node
{
    public Node left = null;
    public Node right = null;

    public int key;

    public Node(int key)
    {
        this.key = key;
    }
}
</code>```

答:
Think about it this way: the moment you reach a node which isn't in the desired range, your algorithm stops. What happens if the root itself is out of range? You'll just return 0 right off the bat.
You need to fix your exit condition so that your recursion stops only when you've reached a null, since you can't know how many nodes that are within range of [min, max] are present in the sub-tree of the node you're currently in. Then, in the recursion itself, you should make the decision whether to add the current node to the overall sum or not.

Possible implementation - spoilers ahead, I suggest you only look after you've solved it yourself:

```<code>private static int problem2(Node root, int min, int max){

 if(root == null){
    return 0;
 }

 int sum = 0;
 // No point in keeping the recursion right/left if the current key is
 // larger/smaller than the desired range - usage of BST property:
 if (root.key <= max) {
    sum += problem2(root.right, min, max);
 }
 if (root.key >= min) {
    sum += problem2(root.left, min, max);
 }
 // If root is within range add it to sum:
 if (root.key <= max && root.key >= min){
    return root.key + sum;
 } else {
    return sum;
 }

}
</code>```

Explanation: each recursive call sums up the results of the left and right subtrees. The key of the node you're currently in is added to the calculation iff it is within the desired range of [min, max].

Body:
I have an assignment where I am given the root of a randomly generated BST. I am given randomly generated test cases for this assignment.

The assignment description is the following:

You are given the root node of a binary search tree, T, and two
  integers: min, and max. Note that min and max are not necessarily stored in the
  tree. Determine the sum of all keys stored in T that are larger than or
  equal to min, and smaller than or equal to max. Implement your algorithm
  recursively

I am not allowed to have global variables or create helper functions

my current code is this:

private static int problem2(Node root, int min, int max){

 if(root = null){
    return 0;
 }

 if(root.key < min || root.key > max){
   int lft = problem2(root.left, min, max);
   int rgt = problem2(root.right, min, max);
   int sum = lft + rgt;
   return sum;
 }

}

my issue is that if at any point during my recursion, the node trips the base case and causes my function to not complete itself properly.
I believe that my ordering may be to blame.

The node classed is defined as:

private static class Node
{
    public Node left = null;
    public Node right = null;

    public int key;

    public Node(int key)
    {
        this.key = key;
    }
}

Body:
Think about it this way: the moment you reach a node which isn't in the desired range, your algorithm stops. What happens if the root itself is out of range? You'll just return 0 right off the bat.
You need to fix your exit condition so that your recursion stops only when you've reached a null, since you can't know how many nodes that are within range of [min, max] are present in the sub-tree of the node you're currently in. Then, in the recursion itself, you should make the decision whether to add the current node to the overall sum or not.

Possible implementation - spoilers ahead, I suggest you only look after you've solved it yourself:

private static int problem2(Node root, int min, int max){

 if(root == null){
    return 0;
 }

 int sum = 0;
 // No point in keeping the recursion right/left if the current key is
 // larger/smaller than the desired range - usage of BST property:
 if (root.key <= max) {
    sum += problem2(root.right, min, max);
 }
 if (root.key >= min) {
    sum += problem2(root.left, min, max);
 }
 // If root is within range add it to sum:
 if (root.key <= max && root.key >= min){
    return root.key + sum;
 } else {
    return sum;
 }

}

Explanation: each recursive call sums up the results of the left and right subtrees. The key of the node you're currently in is added to the calculation iff it is within the desired range of [min, max].


问:
How to navigate from one page to another with Airtable.com reactjs
First to create helloword in airtable. I used the helloword code below from airtable.com sample which works fine as it displays hello world successfully.

```<code>import {
    initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';
import React, { Component } from 'react';

function HelloWorldBlock() {
    // YOUR CODE GOES HERE
    return <div>Hello world </div>;
}

initializeBlock(() => <HelloWorldBlock />);
</code>```

Now I want to implement page navigation hence I have 2 pages(home.js and access.js) linked to index.js
when I run the code via block run. it displays

this error in my airtable

```<code>Error: Objects are not valid as a React child (found: Error: [object Object]).
 If you meant to render a collection of children, use an array instead.
    in Error (created by Context.Consumer)
    in Route (created by HelloWorldBlock)
    in Switch (created by HelloWorldBlock)
    in div (created by HelloWorldBlock)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by HelloWorldBlock)
    in HelloWorldBlock
    in div (created by BlockWrapper)
    in Suspense (created by BlockWrapper)
    in BlockWrapper (created by ForwardRef)
    in ForwardRef
    throwOnInvalidObjectType@https://localhost:9000/__runFrame/bundle.js:59956:15
    reconcileChildFibers@https://localhost:9000/__runFrame/bundle.js:60856:31
</code>```

Here is the code for index.js

```<code>index.js

import {
    initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, NavLink} from 'react-router-dom';
import ReactDOM from 'react-dom';

import Home from './home';
import Access from './access';

function HelloWorldBlock() {
    // YOUR CODE GOES HERE
    //return <div>Hello world brother </div>;

    return (
<BrowserRouter>

<div>Hello world brother</div>

<div className="container">
<div className="heading">

  <div className="heading-right">

<NavLink to="/home">Home</NavLink>
<NavLink to="/access">Home</NavLink>

 </div>
</div>

 <Switch>
             <Route path="/home" component={Home} exact/>
            <Route path="/access" component={Access}/>

            <Route component={Error}/>
           </Switch>
        </div>
      </BrowserRouter>
);

}

initializeBlock(() => <HelloWorldBlock />);
</code>```

here is home.js

```<code>import {initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';

import React, { Component } from 'react'
import {NavLink} from 'react-router-dom';

export default class Home extends Component {
state = {

  }

componentDidMount() {}

render(){

    return (

      <div>

        <h1>
         Welcome to home page
        </h1>

      </div>

    )
  }

}

/*
function Home() {
    // YOUR CODE GOES HERE
    return <div>Hello welcome to home page </div>;
}

initializeBlock(() => <Home />);

*/
</code>```

here is access.js

```<code>import {initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';

import React, { Component } from 'react'
import {NavLink} from 'react-router-dom';

export default class Access extends Component {
state = {}
componentDidMount() {
}

render(){
return (
<div>
<h1>
hello welcome to Access Page
        </h1>
</div>

    )
  }

}

/*

function Access() {
    // YOUR CODE GOES HERE
    return <div>Welcome to Access Page</div>;
}

initializeBlock(() => <Access />);

*/
</code>```

答:
The problem was resolved using hashrouter instead of browser router so I replaced

```<code>import { BrowserRouter, Route, Switch, NavLink} from 'react-router-dom';
</code>```

with

```<code>import { Route,NavLink, HashRouter} from "react-router-dom";
</code>```

Also replace browserRouter element with HashRouter element Eg.

```<code><BrowserRouter>

<div>Hello world brother</div>

<div className="container">
<div className="heading">

  <div className="heading-right">

<NavLink to="/home">Home</NavLink>
<NavLink to="/access">Home</NavLink>

 </div>
</div>

 <Switch>
             <Route path="/home" component={Home} exact/>
            <Route path="/access" component={Access}/>

            <Route component={Error}/>
           </Switch>
        </div>
      </BrowserRouter>
</code>```

with

```<code><HashRouter>Route goes here....
</HashRouter>
</code>```

Body:
First to create helloword in airtable. I used the helloword code below from airtable.com sample which works fine as it displays hello world successfully.

import {
    initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';
import React, { Component } from 'react';

function HelloWorldBlock() {
    // YOUR CODE GOES HERE
    return
Hello world
;
}

initializeBlock(() => <HelloWorldBlock />);

Now I want to implement page navigation hence I have 2 pages(home.js and access.js) linked to index.js
when I run the code via block run. it displays

this error in my airtable

Error: Objects are not valid as a React child (found: Error: [object Object]).
 If you meant to render a collection of children, use an array instead.
    in Error (created by Context.Consumer)
    in Route (created by HelloWorldBlock)
    in Switch (created by HelloWorldBlock)
    in div (created by HelloWorldBlock)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by HelloWorldBlock)
    in HelloWorldBlock
    in div (created by BlockWrapper)
    in Suspense (created by BlockWrapper)
    in BlockWrapper (created by ForwardRef)
    in ForwardRef
    throwOnInvalidObjectType@https://localhost:9000/__runFrame/bundle.js:59956:15
    reconcileChildFibers@https://localhost:9000/__runFrame/bundle.js:60856:31

Here is the code for index.js

index.js

import {
    initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, NavLink} from 'react-router-dom';
import ReactDOM from 'react-dom';

import Home from './home';
import Access from './access';

function HelloWorldBlock() {
    // YOUR CODE GOES HERE
    //return
Hello world brother
;

    return (
<BrowserRouter>

Hello world brother

<NavLink to="/home">Home</NavLink>
<NavLink to="/access">Home</NavLink>

 <Switch>
             <Route path="/home" component={Home} exact/>
            <Route path="/access" component={Access}/>

            <Route component={Error}/>
           </Switch>

      </BrowserRouter>
);

}

initializeBlock(() => <HelloWorldBlock />);

here is home.js

import {initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';

import React, { Component } from 'react'
import {NavLink} from 'react-router-dom';

export default class Home extends Component {
state = {

  }

componentDidMount() {}

render(){

    return (

         Welcome to home page

    )
  }

}

/*
function Home() {
    // YOUR CODE GOES HERE
    return
Hello welcome to home page
;
}

initializeBlock(() => <Home />);

*/

here is access.js

import {initializeBlock,
    useBase,
    useRecords,
} from '@airtable/blocks/ui';

import React, { Component } from 'react'
import {NavLink} from 'react-router-dom';

export default class Access extends Component {
state = {}
componentDidMount() {
}

render(){
return (

hello welcome to Access Page

    )
  }

}

/*

function Access() {
    // YOUR CODE GOES HERE
    return
Welcome to Access Page
;
}

initializeBlock(() => <Access />);

*/

Body:
The problem was resolved using hashrouter instead of browser router so I replaced

import { BrowserRouter, Route, Switch, NavLink} from 'react-router-dom';

with

import { Route,NavLink, HashRouter} from "react-router-dom";

Also replace browserRouter element with HashRouter element Eg.

<BrowserRouter>

<div>Hello world brother</div>

<div className="container">
<div className="heading">

  <div className="heading-right">

<NavLink to="/home">Home</NavLink>
<NavLink to="/access">Home</NavLink>

 </div>
</div>

 <Switch>
             <Route path="/home" component={Home} exact/>
            <Route path="/access" component={Access}/>

            <Route component={Error}/>
           </Switch>
        </div>
      </BrowserRouter>

with

<HashRouter>Route goes here....
</HashRouter>


问:
I get a Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
The Error

Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in C:\xampp\htdocs\login\checklogin.php on line 11

Code

```<code>isset(md5($_POST['password'])) ? $password = $_POST['password'] : $password = '';
</code>```

Thank you for your help

答:
It is giving you the error because you are using a function inside of isset()

You should use it this way -

```<code>$password = isset($_POST['password'])) ? md5( $_POST['password'] ) : '';
</code>```

In ternary operator, it returns the value according to the condition true or false

Body:
The Error

Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in C:\xampp\htdocs\login\checklogin.php on line 11

Code

isset(md5($_POST['password'])) ? $password = $_POST['password'] : $password = '';

Thank you for your help

Body:
It is giving you the error because you are using a function inside of isset()

You should use it this way -

$password = isset($_POST['password'])) ? md5( $_POST['password'] ) : '';

In ternary operator, it returns the value according to the condition true or false


问:
I need to filter all the userGroups from this JSON
TaskProperty.InternalAppConfiguration defines a JSON with various information and I need to get all the userGroups from this JSON. I only need names of the userGroups.

```<code>                    // saving task properties
                    foreach (var TaskProperty in representation.TaskProperties != null ? representation.TaskProperties : new List<TaskProperty>())
                    {
                        await this.taskRepository.AddTaskPropertyAsync(new TaskProperty()
                        {
                            ConnectionId = TaskProperty.ConnectionId,
                            NodeId = result.VertexIdPairs[Convert.ToInt16(TaskProperty.NodeId)],
                            TaskId = TaskProperty.TaskId,
                            InternalAppConfiguration = TaskProperty.InternalAppConfiguration,
                            IsApprovalTask = TaskProperty.IsApprovalTask
                        });
                    };
</code>```

my JSON is looks like this,

in JSON visualizer it looks like this

how can I store all the userGroups into a single array or a list or something I can use in the future?
I've tried to deserialize using Newtonsoft, but I was unable to do anything. please help me out.. I really appreciate your answers and suggesions. Thank you!

答:
Using Newtonsoft, this is what I would do:</p>

```<code>    public static IEnumerable<string> GetNamesFromJson(string json)
    {
        InternalAppConfiguration jsonObject = JsonConvert.DeserializeObject<InternalAppConfiguration>(json);
        return jsonObject.OptionsData.UserGroups.Select(ug => ug.DisplayName);
    }

    public class InternalAppConfiguration
    {
        public OptionsData OptionsData { get; set; }
    }

    public class OptionsData
    {
        public List<UserGroup> UserGroups { get; set; }
    }

    public class UserGroup
    {
        public string DisplayName { get; set; }
    }
</code>```

Body:
TaskProperty.InternalAppConfiguration defines a JSON with various information and I need to get all the userGroups from this JSON. I only need names of the userGroups.

                    // saving task properties
                    foreach (var TaskProperty in representation.TaskProperties != null ? representation.TaskProperties : new List<TaskProperty>())
                    {
                        await this.taskRepository.AddTaskPropertyAsync(new TaskProperty()
                        {
                            ConnectionId = TaskProperty.ConnectionId,
                            NodeId = result.VertexIdPairs[Convert.ToInt16(TaskProperty.NodeId)],
                            TaskId = TaskProperty.TaskId,
                            InternalAppConfiguration = TaskProperty.InternalAppConfiguration,
                            IsApprovalTask = TaskProperty.IsApprovalTask
                        });
                    };

my JSON is looks like this,

in JSON visualizer it looks like this

how can I store all the userGroups into a single array or a list or something I can use in the future?
I've tried to deserialize using Newtonsoft, but I was unable to do anything. please help me out.. I really appreciate your answers and suggesions. Thank you!

Body:
Using Newtonsoft, this is what I would do:

    public static IEnumerable<string> GetNamesFromJson(string json)
    {
        InternalAppConfiguration jsonObject = JsonConvert.DeserializeObject<InternalAppConfiguration>(json);
        return jsonObject.OptionsData.UserGroups.Select(ug => ug.DisplayName);
    }

    public class InternalAppConfiguration
    {
        public OptionsData OptionsData { get; set; }
    }

    public class OptionsData
    {
        public List<UserGroup> UserGroups { get; set; }
    }

    public class UserGroup
    {
        public string DisplayName { get; set; }
    }


问:
Is there a way to make XCode's "Show Invisibles" any less typographically eyeball-assaulting?
I mean, it appears to offer control over this -- but (at least as per my personal, fairly exhaustive investigation) it's Potemkin UX:

... the "Invisibles" color field doesn't actually affect the invisibles (which is that a joke? Like it controls the color of something else which is actually invisible??); the color field that does will not do so without simultaneously lending the tint you ascribe to it to the entirety of the rest of the documents' unhighlighted text.

I'm patient and flexible enough to either deal a text editors' quirks and I am nerdy enough to hack through said quirks when my patience and flexibility are depleted -- I have a haunted museum of 1990s-era elisp snippets and X configuration dotfiles that speak to this -- but I find these dysfunctionally Klein-bottlesque options flummoxing. Can you help me?

答:
It's working now. You can set a lighter color for Invisibles color for light theme.

In my Xcode 11, I can set Invisibles color from Preferences -> Fonts & Colors -> Source Editor. There are some configurable items.

The code looks perfect now.


问:
How to wait until cloud kit data is being synced with core data in swift in iOS13
I developed core data based app and implemented iCloud sync feature after it was introduced in iOS 13.

I enabled iCloud kit, used NSPersistentCloudKitContainer instead of NSPersistentContainer and added several lines of code to sync core data with iCloud.

Sync works fine. The problem is that when I uninstall app and reinstall app, it doesn't fetch iCloud data at first time.
I have to restart app or open another screens to let Core Data to be synced with iCloud.
Is there anyway I can check if core data is being synced with iCloud or wait until it finishes syncing?

Thanks.

答:
There is no API exposed to get the completion handler on sync of all
  CKRecord's to NSManagedObject's.

Also the update is working using a background silent notification so we can expect any change anytime. So its good to not having completion handler

What's next

You can create one attribute to check the sync time, just like a date when last sync happened to local record and check the lastModificationDate (By default CKRecord has this property) of the same record in iCloud.

So everytime when you launch the app check for all the records manually if any update is required, then wait for notification of update and keep on checking the sync status

Note: Be careful this may lead to delay your launch process if from any other device user is very active and new records are getting inserted or modified.


问:
GeneratedPluginRegistrant don't can not be applied - Flutter
When I build my Flutter app, this error shows:

error: incompatible types: MainActivity cannot be converted to FlutterEngine GeneratedPluginRegistrant.registerWith(this);

I went to the github of class and saw the difference: https://github.com/theyakka/fluro/blob/master/example/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java

If I put this in my project, when I build application, my class change automatically for this:

```<code>package io.flutter.plugins;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.FlutterEngine;

/**
 * Generated file. Do not edit.
 * This file is generated by the Flutter tool based on the
 * plugins that support the Android platform.
 */
@Keep
public final class GeneratedPluginRegistrant {
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
  }
}
</code>```

I follow this tutorial:https://www.youtube.com/watch?v=NXuAzXY_KOo

I need to run my app in background to get the current location, but don't works.

答:
You need import the plugin,

import io.flutter.plugin.common.PluginRegistry;

and extend your class with FlutterActivity.

Body:
When I build my Flutter app, this error shows:

error: incompatible types: MainActivity cannot be converted to FlutterEngine GeneratedPluginRegistrant.registerWith(this);

I went to the github of class and saw the difference: https://github.com/theyakka/fluro/blob/master/example/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java

If I put this in my project, when I build application, my class change automatically for this:

package io.flutter.plugins;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.FlutterEngine;

/**
 * Generated file. Do not edit.
 * This file is generated by the Flutter tool based on the
 * plugins that support the Android platform.
 */
@Keep
public final class GeneratedPluginRegistrant {
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
  }
}

I follow this tutorial:https://www.youtube.com/watch?v=NXuAzXY_KOo

I need to run my app in background to get the current location, but don't works.


问:
LinkedIn API OAuth2.0 authorization scopes
I'm trying to set up an examplary ASP.Net Core MVC project to use the LinkedIn API. As this is just for testing purposes, I've created a private company and registered and verified the app.
In accordance to the Microsoft guidelines here: https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context, I'm using the 3 leggeds authentication with MVC.
The redirect seems to work, but I always receive an error:

Exception: unauthorized_scope_error;Description=Scope
  "r_basicprofile" is not authorized for your application

This error appears with all scopes I've found. Unfortunately, the information I find hereby are not clear.

In the examples like http://www.codedigest.com/posts/17/use-linkedin-login-for-authentication-in-aspnet-mvc-50---oauth-20, I can see usually screenshots, which allow to self-register scopes. This isn't possible anymore.

I found this question on SO How can I change a LinkedIn app's permissions?, but this seems to be mostly concerned about campaign scopes, not just basic ones.

Interesting is also this article: https://learn.microsoft.com/en-us/linkedin/shared/references/migrations/default-scopes-migration I'm understanding the information, that I don't need to configure default scopes anymore, but this seems to be the opposite of the error message?

Edit: Here a screenshot of the app on the LinkedIn developer page:

答: you need to go to your app settings page on linkedin and check for what permissions you have, then we can know what is the problem </p>


问:
C++ While statement not working with string and "or"
I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always runs the if not the else. I feel it has something to do with it being a string, so I tested it without the or "||" and it worked. So maybe it has to do with combining strings and or statements. So did research on using these together and could not find much. Thanks for the help.  </p>

```<code>int main()
{
    int year;
    int day = 0;
    string month = "x";

    do
    {
        if (day == 0)
        {
            cout << "hello" << endl;
            cout << "Please Enter your B-Day as Day, Month, Year" << endl;
            cout << "day" << endl;
            cin >> day;
        }
        else
        {
            cout << "Please enter a correct day" << endl;
            cin >> day;
        }

    } while (day > 31 || day < 1);

    do
    {
        if (month == "x")
        {
            cout << "Please enter the month you were born" << endl;
            cin >> month;
        }
        else
        {
            cout << "Please Enter a correct Month." << endl;
            cin >> month;
        }
    }
    **while (month != "june" || month != "july");**

    return 0;
}
</code>```

答:
```<code>while (month != "june" || month != "july");
</code>```

There is something called short-circuit evaluation in C++ which will in this case will not evaluate the right of || if the first operand returns true. Likewise for &&, it will not evaluate right operand if first is false. So be sure how you want the logic to behave and write the code.

Body:
I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always runs the if not the else. I feel it has something to do with it being a string, so I tested it without the or "||" and it worked. So maybe it has to do with combining strings and or statements. So did research on using these together and could not find much. Thanks for the help.

int main()
{
    int year;
    int day = 0;
    string month = "x";

    do
    {
        if (day == 0)
        {
            cout << "hello" << endl;
            cout << "Please Enter your B-Day as Day, Month, Year" << endl;
            cout << "day" << endl;
            cin >> day;
        }
        else
        {
            cout << "Please enter a correct day" << endl;
            cin >> day;
        }

    } while (day > 31 || day < 1);

    do
    {
        if (month == "x")
        {
            cout << "Please enter the month you were born" << endl;
            cin >> month;
        }
        else
        {
            cout << "Please Enter a correct Month." << endl;
            cin >> month;
        }
    }
    **while (month != "june" || month != "july");**

    return 0;
}

Body:
while (month != "june" || month != "july");

There is something called short-circuit evaluation in C++ which will in this case will not evaluate the right of || if the first operand returns true. Likewise for &&, it will not evaluate right operand if first is false. So be sure how you want the logic to behave and write the code.


问:
ResourceAccessException: I/O error on POST request
I have a service method. The method is accessing a third-party resource through a POST request. I am writing a test and I see an error in the logs.
Service:

```<code>@Override
public void sendDoc(String id) throws IOException {
    byte[] zipData = getZipFromIntegration(mongo.getDocument());

    String response;
    HttpStatus httpStatus;
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("file", new MultipartInputStreamFileResource(new ByteArrayInputStream(zipData),
                String.format("%s_some.zip", id)));

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(3000);
        clientHttpRequestFactory.setReadTimeout(3000);
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

        response = restTemplate.postForObject(uploadUrl + system,
                requestEntity, String.class);

    } catch (HttpStatusCodeException e) {
        LOG.error("Some error");
    }
}
</code>```

My Test

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = NONE, classes = {SendServiceImpl.class})
@EnableAutoConfiguration
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
public class SendServiceImplTest {
    @MockBean
    private RestTemplate restTemplate;
    @Autowired
    private SendServiceImpl service;

    @Test
    public void sendDoc() throws IOException {
        when(restTemplate.postForObject(
                anyString(),
                ArgumentMatchers.<HttpEntity<?>>any(),
                ArgumentMatchers.<Class<String>>any()
        ))
                .thenReturn("ok");

        service.sendDoc("55454545uid");
    }
}
</code>```

But I see that there is a call to the real server. The test is successful, but in the logs I see an error:

org.springframework.web.client.ResourceAccessException: I/O error on
  POST request for "http://some-url.digital.cloud.ru/v1/doc/reg"

UPD:
Changed the test like this:

```<code>@RunWith(PowerMockRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SendServiceImpl.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({SendServiceImpl.class, RestTemplate.class})
@PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"})
public class SendServiceImplTest {
    @MockBean
    private RestTemplate restTemplateMock;

    @Autowired
    private SendServiceImpl service;

    @Test
    public void sendDoc() throws IOException {
    RestTemplate restTemplate = PowerMockito.mock(RestTemplate.class);
    whenNew(RestTemplate.class).withArguments(ClientHttpRequestFactory.class).thenReturn(restTemplate);
    when(restTemplate.postForObject(
                anyString(),
                ArgumentMatchers.<HttpEntity<?>>any(),
                ArgumentMatchers.<Class<String>>any()
        ))
                .thenReturn("ok");

        service.sendDoc("55454545uid");
    }
}
</code>```

Now the object is replaced by null. That is, restTemplate in the service is null.

答:
The solution to my problem looks like this:

```<code>@RunWith(PowerMockRunner.class)
@SpringBootTest(webEnvironment = NONE, classes = SendServiceImpl.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({
        SendServiceImpl.class,
        RestTemplate.class,
        HttpComponentsClientHttpRequestFactory.class
})
@MockBean({FileStorageService.class, DocxToPdfConverterService.class})
@PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"})
public class SendServiceImplTest {
    @Test
    public void sendDoc() throws Exception {
        RestTemplate restTemplate = Mockito.mock(RestTemplate.class);

        whenNew(RestTemplate.class).withAnyArguments().thenReturn(restTemplate);

        PowerMockito.when(restTemplate.postForObject(
                anyString(),
                ArgumentMatchers.<HttpEntity<?>>any(),
                ArgumentMatchers.<Class<String>>any()
        )).thenReturn("ok");
    }
// ......any code.......
}
</code>```

The PowerMock library and the withAnyArguments () method helped me.

Body:
I have a service method. The method is accessing a third-party resource through a POST request. I am writing a test and I see an error in the logs.
Service:

@Override
public void sendDoc(String id) throws IOException {
    byte[] zipData = getZipFromIntegration(mongo.getDocument());

    String response;
    HttpStatus httpStatus;
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("file", new MultipartInputStreamFileResource(new ByteArrayInputStream(zipData),
                String.format("%s_some.zip", id)));

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(3000);
        clientHttpRequestFactory.setReadTimeout(3000);
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

        response = restTemplate.postForObject(uploadUrl + system,
                requestEntity, String.class);

    } catch (HttpStatusCodeException e) {
        LOG.error("Some error");
    }
}

My Test

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = NONE, classes = {SendServiceImpl.class})
@EnableAutoConfiguration
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
public class SendServiceImplTest {
    @MockBean
    private RestTemplate restTemplate;
    @Autowired
    private SendServiceImpl service;

    @Test
    public void sendDoc() throws IOException {
        when(restTemplate.postForObject(
                anyString(),
                ArgumentMatchers.<HttpEntity<?>>any(),
                ArgumentMatchers.<Class<String>>any()
        ))
                .thenReturn("ok");

        service.sendDoc("55454545uid");
    }
}

But I see that there is a call to the real server. The test is successful, but in the logs I see an error:

org.springframework.web.client.ResourceAccessException: I/O error on
  POST request for "http://some-url.digital.cloud.ru/v1/doc/reg"

UPD:
Changed the test like this:

@RunWith(PowerMockRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SendServiceImpl.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({SendServiceImpl.class, RestTemplate.class})
@PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"})
public class SendServiceImplTest {
    @MockBean
    private RestTemplate restTemplateMock;

    @Autowired
    private SendServiceImpl service;

    @Test
    public void sendDoc() throws IOException {
    RestTemplate restTemplate = PowerMockito.mock(RestTemplate.class);
    whenNew(RestTemplate.class).withArguments(ClientHttpRequestFactory.class).thenReturn(restTemplate);
    when(restTemplate.postForObject(
                anyString(),
                ArgumentMatchers.<HttpEntity<?>>any(),
                ArgumentMatchers.<Class<String>>any()
        ))
                .thenReturn("ok");

        service.sendDoc("55454545uid");
    }
}

Now the object is replaced by null. That is, restTemplate in the service is null.

Body:
The solution to my problem looks like this:

@RunWith(PowerMockRunner.class)
@SpringBootTest(webEnvironment = NONE, classes = SendServiceImpl.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({
        SendServiceImpl.class,
        RestTemplate.class,
        HttpComponentsClientHttpRequestFactory.class
})
@MockBean({FileStorageService.class, DocxToPdfConverterService.class})
@PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"})
public class SendServiceImplTest {
    @Test
    public void sendDoc() throws Exception {
        RestTemplate restTemplate = Mockito.mock(RestTemplate.class);

        whenNew(RestTemplate.class).withAnyArguments().thenReturn(restTemplate);

        PowerMockito.when(restTemplate.postForObject(
                anyString(),
                ArgumentMatchers.<HttpEntity<?>>any(),
                ArgumentMatchers.<Class<String>>any()
        )).thenReturn("ok");
    }
// ......any code.......
}

The PowerMock library and the withAnyArguments () method helped me.


问:
Django - How to combine two queries after doing a group by
GOAL: Group by ITEM all INCOMING and its OUTGOING then SUM the quantity to come up with a simple table in my template like this:

```<code>Item        | Total In | Total Out| Stock
1. Cement   | 400      | 300      | 100
</code>```

My models.py

```<code>class Incoming(models.Model):
    ...
    project_site = models.ForeignKey(ProjectSite, related_name='in_project_site', default=7, null=True, on_delete = models.SET_NULL)
    item = models.ForeignKey(Item, related_name='item_in', null=True, on_delete = models.SET_NULL)
    quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0)
    ...

class Outgoing(models.Model):
    ...
    base_in = models.ForeignKey('warehouse.Incoming', related_name='out', on_delete = models.SET_NULL, null=True)
    quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0)
    ...
</code>```

Okay so the goal is to group all incoming by ITEM, then annotate the current total Incoming and Outgoing. So naturally I did this in my views.py

```<code> incoming = Incoming.objects.filter(project_site__id=self.object.id)

 context['inventory'] =  incoming.values('item__item_name')\
    .annotate(tot_in=Sum('quantity'))\
    .annotate(tot_out=Sum('out__quantity'))
</code>```

This does not give the proper SUM for the total_in, now after some search this is apparently an issue. One suggestion I found was to separate the query into to so this is what I did.

```<code>context['current_in'] =  incoming.values('item__item_name').annotate(tot_in=Sum('quantity'))
context['current_out'] =  incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity'))
</code>```

This gives me the correct SUM for each In and Out, now my problem is how to UNITE/COMBINE the two again so I could easily loop through it on my template? I did a search and tried the following to no luck.

```<code>list(chain(pagelist1, pagelist2))
# This does not combine items with same ITEM name. The output for this is
Item        | Total In | Total Out| Stock
Cement      | 400      |          |
Cement      |          | 300      |
</code>```

doing a UNION doesn't help either. Any help would do.

答:
How about this:

```<code>incoming.values('item__item_name').annotate(tot_in=Sum('quantity'), tot_out=Sum('out__quantity'))
</code>```

If it does not work then but you can use pythonic approach here using zip_longest:

```<code>from itertools import zip_longest

current_in = incoming.values('item__item_name').annotate(tot_in=Sum('quantity'))
current_out = incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity'))
context['current'] = [{**u, **v} for u, v in zip_longest(current_in, current_out, fillvalue={})]
</code>```

Body:
GOAL: Group by ITEM all INCOMING and its OUTGOING then SUM the quantity to come up with a simple table in my template like this:

Item        | Total In | Total Out| Stock
1. Cement   | 400      | 300      | 100

My models.py

class Incoming(models.Model):
    ...
    project_site = models.ForeignKey(ProjectSite, related_name='in_project_site', default=7, null=True, on_delete = models.SET_NULL)
    item = models.ForeignKey(Item, related_name='item_in', null=True, on_delete = models.SET_NULL)
    quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0)
    ...

class Outgoing(models.Model):
    ...
    base_in = models.ForeignKey('warehouse.Incoming', related_name='out', on_delete = models.SET_NULL, null=True)
    quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0)
    ...

Okay so the goal is to group all incoming by ITEM, then annotate the current total Incoming and Outgoing. So naturally I did this in my views.py

 incoming = Incoming.objects.filter(project_site__id=self.object.id)

 context['inventory'] =  incoming.values('item__item_name')\
    .annotate(tot_in=Sum('quantity'))\
    .annotate(tot_out=Sum('out__quantity'))

This does not give the proper SUM for the total_in, now after some search this is apparently an issue. One suggestion I found was to separate the query into to so this is what I did.

context['current_in'] =  incoming.values('item__item_name').annotate(tot_in=Sum('quantity'))
context['current_out'] =  incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity'))

This gives me the correct SUM for each In and Out, now my problem is how to UNITE/COMBINE the two again so I could easily loop through it on my template? I did a search and tried the following to no luck.

list(chain(pagelist1, pagelist2))
# This does not combine items with same ITEM name. The output for this is
Item        | Total In | Total Out| Stock
Cement      | 400      |          |
Cement      |          | 300      |

doing a UNION doesn't help either. Any help would do.

Body:
How about this:

incoming.values('item__item_name').annotate(tot_in=Sum('quantity'), tot_out=Sum('out__quantity'))

If it does not work then but you can use pythonic approach here using zip_longest:

from itertools import zip_longest

current_in = incoming.values('item__item_name').annotate(tot_in=Sum('quantity'))
current_out = incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity'))
context['current'] = [{**u, **v} for u, v in zip_longest(current_in, current_out, fillvalue={})]


问:
How to quietly remove a directory with content in PowerShell
Using PowerShell, is it possible to remove some directory that contains files without prompting to confirm action?</p>

答:
This worked for me:</p>

```<code>Remove-Item C:\folder_name -Force -Recurse
</code>```

Body:
This worked for me:

Remove-Item C:\folder_name -Force -Recurse


问:
Speed up "NOT EXISTS" database query
I have the following Postgres query generated by SQLAlchemy. The goal is to get submissions related to grading assignments and that are part of 3 of our courses (=programs), but only those that have not been reviewed already.

```<code>SELECT
    submissions.* # edited for brevity
FROM
    submissions
JOIN
    assignments ON assignments.id = submissions.assignment_id
JOIN
    modules ON modules.id = assignments.module_id
WHERE
    assignments.team IN ('grading') AND
    modules.program_id IN (11, 106, 108) AND
    submissions.gets_review IS true AND
    NOT (
        EXISTS (
            SELECT 1
            FROM reviews
            WHERE submissions.id = reviews.submission_id
        )
    )
ORDER BY submissions.created_at asc
LIMIT 15
OFFSET 0
</code>```

Which generates this query plan:

```<code>                                                                            QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=16964.33..16966.08 rows=15 width=167) (actual time=173.618..173.623 rows=3 loops=1)
   ->  Gather Merge  (cost=16964.33..17015.43 rows=438 width=167) (actual time=173.616..173.672 rows=3 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         ->  Sort  (cost=15964.30..15964.85 rows=219 width=167) (actual time=166.425..166.426 rows=1 loops=3)
               Sort Key: submissions.created_at
               Sort Method: quicksort  Memory: 25kB
               Worker 0:  Sort Method: quicksort  Memory: 25kB
               Worker 1:  Sort Method: quicksort  Memory: 25kB
               ->  Nested Loop Anti Join  (cost=356.11..15958.93 rows=219 width=167) (actual time=166.358..166.402 rows=1 loops=3)
                     ->  Hash Join  (cost=355.68..8645.36 rows=7373 width=167) (actual time=12.691..152.481 rows=1545 loops=3)
                           Hash Cond: (submissions.assignment_id = assignments.id)
                           ->  Parallel Seq Scan on submissions  (cost=0.00..7976.62 rows=63809 width=167) (actual time=0.008..101.093 rows=50787 loops=3)
                                 Filter: (gets_review IS TRUE)
                                 Rows Removed by Filter: 93127
                           ->  Hash  (cost=346.16..346.16 rows=762 width=4) (actual time=12.585..12.585 rows=675 loops=3)
                                 Buckets: 1024  Batches: 1  Memory Usage: 32kB
                                 ->  Hash Join  (cost=44.69..346.16 rows=762 width=4) (actual time=0.318..12.372 rows=675 loops=3)
                                       Hash Cond: (assignments.module_id = modules.id)
                                       ->  Seq Scan on assignments  (cost=0.00..285.39 rows=6099 width=8) (actual time=0.010..4.978 rows=6099 loops=3)
                                             Filter: (team = 'grading'::teams)
                                             Rows Removed by Filter: 492
                                       ->  Hash  (cost=43.09..43.09 rows=128 width=4) (actual time=0.225..0.226 rows=128 loops=3)
                                             Buckets: 1024  Batches: 1  Memory Usage: 13kB
                                             ->  Seq Scan on modules  (cost=0.00..43.09 rows=128 width=4) (actual time=0.010..0.182 rows=128 loops=3)
                                                   Filter: (program_id = ANY ('{11,106,108}'::integer[]))
                                                   Rows Removed by Filter: 897
                     ->  Index Only Scan using ix_reviews_submission_id on reviews  (cost=0.42..1.00 rows=1 width=4) (actual time=0.008..0.008 rows=1 loops=4636)
                           Index Cond: (submission_id = submissions.id)
                           Heap Fetches: 4633
 Planning Time: 0.763 ms
 Execution Time: 173.760 ms
</code>```

I might be over-optimizing, but 174ms seems too slow.
We have all the basic indexes plus a couple we created manually.

How could I speed up this query?

答:
try creating partial index on submissions table.</p>

```<code>CREATE INDEX ix_assignment_id_created_at ON submissions (assignment_id, created_at)
WHERE (gets_review IS true);
</code>```

Title: Speed up "NOT EXISTS" database query

Body:
I have the following Postgres query generated by SQLAlchemy. The goal is to get submissions related to grading assignments and that are part of 3 of our courses (=programs), but only those that have not been reviewed already.

SELECT
    submissions.* # edited for brevity
FROM
    submissions
JOIN
    assignments ON assignments.id = submissions.assignment_id
JOIN
    modules ON modules.id = assignments.module_id
WHERE
    assignments.team IN ('grading') AND
    modules.program_id IN (11, 106, 108) AND
    submissions.gets_review IS true AND
    NOT (
        EXISTS (
            SELECT 1
            FROM reviews
            WHERE submissions.id = reviews.submission_id
        )
    )
ORDER BY submissions.created_at asc
LIMIT 15
OFFSET 0

Which generates this query plan:

                                                                            QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=16964.33..16966.08 rows=15 width=167) (actual time=173.618..173.623 rows=3 loops=1)
   ->  Gather Merge  (cost=16964.33..17015.43 rows=438 width=167) (actual time=173.616..173.672 rows=3 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         ->  Sort  (cost=15964.30..15964.85 rows=219 width=167) (actual time=166.425..166.426 rows=1 loops=3)
               Sort Key: submissions.created_at
               Sort Method: quicksort  Memory: 25kB
               Worker 0:  Sort Method: quicksort  Memory: 25kB
               Worker 1:  Sort Method: quicksort  Memory: 25kB
               ->  Nested Loop Anti Join  (cost=356.11..15958.93 rows=219 width=167) (actual time=166.358..166.402 rows=1 loops=3)
                     ->  Hash Join  (cost=355.68..8645.36 rows=7373 width=167) (actual time=12.691..152.481 rows=1545 loops=3)
                           Hash Cond: (submissions.assignment_id = assignments.id)
                           ->  Parallel Seq Scan on submissions  (cost=0.00..7976.62 rows=63809 width=167) (actual time=0.008..101.093 rows=50787 loops=3)
                                 Filter: (gets_review IS TRUE)
                                 Rows Removed by Filter: 93127
                           ->  Hash  (cost=346.16..346.16 rows=762 width=4) (actual time=12.585..12.585 rows=675 loops=3)
                                 Buckets: 1024  Batches: 1  Memory Usage: 32kB
                                 ->  Hash Join  (cost=44.69..346.16 rows=762 width=4) (actual time=0.318..12.372 rows=675 loops=3)
                                       Hash Cond: (assignments.module_id = modules.id)
                                       ->  Seq Scan on assignments  (cost=0.00..285.39 rows=6099 width=8) (actual time=0.010..4.978 rows=6099 loops=3)
                                             Filter: (team = 'grading'::teams)
                                             Rows Removed by Filter: 492
                                       ->  Hash  (cost=43.09..43.09 rows=128 width=4) (actual time=0.225..0.226 rows=128 loops=3)
                                             Buckets: 1024  Batches: 1  Memory Usage: 13kB
                                             ->  Seq Scan on modules  (cost=0.00..43.09 rows=128 width=4) (actual time=0.010..0.182 rows=128 loops=3)
                                                   Filter: (program_id = ANY ('{11,106,108}'::integer[]))
                                                   Rows Removed by Filter: 897
                     ->  Index Only Scan using ix_reviews_submission_id on reviews  (cost=0.42..1.00 rows=1 width=4) (actual time=0.008..0.008 rows=1 loops=4636)
                           Index Cond: (submission_id = submissions.id)
                           Heap Fetches: 4633
 Planning Time: 0.763 ms
 Execution Time: 173.760 ms

I might be over-optimizing, but 174ms seems too slow.
We have all the basic indexes plus a couple we created manually.

How could I speed up this query?

Body:
try creating partial index on submissions table.

CREATE INDEX ix_assignment_id_created_at ON submissions (assignment_id, created_at)
WHERE (gets_review IS true);