问:
Variable becomes undefined when access in a class method
I defined a class variable in a constructor which holds a reference to an imported class instance.

However, when I try to access the variable in my class methods I keep getting undefined for that variable.

Exported class

```<code>import models from '../../database/models'

const {User} = models;

class UserRepository {
  constructor(){
    this.model = User;
  }

 async create({firstname, lastname, email, isadmin, password}){
  return await this.model.create({firstname, lastname, email, isadmin, password})
  }
}

export default new UserRepository();
</code>```

Class using the exported class

```<code>import repository from './repository';
import { sendSuccessMessage } from '../../utils'

class UserController {
  constructor() {
    this.model = repository;
  }

  async createUser({ body }, res, next) {
    try {
      const result = await this.model.create(body);
      sendSuccessMessage(res, 200, result);
    } catch( e ){
      next(e)
    }
  }
}

export default new UserController();
</code>```

However, using the variable repository directory in createUser as specified below:

const result = await repository.create(body);

works as expected.

Current call chain

```<code>// routes.js file
import controller from './controller'

export default [
  {
    path: '/signup',
    method: 'post',
    handlers: [controller.createUser] // createUser from class UserController
  }
]

// utitlity.js file
export const routesLoader = (routes, router) => {
 for (const route of routes) {
   const { path, handlers, method } = route;
   (router)[method](path, handlers);
 }
};

// app.js file
import express from 'express';
import routes from './routes.js';
import { routesLoader } from './utils';

const router = express.Router();

routesLoader(routes, router);

// server.js file
import http from 'http';
import app from './app';

const { PORT = 3000 } = process.env;

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`server listening on localhost: ${PORT}`);
});
</code>```

Error

```<code>TypeError: Cannot read property 'create' of undefined
at _callee$ (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user/controller.js:16:39)
at tryCatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.<computed> [as next] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12
at createUser (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user\controller.js:70:28)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:275:10)
at cors (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:188:7)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:214:15)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:199:9)
</code>```

Technologies used

```<code>@babel/node: "^7.8.4"
terminal: git bash
Os: windows
</code>```

答: Your method create is an instance method. It needs to be static for this to work</p>

Body:
I defined a class variable in a constructor which holds a reference to an imported class instance.

However, when I try to access the variable in my class methods I keep getting undefined for that variable.

Exported class

import models from '../../database/models'

const {User} = models;

class UserRepository {
  constructor(){
    this.model = User;
  }

 async create({firstname, lastname, email, isadmin, password}){
  return await this.model.create({firstname, lastname, email, isadmin, password})
  }
}

export default new UserRepository();

Class using the exported class

import repository from './repository';
import { sendSuccessMessage } from '../../utils'

class UserController {
  constructor() {
    this.model = repository;
  }

  async createUser({ body }, res, next) {
    try {
      const result = await this.model.create(body);
      sendSuccessMessage(res, 200, result);
    } catch( e ){
      next(e)
    }
  }
}

export default new UserController();

However, using the variable repository directory in createUser as specified below:

const result = await repository.create(body);

works as expected.

Current call chain

// routes.js file
import controller from './controller'

export default [
  {
    path: '/signup',
    method: 'post',
    handlers: [controller.createUser] // createUser from class UserController
  }
]

// utitlity.js file
export const routesLoader = (routes, router) => {
 for (const route of routes) {
   const { path, handlers, method } = route;
   (router)[method](path, handlers);
 }
};

// app.js file
import express from 'express';
import routes from './routes.js';
import { routesLoader } from './utils';

const router = express.Router();

routesLoader(routes, router);

// server.js file
import http from 'http';
import app from './app';

const { PORT = 3000 } = process.env;

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`server listening on localhost: ${PORT}`);
});

Error

TypeError: Cannot read property 'create' of undefined
at _callee$ (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user/controller.js:16:39)
at tryCatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.<computed> [as next] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12
at createUser (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user\controller.js:70:28)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:275:10)
at cors (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:188:7)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:214:15)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:199:9)

Technologies used

@babel/node: "^7.8.4"
terminal: git bash
Os: windows


来源: stackexchange

问:
Get file extension native method
I'm using MVS 2010, C++ program without using CRT.

Implementation of finding extension of file:

```<code>LPWSTR findExtension(LPCWSTR fileName)
{
    int pos = findchr(fileName, L".");
    if (pos != -1) {
        int lenght = lstrlenW(fileName);
        wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, lenght - pos + 1);
        for (int i = 0; i < lenght - pos; i++)
        {
            extension[i] = fileName[pos + 1 + i];
        }
        extension[lenght - pos] = 0;
        LPWSTR ret = extension;

        return ret;
    }
}
</code>```

There are problems. Sometimes it can crash application. And memory leak.
How to fix this issues?

答:
Your problem is:

```<code>int lenght = lstrlenW(fileName);
</code>```

lenght is the number of wide characters not the number of bytes. So you allocate a too small buffer here:

```<code>wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, lenght - pos + 1);
</code>```

You need to use this instead:

```<code>wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, sizeof(wchar_t) * (lenght - pos + 1));
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get file extension native method

Body:
I'm using MVS 2010, C++ program without using CRT.

Implementation of finding extension of file:

LPWSTR findExtension(LPCWSTR fileName)
{
    int pos = findchr(fileName, L".");
    if (pos != -1) {
        int lenght = lstrlenW(fileName);
        wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, lenght - pos + 1);
        for (int i = 0; i < lenght - pos; i++)
        {
            extension[i] = fileName[pos + 1 + i];
        }
        extension[lenght - pos] = 0;
        LPWSTR ret = extension;

        return ret;
    }
}

There are problems. Sometimes it can crash application. And memory leak.
How to fix this issues?

Body:
Your problem is:

int lenght = lstrlenW(fileName);

lenght is the number of wide characters not the number of bytes. So you allocate a too small buffer here:

wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, lenght - pos + 1);

You need to use this instead:

wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, sizeof(wchar_t) * (lenght - pos + 1));


问:
unix - head AND tail of file
Say you have a txt file, what is the command to view the top 10 lines and bottom 10 lines of file simultaneously?

i.e. if the file is 200 lines long, then view lines 1-10 and 190-200 in one go.

答:
Consumes stdin, but simple and works for 99% of use cases

head_and_tail

```<code>#!/usr/bin/env bash
COUNT=${1:-10}
IT=$(cat /dev/stdin)
echo "$IT" | head -n$COUNT
echo "..."
echo "$IT" | tail -n$COUNT
</code>```

example

```<code>$ seq 100 | head_and_tail 4
1
2
3
4
...
97
98
99
100
</code>```

ContentLicense: CC BY-SA 3.0

Title: unix - head AND tail of file

Body:
Consumes stdin, but simple and works for 99% of use cases

head_and_tail

#!/usr/bin/env bash
COUNT=${1:-10}
IT=$(cat /dev/stdin)
echo "$IT" | head -n$COUNT
echo "..."
echo "$IT" | tail -n$COUNT

example

$ seq 100 | head_and_tail 4
1
2
3
4
...
97
98
99
100


问:
Ho can save the loss function in a for cycle?
Goodmorning, I built neural network in order to predict a physical quantietis. I want to run 10 times the model in order to see the stability of the model. How can I create a DataFrame with all the loss function (both validation and training) evaluated along the 10 try? </p>

```<code>for i in range(10): #per in numero di esperimenti

    test_size = 0.2

    dataset = pd.read_csv('CompleteDataSet_original_Clean_TP.csv', decimal=',', delimiter = ";")

    label = dataset.iloc[:,-1]
    features = dataset[feat_labels]

    y_max_pre_normalize = max(label)
    y_min_pre_normalize = min(label)

    def denormalize(y):
        final_value = y*(y_max_pre_normalize-y_min_pre_normalize)+y_min_pre_normalize
        return final_value

    X_train1, X_test1, y_train1, y_test1 = train_test_split(features, label, test_size = test_size, shuffle = True)

    y_test2 = y_test1.to_frame()
    y_train2 = y_train1.to_frame()

    scaler1 = preprocessing.MinMaxScaler()
    scaler2 = preprocessing.MinMaxScaler()
    X_train = scaler1.fit_transform(X_train1)
    X_test = scaler2.fit_transform(X_test1)

    scaler3 = preprocessing.MinMaxScaler()
    scaler4 = preprocessing.MinMaxScaler()
    y_train = scaler3.fit_transform(y_train2)
    y_test = scaler4.fit_transform(y_test2)

    from keras import backend as K

    # =============================================================================
    # Creo la rete
    # =============================================================================
    optimizer = tf.keras.optimizers.Adam(lr=0.001)
    model = Sequential()

    model.add(Dense(100, input_shape = (X_train.shape[1],), activation = 'relu',kernel_initializer='glorot_uniform'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation = 'relu',kernel_initializer='glorot_uniform'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation = 'relu',kernel_initializer='glorot_uniform'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation = 'relu',kernel_initializer='glorot_uniform'))

    model.add(Dense(1,activation = 'linear',kernel_initializer='glorot_uniform'))

    model.compile(loss = 'mse', optimizer = optimizer, metrics = ['mse', r2_score])

    history = model.fit(X_train, y_train, epochs = 200,
                        validation_split = 0.1, shuffle=False, batch_size=250)

    history_dict = history.history

    loss_values = history_dict['loss']
    val_loss_values = history_dict['val_loss']

    y_train_pred = model.predict(X_train)
    y_test_pred = model.predict(X_test)

    y_train_pred = denormalize(y_train_pred)
    y_test_pred = denormalize(y_test_pred)
    from sklearn.metrics import r2_score

    from sklearn import metrics

    r2_test.append(r2_score(y_test_pred, y_test1))
    r2_train.append(r2_score(y_train_pred, y_train1))

     # Measure MSE error.
    MSE_test.append(metrics.mean_squared_error(y_test_pred,y_test1))
    MSE_train.append(metrics.mean_squared_error(y_train_pred,y_train1))
    RMSE_test.append(np.sqrt(metrics.mean_squared_error(y_test_pred,y_test1)))
    RMSE_train.append(np.sqrt(metrics.mean_squared_error(y_train_pred,y_train1)))
