答:
There's no such thing as an associative array in JS. You need to convert it to an object.

You can use spread operator to convert the array to an object: let myObj = {...$data}

let $data=[{id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"},{permit_id:"1",document_description:"aa",file_name:"az"},{permit_id:"1",document_description:"aax",file_name:"azx"}];

let myObj = {...$data}

console.log(myObj);```
</div>
</div>
</p>

<p><strong>Update</strong></p>

<p>If you want to search the array to check if an object with a property already exists, you can use <code>Array.some()</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let $data=[{id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"},{permit_id:"1",document_description:"aa",file_name:"az"},{permit_id:"1",document_description:"aax",file_name:"azx"}];

let existingObj = {id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"}
let nonexistingObj = {id:38,permit_id:1,document_description:"foo",file_name:"bar"}

if(!$data.some(item => item.id === existingObj.id)){
  $data.push(existingObj)
  console.log(`ID: ${existingObj.id} pushed`);
}else{
  console.log(`ID: ${existingObj.id} already exists!`);
}

if(!$data.some(item => item.id === nonexistingObj.id)){
  $data.push(nonexistingObj)
  console.log(`ID: ${nonexistingObj.id} pushed`);
}else{
  console.log(`ID: ${nonexistingObj.id} already exists!`);
}

console.log($data);</code>```

Body:
There's no such thing as an associative array in JS. You need to convert it to an object.

You can use spread operator to convert the array to an object: let myObj = {...$data}

let $data=[{id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"},{permit_id:"1",document_description:"aa",file_name:"az"},{permit_id:"1",document_description:"aax",file_name:"azx"}];

let myObj = {...$data}

console.log(myObj);

Update

If you want to search the array to check if an object with a property already exists, you can use Array.some()

let $data=[{id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"},{permit_id:"1",document_description:"aa",file_name:"az"},{permit_id:"1",document_description:"aax",file_name:"azx"}];

let existingObj = {id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"}
let nonexistingObj = {id:38,permit_id:1,document_description:"foo",file_name:"bar"}

if(!$data.some(item => item.id === existingObj.id)){
  $data.push(existingObj)
  console.log(`ID: ${existingObj.id} pushed`);
}else{
  console.log(`ID: ${existingObj.id} already exists!`);
}

if(!$data.some(item => item.id === nonexistingObj.id)){
  $data.push(nonexistingObj)
  console.log(`ID: ${nonexistingObj.id} pushed`);
}else{
  console.log(`ID: ${nonexistingObj.id} already exists!`);
}

console.log($data);


来源: stackexchange

问:
.net core 3.1 not listed in target frameworks
I want to change my target framework from .net core 3.0 to 3.1 preview, but it is not listed.  I am running VS 2019 v16.1.9 and have installed both .net core 3.1 sdk and release.  Restarted the computer, but 3.1 is not listed.  How do I change to .net core 3.1?

Thank you.

答: Installed 32 version of dotnet core and it works. But it is not what people want. 64 version should be visible not 32 version only.</p>

ContentLicense: CC BY-SA 4.0


问:
Indexing exported elements from inxex.ts by string
I have a folder named nodes in my project. Inside there are some classes but important is index.tsx file which is exporting it. The index.tsx looks:

```<code>export * from './processStep/ProcessStepNodeFactory';
export * from './processStep/ProcessStepNodeModel';
export * from './processStep/ProcessStepNodeWidget';
</code>```

Now I would like to import everything from it:

```<code>import * as nodes from './nodes';
</code>```

And now if I am trying to index nodes using string:

```<code>const foo = nodes['ProcessStepNodeFactory']
</code>```

I am getting typescript error:

TrayItemWidget.tsx TypeScript error: Element implicitly has an 'any' type because expression of type 'string' can't be used to
  index type 'typeof
  import("PATHTO/nodes/index")'.
  No index signature with a parameter of type 'string' was found on type
  'typeof
  import("PATHTO/nodes/index")'.
  TS7053

Of course, I can access "nodes.ProcessStepNodeFactory" but I want to change string index programmatically using some prefixes on so. Could someone help please how to avoid this typescript error? Thank you

答:
Came across this question after experiencing it myself. You could fall back to const so it can type-casted.

So, instead of:

import * as nodes from './nodes';

```

<p>You could do it like:</p>

<pre class="lang-js prettyprint-override"><code>const nodes: { [key: string]: any } = require('./nodes');
</code>```

It looks ugly, I know.

Body:
I have a folder named nodes in my project. Inside there are some classes but important is index.tsx file which is exporting it. The index.tsx looks:

export * from './processStep/ProcessStepNodeFactory';
export * from './processStep/ProcessStepNodeModel';
export * from './processStep/ProcessStepNodeWidget';

Now I would like to import everything from it:

import * as nodes from './nodes';

And now if I am trying to index nodes using string:

const foo = nodes['ProcessStepNodeFactory']

I am getting typescript error:

TrayItemWidget.tsx TypeScript error: Element implicitly has an 'any' type because expression of type 'string' can't be used to
  index type 'typeof
  import("PATHTO/nodes/index")'.
  No index signature with a parameter of type 'string' was found on type
  'typeof
  import("PATHTO/nodes/index")'.
  TS7053

Of course, I can access "nodes.ProcessStepNodeFactory" but I want to change string index programmatically using some prefixes on so. Could someone help please how to avoid this typescript error? Thank you

Body:
Came across this question after experiencing it myself. You could fall back to const so it can type-casted.

So, instead of:

import * as nodes from './nodes';

You could do it like:

const nodes: { [key: string]: any } = require('./nodes');

It looks ugly, I know.


问:
In SwiftUI, How do I increase the height of a button?
As you can see in the screenshot, the button height does not adjust to fit the text size, making it look ugly. How can I increase the hight of the buttons, so it does not look stupid. My question is, how do I increase the height of buttons in SwiftUI? I am trying to make the titlescreen of my Minecraft-like game.

```<code>struct ContentView: View {
var body: some View {
    GeometryReader { geometry in
        VStack (spacing: 8) {
            Text("[Name not disclosed]Craft").font(.system(size: geometry.size.width/8))
            Button(action: {

            }) {
                Text("Singleplayer").font(.system(size: geometry.size.width/20))
                    .frame(minWidth: geometry.size.width/2)
            }
            Button(action: {

            }) {
                Text("Multiplayer").font(.system(size: geometry.size.width/20))
                    .frame(minWidth: geometry.size.width/2)
            }
            HStack (spacing: 8) {
                Button(action: {

                }) {
                    Text("Options").font(.system(size: geometry.size.width/20))
                        .frame(minWidth: (geometry.size.width/4)-16)
                }
                Button(action: {
                    exit(EXIT_SUCCESS);
                }) {
                    Text("Quit Game").font(.system(size: geometry.size.width/20))
                        .frame(minWidth: (geometry.size.width/4)-16)
                }
            }
        }
    }
}
</code>```

答:
Please try below Code:

```<code>Button(action: {
       //do action
}) {
    Text("SIGN IN")
        .frame(width: 200 , height: 50, alignment: .center)
        //You need to change height & width as per your requirement
}
 .background(Color.blue)
 .foregroundColor(Color.white)
 .cornerRadius(5)
</code>```

Output

Body:
As you can see in the screenshot, the button height does not adjust to fit the text size, making it look ugly. How can I increase the hight of the buttons, so it does not look stupid. My question is, how do I increase the height of buttons in SwiftUI? I am trying to make the titlescreen of my Minecraft-like game.

struct ContentView: View {
var body: some View {
    GeometryReader { geometry in
        VStack (spacing: 8) {
            Text("[Name not disclosed]Craft").font(.system(size: geometry.size.width/8))
            Button(action: {

            }) {
                Text("Singleplayer").font(.system(size: geometry.size.width/20))
                    .frame(minWidth: geometry.size.width/2)
            }
            Button(action: {

            }) {
                Text("Multiplayer").font(.system(size: geometry.size.width/20))
                    .frame(minWidth: geometry.size.width/2)
            }
            HStack (spacing: 8) {
                Button(action: {

                }) {
                    Text("Options").font(.system(size: geometry.size.width/20))
                        .frame(minWidth: (geometry.size.width/4)-16)
                }
                Button(action: {
                    exit(EXIT_SUCCESS);
                }) {
                    Text("Quit Game").font(.system(size: geometry.size.width/20))
                        .frame(minWidth: (geometry.size.width/4)-16)
                }
            }
        }
    }
}

Body:
Please try below Code:

Button(action: {
       //do action
}) {
    Text("SIGN IN")
        .frame(width: 200 , height: 50, alignment: .center)
        //You need to change height & width as per your requirement
}
 .background(Color.blue)
 .foregroundColor(Color.white)
 .cornerRadius(5)

Output


问:
How to execute python program and save output in different file names automatically
I have a Python program which processes images and save the resulting output to a file. I am receiving the input and output file names via console using input(). But I want to save the output automatically with the file name as something like "input_file_name_out". Note the string "_out" attached to the input file name

This will help me get user input only for Input file names thereby saving little time for the user since he doesn't need to think everytime what should be the output file name

Sample code snippet

```<code>if __name__ == "__main__":

    in_file = input()
    out_file = input()

    processed = process_image(in_file,out_file)
</code>```

Expected code snippet

```<code>if __name__ == "__main__":

    in_file = input()
    # out_file = input() ------Not getting the file name from user thereby supplying only one argument to the below function

        processed = process_image(in_file)

# And within the function
def process_image(img):
    .
    .
    .
    out_file = img+"_out.jpg" ##### What should come here to achieve my requirement ########
    cv2.imwrite(out_file,processed_image)
</code>```

答:
All you have to do is,

Take the input_img.jpg that you get from user input

Split the input_img.jpg with delimiter . and that will give you this list:
['input_img', 'jpg']

Pick up the first element and add _out.jpg suffix

def process_image(img):

    # you should split with delimiter ('.'), take the first
    # element of the list and add "_out.jpg" suffix

    split_name = img.split('.')
    out_file = split_name[0] + "_out" + "." + split_name[1]
    cv2.imwrite(out_file, processed_image)

if __name__ == "__main__":

    in_file = input()
    processed = process_image(in_file)

```

Body:
I have a Python program which processes images and save the resulting output to a file. I am receiving the input and output file names via console using input(). But I want to save the output automatically with the file name as something like "input_file_name_out". Note the string "_out" attached to the input file name

This will help me get user input only for Input file names thereby saving little time for the user since he doesn't need to think everytime what should be the output file name

Sample code snippet

if __name__ == "__main__":

    in_file = input()
    out_file = input()

    processed = process_image(in_file,out_file)

Expected code snippet

if __name__ == "__main__":

    in_file = input()
    # out_file = input() ------Not getting the file name from user thereby supplying only one argument to the below function

        processed = process_image(in_file)

# And within the function
def process_image(img):
    .
    .
    .
    out_file = img+"_out.jpg" ##### What should come here to achieve my requirement ########
    cv2.imwrite(out_file,processed_image)


问:
use macro to test function return value in C
I want to have a macro which does something like:

#define TEST(_ptr) ({ if ((_ptr) == NULL) ERROR; (_ptr); })

which check _ptr and calls ERROR macro or return its value.

However, if I use something like var = TEST(fun()) this results in fun() being called two times.

I can do something like:

#define TEST(_tmp, _ptr) ({ _tmp = _ptr; if ((_tmp) == NULL) ERROR; (_tmp); })

is there any clean way of doing this without passing temporary storage, e.g. using typeof operator!?

答:
You can do like this:</p>

```<code>/* Assuming your ERROR, something like this */
#define ERROR \
({ \
    printf("Error, Null pointer passed\n"); \
    exit(1); \
})

#define TEST1(_ptr) \
({ \
    typeof(_ptr) _tmp = _ptr; \
    if ((_tmp) == NULL) ERROR; \
    (_tmp); \
})
</code>```

Body:
You can do like this:

/* Assuming your ERROR, something like this */
#define ERROR \
({ \
    printf("Error, Null pointer passed\n"); \
    exit(1); \
})

#define TEST1(_ptr) \
({ \
    typeof(_ptr) _tmp = _ptr; \
    if ((_tmp) == NULL) ERROR; \
    (_tmp); \
})


问:
C Segmentation Fault While using scanf for 2D array
As suggested by a book of "Gottfried", I tried to input an array and display the contents of array in matrix form :

```<code>#include<stdio.h>

#define row 2
#define col 3

int main(){
    int (*a)[col];
    int i,j;

    for(i=0;i<row;i++){
        for(j=0;i<col;j++){
            printf("Enter a(%d,%d)",i,j);
            scanf("%d",(*(a+i)+j));
        }
    }

    return 0;
}
</code>```

I get the following output after inputting an element :

Segmentation fault (core dumped)

What is the problem in the code? Was it working in previous version of GCC so the writer wrote it down? What is the correct way to solve the problem with the same level of simplicity?

答:
As it was pointed out in the comments it is not a 2D array, but a 1D array of pointers.
Also in the second for loop you accidently use i<col instead of j<col.
This will work

```<code>#include<stdio.h>

#define ROW 2
#define COL 3

int main(){
    int a[ROW][COL];
    int i, j;

    for(i = 0; i < ROW; i++){
        for(j = 0;j < COL; j++){
            printf("Enter a(%d,%d)", i, j);
            scanf("%d", (*(a + i ) + j));
        }
    }
    return 0;
}
</code>```

Body:
As suggested by a book of "Gottfried", I tried to input an array and display the contents of array in matrix form :

#include<stdio.h>

#define row 2
#define col 3

int main(){
    int (*a)[col];
    int i,j;

    for(i=0;i<row;i++){
        for(j=0;i<col;j++){
            printf("Enter a(%d,%d)",i,j);
            scanf("%d",(*(a+i)+j));
        }
    }

    return 0;
}

I get the following output after inputting an element :

Segmentation fault (core dumped)

What is the problem in the code? Was it working in previous version of GCC so the writer wrote it down? What is the correct way to solve the problem with the same level of simplicity?

Body:
As it was pointed out in the comments it is not a 2D array, but a 1D array of pointers.
Also in the second for loop you accidently use i<col instead of j<col.
This will work

#include<stdio.h>

#define ROW 2
#define COL 3

int main(){
    int a[ROW][COL];
    int i, j;

    for(i = 0; i < ROW; i++){
        for(j = 0;j < COL; j++){
            printf("Enter a(%d,%d)", i, j);
            scanf("%d", (*(a + i ) + j));
        }
    }
    return 0;
}


问:
Facing Error : TypeError: $(...).fullCalendar is not a function
I have added all the required Js and CSS file for FullCalander but I am still facing an error. when I remove vendors.min.js then its works. I don't know why vendors.min.js is creating the problem.</p>

```<code>Uncaught TypeError: $(...).fullCalendar is not a function
    at GenerateCalender (Events2:271)
    at Object.success (Events2:262)
    at c (vendors.min.js:2)
    at Object.fireWith [as resolveWith] (vendors.min.js:2)
    at l (vendors.min.js:2)
    at XMLHttpRequest.<anonymous> (vendors.min.js:2)
</code>```

答:
Include your script after including your jquery library</p>

```<code><html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://momentjs.com/downloads/moment.min.js"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.js'></script>
    <link rel='stylesheet' href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" />
    </head>
  <body>
     <div id='calendar'></div>

    <script>
        $(document).ready(function() {

        // page is now ready, initialize the calendar...

        $('#calendar').fullCalendar({
            // put your options and callbacks here
            left:   'Calendar',
            center: '',
            right:  'today prev,next'
            });

        });
    </script>
  </body>
  </html>
</code>```

Body:
I have added all the required Js and CSS file for FullCalander but I am still facing an error. when I remove vendors.min.js then its works. I don't know why vendors.min.js is creating the problem.

Uncaught TypeError: $(...).fullCalendar is not a function
    at GenerateCalender (Events2:271)
    at Object.success (Events2:262)
    at c (vendors.min.js:2)
    at Object.fireWith [as resolveWith] (vendors.min.js:2)
    at l (vendors.min.js:2)
    at XMLHttpRequest.<anonymous> (vendors.min.js:2)

Body:
Include your script after including your jquery library

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://momentjs.com/downloads/moment.min.js"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.js'></script>
    <link rel='stylesheet' href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" />
    </head>
  <body>
     <div id='calendar'></div>

    <script>
        $(document).ready(function() {

        // page is now ready, initialize the calendar...

        $('#calendar').fullCalendar({
            // put your options and callbacks here
            left:   'Calendar',
            center: '',
            right:  'today prev,next'
            });

        });
    </script>
  </body>
  </html>


问:
Transpile npm module in Next.js
I am trying to transpile a module "react-device-detect" from node_modules but unable to achieve yet. Following is what I have tried:

module.exports = withLess({
  webpack: (config, { isServer, defaultLoaders }) => {
    // other configs
    config.module.rules.push({
      test: /\\.+(ts|tsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'ts-loader' }],
    });

    config.module.rules.push({
      test: /\\.+(js|jsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'babel-loader' }],
    });
    return config;
  },
});
```
<p>I have tried the rules individually as well but didn't work.</p>
<p><strong>UPDATE 1:</strong>
Complete next.config.js configurations @felixmosh</p>
<pre class="lang-js prettyprint-override"><code>const webpack = require("webpack");
const withLess = require("@zeit/next-less");
const { parsed: localEnv } = require("dotenv").config();
require("dotenv").config({
  path: process.env.NODE_ENV === "production" ? ".env.production" : ".env"
});
const Dotenv = require("dotenv-webpack");

module.exports = withLess({
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: "empty"
    };
    // add env variables on client end
    config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
    config.plugins.push(new Dotenv());

    if (!isServer) {
      config.resolve.alias["@sentry/node"] = "@sentry/browser";
    }
    return config;
  }
});
</code>```

UPDATE 2:

It seems that next-transpile-modules does not work comfortably with next-i18next. I got in IE browser's console:

```<code>'exports' is undefined
</code>```

I got errors like following when I run npm run build:

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'osName' is not exported from 'react-device-detect'.
```

I got following when I run npm start:

react-i18next:: i18n.languages were undefined or empty undefined

答:
There is an NPM module for this next-transpile-modules that allows you to specify which modules to transpile.

// next.config.js
const withTM = require('next-transpile-modules')(['somemodule', 'and-another']); // pass the modules you would like to see transpiled

module.exports = withTM(withLess({
  ... // your custom next config

}));
```
<h3>Edit:</h3>
<p>As of Next 13.1, there is a built in support for transpiling given packages.</p>
<pre class="lang-js prettyprint-override"><code>// next.config.js

const nextConfig = {
  transpilePackages: ['@acme/ui', 'lodash-es'],
};

module.exports = nextConfig;
</code>```

Title: Transpile npm module in Next.js

Body:
I am trying to transpile a module "react-device-detect" from node_modules but unable to achieve yet. Following is what I have tried:

module.exports = withLess({
  webpack: (config, { isServer, defaultLoaders }) => {
    // other configs
    config.module.rules.push({
      test: /\\.+(ts|tsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'ts-loader' }],
    });

    config.module.rules.push({
      test: /\\.+(js|jsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'babel-loader' }],
    });
    return config;
  },
});

I have tried the rules individually as well but didn't work.

UPDATE 1:
Complete next.config.js configurations @felixmosh

const webpack = require("webpack");
const withLess = require("@zeit/next-less");
const { parsed: localEnv } = require("dotenv").config();
require("dotenv").config({
  path: process.env.NODE_ENV === "production" ? ".env.production" : ".env"
});
const Dotenv = require("dotenv-webpack");

module.exports = withLess({
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: "empty"
    };
    // add env variables on client end
    config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
    config.plugins.push(new Dotenv());

    if (!isServer) {
      config.resolve.alias["@sentry/node"] = "@sentry/browser";
    }
    return config;
  }
});

UPDATE 2:

It seems that next-transpile-modules does not work comfortably with next-i18next. I got in IE browser's console:

'exports' is undefined

I got errors like following when I run npm run build:

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'osName' is not exported from 'react-device-detect'.

I got following when I run npm start:

react-i18next:: i18n.languages were undefined or empty undefined

Body:
There is an NPM module for this next-transpile-modules that allows you to specify which modules to transpile.

// next.config.js
const withTM = require('next-transpile-modules')(['somemodule', 'and-another']); // pass the modules you would like to see transpiled

module.exports = withTM(withLess({
  ... // your custom next config

}));

Edit:

As of Next 13.1, there is a built in support for transpiling given packages.

// next.config.js

const nextConfig = {
  transpilePackages: ['@acme/ui', 'lodash-es'],
};

module.exports = nextConfig;


问:
How to loop a dataframe in Pytorch?
I have a problem when I want to loop my DataFrame created before so I can pass it into my classifier, but I can't neither loop my DataFrame nor pass a filename to the classifier. What can I do?

```<code>dataset=pd.DataFrame({
                      'filename':train,
                      'category':categories
                    })
images=dataset.iloc[:,0]
labels=dataset.iloc[:,-1]

from torch import nn,optim
class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1=nn.Linear(49152,256)
        self.fc2=nn.Linear(256,128)
        self.fc3=nn.Linear(128,64)
        self.fc4=nn.Linear(64,2)
        # add the dropout
        self.dropout=nn.Dropout(p=0.2)
    def forward(self,x):
        #flatten the input
        x=x.view(x.shape[0],-1)
        x=self.dropout(F.relu(self.fc1(x)))
        x=self.dropout(F.relu(self.fc2(x)))
        x=self.dropout(F.relu(self.fc3(x)))
        x=F.log_softmax(self.fc4(x),dim=1)
        return x
model=Classifier()
criterion=nn.NLLLoss()
optimizer=optim.Adam(model.parameters(),lr=0.005)
epochs=20
steps=0
for epoch in range(epochs):
    running_loss=0
    for filename,label in dataset:
        image=cv2.imread(filename)
        image=cv2.resize(image,dsize=(128,128),interpolation=cv2.INTER_CUBIC)
        output=model.forward(image)
        loss=criterion(output,label)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        running_loss+=loss.item()
    print(running_loss)
</code>```

答:
Maybe you can try wrapping up your dataframe in PyTorch's dataloader. This will help you generate batches of train/validation dataset. This answer by Allen will give you some direction.
Once you have a dataloader in place, you can easily iterate over it during training or validation. </p>

Title: How to loop a dataframe in Pytorch?

Body:
I have a problem when I want to loop my DataFrame created before so I can pass it into my classifier, but I can't neither loop my DataFrame nor pass a filename to the classifier. What can I do?

dataset=pd.DataFrame({
                      'filename':train,
                      'category':categories
                    })
images=dataset.iloc[:,0]
labels=dataset.iloc[:,-1]

from torch import nn,optim
class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1=nn.Linear(49152,256)
        self.fc2=nn.Linear(256,128)
        self.fc3=nn.Linear(128,64)
        self.fc4=nn.Linear(64,2)
        # add the dropout
        self.dropout=nn.Dropout(p=0.2)
    def forward(self,x):
        #flatten the input
        x=x.view(x.shape[0],-1)
        x=self.dropout(F.relu(self.fc1(x)))
        x=self.dropout(F.relu(self.fc2(x)))
        x=self.dropout(F.relu(self.fc3(x)))
        x=F.log_softmax(self.fc4(x),dim=1)
        return x
model=Classifier()
criterion=nn.NLLLoss()
optimizer=optim.Adam(model.parameters(),lr=0.005)
epochs=20
steps=0
for epoch in range(epochs):
    running_loss=0
    for filename,label in dataset:
        image=cv2.imread(filename)
        image=cv2.resize(image,dsize=(128,128),interpolation=cv2.INTER_CUBIC)
        output=model.forward(image)
        loss=criterion(output,label)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        running_loss+=loss.item()
    print(running_loss)


问:
Is there a way to perform "if" in python's lambda?
In Python 2.6, I want to do:

```<code>f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
</code>```

This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it?

答:
An easy way to perform an if in lambda is by using list comprehension.

You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

```<code>f = lambda x: print(x) if x==2 else print("exception")
</code>```

Another example:

return 1 if M otherwise 0

```<code>f = lambda x: 1 if x=="M" else 0
</code>```

Body:
In Python 2.6, I want to do:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it?

Body:
An easy way to perform an if in lambda is by using list comprehension.

You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

f = lambda x: print(x) if x==2 else print("exception")

Another example:

return 1 if M otherwise 0

f = lambda x: 1 if x=="M" else 0


问:
keda func deploy from a dir which contains spaces is failing
I am using Visual Code with Azure Core Tools to deploy a container to a K8S cluster which has KEDA installed. But seeing this docker error. The error is caused because the docker build is run without the double quotes.

```<code>$ func kubernetes deploy --name bollaservicebusfunc --registry sbolladockerhub --python
Running 'docker build -t sbolladockerhub/bollaservicebusfunc C:\Users\20835918\work\welcome to space'....done
Error running docker build -t sbolladockerhub/bollaservicebusfunc C:\Users\20835918\work\welcome to space.
output:

"docker build" requires exactly 1 argument.
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

(.venv)
20835918@CROC1LWPF1S99JJ MINGW64 ~/work/welcome to space (master)
</code>```

I know there is a known bug Spaces in directory

But posting to see if there is a workaround, this is important as I have eveything in Onedrive - Comapny Name and it has spaces in it

答:
Looking into the code for func, you could specify --image-name instead of --registry which seems to skip building the container.

You would have to build your docker container manually using the same code shown in the output and provide the value for the -t argument of the docker command for --image-name of the func command after.

Also, since this would not push your docker container as well, make sure to push it before running the func command.

Body:
I am using Visual Code with Azure Core Tools to deploy a container to a K8S cluster which has KEDA installed. But seeing this docker error. The error is caused because the docker build is run without the double quotes.

$ func kubernetes deploy --name bollaservicebusfunc --registry sbolladockerhub --python
Running 'docker build -t sbolladockerhub/bollaservicebusfunc C:\Users\20835918\work\welcome to space'....done
Error running docker build -t sbolladockerhub/bollaservicebusfunc C:\Users\20835918\work\welcome to space.
output:

"docker build" requires exactly 1 argument.
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

(.venv)
20835918@CROC1LWPF1S99JJ MINGW64 ~/work/welcome to space (master)

I know there is a known bug Spaces in directory

But posting to see if there is a workaround, this is important as I have eveything in Onedrive - Comapny Name and it has spaces in it


问:
How pass data from component to external js file
I want to use my component's data within my external JavaScript file, containing my Dropzone configuration. I tried unsuccessfully to use Function.prototype.bind:

export const dropzoneConfig = {
    url: api.http.baseUrl + '/files',
    thumbnailWidth: 150,
    maxFilesize: 5,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    sending: function (file, xhr, formData) {
        formData.append('type', 'photo');
    },
    success: function (file, xhr) {
        file.id = xhr.data.id;
        if (this.entry.files === undefined) {
            this.entry.files = [];
        }
        this.entry.files.push(xhr.data);
        this.saveNote();
    }.bind(this),
    headers: api.http.authHeaders().headers
};
```

In the code above, this.entry and this.saveNote are unavailable because they're from my Vue component. How do I make them accessible to the external file?

答:
A more general solution would be for the component to pass in a success-event handler that has access to the component's data and methods, as shown below. This solution decouples the configuration from the component's internals.

dropzoneConfig.js:

export const dropzoneConfig = ({ onSuccess }) => ({
  //...
  success(file, xhr) {
    //...
    onSuccess(xhr.data)
  }
})
```

<p><em>App.vue:</em></p>

<pre class="lang-html prettyprint-override"><code><script>
import Dropzone from 'dropzone'
import { dropzoneConfig } from './dropzoneConfig'

export default {
  data() {
    return {
      entry: {
        files: []
      }
    }
  },
  created() {
    Dropzone.options.myComponent = dropzoneConfig({
      onSuccess: fileData => this.onDropzoneSuccess(fileData)
    })
  },
  methods: {
    saveNote() {
      //...
    },
    onDropzoneSuccess(fileData) {
      this.entry.files.push(fileData)
      this.saveNote()
    }
  }
}
</script>
</code>```

Body:
I want to use my component's data within my external JavaScript file, containing my Dropzone configuration. I tried unsuccessfully to use Function.prototype.bind:

export const dropzoneConfig = {
    url: api.http.baseUrl + '/files',
    thumbnailWidth: 150,
    maxFilesize: 5,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    sending: function (file, xhr, formData) {
        formData.append('type', 'photo');
    },
    success: function (file, xhr) {
        file.id = xhr.data.id;
        if (this.entry.files === undefined) {
            this.entry.files = [];
        }
        this.entry.files.push(xhr.data);
        this.saveNote();
    }.bind(this),
    headers: api.http.authHeaders().headers
};

In the code above, this.entry and this.saveNote are unavailable because they're from my Vue component. How do I make them accessible to the external file?

Body:
A more general solution would be for the component to pass in a success-event handler that has access to the component's data and methods, as shown below. This solution decouples the configuration from the component's internals.

dropzoneConfig.js:

export const dropzoneConfig = ({ onSuccess }) => ({
  //...
  success(file, xhr) {
    //...
    onSuccess(xhr.data)
  }
})

App.vue:

<script>
import Dropzone from 'dropzone'
import { dropzoneConfig } from './dropzoneConfig'

export default {
  data() {
    return {
      entry: {
        files: []
      }
    }
  },
  created() {
    Dropzone.options.myComponent = dropzoneConfig({
      onSuccess: fileData => this.onDropzoneSuccess(fileData)
    })
  },
  methods: {
    saveNote() {
      //...
    },
    onDropzoneSuccess(fileData) {
      this.entry.files.push(fileData)
      this.saveNote()
    }
  }
}
</script>


问:
Ignite cache transactioin and putAsync
I'm using Apache Ignite Cache with transactions. Currently I use regular cache.put() methods but wonder if I should better use recommended putAsync()? If using the async methods, does Transaction.commit() wait for all async puts to finish or do I have to do this in my code?

This would be my simplified code:

```<code>Ignite ignite = Ignition.ignite();
IgniteTransactions transactions = ignite.transactions();
tx = transactions.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.SERIALIZABLE, 10 * 1000, 0);

IgniteFuture fut = cache.putAsync("KEY", "VALUE");

fut.get(); // do I need to call this?

tx.commit();
</code>```

答: Yes, commit() will wait for async methods to finish. Please note that you can only have one async method running at the same time - if you have one, the next one will run synchronously.</p>

Title: Ignite cache transactioin and putAsync

Body:
I'm using Apache Ignite Cache with transactions. Currently I use regular cache.put() methods but wonder if I should better use recommended putAsync()? If using the async methods, does Transaction.commit() wait for all async puts to finish or do I have to do this in my code?

This would be my simplified code:

Ignite ignite = Ignition.ignite();
IgniteTransactions transactions = ignite.transactions();
tx = transactions.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.SERIALIZABLE, 10 * 1000, 0);

IgniteFuture fut = cache.putAsync("KEY", "VALUE");

fut.get(); // do I need to call this?

tx.commit();


问:
Find a regex call in R to return first and last name or full team name only
I'm trying to clean a column by retaining only first and last names (or full team name: ex "New England Patriots".

Here is a set of names with differing styles that need to be matched. I need a capture group around the first and last name together or full team name:

```<code>Matt Schaub QB - ATL
Phillip Andersen K
Cleveland Browns DEF
San Francisco 49ers DEF
New England Patriots DEF
J.T. Barrett QB - PIT
Tre McBride WR
N'Keal Harry WR - NE
MyCole Pruitt TE - TEN
J.J. Arcega-Whiteside WR - PHI
Tre'Quan Smith WR - NO
</code>```

This is as far as I got in a regex engine before I started getting lost. Not even sure how close it even was:

```<code>[A-Z](\\.|[a-z]+)([A-Z]|\\s)
</code>```

答:
Here is a solution which might work here:

```<code>input <- c("Matt Schaub QB - ATL", "Phillip Andersen K", "Cleveland Browns DEF",
           "San Francisco 49ers DEF", "New England Patriots DEF", "J.T. Barrett QB - PIT",
           "Tre McBride WR", "N'Keal Harry WR - NE", "MyCole Pruitt TE - TEN",
           "J.J. Arcega-Whiteside WR - PHI", "Tre'Quan Smith WR - NO")
output <- sub("\\s*\\b[A-Z]+(?: - [A-Z]+)?$", "", input)
output

 [1] "Matt Schaub"           "Phillip Andersen"      "Cleveland Browns"
 [4] "San Francisco 49ers"   "New England Patriots"  "J.T. Barrett"
 [7] "Tre McBride"           "N'Keal Harry"          "MyCole Pruitt"
[10] "J.J. Arcega-Whiteside" "Tre'Quan Smith"
</code>```

The idea here is to remove the initial or initials which occur at the ends of the sport team names.

Body:
I'm trying to clean a column by retaining only first and last names (or full team name: ex "New England Patriots".

Here is a set of names with differing styles that need to be matched. I need a capture group around the first and last name together or full team name:

Matt Schaub QB - ATL
Phillip Andersen K
Cleveland Browns DEF
San Francisco 49ers DEF
New England Patriots DEF
J.T. Barrett QB - PIT
Tre McBride WR
N'Keal Harry WR - NE
MyCole Pruitt TE - TEN
J.J. Arcega-Whiteside WR - PHI
Tre'Quan Smith WR - NO

This is as far as I got in a regex engine before I started getting lost. Not even sure how close it even was:

[A-Z](\\.|[a-z]+)([A-Z]|\\s)

Body:
Here is a solution which might work here:

input <- c("Matt Schaub QB - ATL", "Phillip Andersen K", "Cleveland Browns DEF",
           "San Francisco 49ers DEF", "New England Patriots DEF", "J.T. Barrett QB - PIT",
           "Tre McBride WR", "N'Keal Harry WR - NE", "MyCole Pruitt TE - TEN",
           "J.J. Arcega-Whiteside WR - PHI", "Tre'Quan Smith WR - NO")
output <- sub("\\s*\\b[A-Z]+(?: - [A-Z]+)?$", "", input)
output

 [1] "Matt Schaub"           "Phillip Andersen"      "Cleveland Browns"
 [4] "San Francisco 49ers"   "New England Patriots"  "J.T. Barrett"
 [7] "Tre McBride"           "N'Keal Harry"          "MyCole Pruitt"
[10] "J.J. Arcega-Whiteside" "Tre'Quan Smith"

The idea here is to remove the initial or initials which occur at the ends of the sport team names.


问:
Losing reference to DOM elements after I clone them
Using MooTools, I'm caching some DOM elements in variables when the DOM is ready, like so:

```<code>var mc = $('main-content'),
    bg = $('bg'),
    arrows = $$('arrows');
</code>```

Both bg and arrows are located within the mc DOM element. I want to clone the mc node, perform some operations on it and then insert the clone into the DOM:

```<code>function updateDOM (parent) {
    var parentID = parent.id,
        oldNode = document.getElementById(parentID),
        clone = oldNode.cloneNode(true);

    // work with clone

    oldNode.parentNode.replaceChild(clone, oldNode);

}
</code>```

When I run updateDOM(mc), I find that any other subsequent functions that would change mc, bg, or arrows don't work. When I do console.log() the elements, they show up, but they don't reflect any of the changes that have been made since their initialization.

Considering that I'm cloning the element, it makes sense to me that mc no longer references div#main-content. updateDOM() is a function that could be used by any element. Do I really need to hard code a way to re-instantiate each variables that I cache or is there a more dynamic way of doing this?

答:
```<code>> function updateDOM (parent) {
>     var parentID = parent.id,
>         oldNode = document.getElementById(parentID),
>         clone = oldNode.cloneNode(true);
</code>```

Maybe I'm thick, but it seems to me that the above function is passed an element reference that is assigned to parent. It then uses getElementById(parent.id) to get a reference to the same element, then clone it. How is this different to:

```<code>function updateDOM (parent) {
    var clone = parent.cloneNode(true);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using MooTools, I'm caching some DOM elements in variables when the DOM is ready, like so:

var mc = $('main-content'),
    bg = $('bg'),
    arrows = $$('arrows');

Both bg and arrows are located within the mc DOM element. I want to clone the mc node, perform some operations on it and then insert the clone into the DOM:

function updateDOM (parent) {
    var parentID = parent.id,
        oldNode = document.getElementById(parentID),
        clone = oldNode.cloneNode(true);

    // work with clone

    oldNode.parentNode.replaceChild(clone, oldNode);

}

When I run updateDOM(mc), I find that any other subsequent functions that would change mc, bg, or arrows don't work. When I do console.log() the elements, they show up, but they don't reflect any of the changes that have been made since their initialization.

Considering that I'm cloning the element, it makes sense to me that mc no longer references div#main-content. updateDOM() is a function that could be used by any element. Do I really need to hard code a way to re-instantiate each variables that I cache or is there a more dynamic way of doing this?

Body:
> function updateDOM (parent) {
>     var parentID = parent.id,
>         oldNode = document.getElementById(parentID),
>         clone = oldNode.cloneNode(true);

Maybe I'm thick, but it seems to me that the above function is passed an element reference that is assigned to parent. It then uses getElementById(parent.id) to get a reference to the same element, then clone it. How is this different to:

function updateDOM (parent) {
    var clone = parent.cloneNode(true);


问:
Can I create a Google account programmatically?
Does anybody know if via the google api in java
I can create google accounts programmatically. </p>

答:
YES...

Actually you can do that. You can write CUrl scripts and can use different APIs available to break the captcha.
Breaking a captcha is key thing here.


问:
Header Bidding In adserver
I need to learn about header bidding in adserver, I have find below site https://martechtoday.com/martech-landscape-what-is-header-bidding-and-why-should-publishers-care-157065 after reading this site also can't able to understand about header bidding, Can anyone suggest the best site to learn about header bidding

答:
there are a few articles that may help you to understand header bidding and how it works with respect to an ad server:

https://headerbidding.co/header-bidding/ - This will help to understand what is header bidding and how it is different than the traditional waterfall method.

https://headerbidding.co/header-bidding-amp/ - This article has simplified the header bidding process for accelerated mobile pages.

https://headerbidding.co/prebid-setup-google-ad-manager/ - Google's ad server is one of the best ad servers for a publisher. And via Prebid, the open-source platform, you can easily get started with header bidding.

https://headerbidding.co/setup-exchange-bidding/- This article will help you understand how to enable open bidding in Google Ad Manager and why it is less efficient than client-side header bidding.

Hope this helps! Let me know if you have any questions about header bidding.

Title: Header Bidding In adserver


问:
Javascript Element scrollTo compatibility difference between caniuse and mozilla
I am looking for browser support information of Element.scrollTo method.
However, there is difference in results from caniuse and mozilla for the latest safari(iOS) and Edge.

From mozilla, it says these browsers do not support this method. But caniuse says they do support.

When I tested with iPhone X, iOS 13.3.1, the method worked perfectly, which means that mozilla is wrong.

So far, I have trusted mozilla for the compatibility check purpose because this website is more descriptive on (other) technical information (thus, more reliable?).

In a long term, should I rely on caniuse, rather than mozilla?

答:
If you search specific scrollTo keyword(not just scroll) on caniuse, you will get almost identicle results as Mozilla.

But interesting fact is, data on caniuse, is powered by Mozilla's MDN browser-compat-data(refer Notes tab at the bottom on caniuse) and going forward, this collaboration with MDN is going to improve. So in a long term, referring to either caniuse or mozilla, is going to be the same. But I personally prefer MDN because of its clutter-free simple portal with additional(essential) details.

Here is an article about caniuse-MDN collaboration.


问:
Angular 7 routerLink directive warning 'Navigation triggered outside Angular zone'
I am struggling with Angular framework to get my application run smoothly, but I can't resolve an issue with routing.
I have a top level AppComponent and app-routing.module.ts which manage the navigation via my custom SlideMenuComponent. My simplified html template of AppComponent:

```<code><app-slide-menu [buttons]="menuButtons"></app-slide-menu>
<router-outlet></router-outlet>
</code>```

My SlideMenuComponent has the following html as its core:

```<code><nav><div *ngFor="let button of buttons">
    <a routerLink="{{button.routerLink}}"
    >{{button.name}}</a>
</div></nav>
</code>```

A user can navigate to '/courses' through this slide menu, which is supervised by CoursesComponent that paginates links to a particular CourseComponents that are retrieved from the server. These components reside in their own courses.module.ts module whith their own courses-routing.module.ts. But when I click any of those links I get Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'? console warning, ngOnInit() is not called for openned CourseCompontent, and it doesn't update untill I click any of the buttons on the page. I had this issue when manually navigating via router.navigate() that was resolved by forwarding this task to NgZone.runTask(router.navigate()), but why does this happen with anchor tags and routerLink direcrives?
Here is my CoursesComponent code excerpt:

```<code><nav><ul>
        <li *ngFor="let course of api.data | paginate: {
            currentPage: currentPage, itemsPerPage: limit, totalItems: api.total
        }">
           <a
               [routerLink]="course._id"
               [queryParams]="{ page: '1', limit: '5' }"
           >
            {{course.name}} ({{course.description}})
           </a>
        </li>
</ul></nav>
</code>```

A gif to demonstrate the issue:

答:
Since there is no accepted answer, and since I found, using Angular 8, the top ranked answer does not quite work, and needs a little more explanation, I have the following to add:

My specific issue was with ag-grid, but I suspect any place where a component is injected, within an *ngFor or otherwise, can potentially cause this problem. This is very close to the previous answer, but instead declares a string parameter into the navigate function and then calls navigateByUrl instead of navigate.

```<code>import { Component, NgZone } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  template: `<tag (click)="navigate(path)">clickable text</tag>`
})

constructor(private ngZone: NgZone, private router: Router) { }

public navigate(path: string): void {
  this.ngZone.run(() => this.router.navigateByUrl(path)).then();
}
</code>```

Your mileage may vary, but this worked beautifully for me.

Body:
I am struggling with Angular framework to get my application run smoothly, but I can't resolve an issue with routing.
I have a top level AppComponent and app-routing.module.ts which manage the navigation via my custom SlideMenuComponent. My simplified html template of AppComponent:

<app-slide-menu [buttons]="menuButtons"></app-slide-menu>
<router-outlet></router-outlet>

My SlideMenuComponent has the following html as its core:

    {{button.name}}

A user can navigate to '/courses' through this slide menu, which is supervised by CoursesComponent that paginates links to a particular CourseComponents that are retrieved from the server. These components reside in their own courses.module.ts module whith their own courses-routing.module.ts. But when I click any of those links I get Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'? console warning, ngOnInit() is not called for openned CourseCompontent, and it doesn't update untill I click any of the buttons on the page. I had this issue when manually navigating via router.navigate() that was resolved by forwarding this task to NgZone.runTask(router.navigate()), but why does this happen with anchor tags and routerLink direcrives?
Here is my CoursesComponent code excerpt:

            {{course.name}} ({{course.description}})

A gif to demonstrate the issue:

Body:
Since there is no accepted answer, and since I found, using Angular 8, the top ranked answer does not quite work, and needs a little more explanation, I have the following to add:

My specific issue was with ag-grid, but I suspect any place where a component is injected, within an *ngFor or otherwise, can potentially cause this problem. This is very close to the previous answer, but instead declares a string parameter into the navigate function and then calls navigateByUrl instead of navigate.

import { Component, NgZone } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  template: `<tag (click)="navigate(path)">clickable text</tag>`
})

constructor(private ngZone: NgZone, private router: Router) { }

public navigate(path: string): void {
  this.ngZone.run(() => this.router.navigateByUrl(path)).then();
}

Your mileage may vary, but this worked beautifully for me.


问:
Maven exec:java : how to open and read a file in the resources directory?
here is the structure of my project.

```<code>proj
  ---src
    ----main
        ----java
            ----Main.java
        ----resources
             ----res.txt
</code>```

I am using m2eclipse plugin with Eclipse.
In Main.java, I have

```<code>File f = new File("res.txt");  System.out.println(f.getAbsolutePath());
</code>```

When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?

EDIT:

Thanks for the answers to my original question. I have a follow-up questions:

So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?

答:
When run from eclipse, res.txt is created in/reader from the folder where eclipse is started.  Hence the output.

If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.

Alternately you can specify the absolute path of the file.

Body:
here is the structure of my project.

proj
  ---src
    ----main
        ----java
            ----Main.java
        ----resources
             ----res.txt

I am using m2eclipse plugin with Eclipse.
In Main.java, I have

File f = new File("res.txt");  System.out.println(f.getAbsolutePath());

When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?

EDIT:

Thanks for the answers to my original question. I have a follow-up questions:

So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?


问:
Is this good approach to create new branch without merging current one using git?
kindly guide me about it please, for example, I have master branch. My team lead assigned a task to me for terms and conditions content. So I pulled from master and then created branch feature/terms-and-conditions through git checkout -b and then commit, pushed. Just guess for one minute that my team lead does not merged with master.

Now feature/terms-and-conditions is 1 commit ahead from master. So here I am confused that if I created again one new branch for another feature suppose feature/user-list and when I will commit and push for it then there would be two branches. Both would be 1 commit ahead from master. In such a case there would be any conflict?

答:
You described what is probably the best approach. Assuming the two features are not related, you should have two separate branches split from master, and work on them independently.

Splitting feature/user-list from feature/terms-and-conditions is a bad idea since you would be mixing unrelated content in the same branch, and making the reviewer's life harder. Even worse, every time you get comments on the feature/terms-and-conditions branch, you'd have to rebase the feature/user-list branch, which is just a lot of grunt work.

Waiting until feature/terms-and-conditions is merged before starting the work on feature/user-list isn't technically wrong, but it's redundantly slow, and I doubt your manager will be OK with that.

Regarding conflicts - Git was designed to handle multiple parallel branches. Once the first branch is merged, you can (will?) simply rebase the second one on top of master. If the two branches didn't touch the same files, the rebase will succeed cleanly. If they did, you'll have to manage the conflict manually, but that usually shouldn't be a big deal - if it is, it means both branches touched the same areas of the code, and it was probably a bad idea working on them in parallel in the first place.


问:
Solution to cigars and squirrels puzzle on CodingBat throws syntax error
I am trying to solve this CodingBat problem:

Squirrels who like to party get together and smoke cigars. Such a party is only deemed successful when the number of cigars is between 40 and 60, on a weekday. On weekends, however, there is no upper bound on number of cigars. Write a function that returns True if the party with the given values was successful.

Unfortunately, although I have used Python occasionally, I am not good enough at it to understand why my code fails with a syntax error on line 5:

```<code>def cigar_party(cigars, is_weekend):
  if is_weekend:
    if cigars >= 40:
      return True
  else if:
    cigars >= 40 and cigars =< 60:
      return True
  else:
    return False
</code>```

答:
```<code>def cigar_party(cigars, is_weekend):
  if is_weekend:
    if cigars>=40:
      return is_weekend
  else:
    if cigars in range(40,61):
      return True
  return False
</code>```

Body:
I am trying to solve this CodingBat problem:

Squirrels who like to party get together and smoke cigars. Such a party is only deemed successful when the number of cigars is between 40 and 60, on a weekday. On weekends, however, there is no upper bound on number of cigars. Write a function that returns True if the party with the given values was successful.

Unfortunately, although I have used Python occasionally, I am not good enough at it to understand why my code fails with a syntax error on line 5:

def cigar_party(cigars, is_weekend):
  if is_weekend:
    if cigars >= 40:
      return True
  else if:
    cigars >= 40 and cigars =< 60:
      return True
  else:
    return False


问:
How to pass search parameter, into function that will search a c# collection
Assume I have a collection of the form:

```<code>List<Member> myMembers= new List<Member>()
{
    new Member(){ID=1,FirstName="John",LastName="Doe"},
    new Member(){ID=3,FirstName="Allan",LastName="Jones"},
    new Member(){ID=2,FirstName="Martin",LastName="Moe"},
    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"}
};
</code>```

I can sort this list via FirstName by using:

```<code>myMembers.Sort((x, y) => x.FirstName.CompareTo(y.FirstName));
</code>```

I would like to do this inside of a function, so that I can pass the desired search parameter.  Something like:

```<code>public void sortCollection( parameter SearchTerm, List<Member> myCollection )
{
    myCollection ((x, y) => x.SearchTerm.CompareTo(y.FirstName));
}
</code>```

Obviously here, I cannot pass in the desired search field this way, but is it possible to do what I am asking?

答:
Demo on dotnet fiddle

It seems to me that you can use Func<> to be able to dynamic order by.

```<code>var result = sortCollection(p => p.ID, myMembers);

public static IEnumerable<Member> sortCollection(Func<Member, object> keySelector, List<Member> myCollection)
{
    return myCollection.OrderBy(keySelector);
}
</code>```

Read the following post to have a better understanding

Dynamic Order By in Linq

Body:
Assume I have a collection of the form:

List<Member> myMembers= new List<Member>()
{
    new Member(){ID=1,FirstName="John",LastName="Doe"},
    new Member(){ID=3,FirstName="Allan",LastName="Jones"},
    new Member(){ID=2,FirstName="Martin",LastName="Moe"},
    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"}
};

I can sort this list via FirstName by using:

myMembers.Sort((x, y) => x.FirstName.CompareTo(y.FirstName));

I would like to do this inside of a function, so that I can pass the desired search parameter.  Something like:

public void sortCollection( parameter SearchTerm, List<Member> myCollection )
{
    myCollection ((x, y) => x.SearchTerm.CompareTo(y.FirstName));
}

Obviously here, I cannot pass in the desired search field this way, but is it possible to do what I am asking?

Body:
Demo on dotnet fiddle

It seems to me that you can use Func<> to be able to dynamic order by.

var result = sortCollection(p => p.ID, myMembers);

public static IEnumerable<Member> sortCollection(Func<Member, object> keySelector, List<Member> myCollection)
{
    return myCollection.OrderBy(keySelector);
}

Read the following post to have a better understanding

Dynamic Order By in Linq


问:
How to replace variable in user input with math operation?
I need replace variable in string from user. For example:

User input: Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd

I know how replace only {price} but I don't know how to replace other cases.

I need support these cases:

```<code>{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}
</code>```

And user can use variable {price} many times.

After user submit text, my app replace variable {price} or calc {price-xx%} and create a new string.

答:
If I understood your problem correctly then I think you can evaluate the whole expression without Replacing variables (might you have to change placements of variables)

First, add 'System.Data' name space in your project

then:

```<code>double price = 110;
double xx = 15;
double result = 0;

result = Convert.ToDouble(new DataTable().Compute($"({price-(price*xx)/100})", null));
Console.WriteLine("{price - xx%} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price + (price * xx) / 100})", null));
Console.WriteLine("{price + xx%} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}-{xx})", null));
Console.WriteLine("{price - xx} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}+{xx})", null));
Console.WriteLine("{price + xx} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}/{xx})", null));
Console.WriteLine("{price / xx} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}*{xx})", null));
Console.WriteLine("{price * xx} = " + result);
</code>```

Body:
I need replace variable in string from user. For example:

User input: Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd

I know how replace only {price} but I don't know how to replace other cases.

I need support these cases:

{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}

And user can use variable {price} many times.

After user submit text, my app replace variable {price} or calc {price-xx%} and create a new string.

Body:
If I understood your problem correctly then I think you can evaluate the whole expression without Replacing variables (might you have to change placements of variables)

First, add 'System.Data' name space in your project

then:

double price = 110;
double xx = 15;
double result = 0;

result = Convert.ToDouble(new DataTable().Compute($"({price-(price*xx)/100})", null));
Console.WriteLine("{price - xx%} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price + (price * xx) / 100})", null));
Console.WriteLine("{price + xx%} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}-{xx})", null));
Console.WriteLine("{price - xx} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}+{xx})", null));
Console.WriteLine("{price + xx} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}/{xx})", null));
Console.WriteLine("{price / xx} = " + result);

result = Convert.ToDouble(new DataTable().Compute($"({price}*{xx})", null));
Console.WriteLine("{price * xx} = " + result);


问:
Cannot pass data from JSONResult back to handler using ajax
I would like to have the following workflow:

Ajax call to page model handler to trigger database and creation of some viewmodels and return the result as JSONResult

Pass back the result of step 1 to another handler in order to reload a partial view

Between step 1 and 2 there is some data handling using JS. But this is out of scope, since the data is only read and not changed.

Step 1 is working fine. But step 2 does not. Here is a short code example:

Step 1:
Ajax:

```<code>            var searchArea = parseFloat(document.getElementById('txtSearchArea').value);
            var latitude = parseFloat(document.getElementById('hiddenLat').value);
            var longitude = parseFloat(document.getElementById('hiddenLong').value);

            var requestData = JSON.stringify({'latitude': latitude, 'longitude': longitude, 'searchArea': searchArea});

            $.ajax({
                type: "POST",
                url: '@Request.Scheme://@Request.Host@Request.Path?handler=GetCompaniesWithinSearchArea',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: requestData
            }).fail(function (x) {
                alert('Error fetching companies in search area.');
            }).done(function (result) {
                reloadSearchResultPartialView(result);
            });
</code>```

C#:

```<code>        public async Task<JsonResult> OnPostGetCompaniesWithinSearchAreaAsync([FromBody] LatitudeLongitudeSearchArea latitudeLongitudeSearchArea)
        {
            var latitude = latitudeLongitudeSearchArea.Latitude;
            var longitude = latitudeLongitudeSearchArea.Longitude;
            var searchArea = latitudeLongitudeSearchArea.SearchArea;

            var idsOfcompaniesInArea = await _companiesService.GetIdsOfCompaniesWithinSearchAreaAsync(latitude, longitude, searchArea));

            var companyInSearchAreaVMs = await _companiesInSearchAreaViewModelFactory.Create(idsOfcompaniesInArea);

            return new JsonResult(companyInSearchAreaVMs);
        }
</code>```