</code>```

答:
Without even using Pandas, just append them to a list. You can then use the pd.DataFrame() constructor if you really need a dataframe.

```<code>loss_and_val_loss = []
for i in range(...):
    # ...
    loss_values = history_dict['loss']
    val_loss_values = history_dict['val_loss']
    loss_and_val_loss.append((loss_values, val_loss_values))
# ...
</code>```

Assuming  both of those _valueses are lists of numbers, one per epoch, this can be pivoted into dataframes as follows:

```<code># (Example data with two trials, each with 3 epochs)
loss_and_val_loss = [
    ([1, 2, 3], [4, 5, 6]),
    ([7, 8, 9], [10, 11, 12]),
]
losses, val_losses = zip(*loss_and_val_loss)
losses_df = pd.DataFrame(losses)
val_losses_df = pd.DataFrame(val_losses)
</code>```

Body:
Goodmorning, I built neural network in order to predict a physical quantietis. I want to run 10 times the model in order to see the stability of the model. How can I create a DataFrame with all the loss function (both validation and training) evaluated along the 10 try?

for i in range(10): #per in numero di esperimenti

    test_size = 0.2

    dataset = pd.read_csv('CompleteDataSet_original_Clean_TP.csv', decimal=',', delimiter = ";")

    label = dataset.iloc[:,-1]
    features = dataset[feat_labels]

    y_max_pre_normalize = max(label)
    y_min_pre_normalize = min(label)

    def denormalize(y):
        final_value = y*(y_max_pre_normalize-y_min_pre_normalize)+y_min_pre_normalize
        return final_value

    X_train1, X_test1, y_train1, y_test1 = train_test_split(features, label, test_size = test_size, shuffle = True)

    y_test2 = y_test1.to_frame()
    y_train2 = y_train1.to_frame()

    scaler1 = preprocessing.MinMaxScaler()
    scaler2 = preprocessing.MinMaxScaler()
    X_train = scaler1.fit_transform(X_train1)
    X_test = scaler2.fit_transform(X_test1)

    scaler3 = preprocessing.MinMaxScaler()
    scaler4 = preprocessing.MinMaxScaler()
    y_train = scaler3.fit_transform(y_train2)
    y_test = scaler4.fit_transform(y_test2)

    from keras import backend as K

    # =============================================================================
    # Creo la rete
    # =============================================================================
    optimizer = tf.keras.optimizers.Adam(lr=0.001)
    model = Sequential()

    model.add(Dense(100, input_shape = (X_train.shape[1],), activation = 'relu',kernel_initializer='glorot_uniform'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation = 'relu',kernel_initializer='glorot_uniform'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation = 'relu',kernel_initializer='glorot_uniform'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation = 'relu',kernel_initializer='glorot_uniform'))

    model.add(Dense(1,activation = 'linear',kernel_initializer='glorot_uniform'))

    model.compile(loss = 'mse', optimizer = optimizer, metrics = ['mse', r2_score])

    history = model.fit(X_train, y_train, epochs = 200,
                        validation_split = 0.1, shuffle=False, batch_size=250)

    history_dict = history.history

    loss_values = history_dict['loss']
    val_loss_values = history_dict['val_loss']

    y_train_pred = model.predict(X_train)
    y_test_pred = model.predict(X_test)

    y_train_pred = denormalize(y_train_pred)
    y_test_pred = denormalize(y_test_pred)
    from sklearn.metrics import r2_score

    from sklearn import metrics

    r2_test.append(r2_score(y_test_pred, y_test1))
    r2_train.append(r2_score(y_train_pred, y_train1))

     # Measure MSE error.
    MSE_test.append(metrics.mean_squared_error(y_test_pred,y_test1))
    MSE_train.append(metrics.mean_squared_error(y_train_pred,y_train1))
    RMSE_test.append(np.sqrt(metrics.mean_squared_error(y_test_pred,y_test1)))
    RMSE_train.append(np.sqrt(metrics.mean_squared_error(y_train_pred,y_train1)))

Body:
Without even using Pandas, just append them to a list. You can then use the pd.DataFrame() constructor if you really need a dataframe.

loss_and_val_loss = []
for i in range(...):
    # ...
    loss_values = history_dict['loss']
    val_loss_values = history_dict['val_loss']
    loss_and_val_loss.append((loss_values, val_loss_values))
# ...

Assuming  both of those _valueses are lists of numbers, one per epoch, this can be pivoted into dataframes as follows:

# (Example data with two trials, each with 3 epochs)
loss_and_val_loss = [
    ([1, 2, 3], [4, 5, 6]),
    ([7, 8, 9], [10, 11, 12]),
]
losses, val_losses = zip(*loss_and_val_loss)
losses_df = pd.DataFrame(losses)
val_losses_df = pd.DataFrame(val_losses)


问:
Overwrite style for specific pages
I don't know if this is possible, but this is what I am trying to achieve.
For class category icon and icon-location-pin-4 styles are generating automatically in code. Actually they are defined inside the plugin in wp. If I change color there, it reflects on all pages.

For some pages on the site, I don't want to have these colors displayed, I want specific colors just for few sites and those colors will remain always.

```<code><span class="category-icon" style="background-color: #649744;">
   <i class="icon-location-pin-4" style="color: #ffffff; "></i>
</span>
</code>```

I am not sure how to achieve this, or it is possible? On some pages, the code will look like.. This is what I want to achieve.

```<code><span class="category-icon" style="background-color: #fff;">
   <i class="icon-location-pin-4" style="color: #000; "></i>
</span>
</code>```

I am having two rows in same section, I want it to apply only for second row..

```<code><div class="listing-details footer-section">
    <ul class="preview-category-list">
        <li>
            <a href="">
                <span class="category-icon" style="background-color: #281784;">
                    <i class="fa fa-ticket" style="color: #fff; "></i>
                </span>
                <span class="category-name">Category 1</span>
            </a>
        </li>

    </ul>
</div>
<div class="listing-details footer-section">
    <ul class="preview-category-list">
        <li>
            <a href="">
                <span class="category-icon" style="background-color: #281784;">
                    <i class="icon-location-pin-4" style="color: #fff; "></i>
                </span>
                <span class="category-name">Category 2</span>
            </a>
        </li>

    </ul>
</div>
</code>```

I want to make changes for for backgorund where icon-location-pin-4 is printed out, not for code above. But when I change backgorund, it gets applied for code above too

答:
If you want to give styles for odd/event row then you can use :child() css selector like as below :

```<code>div.listing-details:nth-child(2) {
  background: red;
}
</code>```

The above code only usable when you want to apply CSS for 2nd div with 'listing-details' class.

If you want to apply css for all event div's  then you can use following code :

```<code> div.listing-details:nth-child(even) {
      background: red;
    }
</code>```

Or you want to apply css for all div's but particular page then you can use ID(#) for that, like as follow:

```<code>#ID_Of_Page div.listing-details:nth-child(even) {
  background: red;
}
</code>```

Title: Overwrite style for specific pages

Body:
I don't know if this is possible, but this is what I am trying to achieve.
For class category icon and icon-location-pin-4 styles are generating automatically in code. Actually they are defined inside the plugin in wp. If I change color there, it reflects on all pages.

For some pages on the site, I don't want to have these colors displayed, I want specific colors just for few sites and those colors will remain always.

I am not sure how to achieve this, or it is possible? On some pages, the code will look like.. This is what I want to achieve.

I am having two rows in same section, I want it to apply only for second row..

                Category 1

                Category 2

I want to make changes for for backgorund where icon-location-pin-4 is printed out, not for code above. But when I change backgorund, it gets applied for code above too

Body:
If you want to give styles for odd/event row then you can use :child() css selector like as below :

div.listing-details:nth-child(2) {
  background: red;
}

The above code only usable when you want to apply CSS for 2nd div with 'listing-details' class.

If you want to apply css for all event div's  then you can use following code :

 div.listing-details:nth-child(even) {
      background: red;
    }

Or you want to apply css for all div's but particular page then you can use ID(#) for that, like as follow:

#ID_Of_Page div.listing-details:nth-child(even) {
  background: red;
}


问:
Delete a folder already exist php
I have created folder based on year and month (while I upload image), eg: if I upload an pdf on February 1 2018 then I have created folder 2018 and folder 2.

```<code> $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder1/admin/slip' . '/' . $year . '';
                    $filename2 = $filename . '/' . $month;
                    if (file_exists($filename)) {
                        if (file_exists($filename2) == false) {
                            mkdir($filename2, 0777);
                        }
                    } else {
                        mkdir($filename, 0777);
                    }