with _companiesInSearchAreaViewModelFactory.Create returning List<CompanyInSearchAreaViewModel>.

Step 2:
Normally I use the javascript load(...) method to invoke reloading of a partial view.
So I was trying to use this approach again.

JS:

```<code>function reloadSearchResultPartialView(searchResult) {
$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
}
</code>```

where searchResult is the response result of step 1. Data have not been changed between step 1 and 2.

C# - this is the handler for reloading the partial view.

```<code>        public PartialViewResult OnGetReloadCompaniesInAreaList(List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
        {
            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, companyInSearchAreaViewModels)
            };

            return result;
        }
</code>```

The handler for reloading the partial view is called, but the list of viewmodels is always an empty list.

Hopefully someone can point me in the right direction.

Thanks in advance!

答:
Why it happens

but the list of viewmodels is always an empty list.

That's because your server expects a querystring like this:

```<code>handler=ReloadCompaniesInAreaList
&[0].prop1= 11
&[0].prop2=12
...
&[1].prop1=21
&[1].prop2=22
...
</code>```

However, by using

```<code>$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
</code>```

You're sending the querystring like:

```<code>handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=[object
</code>```

How to Fix

There're several ways to fix that problem.

The easiest way is to change the json array to a form-urlencoded string, for example, change your reloadSearchResultPartialView()function as below:

function reloadSearchResultPartialView(searchResult) {
    //$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
    $('#divSearchResult').load('@Request.Path?handler=ReloadCompaniesInAreaList', $.param(createFormUrlEncodedPayload("",searchResult)));
}
// my helper function that recursively convert a plain js obj to a form-urlencoded string
function createFormUrlEncodedPayload(name,o){
    var payload = {};
    function _objectNotNull(value){ return value !== null && typeof value === "object"; }
    function _create(prefix,obj) {
        for(var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                var key =prefix?
                    (isNaN(prop)? key = prefix + "." + prop : key = prefix + ".[" + prop + "]") :
                    (isNaN(prop)? key = prop : key = "[" + prop + "]");
                var value = obj[prop];
                if(_objectNotNull(value))
                    _create(key, value);
                else
                    payload[key]=value;
            }
        }
    };
    _create(name,o);
    return payload;
}
```</li>
<li><p>Or as an alternative, you can make your server to receive <strong>HTTP POST</strong> request instead <code>GET</code>,</p>

```public PartialViewResult OnPostReloadCompaniesInAreaList([FormBody]List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
{
    ...
}
```

<p>and then replace the <code>$.load()</code> to :</p>

```$.ajax({
   url: '@Request.Path?handler=ReloadCompaniesInAreaList',
   method:'POST',
   contentType:"application/json",
   data: searchResult,
   success: function(resp){
      $('#divSearchResult').html(resp)
   },
});
```

Body:
I would like to have the following workflow:

Ajax call to page model handler to trigger database and creation of some viewmodels and return the result as JSONResult

Pass back the result of step 1 to another handler in order to reload a partial view

Between step 1 and 2 there is some data handling using JS. But this is out of scope, since the data is only read and not changed.

Step 1 is working fine. But step 2 does not. Here is a short code example:

Step 1:
Ajax:

            var searchArea = parseFloat(document.getElementById('txtSearchArea').value);
            var latitude = parseFloat(document.getElementById('hiddenLat').value);
            var longitude = parseFloat(document.getElementById('hiddenLong').value);

            var requestData = JSON.stringify({'latitude': latitude, 'longitude': longitude, 'searchArea': searchArea});

            $.ajax({
                type: "POST",
                url: '@Request.Scheme://@Request.Host@Request.Path?handler=GetCompaniesWithinSearchArea',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: requestData
            }).fail(function (x) {
                alert('Error fetching companies in search area.');
            }).done(function (result) {
                reloadSearchResultPartialView(result);
            });

C#:

        public async Task<JsonResult> OnPostGetCompaniesWithinSearchAreaAsync([FromBody] LatitudeLongitudeSearchArea latitudeLongitudeSearchArea)
        {
            var latitude = latitudeLongitudeSearchArea.Latitude;
            var longitude = latitudeLongitudeSearchArea.Longitude;
            var searchArea = latitudeLongitudeSearchArea.SearchArea;

            var idsOfcompaniesInArea = await _companiesService.GetIdsOfCompaniesWithinSearchAreaAsync(latitude, longitude, searchArea));

            var companyInSearchAreaVMs = await _companiesInSearchAreaViewModelFactory.Create(idsOfcompaniesInArea);

            return new JsonResult(companyInSearchAreaVMs);
        }

with _companiesInSearchAreaViewModelFactory.Create returning List<CompanyInSearchAreaViewModel>.

Step 2:
Normally I use the javascript load(...) method to invoke reloading of a partial view.
So I was trying to use this approach again.

JS:

function reloadSearchResultPartialView(searchResult) {
$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
}

where searchResult is the response result of step 1. Data have not been changed between step 1 and 2.

C# - this is the handler for reloading the partial view.

        public PartialViewResult OnGetReloadCompaniesInAreaList(List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
        {
            var result = new PartialViewResult
            {
                ViewName = "_CompaniesInAreaList",
                ViewData = new ViewDataDictionary<IList<CompanyInSearchAreaViewModel>>(ViewData, companyInSearchAreaViewModels)
            };

            return result;
        }

The handler for reloading the partial view is called, but the list of viewmodels is always an empty list.

Hopefully someone can point me in the right direction.

Thanks in advance!

Body:
Why it happens

but the list of viewmodels is always an empty list.

That's because your server expects a querystring like this:

handler=ReloadCompaniesInAreaList
&[0].prop1= 11
&[0].prop2=12
...
&[1].prop1=21
&[1].prop2=22
...

However, by using

$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);

You're sending the querystring like:

handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=[object

How to Fix

There're several ways to fix that problem.

The easiest way is to change the json array to a form-urlencoded string, for example, change your reloadSearchResultPartialView()function as below:

function reloadSearchResultPartialView(searchResult) {
    //$('#divSearchResult').load('@Request.Scheme://@Request.Host@Request.Path?handler=ReloadCompaniesInAreaList&companyInSearchAreaViewModels=' + searchResult);
    $('#divSearchResult').load('@Request.Path?handler=ReloadCompaniesInAreaList', $.param(createFormUrlEncodedPayload("",searchResult)));
}
// my helper function that recursively convert a plain js obj to a form-urlencoded string
function createFormUrlEncodedPayload(name,o){
    var payload = {};
    function _objectNotNull(value){ return value !== null && typeof value === "object"; }
    function _create(prefix,obj) {
        for(var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                var key =prefix?
                    (isNaN(prop)? key = prefix + "." + prop : key = prefix + ".[" + prop + "]") :
                    (isNaN(prop)? key = prop : key = "[" + prop + "]");
                var value = obj[prop];
                if(_objectNotNull(value))
                    _create(key, value);
                else
                    payload[key]=value;
            }
        }
    };
    _create(name,o);
    return payload;
}

Or as an alternative, you can make your server to receive HTTP POST request instead GET,

public PartialViewResult OnPostReloadCompaniesInAreaList([FormBody]List<CompanyInSearchAreaViewModel> companyInSearchAreaViewModels)
{
    ...
}

and then replace the $.load() to :

$.ajax({
   url: '@Request.Path?handler=ReloadCompaniesInAreaList',
   method:'POST',
   contentType:"application/json",
   data: searchResult,
   success: function(resp){
      $('#divSearchResult').html(resp)
   },
});


问:
How do I restart airflow webserver?
I am using airflow for my data pipeline project. I have configured my project in airflow and start the airflow server as a backend process using following command

```<code>airflow webserver -p 8080 -D True
</code>```

Server running successfully in backend. Now I want to enable authentication in airflow and done configuration changes in airflow.cfg, but authentication functionality is not reflected in server. when I stop and start airflow server in my local machine it works.

So How can I restart my daemon airflow webserver process in my server??

答:
The recommended approach is to create and enable the airflow webserver as a service. If you named the webserver as 'airflow-webserver', run the following command to restart the service:

systemctl restart airflow-webserver

You can use a ready-made AMI (namely, LightningFLow) from AWS Marketplace which provides Airflow services (webserver, scheduler, worker) which are enabled at startup.

Note: LightningFlow comes pre-integrated with all required libraries, Livy, custom operators, and local Spark cluster.

Link for AWS Marketplace: https://aws.amazon.com/marketplace/pp/Lightning-Analytics-Inc-LightningFlow-Integrated-o/B084BSD66V

Title: How do I restart airflow webserver?

Body:
I am using airflow for my data pipeline project. I have configured my project in airflow and start the airflow server as a backend process using following command

airflow webserver -p 8080 -D True

Server running successfully in backend. Now I want to enable authentication in airflow and done configuration changes in airflow.cfg, but authentication functionality is not reflected in server. when I stop and start airflow server in my local machine it works.

So How can I restart my daemon airflow webserver process in my server??


问:
Disable some future dates selection in FScalendar swift
Please help me! I am using https://github.com/WenchaoD/FSCalendar in my project . I want to disable some dates after current date. I want only 28 dates will be enable after current days. Is it possible?</p>

答:
Yes you can set number of day, for this you have to set minimum and maximum date of FScalander and for this you have to implement below code into your view controller.

```<code>extension ViewController:FSCalendarDataSource
{
    func minimumDate(for calendar: FSCalendar) -> Date {
        return Date()
    }
    func maximumDate(for calendar: FSCalendar) -> Date {
        var dateComponents:DateComponents = DateComponents()
        dateComponents.day = 28
        let currentCalander:Calendar = Calendar.current
        return currentCalander.date(byAdding:dateComponents, to: Date())!
    }
}
</code>```

and Make sure don't forget connect datasource of FSCalander in your viewcontroller

Body:
Yes you can set number of day, for this you have to set minimum and maximum date of FScalander and for this you have to implement below code into your view controller.

extension ViewController:FSCalendarDataSource
{
    func minimumDate(for calendar: FSCalendar) -> Date {
        return Date()
    }
    func maximumDate(for calendar: FSCalendar) -> Date {
        var dateComponents:DateComponents = DateComponents()
        dateComponents.day = 28
        let currentCalander:Calendar = Calendar.current
        return currentCalander.date(byAdding:dateComponents, to: Date())!
    }
}

and Make sure don't forget connect datasource of FSCalander in your viewcontroller


问:
Node offline API
Is it possible to create an API (with node.js) than handles get request from a mobile app?

I've read about service workers but I don't know if it's possible to use one to make an api to handle get request even when the client has no internet connection.

I'm trying to build an application which returns information about pediatric medicines even if the client is offline.

答:
Is it possible to create an API (with node.js) than handles get request from a mobile app?

Yes, it is possible. Node.js is a great choice to build your API and it has many advantages. API for a mobile app is not gonna be different from API for a regular website - same handlers, same get and post verbs.

I've read about service workers but I don't know if it's possible to use one to make an api work offline

I'm not 100% sure what do you mean by api work offline. API is just a piece of code which is executed on a server and this piece of code (usually) simply waits for a request to come so API can handle it. Some APIs can push data to clients, for example, thru WebSockets.

According to the documentation service worker is:

It's essentially a JavaScript file that runs separately from the main
  browser thread, intercepting network requests, caching or retrieving
  resources from the cache, and delivering push messages.

So, you can use service worker to make your PWA website/app look alive even if you backend is down/unavailable.

The schema is more like this:

Update

So, service worker lives on the client side and intercepts calls from a web page. Imagine that you simply make an AJAX request to your API from a page. Usually it goes directly to API, but service worker has an ability to intercept it and check if app is online or not. If yes, service worker gets information from API and stores it to Cache. If not service worker gets information from the Cache so for a web page it looks the same - page just got data.

Here is a good example and a video and I'll put some code here too, just in case.

index.html

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Boilerplate Service Worker</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">

</head>
<body>
    <div class="container">
        <h1>Boilerplate Service Worker</h1>

        <p>Below is an image of Earth from NASA</p>

        <p><img src="" alt="Image of Earth from Nasa" class="targetImage"></p>
    </div>
    <script src="js/app.js"></script>
</body>
</html>
</code>```

app.js

```<code>if ('serviceWorker' in navigator) {

  navigator.serviceWorker
    .register('./service-worker.js', { scope: './' })
    .then(function(registration) {
      console.log("Service Worker Registered");
    })
    .catch(function(err) {
      console.log("Service Worker Failed to Register", err);
    })
}

// Function to perform HTTP request
var get = function(url) {
  return new Promise(function(resolve, reject) {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var result = xhr.responseText
                result = JSON.parse(result);
                resolve(result);
            } else {
                reject(xhr);
            }
        }
    };

    xhr.open("GET", url, true);
    xhr.send();

  });
};

get('https://api.nasa.gov/planetary/earth/imagery?api_key=fWfSMcDzyHfMuH3BW6jiIUBYaj3hKRyKBRTBqgEQ')
  .then(function(response) {
    // There is an issue with the image being pulled from the API, so using a different one instead
    document.getElementsByClassName('targetImage')[0].src = "https://api.nasa.gov/images/earth.png";

  })
  .catch(function(err) {
    console.log("Error", err);
  })
</code>```

service-worker.js

```<code>// Set a name for the current cache
var cacheName = 'v1';

// Default files to always cache
var cacheFiles = [
    './',
    './index.html',
    './js/app.js',
    './css/reset.css',
    './css/style.css',
    'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic'
]

self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Installed');

    // e.waitUntil Delays the event until the Promise is resolved
    e.waitUntil(

        // Open the cache
        caches.open(cacheName).then(function(cache) {

            // Add all the default files to the cache
            console.log('[ServiceWorker] Caching cacheFiles');
            return cache.addAll(cacheFiles);
        })
    ); // end e.waitUntil
});

self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activated');

    e.waitUntil(

        // Get all the cache keys (cacheName)
        caches.keys().then(function(cacheNames) {
            return Promise.all(cacheNames.map(function(thisCacheName) {

                // If a cached item is saved under a previous cacheName
                if (thisCacheName !== cacheName) {

                    // Delete that cached file
                    console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
                    return caches.delete(thisCacheName);
                }
            }));
        })
    ); // end e.waitUntil

});

self.addEventListener('fetch', function(e) {
    console.log('[ServiceWorker] Fetch', e.request.url);

    // e.respondWidth Responds to the fetch event
    e.respondWith(

        // Check in cache for the request being made
        caches.match(e.request)

            .then(function(response) {

                // If the request is in the cache
                if ( response ) {
                    console.log("[ServiceWorker] Found in Cache", e.request.url, response);
                    // Return the cached version
                    return response;
                }

                // If the request is NOT in the cache, fetch and cache

                var requestClone = e.request.clone();
                return fetch(requestClone)
                    .then(function(response) {

                        if ( !response ) {
                            console.log("[ServiceWorker] No response from fetch ")
                            return response;
                        }

                        var responseClone = response.clone();

                        //  Open the cache
                        caches.open(cacheName).then(function(cache) {

                            // Put the fetched response in the cache
                            cache.put(e.request, responseClone);
                            console.log('[ServiceWorker] New Data Cached', e.request.url);

                            // Return the response
                            return response;

                        }); // end caches.open

                    })
                    .catch(function(err) {
                        console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
                    });

            }) // end caches.match(e.request)
    ); // end e.respondWith
});
</code>```

and you can find a style.css here and reset.css here. Those are not really important for this question, but just in case.

This example shows how to cache files, register service worker and subscribe for install, activate and fetch events.

I hope it helps

Title: Node offline API

Body:
Is it possible to create an API (with node.js) than handles get request from a mobile app?

Yes, it is possible. Node.js is a great choice to build your API and it has many advantages. API for a mobile app is not gonna be different from API for a regular website - same handlers, same get and post verbs.

I've read about service workers but I don't know if it's possible to use one to make an api work offline

I'm not 100% sure what do you mean by api work offline. API is just a piece of code which is executed on a server and this piece of code (usually) simply waits for a request to come so API can handle it. Some APIs can push data to clients, for example, thru WebSockets.

According to the documentation service worker is:

It's essentially a JavaScript file that runs separately from the main
  browser thread, intercepting network requests, caching or retrieving
  resources from the cache, and delivering push messages.

So, you can use service worker to make your PWA website/app look alive even if you backend is down/unavailable.

The schema is more like this:

Update

So, service worker lives on the client side and intercepts calls from a web page. Imagine that you simply make an AJAX request to your API from a page. Usually it goes directly to API, but service worker has an ability to intercept it and check if app is online or not. If yes, service worker gets information from API and stores it to Cache. If not service worker gets information from the Cache so for a web page it looks the same - page just got data.

Here is a good example and a video and I'll put some code here too, just in case.

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Boilerplate Service Worker</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">

</head>
<body>
    <div class="container">
        <h1>Boilerplate Service Worker</h1>

        <p>Below is an image of Earth from NASA</p>

        <p><img src="" alt="Image of Earth from Nasa" class="targetImage"></p>
    </div>
    <script src="js/app.js"></script>
</body>
</html>

app.js

if ('serviceWorker' in navigator) {

  navigator.serviceWorker
    .register('./service-worker.js', { scope: './' })
    .then(function(registration) {
      console.log("Service Worker Registered");
    })
    .catch(function(err) {
      console.log("Service Worker Failed to Register", err);
    })
}

// Function to perform HTTP request
var get = function(url) {
  return new Promise(function(resolve, reject) {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var result = xhr.responseText
                result = JSON.parse(result);
                resolve(result);
            } else {
                reject(xhr);
            }
        }
    };

    xhr.open("GET", url, true);
    xhr.send();

  });
};