</code>```

If I again upload an pdf in February, I want to delete this folder and create it again. I use the following code

```<code>rmdir($filename2)
</code>```

but its not working.

please help me

答:
```<code><?php

delete_files('/path/for/the/directory/');

/*
 * php delete function that deals with directories recursively
 */
function delete_files($target) {
    if(is_dir($target)){
        $files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

        foreach( $files as $file ){
            delete_files( $file );
        }

        rmdir( $target );
    } elseif(is_file($target)) {
        unlink( $target );
    }
}
?>
</code>```

Title: Delete a folder already exist php

Body:
I have created folder based on year and month (while I upload image), eg: if I upload an pdf on February 1 2018 then I have created folder 2018 and folder 2.

 $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder1/admin/slip' . '/' . $year . '';
                    $filename2 = $filename . '/' . $month;
                    if (file_exists($filename)) {
                        if (file_exists($filename2) == false) {
                            mkdir($filename2, 0777);
                        }
                    } else {
                        mkdir($filename, 0777);
                    }

If I again upload an pdf in February, I want to delete this folder and create it again. I use the following code

rmdir($filename2)

but its not working.

please help me


问:
Spring Boot command line property not overriding property defined in application.properties
I have created a Spring Boot app which uses a legacy library.  This legacy library defines a number of Spring Beans in XML.  One of which take in a property value as a constructor argument:

```<code><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myBean" class="com.em.MyBean">
        <constructor-arg name="url" value="${my.url}"/>
    </bean>
</beans>
</code>```

In my Spring Boot app, I have an application.properties which defines this property as follows:

```<code>my.url=http://localhost:8080
</code>```

I use the Maven Spring Boot plugin to run my app locally as follows:

```<code>mvn spring-boot:run
</code>```

And the property value is injected into the bean as expected.

If I try and override the my.url property on the command line like this:

```<code>mvn spring-boot:run -Dmy.url=http://www.override.net
</code>```

The overriden value is not used and instead, the value inside application.properties is used.

According to the Spring Boot docs, values from the command line should be picked up as the first priority: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html.  That does not appear to be the case here because if I remove the property from application.properties then the value passed in on the command line is used so it is not a case of the command line value being ignored altogether.  It seems like the application.properties value is overriding the command line value.

Does anyone have any ideas as to what is going on?

答:
Just adding a typical mistake: The SpringApplication.run method used in the application main class accepts a variable-length argument and won't throw a compile-time warning if you provide no arguments:

public static void main( String[] args )
{
    SpringApplication.run( MyApplication.class, args );
}
```

It's important to pass the args argument from the main method on to SpringApplication.run. If you don't then no command line arguments will be picked up or take effect.

Body:
I have created a Spring Boot app which uses a legacy library.  This legacy library defines a number of Spring Beans in XML.  One of which take in a property value as a constructor argument:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myBean" class="com.em.MyBean">
        <constructor-arg name="url" value="${my.url}"/>
    </bean>
</beans>

In my Spring Boot app, I have an application.properties which defines this property as follows:

my.url=http://localhost:8080

I use the Maven Spring Boot plugin to run my app locally as follows:

mvn spring-boot:run

And the property value is injected into the bean as expected.

If I try and override the my.url property on the command line like this:

mvn spring-boot:run -Dmy.url=http://www.override.net

The overriden value is not used and instead, the value inside application.properties is used.

According to the Spring Boot docs, values from the command line should be picked up as the first priority: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html.  That does not appear to be the case here because if I remove the property from application.properties then the value passed in on the command line is used so it is not a case of the command line value being ignored altogether.  It seems like the application.properties value is overriding the command line value.

Does anyone have any ideas as to what is going on?

Body:
Just adding a typical mistake: The SpringApplication.run method used in the application main class accepts a variable-length argument and won't throw a compile-time warning if you provide no arguments:

public static void main( String[] args )
{
    SpringApplication.run( MyApplication.class, args );
}

It's important to pass the args argument from the main method on to SpringApplication.run. If you don't then no command line arguments will be picked up or take effect.


问:
Unable to click on radio buttons while executing script-UFT tool
I am unable to click on radio button while executing script by using UFT/QTP tool. Below is my code:

```<code>Browser("Welcome!").Page("Welcome!_9").WebList("pickupOnePauId").Select "Aisha Shop"
Browser("Welcome!").Page("Welcome!_9").WebRadioGroup("pdaId_Mon").Select "#3"
Browser("Welcome!").Page("Welcome!_9").WebRadioGroup("pdaId_Tue").Select "#3"
</code>```

答:
You need to select the what is mentioned in the value property of the input tag for that radio element.

For Example

if your html tag is like this

```<code><input name="priceOrder" class="custom-control-input priceOrderAsc" id="priceOrderDes" type="radio" value="des">
</code>```

then your UFT object selection should be

```<code>Browser("Hotels Results").Page("Hotels Results").WebRadioGroup("high to low").Select "acs"
</code>```

You can also specify the index for the select value using "#index" as you have done, but index starts with 0, which means as per your code you are trying to select 4th radio button in that radio group

If you paste your html markup for those dropdowns we can tell what needs to go in the select.

Body:
I am unable to click on radio button while executing script by using UFT/QTP tool. Below is my code:

Browser("Welcome!").Page("Welcome!_9").WebList("pickupOnePauId").Select "Aisha Shop"
Browser("Welcome!").Page("Welcome!_9").WebRadioGroup("pdaId_Mon").Select "#3"
Browser("Welcome!").Page("Welcome!_9").WebRadioGroup("pdaId_Tue").Select "#3"

Body:
You need to select the what is mentioned in the value property of the input tag for that radio element.

For Example

if your html tag is like this

<input name="priceOrder" class="custom-control-input priceOrderAsc" id="priceOrderDes" type="radio" value="des">

then your UFT object selection should be

Browser("Hotels Results").Page("Hotels Results").WebRadioGroup("high to low").Select "acs"

You can also specify the index for the select value using "#index" as you have done, but index starts with 0, which means as per your code you are trying to select 4th radio button in that radio group

If you paste your html markup for those dropdowns we can tell what needs to go in the select.


问:
grep extract specific pattern from a large file of 190GB
I need to extract the email addresses from a large 190GB flat file (only error log) that I cut into a 5mb files. (with 152,353,216 lines)

The grep command works well, but the memory quickly becomes saturated and I end up getting errors.

The content of the files is not formatted, so I have to use regexp.

```<code>grep -r -E -h -o "\b(pattern)\b" /dir/* > outs.txt
</code>```

How to process files one by one?

答:
Use xargs to execute your grep command on each file separately (rather than on all the files)

```<code>ls -1 /dir/ | xargs -n 1 -I '{}' grep -r -E -h -o "\b(pattern)\b" '{}' > outs.txt
</code>```

The -n 1 flag instructs xargs to run one process on each file.

The -I '{}' argument instructs xargs to replace '{}' with the name of the file.

In other words, if /dir contains file1, file2, ..., it executes successively

```<code>grep -r -E -h -o "\b(pattern)\b" /dir/file1
grep -r -E -h -o "\b(pattern)\b" /dir/file2
grep -r -E -h -o "\b(pattern)\b" /dir/file3...
</code>```

Body:
I need to extract the email addresses from a large 190GB flat file (only error log) that I cut into a 5mb files. (with 152,353,216 lines)

The grep command works well, but the memory quickly becomes saturated and I end up getting errors.

The content of the files is not formatted, so I have to use regexp.