get('https://api.nasa.gov/planetary/earth/imagery?api_key=fWfSMcDzyHfMuH3BW6jiIUBYaj3hKRyKBRTBqgEQ')
  .then(function(response) {
    // There is an issue with the image being pulled from the API, so using a different one instead
    document.getElementsByClassName('targetImage')[0].src = "https://api.nasa.gov/images/earth.png";

  })
  .catch(function(err) {
    console.log("Error", err);
  })

service-worker.js

// Set a name for the current cache
var cacheName = 'v1';

// Default files to always cache
var cacheFiles = [
    './',
    './index.html',
    './js/app.js',
    './css/reset.css',
    './css/style.css',
    'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic'
]

self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Installed');

    // e.waitUntil Delays the event until the Promise is resolved
    e.waitUntil(

        // Open the cache
        caches.open(cacheName).then(function(cache) {

            // Add all the default files to the cache
            console.log('[ServiceWorker] Caching cacheFiles');
            return cache.addAll(cacheFiles);
        })
    ); // end e.waitUntil
});

self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activated');

    e.waitUntil(

        // Get all the cache keys (cacheName)
        caches.keys().then(function(cacheNames) {
            return Promise.all(cacheNames.map(function(thisCacheName) {

                // If a cached item is saved under a previous cacheName
                if (thisCacheName !== cacheName) {

                    // Delete that cached file
                    console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
                    return caches.delete(thisCacheName);
                }
            }));
        })
    ); // end e.waitUntil

});