grep -r -E -h -o "\b(pattern)\b" /dir/* > outs.txt

How to process files one by one?

Body:
Use xargs to execute your grep command on each file separately (rather than on all the files)

ls -1 /dir/ | xargs -n 1 -I '{}' grep -r -E -h -o "\b(pattern)\b" '{}' > outs.txt

The -n 1 flag instructs xargs to run one process on each file.

The -I '{}' argument instructs xargs to replace '{}' with the name of the file.

In other words, if /dir contains file1, file2, ..., it executes successively

grep -r -E -h -o "\b(pattern)\b" /dir/file1
grep -r -E -h -o "\b(pattern)\b" /dir/file2
grep -r -E -h -o "\b(pattern)\b" /dir/file3...


问:
Problems to import json with VueJs
So, I'm trying to import a json file to be able to set some params in my application. The code I'm using to import my json is:

```<code>import json from './json/config.json'
export default {
    data() {
        return {
            URL_FILE_IMPORT: json.fileImport,
        }
    }
}
</code>```

... and my config.json is very simple so far:

```<code>{
    "fileImport": "<my_url_goes_here>",
}
</code>```

The problem is that I'm facing this error:

```<code>ERROR  Failed to compile with 1 errors

This relative module was not found:

* ./json/config.json in ./src/services/config.js
</code>```

But I have access to the file, if I click in the ./json/config.json path.

I've seen that there are some differences between some vue.js versions about the json configuration. I'm not 100% sure how to see the version I'm using, but my @vue/cli-service is version 4.2.2. Does anyone knows how to solve it?

So, I've found my solution. It was very simple, I just needed to use

```<code>const jsonData = require('../json/config.json');
</code>```

... and with this I can access jsonData.fileImport

答: Маке sure the path is correct, if you make import in file ./src/services/config.js with path "./json/data.json" it will look for json in ./src/services/json. Where exactly is your folder /json, if it is in src folder then import should be "../json/data.json". Usually there is alias in web-pack "@" which is to "/src", then import will be "@/json/config.json"</p>

Title: Problems to import json with VueJs

Body:
So, I'm trying to import a json file to be able to set some params in my application. The code I'm using to import my json is:

import json from './json/config.json'
export default {
    data() {
        return {
            URL_FILE_IMPORT: json.fileImport,
        }
    }
}

... and my config.json is very simple so far:

{
    "fileImport": "<my_url_goes_here>",
}

The problem is that I'm facing this error:

ERROR  Failed to compile with 1 errors

This relative module was not found:

* ./json/config.json in ./src/services/config.js

But I have access to the file, if I click in the ./json/config.json path.

I've seen that there are some differences between some vue.js versions about the json configuration. I'm not 100% sure how to see the version I'm using, but my @vue/cli-service is version 4.2.2. Does anyone knows how to solve it?

So, I've found my solution. It was very simple, I just needed to use

const jsonData = require('../json/config.json');

... and with this I can access jsonData.fileImport


问:
Android immersive fullscreen mode on a single fragment
I am trying to apply immersive full screen on one of my 3 fragments,  just like given in the tutorial as:

```<code>private void hideSystemUI() {
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    View decorView = getActivity(). getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            // Hide the nav bar and status bar
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
</code>```

And called the method from the fragments's  onCreateView method.

I expected this to effect the fragment only, but instead, its effecting all fragments.

How can I force the immersive screen to effect a screen single fragment only?

答:
You apply immersive mode to activity's decor view and as I understand you have a single activity application, so it applies to your "root" activity.
Try to exit immerse mode on destroying of fragment. For example:</p>

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//...
    Handler().post {
        activity?.window?.decorView?.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        }
//...
}

//...

override fun onDestroyView() {
//...
    Handler().post {
        activity?.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
    }
    super.onDestroyView()
}
</code>```

Body:
I am trying to apply immersive full screen on one of my 3 fragments,  just like given in the tutorial as:

private void hideSystemUI() {
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    View decorView = getActivity(). getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            // Hide the nav bar and status bar
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

And called the method from the fragments's  onCreateView method.

I expected this to effect the fragment only, but instead, its effecting all fragments.

How can I force the immersive screen to effect a screen single fragment only?

Body:
You apply immersive mode to activity's decor view and as I understand you have a single activity application, so it applies to your "root" activity.
Try to exit immerse mode on destroying of fragment. For example:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//...
    Handler().post {
        activity?.window?.decorView?.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        }
//...
}

//...

override fun onDestroyView() {
//...
    Handler().post {
        activity?.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
    }
    super.onDestroyView()
}


问:
Bootstrap 4 carousel-fade animation not working properly
So I was working on my web project where I used form over carousel using css. It's working perfectly with sliding animation but when I am adding class carousel-fade the form at the center is also fading with the carousel but I want to prevent that. Here, In example instead of that big form I used a simple
 tag for demonstration. How can I solve this issue ?

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

I am at center

```

答:
Just add a z-index higher then 1 to #vcenter:

```<code>#vcenter {
   position: absolute ;
   top: 55%;
   left: 50%;
   transform: translate(-50%, -50%);
   font-weight: bold ;
   z-index: 9;
}
</code>```

You need that because the active slide has a z-index of 1. Check that yourself. :)

Body:
Just add a z-index higher then 1 to #vcenter:

#vcenter {
   position: absolute ;
   top: 55%;
   left: 50%;
   transform: translate(-50%, -50%);
   font-weight: bold ;
   z-index: 9;
}

You need that because the active slide has a z-index of 1. Check that yourself. :)


问:
SLIME setup for both Common Lisp and Clojure development
I've been having trouble with setting up SLIME to work with both Clojure and Common Lisp. Most Clojure devs tend to use the stripped down SLIME available via ELPA that is frozen for Clojure compatibility. I, however, do a lot of Common Lisp hacking as well and I generally use the SLIME CVS version (obtained via QuickLisp).

There are some well known problems with the swank implementation for Clojure - it doesn't work with autodoc (if it's enabled SLIME freezes), it doesn't support some things like fuzzy-completion, etc. This question discusses the same subject the the answer suggested there is a no go for me.

```<code>(add-hook 'slime-connected-hook
          (lambda ()
            (if (string= (slime-lisp-implementation-type) "Clojure")
                (setq slime-use-autodoc-mode nil)
              (setq slime-use-autodoc-mode t))
            ))

(add-hook 'slime-mode-hook
          (lambda ()
            (if (eq major-mode 'clojure-mode)
                  (slime-autodoc-mode 0)
                (slime-autodoc-mode 1))))

(add-hook 'slime-repl-mode-hook
          (lambda ()
            (if (string= (slime-lisp-implementation-type) "Clojure")
                (progn (setq slime-use-autodoc-mode nil)
                       (slime-autodoc-mode 0))
              (progn (setq slime-use-autodoc-mode t)
                     (slime-autodoc-mode 1)))))
</code>```

The solution looks great on paper, but for me slime-lisp-implementation-type is always nil. (same for slime-lisp-implementation-type:connlocal with local connections).

What I basically need is just a way to know I running SLIME with Clojure's swank to be able to modify the problematic settings.

答:
It seems that the solution to this problem was just created. It's called jack-in. Basically you just need to do three things:

Install clojure-mode via git or Marmalade

lein plugin install swank-clojure 1.3.1

Invoke M-x clojure-jack-in from a project

This will bootstrap the supported SLIME automatically. You no longer need to install it via ELPA. I've wrapped my Common Lisp init in an interactive function that I can call when I need it, because loading the Clojure SLIME naturally messes up a few settings. It's not as ideal a solution as upstream Clojure support in SLIME, but it's much better than most alternative...

Update:

SLIME is no longer needed for Clojure development. I recommend you to use CIDER instead.

Body:
I've been having trouble with setting up SLIME to work with both Clojure and Common Lisp. Most Clojure devs tend to use the stripped down SLIME available via ELPA that is frozen for Clojure compatibility. I, however, do a lot of Common Lisp hacking as well and I generally use the SLIME CVS version (obtained via QuickLisp).

There are some well known problems with the swank implementation for Clojure - it doesn't work with autodoc (if it's enabled SLIME freezes), it doesn't support some things like fuzzy-completion, etc. This question discusses the same subject the the answer suggested there is a no go for me.

(add-hook 'slime-connected-hook
          (lambda ()
            (if (string= (slime-lisp-implementation-type) "Clojure")
                (setq slime-use-autodoc-mode nil)
              (setq slime-use-autodoc-mode t))
            ))

(add-hook 'slime-mode-hook
          (lambda ()
            (if (eq major-mode 'clojure-mode)
                  (slime-autodoc-mode 0)
                (slime-autodoc-mode 1))))

(add-hook 'slime-repl-mode-hook
          (lambda ()
            (if (string= (slime-lisp-implementation-type) "Clojure")
                (progn (setq slime-use-autodoc-mode nil)
                       (slime-autodoc-mode 0))
              (progn (setq slime-use-autodoc-mode t)
                     (slime-autodoc-mode 1)))))

The solution looks great on paper, but for me slime-lisp-implementation-type is always nil. (same for slime-lisp-implementation-type:connlocal with local connections).

What I basically need is just a way to know I running SLIME with Clojure's swank to be able to modify the problematic settings.


答:
First, you need to import UserRepository properly before its utilization.

```<code>import UserRepository from 'path to UserRepository class';
</code>```

then
Use self in your function as follows:

```<code>async createUser({ body }, res, next) {
 const self = this;
 try {
   const result = await self.model.create(body);
   sendSuccessMessage(res, 200, result);
 } catch( e ){
   next(e)
 }
}
</code>```

I think better to use self as compared to this in your createUser() function.

Title: Variable becomes undefined when access in a class method

Body:
I defined a class variable in a constructor which holds a reference to an imported class instance.

However, when I try to access the variable in my class methods I keep getting undefined for that variable.

Exported class

import models from '../../database/models'

const {User} = models;

class UserRepository {
  constructor(){
    this.model = User;
  }

 async create({firstname, lastname, email, isadmin, password}){
  return await this.model.create({firstname, lastname, email, isadmin, password})
  }
}

export default new UserRepository();

Class using the exported class

import repository from './repository';
import { sendSuccessMessage } from '../../utils'

class UserController {
  constructor() {
    this.model = repository;
  }

  async createUser({ body }, res, next) {
    try {
      const result = await this.model.create(body);
      sendSuccessMessage(res, 200, result);
    } catch( e ){
      next(e)
    }
  }
}

export default new UserController();

However, using the variable repository directory in createUser as specified below:

const result = await repository.create(body);

works as expected.

Current call chain

// routes.js file
import controller from './controller'

export default [
  {
    path: '/signup',
    method: 'post',
    handlers: [controller.createUser] // createUser from class UserController
  }
]

// utitlity.js file
export const routesLoader = (routes, router) => {
 for (const route of routes) {
   const { path, handlers, method } = route;
   (router)[method](path, handlers);
 }
};

// app.js file
import express from 'express';
import routes from './routes.js';
import { routesLoader } from './utils';

const router = express.Router();

routesLoader(routes, router);

// server.js file
import http from 'http';
import app from './app';

const { PORT = 3000 } = process.env;

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`server listening on localhost: ${PORT}`);
});

Error

TypeError: Cannot read property 'create' of undefined
at _callee$ (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user/controller.js:16:39)
at tryCatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.<computed> [as next] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12
at createUser (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user\controller.js:70:28)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:275:10)
at cors (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:188:7)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:214:15)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:199:9)

Technologies used

@babel/node: "^7.8.4"
terminal: git bash
Os: windows

Body:
First, you need to import UserRepository properly before its utilization.

import UserRepository from 'path to UserRepository class';

then
Use self in your function as follows:

async createUser({ body }, res, next) {
 const self = this;
 try {
   const result = await self.model.create(body);
   sendSuccessMessage(res, 200, result);
 } catch( e ){
   next(e)
 }
}

I think better to use self as compared to this in your createUser() function.


问:
The HTTP request is not being executed in response - Flutter/Dart
I'm trying to perform a request to a Web API written in C# (.NET Core). The endpoint runs a async function and return a JSON with result of operation.

In Dart I can't get the response. then() or catchError() just don't executes.

The endpoint get products in payload. When I send only one product I can get the response but when ai send two or more I can't.

The payload is:

http .post('http://192.168.0.10:5000/api/v1/oficina/dart',
                  body: jsonEncode({
                    "usuario": "edigleyssonsilva",
                    "senha": "123456",
                    "codEmp": 1,
                    "codFil": 1,
                    "produtos": [
                      {
                        "ccuRes": "160",
                        "codEmp": 1,
                        "codFil": 1,
                        "codPro": "570.0001",
                        "codTns": "90250",
                        "datPrv": "2020-02-17",
                        "datEme": "2020-02-17",
                        "qtdEme": 2
                      }
                    ]
                  }),
                  headers: {'Content-Type': 'application/json'})
              .then((value) => print(value.body))
              .catchError((err) {
                print('Ocorreu um erro');
                print(err);
              });
```

I already tested the same endpoint with the same payload on Postman, Angular app and on a test file written in Dart and this works perfectly.

So, I have no idea why it doesn't work in Flutter

答:
It's not very clear tell with the code you shared, either also share the code calling this function, but you can also try, with assigning your body to a Map object, and then encode it with json.encode, as jsonEncode was deprecated in new versions, though it works, but you should use the new way to encode it.
Also, you should use async-await while doing any asynchronous work.</p>

```<code>Future<void> request() async {

 Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
Map body = {"usuario": "edigleyssonsilva",
                    "senha": "123456",
                    "codEmp": 1,
                    "codFil": 1,
                    "produtos": [
                      {
                        "ccuRes": "160",
                        "codEmp": 1,
                        "codFil": 1,
                        "codPro": "570.0001",
                        "codTns": "90250",
                        "datPrv": "2020-02-17",
                        "datEme": "2020-02-17",
                        "qtdEme": 2
                      }
                    ]};
final response = await http.post(url,
                body: json.encode(body),
                headers: headers,
              ).catchError((err) {
                print('Ocorreu um erro');
                print(err);
              });
print('Response: ${response.body}');
}
</code>```

Body:
I'm trying to perform a request to a Web API written in C# (.NET Core). The endpoint runs a async function and return a JSON with result of operation.

In Dart I can't get the response. then() or catchError() just don't executes.

The endpoint get products in payload. When I send only one product I can get the response but when ai send two or more I can't.

The payload is:

http .post('http://192.168.0.10:5000/api/v1/oficina/dart',
                  body: jsonEncode({
                    "usuario": "edigleyssonsilva",
                    "senha": "123456",
                    "codEmp": 1,
                    "codFil": 1,
                    "produtos": [
                      {
                        "ccuRes": "160",
                        "codEmp": 1,
                        "codFil": 1,
                        "codPro": "570.0001",
                        "codTns": "90250",
                        "datPrv": "2020-02-17",
                        "datEme": "2020-02-17",
                        "qtdEme": 2
                      }
                    ]
                  }),
                  headers: {'Content-Type': 'application/json'})
              .then((value) => print(value.body))
              .catchError((err) {
                print('Ocorreu um erro');
                print(err);
              });

I already tested the same endpoint with the same payload on Postman, Angular app and on a test file written in Dart and this works perfectly.

So, I have no idea why it doesn't work in Flutter

Body:
It's not very clear tell with the code you shared, either also share the code calling this function, but you can also try, with assigning your body to a Map object, and then encode it with json.encode, as jsonEncode was deprecated in new versions, though it works, but you should use the new way to encode it.
Also, you should use async-await while doing any asynchronous work.

Future<void> request() async {

 Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
Map body = {"usuario": "edigleyssonsilva",
                    "senha": "123456",
                    "codEmp": 1,
                    "codFil": 1,
                    "produtos": [
                      {
                        "ccuRes": "160",
                        "codEmp": 1,
                        "codFil": 1,
                        "codPro": "570.0001",
                        "codTns": "90250",
                        "datPrv": "2020-02-17",
                        "datEme": "2020-02-17",
                        "qtdEme": 2
                      }
                    ]};
final response = await http.post(url,
                body: json.encode(body),
                headers: headers,
              ).catchError((err) {
                print('Ocorreu um erro');
                print(err);
              });
print('Response: ${response.body}');
}


问:
Numpy Array operation Y[ ..., 0]
Just a quick question,

I came across a NumPy array operation which is important for the code and i cannot understand what this does.

```<code>Probs = Y[ ... , 0]
</code>```

Code for reference Python code

Any help will be appreciated.

答:
In a 2d numpy array this should give you the first element of each nested list, so for example:

import numpy as np
Y = np.asarray([[1,2,3,4], [1,2,3,4], [2,3,4,5]])
Y[..., 0]
>>> array([1, 1, 2])
```

Title: Numpy Array operation Y[ ..., 0]

Body:
Just a quick question,

I came across a NumPy array operation which is important for the code and i cannot understand what this does.

Probs = Y[ ... , 0]

Code for reference Python code

Any help will be appreciated.


问:
I keep getting a "Failed to load resource: net::ERR_FILE_NOT_FOUND" error, and have no idea how to fix it
This is the error Im faced with. I have a localhost server stood up, and am trying to get my background, and logo working, but I am confused on file pathing. (/, ../, etc). Does anyone have an absolute solution to what Im doing wrong? Below Ive listed the html, css, and error message Im getting. If anyone can give me some helpful tips of EXACTLY what should be where using an example I would appreciate it. Thanks

答:
You have to change the paths of your code as follow:

index.html

```<code><img src="Nozamalogo.png" width="112" height="28">
</code>```

style.css

```<code>body, html, .navbar{
   background-image: url(../books.jpg);
}
</code>```

Body:
You have to change the paths of your code as follow:

index.html

<img src="Nozamalogo.png" width="112" height="28">

style.css

body, html, .navbar{
   background-image: url(../books.jpg);
}


问:
Set x XML node to value in Powershell
I have this PowerShell script in which values for an XML-file will be set by the script. This works perfectly fine when all child nodes are uniquely named. However, I'm adapting the XML-file to one where some nodes are repeated. Now I get an error in Powershell.

My question is, how to set the X'th node in XML to a certain value via PowerShell?

In short, my script works like the following:

```<code>cls

[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>'

$xml1.Lvl1.Lvl2='./'

$xml1.Save("text.xml")
</code>```

There is two times the same node (Lvl2), that's why I get the following error in PowerShell: "Cannot set "Lvl2" because only strings can be used as values to set XmlNode properties."

When I remove one (Lvl2) node, the script works like a charm.

Please advice.

答:
You can always use .NET syntax, it works like a charm.</p>

```<code>$xml1.SelectSingleNode('Lvl1/Lvl2[2]').InnerText='./'
</code>```

Title: Set x XML node to value in Powershell

Body:
I have this PowerShell script in which values for an XML-file will be set by the script. This works perfectly fine when all child nodes are uniquely named. However, I'm adapting the XML-file to one where some nodes are repeated. Now I get an error in Powershell.

My question is, how to set the X'th node in XML to a certain value via PowerShell?

In short, my script works like the following:

cls

[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>'

$xml1.Lvl1.Lvl2='./'

$xml1.Save("text.xml")

There is two times the same node (Lvl2), that's why I get the following error in PowerShell: "Cannot set "Lvl2" because only strings can be used as values to set XmlNode properties."

When I remove one (Lvl2) node, the script works like a charm.

Please advice.

Body:
You can always use .NET syntax, it works like a charm.

$xml1.SelectSingleNode('Lvl1/Lvl2[2]').InnerText='./'


问:
How do I run Google Dataprep jobs automatically?
Is there a way to trigger Google Dataprep flow over API?

I need to run like 30 different flows every day. Every day the source dataset changes and the result has to be appended to Google BigQuery table. Is there a way to automate this process? Source files are .xls files. I can upload them to cloud storage and write a cloud function that will upload it wherever Dataprep needs. The problem is that it seems to be impossible to replace the source dataset in a Dataprep flow. If so, then what's the point of scheduled runs and the new Job Run API?

答:
You are asking two different things.

How to trigger jobs via API: https://cloud.google.com/dataprep/docs/html/API-JobGroups-Create-v4_145281446

How to effectively replace datasets dynamically:    https://cloud.google.com/dataprep/docs/html/Overview-of-Parameterization_118228665


问:
How to properly read an HTTP Post message segmented into two TCP segments?
When I execute the following Python code on a pcap file:

```<code>if tcp.dport == 80:
   try:
      http=dpkt.http.Request(tcp.data)
   except (dpkt.dpkt.NeedData):
      continue
   except (dpkt.dpkt.UnpackError):
      continue
if http.method == 'POST':
   print('POST Message')
</code>```

Packets such as the following ones create a problem:

These are a single HTTP Post message segmented into two TCP segments and each one is sent in a different packet. However, because the first segment is a TCP only and the second one is recognised as HTTP, it seems that when dpkt.http.Request tries to read the first segment as HTTP it fails.

So far no problem. It is OK to fail as it is not really a full HTTP message. However, the issue is that it does not seem to be reading the second segment at all ("POST Message" is not printed)!!! The second segment is totally ignored as if it does not exist!!! The only possible explanation for that is that dpkt automatically reads the second segment at once as it recognises they both are segments for the same message.

The issue is that, though both TCP segments are read at once (following the above assumption), the resulted tcp.data is not recognised as an HTTP packet, rather it is still recognised as TCP only because the first segment of the message is a TCP only packet.

So what shall I do to read the HTTP header and data of such pcap file?

答:
Or you could use the builtin feature in Scapy 2.4.3+
https://scapy.readthedocs.io/en/latest/layers/http.html</p>

```<code>sniff(session=TCPSession, [...])
</code>```

Body:
When I execute the following Python code on a pcap file:

if tcp.dport == 80:
   try:
      http=dpkt.http.Request(tcp.data)
   except (dpkt.dpkt.NeedData):
      continue
   except (dpkt.dpkt.UnpackError):
      continue
if http.method == 'POST':
   print('POST Message')

Packets such as the following ones create a problem:

These are a single HTTP Post message segmented into two TCP segments and each one is sent in a different packet. However, because the first segment is a TCP only and the second one is recognised as HTTP, it seems that when dpkt.http.Request tries to read the first segment as HTTP it fails.

So far no problem. It is OK to fail as it is not really a full HTTP message. However, the issue is that it does not seem to be reading the second segment at all ("POST Message" is not printed)!!! The second segment is totally ignored as if it does not exist!!! The only possible explanation for that is that dpkt automatically reads the second segment at once as it recognises they both are segments for the same message.

The issue is that, though both TCP segments are read at once (following the above assumption), the resulted tcp.data is not recognised as an HTTP packet, rather it is still recognised as TCP only because the first segment of the message is a TCP only packet.

So what shall I do to read the HTTP header and data of such pcap file?

Body:
Or you could use the builtin feature in Scapy 2.4.3+
https://scapy.readthedocs.io/en/latest/layers/http.html

sniff(session=TCPSession, [...])


问:
How can I use the value of one variable when i declare another
I am new to jquery but getting there. I am stuck trying to add the value from one var to when I declare another.

Here is my code -

```<code>var selected = jQuery(this).val();

var vt = jQuery('.details-tcs').find('input:radio:checked').val();
</code>```

I need to use the first var 'selected' with a value of 'AI' and add it to the second var 'vt' so it looks like -

```<code>var vt = jQuery('.details-tcs.AI').find('input:radio:checked').val();
</code>```

Any help really appreciated.

答:
You can do it like this

var vt = jQuery(`.details-tcs.${selected}`).find('input:radio:checked').val();```

Body:
I am new to jquery but getting there. I am stuck trying to add the value from one var to when I declare another.

Here is my code -

var selected = jQuery(this).val();

var vt = jQuery('.details-tcs').find('input:radio:checked').val();

I need to use the first var 'selected' with a value of 'AI' and add it to the second var 'vt' so it looks like -

var vt = jQuery('.details-tcs.AI').find('input:radio:checked').val();

Any help really appreciated.


问:
Data from Three MySQL table to one master table
I have three customer tables:

example:

```<code>customers_1, customers_2, customers_3
</code>```

And want to create a new master table which will have ONLY the LATEST UPDATED record of a single customer.

One customer can have 1 record in all three tables.
One customer can have multiple records in all three tables.
One customer can have ONLY 1 record in any one table.

```<code>'mobile_no' is used to identify uniqueness.
'updated_at' is used to know the latest record.
</code>```

I am going to write it in PHP. I just want to know what is the best approach.

Note: Assume that one table (say customers_1) will always have more records than the other two.
Example:

```<code>customers_1: 500000 records
customers_2: 250000 records
customers_3: 220000 records
</code>```

答:
I would suggest window functions:

```<code>select c.*
from (select c.*,
             row_number() over (partition by mobile_no order by updated_at) as seqnum
      from ((select c.* from customers_1
            ) union all
            (select c.* from customers_2
            ) union all
            (select c.* from customers_3
            )
           ) c
      ) c
where seqnum = 1;
</code>```

You may not want to use select *.  It is typically better to list all the columns that you want.

Body:
I have three customer tables:

example:

customers_1, customers_2, customers_3

And want to create a new master table which will have ONLY the LATEST UPDATED record of a single customer.

One customer can have 1 record in all three tables.
One customer can have multiple records in all three tables.
One customer can have ONLY 1 record in any one table.

'mobile_no' is used to identify uniqueness.
'updated_at' is used to know the latest record.

I am going to write it in PHP. I just want to know what is the best approach.

Note: Assume that one table (say customers_1) will always have more records than the other two.
Example:

customers_1: 500000 records
customers_2: 250000 records
customers_3: 220000 records

Body:
I would suggest window functions:

select c.*
from (select c.*,
             row_number() over (partition by mobile_no order by updated_at) as seqnum
      from ((select c.* from customers_1
            ) union all
            (select c.* from customers_2
            ) union all
            (select c.* from customers_3
            )
           ) c
      ) c
where seqnum = 1;

You may not want to use select *.  It is typically better to list all the columns that you want.


问:
Display real progress of loading WPF DataGrid instead of .IsIndeterminate
I have managed to get ProgressBar into my WPF form. However  my current skill is stuck on using:

```<code>ProgressBar.IsIndeterminate = true;

DataGrid1.ItemsSource = await GetDataAsync();

ProgressBar.IsIndeterminate = false;
</code>```

Any professional ready to describe how to get ProgressBar to display actual loading progress?

Here is my full code:

```<code>    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
        try
        {
            ProgressBar.IsIndeterminate = true;

            DataGrid1.ItemsSource = await GetDataAsync();

            ProgressBar.IsIndeterminate = false;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private Task<DataView> GetDataAsync()
    {
        return Task.Run(() =>
        {

            string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=@DEDBFS;Uid=DEUsername;Pwd=DEPassword;";
            string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
            string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=@FRDBFS;Uid=FRUsername;Pwd=FRPassword;";
            string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

            DataTable dataTable = new DataTable("COMPANY");
            // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
            using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
            {
                dbConnectionDE.Open();
                OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                dadapterDE.Fill(dataTable);

            }
            using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
            {
                dbConnectionFR.Open();
                OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                var newTable = new DataTable("COMPANY");
                dadapterFR.Fill(newTable);

                dataTable.Merge(newTable);

            }

            return dataTable.DefaultView;
        });
    }
</code>```

答:
You can't display the actual process unless you know it and you don't unless the API that you are using actually reports the current progress to you.

The OdbcCommand API doesn't so you should stick to using indeterminate progress bars.

Body:
I have managed to get ProgressBar into my WPF form. However  my current skill is stuck on using:

ProgressBar.IsIndeterminate = true;

DataGrid1.ItemsSource = await GetDataAsync();

ProgressBar.IsIndeterminate = false;

Any professional ready to describe how to get ProgressBar to display actual loading progress?

Here is my full code:

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
        try
        {
            ProgressBar.IsIndeterminate = true;

            DataGrid1.ItemsSource = await GetDataAsync();

            ProgressBar.IsIndeterminate = false;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private Task<DataView> GetDataAsync()
    {
        return Task.Run(() =>
        {

            string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=@DEDBFS;Uid=DEUsername;Pwd=DEPassword;";
            string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
            string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=@FRDBFS;Uid=FRUsername;Pwd=FRPassword;";
            string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

            DataTable dataTable = new DataTable("COMPANY");
            // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
            using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
            {
                dbConnectionDE.Open();
                OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                dadapterDE.Fill(dataTable);

            }
            using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
            {
                dbConnectionFR.Open();
                OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                var newTable = new DataTable("COMPANY");
                dadapterFR.Fill(newTable);

                dataTable.Merge(newTable);

            }

            return dataTable.DefaultView;
        });
    }


问:
Laravel api authenticates POST requests but returns 'Unauthenticated' with GET
I have setup a Route group to authenticate my API calls with a token.

POST requests work fine, valid token passes authentication and an invalid one returns "Unauthenticated" as expected.

When making a GET request I get "Unauthenticated" every time.

I'm making GET requests with the same api_token that I made the POST requests with and still get "Unauthenticated"

This is my route group

```<code>Route::group(['middleware' => ['auth:api', 'api']], function () {
    Route::post('/', 'ApiPostController@store');
    Route::get('/', 'ApiPostController@fetch');
});

</code>```

I tried removing the POST route from the group, that didn't work. Tried changing the route (from / to /get) that didn't do anything either.

What is causing the GET requests to fail even though I'm sending a valid token?

答: The problem is you send api_token in body and the request body is different for GET and POST requests. Also sending tokens in the GET body is insecure, that's why you have to send tokens via headers.

Body:
I have setup a Route group to authenticate my API calls with a token.

POST requests work fine, valid token passes authentication and an invalid one returns "Unauthenticated" as expected.

When making a GET request I get "Unauthenticated" every time.

I'm making GET requests with the same api_token that I made the POST requests with and still get "Unauthenticated"

This is my route group

Route::group(['middleware' => ['auth:api', 'api']], function () {
    Route::post('/', 'ApiPostController@store');
    Route::get('/', 'ApiPostController@fetch');
});

I tried removing the POST route from the group, that didn't work. Tried changing the route (from / to /get) that didn't do anything either.

What is causing the GET requests to fail even though I'm sending a valid token?


问:
Identify connection between two columns and insert corresponding values
I have the following table which you can also find in the SQL fiddle here:

```<code>CREATE TABLE Products (
    Eventtype TEXT,
    CampaignID TEXT,
    Product TEXT,
    Quantity VARCHAR(255)
);

INSERT INTO Products
(Eventtype, CampaignID, Product, Quantity)
VALUES

("Event_01", "9857", NULL, "500"),
("Event_01", "5504", NULL, "670"),
("Event_01", "4589", NULL, "950"),
("Event_01", "77801", NULL, "750"),

("Event_02", "9857", "Product A", "300"),
("Event_03", "9857", "Product A", "250"),
("Event_02", "77801", "Product A", "350"),
("Event_03", "77801", "Product A", "150"),

("Event_02", "5504", "Product B", "270"),
("Event_03", "5504", "Product B", "850"),
("Event_02", "4589", "Product B", "420"),
("Event_03", "4589", "Product B", "630");
</code>```

I use the following query:

```<code>Select Eventtype, CampaignID, Product, Quantity
FROM Products
WHERE Product = "Product B";
</code>```

All this works fine so far.

Event_01 only has a CampaignID.

Event_02 and Event_03 have a CampaignID and Products.

Now I want that if I select Product B in the query the corresponding values on CampaignID level for Event_01 are inserted into the results.

Basically, Event_02 and Event_03 should be used to identify that Product B is connected to a certain CampaignID and then the quantity for this CampaignID in Event_01 is displayed:

The desired result should look like this:

```<code>Eventtype         CampaignID         Product         Quantity
Event_01          4589               NULL               950
Event_01          5504               NULL               670
Event_02          4589               Product B          420
Event_02          5504               Product B          270
Event_03          4589               Product B          630
Event_04          5504               Product B          850
</code>```

How do I have to modify my query to achieve this result?

答:
With reference to this this question the solution is:

```<code>SELECT Eventtype, CampaignID, Product, Quantity
FROM Products
WHERE
CampaignID IN
   (Select CampaignID
    FROM Products
    WHERE Product = "Product B")
 GROUP BY 1,2;
</code>```

http://www.sqlfiddle.com/#!9/c6b4322/1

Body:
I have the following table which you can also find in the SQL fiddle here:

CREATE TABLE Products (
    Eventtype TEXT,
    CampaignID TEXT,
    Product TEXT,
    Quantity VARCHAR(255)
);

INSERT INTO Products
(Eventtype, CampaignID, Product, Quantity)
VALUES

("Event_01", "9857", NULL, "500"),
("Event_01", "5504", NULL, "670"),
("Event_01", "4589", NULL, "950"),
("Event_01", "77801", NULL, "750"),

("Event_02", "9857", "Product A", "300"),
("Event_03", "9857", "Product A", "250"),
("Event_02", "77801", "Product A", "350"),
("Event_03", "77801", "Product A", "150"),

("Event_02", "5504", "Product B", "270"),
("Event_03", "5504", "Product B", "850"),
("Event_02", "4589", "Product B", "420"),
("Event_03", "4589", "Product B", "630");

I use the following query:

Select Eventtype, CampaignID, Product, Quantity
FROM Products
WHERE Product = "Product B";

All this works fine so far.

Event_01 only has a CampaignID.

Event_02 and Event_03 have a CampaignID and Products.

Now I want that if I select Product B in the query the corresponding values on CampaignID level for Event_01 are inserted into the results.

Basically, Event_02 and Event_03 should be used to identify that Product B is connected to a certain CampaignID and then the quantity for this CampaignID in Event_01 is displayed:

The desired result should look like this:

Eventtype         CampaignID         Product         Quantity
Event_01          4589               NULL               950
Event_01          5504               NULL               670
Event_02          4589               Product B          420
Event_02          5504               Product B          270
Event_03          4589               Product B          630
Event_04          5504               Product B          850

How do I have to modify my query to achieve this result?

Body:
With reference to this this question the solution is:

SELECT Eventtype, CampaignID, Product, Quantity
FROM Products
WHERE
CampaignID IN
   (Select CampaignID
    FROM Products
    WHERE Product = "Product B")
 GROUP BY 1,2;

http://www.sqlfiddle.com/#!9/c6b4322/1


问:
Can I color the same string in one Excel file or CSV file?
For example, the first and third columns are compared, and if they are the same character string, they are colored.
Repeat this line by line.

I want to know how to do this using python.
It would be nice if you could give me an example.

答:
I do not know how this can done in an excel file. The openpyxl or xlswriter module could be an good starting point -google for python excel module for more).

But for a csv file, I am sorry the the only way is to print it and then use coloured pencils on the printed paper. A CSV file is a plain text file


问:
Generating a basic sales report
So close to finish generating a report using SQL only. Very proud, but I'm stuck because I know I'm doing something the long way (the subquery in the SELECT statement).

I'm trying to fix the jan2019_sales, because its just giving me the SUM of sales in total, but I need it divided into the divisional sales for 2019, but I know that a subquery can only return 1 column, so I can't have both the division and the sales come up for 2019.

What's the best way to tackle this simple piece??? Ugh. I made a region for the portion that I (strongly believe) is the issue, wherein there is a much easier way. Here's a picture of what I am trying to fix (column C):

```<code>SELECT
    t2.new_division AS division,
    SUM(extended_amount) AS jan2020_sales,
-- region
    ((SELECT
    t2.new_division AS division,
    SUM(extended_amount)
FROM
    mdwh.us_raw.l_dmw_order_report t1 INNER JOIN item_master_zs t2 ON SUBSTRING(t1.upc,1,6) = t2.item_code
WHERE
    quantity_ordered > 0
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND oms_order_date BETWEEN '2019-01-01' AND '2019-01-31'
GROUP BY
    division
ORDER BY
    division)) AS jan2019_sales,
-- endregion
    ROUND((jan2020_sales / jan2019_sales * 100)) || '%' AS pct_change
FROM
    mdwh.us_raw.l_dmw_order_report t1 INNER JOIN item_master_zs t2 ON SUBSTRING(t1.upc,1,6) = t2.item_code
WHERE
    quantity_ordered > 0
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND oms_order_date BETWEEN '2020-01-01' AND '2020-01-31'
    AND t2.new_division BETWEEN '11' AND '38'
GROUP BY
    division
ORDER BY
    division
</code>```

答:
One of the issues here is that  you have the same alias' for both inner (2019) and outer (2020) queries. Also, the inner query is returning multiple rows because there is no join on the division for the different year sales.

In your 2019 sales query (inner query), you have to have that division joined to your outer query (2020) division. You may want to alias the queries differently so you can reference the outer query.

Change your inner query alias' to t3 and t4. Then in your inner query Where clause. Add, t2.new_division = t4.new_division.

Title: Generating a basic sales report

Body:
So close to finish generating a report using SQL only. Very proud, but I'm stuck because I know I'm doing something the long way (the subquery in the SELECT statement).

I'm trying to fix the jan2019_sales, because its just giving me the SUM of sales in total, but I need it divided into the divisional sales for 2019, but I know that a subquery can only return 1 column, so I can't have both the division and the sales come up for 2019.

What's the best way to tackle this simple piece??? Ugh. I made a region for the portion that I (strongly believe) is the issue, wherein there is a much easier way. Here's a picture of what I am trying to fix (column C):

SELECT
    t2.new_division AS division,
    SUM(extended_amount) AS jan2020_sales,
-- region
    ((SELECT
    t2.new_division AS division,
    SUM(extended_amount)
FROM
    mdwh.us_raw.l_dmw_order_report t1 INNER JOIN item_master_zs t2 ON SUBSTRING(t1.upc,1,6) = t2.item_code
WHERE
    quantity_ordered > 0
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND oms_order_date BETWEEN '2019-01-01' AND '2019-01-31'
GROUP BY
    division
ORDER BY
    division)) AS jan2019_sales,
-- endregion
    ROUND((jan2020_sales / jan2019_sales * 100)) || '%' AS pct_change
FROM
    mdwh.us_raw.l_dmw_order_report t1 INNER JOIN item_master_zs t2 ON SUBSTRING(t1.upc,1,6) = t2.item_code
WHERE
    quantity_ordered > 0
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND oms_order_date BETWEEN '2020-01-01' AND '2020-01-31'
    AND t2.new_division BETWEEN '11' AND '38'
GROUP BY
    division
ORDER BY
    division


问:
Enabling autocomplete in sbcl
I have recently started to learn lisp, and have mainly bin using clisp and vim. I wanted to try sbcl as well, since this is often recommended as one of the best, free lisp compilers. There is one thing, though, which makes sbcl more difficult to use for me: I can not get autocomplete in the REPL, which I do have in clisp. That is, when I start sbcl and type the following (as an example),

```<code>* (requi<tab>
</code>```

where <tab> is the literal tab character, I do not get a list of completions, but rather a verbose tab character. In clisp, <tab> will complete the previous line to * (require.

As I am fairly new to lisp, the autocomplete functionality in clisp is really handy, so it would really be very convenient if anyone could explain how to get it in sbcl as well.

答:
Actually it's completely possible. Yes, You want to work with Common Lisp via Emacs and Slime (I prefer SLY). But it's another wall beginners hit.

You want to just play from the REPL?
The following instructions allow autocomplete in SBCL with rlwrap.

https://www.cliki.net/CMUCL%20Hints

1) install rlwrap

2) create shell alias, for example putting text like

```<code>alias rs="rlwrap sbcl"
</code>```

into your ~/.bashrc (or ~/.profile or whatever).
(or you can continue calling sbcl rlwrapped via "rlwrap sbcl")

3)Edi Weitz created a completion list file that is now gone from his website, so i'm linking to the Internet Archive. save this wordlist into a file "sbcl"
https://web.archive.org/web/20031207221537/http://weitz.de/files/cmucl_completions

4)You can try putting the file according to the instructions on Cliki, this will only apply for the user you are logged in under. I wanted it to work for all users, so I put the "sbcl" file into my rlwrap completion directory, which is in
/usr/share/rlwrap/completions/

So now I have a file /usr/share/rlwrap/completions/sbcl
That contains the words.

5)Create / adjust
~/.inputrc file add the line

```<code>TAB: complete
</code>```

5) Done, now in a new terminal (or after reloading .bashrc)
I can launch SBCL via rlwrap with the alias "rs"
start typing (def (or whatever) and hit  TAB, and get auto-completion suggestions.

Beginner Bonus - if you want to edit lisp in the terminal, from the REPL, in say, vim with parinfer, try magic-ed, which will allow you to edit files from the repl. Configuring SBCL to use ED is esoteric. This solves that issue for You.
https://github.com/sanel/magic-ed
With tab auto-completion and convenient way to edit lisp from the terminal, one can start learning Common Lisp in the terminal.

ContentLicense: CC BY-SA 2.5

Title: Enabling autocomplete in sbcl

Body:
I have recently started to learn lisp, and have mainly bin using clisp and vim. I wanted to try sbcl as well, since this is often recommended as one of the best, free lisp compilers. There is one thing, though, which makes sbcl more difficult to use for me: I can not get autocomplete in the REPL, which I do have in clisp. That is, when I start sbcl and type the following (as an example),

* (requi<tab>

where <tab> is the literal tab character, I do not get a list of completions, but rather a verbose tab character. In clisp, <tab> will complete the previous line to * (require.

As I am fairly new to lisp, the autocomplete functionality in clisp is really handy, so it would really be very convenient if anyone could explain how to get it in sbcl as well.

Body:
Actually it's completely possible. Yes, You want to work with Common Lisp via Emacs and Slime (I prefer SLY). But it's another wall beginners hit.

You want to just play from the REPL?
The following instructions allow autocomplete in SBCL with rlwrap.

https://www.cliki.net/CMUCL%20Hints

1) install rlwrap

2) create shell alias, for example putting text like

alias rs="rlwrap sbcl"

into your ~/.bashrc (or ~/.profile or whatever).
(or you can continue calling sbcl rlwrapped via "rlwrap sbcl")

3)Edi Weitz created a completion list file that is now gone from his website, so i'm linking to the Internet Archive. save this wordlist into a file "sbcl"
https://web.archive.org/web/20031207221537/http://weitz.de/files/cmucl_completions

4)You can try putting the file according to the instructions on Cliki, this will only apply for the user you are logged in under. I wanted it to work for all users, so I put the "sbcl" file into my rlwrap completion directory, which is in
/usr/share/rlwrap/completions/

So now I have a file /usr/share/rlwrap/completions/sbcl
That contains the words.

5)Create / adjust
~/.inputrc file add the line

TAB: complete

5) Done, now in a new terminal (or after reloading .bashrc)
I can launch SBCL via rlwrap with the alias "rs"
start typing (def (or whatever) and hit  TAB, and get auto-completion suggestions.

Beginner Bonus - if you want to edit lisp in the terminal, from the REPL, in say, vim with parinfer, try magic-ed, which will allow you to edit files from the repl. Configuring SBCL to use ED is esoteric. This solves that issue for You.
https://github.com/sanel/magic-ed
With tab auto-completion and convenient way to edit lisp from the terminal, one can start learning Common Lisp in the terminal.


问:
How to loop through each entry in using For Loop JavaScript
My loop function is as below

```<code> var resources= jsonObj.entry;
 var resourceType;
 var i;
 for (i = 0; i < resources.length; i++) {
  resourceType += resources[i];
  }

  console.log(resourceType)
</code>```

if i do jsonObj.entry[0] i get the first entry so i implemented for-loop to get all the entries but console.log on resourceType prints the following

答:
So, one way to do it is

```<code>var resources = jsonObj.entry;
var resourceTypeArray = [];
var resourceType = "";

for (let item = 0; item <= resources.length; item++) {
  // This will remove all cases where the item doesn't exist and/or resource doesn't exist
  if(resources[item] && resources[item].resource){
      resourceTypeArray.push(resources[item].resource);
      resourceType += JSON.stringify(resources[item].resource);
  }
}

// printing out to the console the array with resources
console.info(resourceTypeArray);

// printing out to the console the string with the concatenation of the resources
console.info(resourceType);
</code>```

I also created a StackBlitz with the working solution and your json file kindly provided.

hope it helps.

Body:
My loop function is as below

 var resources= jsonObj.entry;
 var resourceType;
 var i;
 for (i = 0; i < resources.length; i++) {
  resourceType += resources[i];
  }

  console.log(resourceType)

if i do jsonObj.entry[0] i get the first entry so i implemented for-loop to get all the entries but console.log on resourceType prints the following

Body:
So, one way to do it is

var resources = jsonObj.entry;
var resourceTypeArray = [];
var resourceType = "";

for (let item = 0; item <= resources.length; item++) {
  // This will remove all cases where the item doesn't exist and/or resource doesn't exist
  if(resources[item] && resources[item].resource){
      resourceTypeArray.push(resources[item].resource);
      resourceType += JSON.stringify(resources[item].resource);
  }
}

// printing out to the console the array with resources
console.info(resourceTypeArray);

// printing out to the console the string with the concatenation of the resources
console.info(resourceType);

I also created a StackBlitz with the working solution and your json file kindly provided.

hope it helps.


问:
Is there a way to use a custom Angular Directive to apply a ngIf "effect"?
I have an application which has a Role based access. I'm using *ngIf's to allow/block users from access some components.

Is there a way to use a custom directive that will process the "existence" of the component based on the user role; instead of a complete *ngIf condition like this:

```<code><admin-menu *ngIf="user.role =='admin'"></admin-menu>

<admin-menu my-custom-directive ></admin-menu>

    my-custom-directive {

    //make the component where this directive is attached render or vanish based on the user.role
    ngAfterViewInit() {
        if(user.role == 'admin'){
            //render the component
        } else {
            //vanish the component
        }
    }
}
</code>```

答:
You can use TemplateRef and ViewContainerRef to create custom *ngIf directive. For example:

@Directive({
    selector: '[claims]'
})
export class CustomNgIfDirective {

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
    ){}

    @Input()
    set claims(claims) {
        let createEmbeddedView: boolean = false;

        if(claims) {
            if(Array.isArray(claims)) {
                createEmbeddedView = claims.every((passedClaim: string | number) => {
                    return claimExists(passedClaim);
                });
            } else {
                createEmbeddedView = claimExists(claims);
            }
        } else {
            createEmbeddedView = true;
        }

        if(createEmbeddedView) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        }
    }

}
```

<p>And in the html:</p>

<pre class="lang-html prettyprint-override"><code>
<button *claims="'canSubmitClaim'">submit</button>

</code>```

Body:
I have an application which has a Role based access. I'm using *ngIf's to allow/block users from access some components.

Is there a way to use a custom directive that will process the "existence" of the component based on the user role; instead of a complete *ngIf condition like this:

<admin-menu *ngIf="user.role =='admin'"></admin-menu>

<admin-menu my-custom-directive ></admin-menu>

    my-custom-directive {

    //make the component where this directive is attached render or vanish based on the user.role
    ngAfterViewInit() {
        if(user.role == 'admin'){
            //render the component
        } else {
            //vanish the component
        }
    }
}

Body:
You can use TemplateRef and ViewContainerRef to create custom *ngIf directive. For example:

@Directive({
    selector: '[claims]'
})
export class CustomNgIfDirective {

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
    ){}

    @Input()
    set claims(claims) {
        let createEmbeddedView: boolean = false;

        if(claims) {
            if(Array.isArray(claims)) {
                createEmbeddedView = claims.every((passedClaim: string | number) => {
                    return claimExists(passedClaim);
                });
            } else {
                createEmbeddedView = claimExists(claims);
            }
        } else {
            createEmbeddedView = true;
        }

        if(createEmbeddedView) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        }
    }

}

And in the html:

<button *claims="'canSubmitClaim'">submit</button>