self.addEventListener('fetch', function(e) {
    console.log('[ServiceWorker] Fetch', e.request.url);

    // e.respondWidth Responds to the fetch event
    e.respondWith(

        // Check in cache for the request being made
        caches.match(e.request)

            .then(function(response) {

                // If the request is in the cache
                if ( response ) {
                    console.log("[ServiceWorker] Found in Cache", e.request.url, response);
                    // Return the cached version
                    return response;
                }

                // If the request is NOT in the cache, fetch and cache

                var requestClone = e.request.clone();
                return fetch(requestClone)
                    .then(function(response) {

                        if ( !response ) {
                            console.log("[ServiceWorker] No response from fetch ")
                            return response;
                        }

                        var responseClone = response.clone();

                        //  Open the cache
                        caches.open(cacheName).then(function(cache) {

                            // Put the fetched response in the cache
                            cache.put(e.request, responseClone);
                            console.log('[ServiceWorker] New Data Cached', e.request.url);

                            // Return the response
                            return response;

                        }); // end caches.open

                    })
                    .catch(function(err) {
                        console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
                    });

            }) // end caches.match(e.request)
    ); // end e.respondWith
});

and you can find a style.css here and reset.css here. Those are not really important for this question, but just in case.

This example shows how to cache files, register service worker and subscribe for install, activate and fetch events.

I hope it helps