问:
ServerSocket how to receive multiple files
I have studies project. I my teacherd don't want to tell me how to solve problem with receive multiple files. I know I need to use function getInputStream() but I don't know how to split those files in this inputStream object. I need to split this inputStream beacuse I need to save each file in folder.

Thank you for your help and for explaining this problem to me.

答:
It sounds like your instructor wants you to create a protocol. The reason you will need a protocol is that if you send multiple files across the same socket you wont know when one file stops and another begins. To simplify the problem I will use a simple chat application as example, but the same will apply to files.

Lets say you have a chat app which has only 2 users (one server to client). Each user can send a message of any length. Lets say User1 wants to send User2 the following messages (each line is one message)

```<code>Hello User
How are you doing today?
</code>```

If you send each of those raw messages across the socket you would likely get
Hello UserHow are you doing today?. Now how do you know where one message started and another stopped?

Simple solution is to send something before each message stating a length of characters in the upcoming message, so your message might be

```<code>11Hello User24How are you doing today?
</code>```

So the end user knows that I read an int which tells me <length>, then read <length> characters to get a full message.

Now thats a pretty basic example and not super great. Lets look at a simple packet format I have seen used in a video game:

```<code>Field Name   Field Type   Notes
Length       VarInt       Length of packet data + length of the packet ID
Packet ID    VarInt
Data         Byte Array   Depends on the connection state and packet ID, see the sections below
</code>```

This is the basic format all information between the client and server uses. A length of data to be read, a packet type followed by its data for that packet type.

For your use case you likely need something similar, some sort of meta data about the bytes you are sending. EG: Length of file, file name.

I would start by looking at the DataInputStream class for easily reading primitive data types.

Body:
It sounds like your instructor wants you to create a protocol. The reason you will need a protocol is that if you send multiple files across the same socket you wont know when one file stops and another begins. To simplify the problem I will use a simple chat application as example, but the same will apply to files.

Lets say you have a chat app which has only 2 users (one server to client). Each user can send a message of any length. Lets say User1 wants to send User2 the following messages (each line is one message)

Hello User
How are you doing today?

If you send each of those raw messages across the socket you would likely get
Hello UserHow are you doing today?. Now how do you know where one message started and another stopped?

Simple solution is to send something before each message stating a length of characters in the upcoming message, so your message might be

11Hello User24How are you doing today?

So the end user knows that I read an int which tells me <length>, then read <length> characters to get a full message.

Now thats a pretty basic example and not super great. Lets look at a simple packet format I have seen used in a video game:

Field Name   Field Type   Notes
Length       VarInt       Length of packet data + length of the packet ID
Packet ID    VarInt
Data         Byte Array   Depends on the connection state and packet ID, see the sections below

This is the basic format all information between the client and server uses. A length of data to be read, a packet type followed by its data for that packet type.

For your use case you likely need something similar, some sort of meta data about the bytes you are sending. EG: Length of file, file name.

I would start by looking at the DataInputStream class for easily reading primitive data types.


来源: stackexchange

问:
iOS 12.3.1 (16F203) Support Files needed
I downloaded the newest iOS update to my iPhone 7+ and got this message

When it happened to me before on the 12.1 update I used this answer to add the file to the DeviceSupport folder.

I've been looking around on SO and I can't find anything that supports 12.3.1, the closest I found is 12.2. I tried this answer which led to this answer but it didn't work for me:

Does anyone know where the 12.3.1 update is at?

答: You need to update your Xcode too, every time you do an OS update on your device, you need to update Xcode also.</p>

ContentLicense: CC BY-SA 4.0


问:
Keras: Transfer Learning - Image scaling worsens performance of the model significantly
I am working on an image classification problem with keras and tensorflow. I am using the VGG16 model with Imagenet weights and I am importing my data using the ImageDataGenerator from Keras.

Now I've been reading that one should always rescale the images using 1./255 for an efficient tranining. However, once I implement the scaling my model performs significantly worse than before. Changing the learning rate and batch size didn't help either.

Now I am questioning whether this is possible or if my model has some error. I am using standard .jpg image files.

```<code>from keras.preprocessing.image import ImageDataGenerator
IMAGE_SIZE = 224
BATCH_SIZE = 32

num_classes = 27

main_path = "C:/Users/abc/data"

final_path = os.path.join(main_path, "ML_DATA")
labels = listdir(gesamt_path)

data_generator = ImageDataGenerator(rescale=1./255, ### rescaling done here
                                    validation_split=0.20)

train_generator = data_generator.flow_from_directory(final_path, target_size=(IMAGE_SIZE, IMAGE_SIZE), shuffle=True, seed=13,
                                                     class_mode='categorical', batch_size=BATCH_SIZE, subset="training")

validation_generator = data_generator.flow_from_directory(final_path, target_size=(IMAGE_SIZE, IMAGE_SIZE), shuffle=False, seed=13,
                                                     class_mode='categorical', batch_size=BATCH_SIZE, subset="validation")
</code>```

Model definition and training

```<code>vgg16_model = keras.applications.vgg16.VGG16(weights='imagenet', include_top=True)
model = Sequential()
for layer in vgg16_model.layers[:-1]:
    model.add(layer)

for layer in model.layers:
    layer.trainable = False

model.add(Dense(num_classes, activation='softmax'))

model.compile(Adam(lr=.001), loss='categorical_crossentropy', metrics=['accuracy'])

history = model.fit_generator(train_generator,
                    validation_data=validation_generator,
                    epochs=85, verbose=1,callbacks=[tbCallBack,earlystopCallback])
</code>```

答:
Working with ResNet and imagenet weights I improved my results using:

ImageDataGenerator(preprocessing_function=preprocess_input)

With rescaling I obtained worse results too.

This information was useful to me:

https://github.com/matterport/Mask_RCNN/issues/231

Body:
I am working on an image classification problem with keras and tensorflow. I am using the VGG16 model with Imagenet weights and I am importing my data using the ImageDataGenerator from Keras.

Now I've been reading that one should always rescale the images using 1./255 for an efficient tranining. However, once I implement the scaling my model performs significantly worse than before. Changing the learning rate and batch size didn't help either.

Now I am questioning whether this is possible or if my model has some error. I am using standard .jpg image files.

from keras.preprocessing.image import ImageDataGenerator
IMAGE_SIZE = 224
BATCH_SIZE = 32

num_classes = 27

main_path = "C:/Users/abc/data"

final_path = os.path.join(main_path, "ML_DATA")
labels = listdir(gesamt_path)

data_generator = ImageDataGenerator(rescale=1./255, ### rescaling done here
                                    validation_split=0.20)

train_generator = data_generator.flow_from_directory(final_path, target_size=(IMAGE_SIZE, IMAGE_SIZE), shuffle=True, seed=13,
                                                     class_mode='categorical', batch_size=BATCH_SIZE, subset="training")

validation_generator = data_generator.flow_from_directory(final_path, target_size=(IMAGE_SIZE, IMAGE_SIZE), shuffle=False, seed=13,
                                                     class_mode='categorical', batch_size=BATCH_SIZE, subset="validation")

Model definition and training

vgg16_model = keras.applications.vgg16.VGG16(weights='imagenet', include_top=True)
model = Sequential()
for layer in vgg16_model.layers[:-1]:
    model.add(layer)

for layer in model.layers:
    layer.trainable = False

model.add(Dense(num_classes, activation='softmax'))

model.compile(Adam(lr=.001), loss='categorical_crossentropy', metrics=['accuracy'])

history = model.fit_generator(train_generator,
                    validation_data=validation_generator,
                    epochs=85, verbose=1,callbacks=[tbCallBack,earlystopCallback])


问:
Could someone explain to me "read var1 _ < <(ls -1l | wc -l); echo $var1"
```<code>read start _ < <(ls -1l | wc -l); echo $start
</code>```

In particular:

the underscore after read command

the second minus (<)

how does the "echo $var1" take the value of previous command

The original code:

```<code>read start _ < <(du -bcm kali-linux-2016.2-amd64.iso | tail -1); echo $start
</code>```

I have just simplify the code because  i'm interested in the syntax

答:
The following should help about the "_":
https://unix.stackexchange.com/questions/280453/understand-the-meaning-of

This will about the "<<":
https://askubuntu.com/questions/678915/whats-the-difference-between-and-in-bash

please do more research before dumping it on SO to do your work.

and echo generally just repeats what it's told ('echoes' it). "$" is a signifier of variables in shell script, so $var1 is a variable named var1. In order to access any variable, you must prefix it with a '$'

Body:
read start _ < <(ls -1l | wc -l); echo $start

In particular:

the underscore after read command

the second minus (<)

how does the "echo $var1" take the value of previous command

The original code:

read start _ < <(du -bcm kali-linux-2016.2-amd64.iso | tail -1); echo $start

I have just simplify the code because  i'm interested in the syntax


问:
How to manually set a value in MultiSelect widget in AppMaker?
I'm using REST API as a datasource and not sure how to manually set a value in the MultiSelect widget

The widget datasource is named Service and has an id and name

What I tried is widget.values = [...IDs of the values...] but it doesn't work

答:
Two things:

The binding in your follow-up comment -- @datasources.Services.items -- won't work for a multiselect, because it represents the entire set of records in your Services datasource. The binding that Markus suggests is what projects to grab just the names of each of the items. If you are trying to present the name as the human-readable choice but use the id as the value you're going to do something with, then you'll want this:

```<code>widget.names = @datasources.Service.items..name;
widget.options = @datasources.Service.items..id;
</code>```

The multiselect options property represents the possibilities for the values property, and the values property represents the options that have been selected. They are each set as an array. The stuff in 1. above gets you the right set of options but doesn't deal with values. If you want to present particular values as selected or not, you'll either need to:

Pass in values from another datasource, turned into an array. This would be if you're reading the values from a specific field in another record. So if you had a User datasource, and the User had a Services field, you might get the existing selections from the User record like this: @datasources.User.item.Services#strToArray(); or

Set the values programmatically. This would be if you're doing something else behind the scenes to generate the pre-selected values. So if your Service datasource has six things in it that are potential options, but only some of them should be selected, your script would contain something like this: widget.values = [selection1, selection5, selection6];

Body:
Two things:

The binding in your follow-up comment -- @datasources.Services.items -- won't work for a multiselect, because it represents the entire set of records in your Services datasource. The binding that Markus suggests is what projects to grab just the names of each of the items. If you are trying to present the name as the human-readable choice but use the id as the value you're going to do something with, then you'll want this:

widget.names = @datasources.Service.items..name;
widget.options = @datasources.Service.items..id;

The multiselect options property represents the possibilities for the values property, and the values property represents the options that have been selected. They are each set as an array. The stuff in 1. above gets you the right set of options but doesn't deal with values. If you want to present particular values as selected or not, you'll either need to:

Pass in values from another datasource, turned into an array. This would be if you're reading the values from a specific field in another record. So if you had a User datasource, and the User had a Services field, you might get the existing selections from the User record like this: @datasources.User.item.Services#strToArray(); or

Set the values programmatically. This would be if you're doing something else behind the scenes to generate the pre-selected values. So if your Service datasource has six things in it that are potential options, but only some of them should be selected, your script would contain something like this: widget.values = [selection1, selection5, selection6];


问:
Why am I in an endless loop when using LIKE in Access VBA query
I am using openrecordset to do a select query but I want the query to look for a specific word within a column and only return those records.

I tried different styles and it seems I keep getting the same type of error:
runtime error 6: overflow. that is because of a counter that I have, which an integer can only hold no more that 32,000 bytes.

If I remove the counter, It because an endless loop, no error messages just stuff running in the background. I have to restart access.

```<code>'Variables
Dim counter As Integer

'DB variables
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb

'Get records query
Set rs = db.OpenRecordset("SELECT * FROM Price_List WHERE Description LIKE '*cabin*'")

'Determine if the specified valve for this project was found
If rs.EOF Then
    MsgBox "No records were found for enclosures." & vbNewLine & vbNewLine & _
    "You can contact someone", vbInformation + vbOKOnly, "No Records Found"
    End
End If

List10.RowSource = ""

'display
List10.ColumnCount = 5
List10.ColumnWidths = "1500;4000;1200;1200;1200" 'Setting column widths for each record

counter = 0
Do
    If counter = 0 Then
        List10.AddItem ("Part Number)
        List10.AddItem (rs!PartNumber)
    Else
        List10.AddItem (rs!PartNumber)
    End If

    'counter = counter + 1
Loop Until rs.EOF

Label14.Caption = rs.RecordCount

rs.Close
db.Close
</code>```

I expect it to return at least 5 records but I guess it's returning way more!

答:
Several issues.

First of all, there is no guarantee the cursor will be the first record so you have to use

```<code>If rs.EOF AND rs.BOF
</code>```

to check for no records returned.

You then have to start with

```<code>rs.MoveFirst
</code>```

to go to the first record and then in your loop you need

```<code>rs.MoveNext
</code>```

to move to the next record and so on

Your current code just infinitely runs on the one record the recordset happens to open in.

Body:
I am using openrecordset to do a select query but I want the query to look for a specific word within a column and only return those records.

I tried different styles and it seems I keep getting the same type of error:
runtime error 6: overflow. that is because of a counter that I have, which an integer can only hold no more that 32,000 bytes.

If I remove the counter, It because an endless loop, no error messages just stuff running in the background. I have to restart access.

'Variables
Dim counter As Integer

'DB variables
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb

'Get records query
Set rs = db.OpenRecordset("SELECT * FROM Price_List WHERE Description LIKE '*cabin*'")

'Determine if the specified valve for this project was found
If rs.EOF Then
    MsgBox "No records were found for enclosures." & vbNewLine & vbNewLine & _
    "You can contact someone", vbInformation + vbOKOnly, "No Records Found"
    End
End If

List10.RowSource = ""

'display
List10.ColumnCount = 5
List10.ColumnWidths = "1500;4000;1200;1200;1200" 'Setting column widths for each record

counter = 0
Do
    If counter = 0 Then
        List10.AddItem ("Part Number)
        List10.AddItem (rs!PartNumber)
    Else
        List10.AddItem (rs!PartNumber)
    End If

    'counter = counter + 1
Loop Until rs.EOF

Label14.Caption = rs.RecordCount

rs.Close
db.Close

I expect it to return at least 5 records but I guess it's returning way more!

Body:
Several issues.

First of all, there is no guarantee the cursor will be the first record so you have to use

If rs.EOF AND rs.BOF

to check for no records returned.

You then have to start with

rs.MoveFirst

to go to the first record and then in your loop you need

rs.MoveNext

to move to the next record and so on

Your current code just infinitely runs on the one record the recordset happens to open in.


问:
Moving up a directory
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

```<code>chdir("../");
chdir("..")
system("cd ..");
</code>```

none of the above have any effect on the present working directory

答:
You could do something like this to be more explicit about your intended paths:</p>

```<code>$cwd = getcwd(); // remember the current path
chdir(<your target path>);
chdir($cwd); // go back to the inital working directory
</code>```

ContentLicense: CC BY-SA 3.0

Title: Moving up a directory

Body:
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

chdir("../");
chdir("..")
system("cd ..");

none of the above have any effect on the present working directory

Body:
You could do something like this to be more explicit about your intended paths:

$cwd = getcwd(); // remember the current path
chdir(<your target path>);
chdir($cwd); // go back to the inital working directory


问:
Git ignore compiled CSS but keep the latest version for production-ready state
I used to commit my compiled minified CSS files to the repo, then I realized each time, the entire file is sent since it's minified on a single line. So it means for each small modification, I save an entire CSS file in my history and it will quickly add up for no reason.

Can we ignore the CSS files compiled automatically by my Text Editor from a LESS file?

If I put these CSS files in .gitignore, they won't be in the repo but I also use the repository to immediately get a working website.

I always compile the LESS files from my local computer and I want to keep it that way (so don't suggest me to use Grunt or something to automatically compile when a user loads the page, please :P).

The ideal solution would be to only keep the latest file in the repo for CSS files only. For history I'd check the LESS files. The CSS files would be there only to make the site works right after a git clone/pull.

答:
The key is to distinguish between versioned source files, and the resulting build artifacts.

The LESS files are source files and belong in your Git source repository.  However, the generated CSS files are a product of the build process, and are a build artifact, just like a Windows .exe/.dll or Java .class files.

Build artifacts should not be committed to the source repository for several reasons, including:

adding noise to the version control history, with commits updating the generated files

causes additional merge conflicts when branching/merging is used

does not work if you want to use .gitignore to ignore files; if a file is committed to the repository, it will not be ignored, and changes will be displayed

Best practices generally isolate build products into a specific subdirectory of the project root, such as build, or output, or bin, where all build artifacts are stored.  This single subdirectory can then be added to .gitignore.

Your automated build process should be making the build artifacts available for deployment or download.  But these artifacts won't be committed to the source repository.


问:
HTML Webpack Plugin not creating correct index.html file
I am using HTMLWEBPACKPLUGIN to create an html file in the dist folder. I am using the template option of the plugin so that i can add a div in the html file for the root div where my react components will be injected.

Strangely, a hashed file is created with the correct code, and another file, index.html file is created with the name of the other file and the script junction to the bundle.js file instead of having one single html file

webpack.config.js File :

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: "none",
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    plugins: [new HtmlWebpackPlugin({template: './src/index.html'})],

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                options:
                {
                    configFile: 'tsconfig.client.json'
                } ,
                exclude: /node_modules/
            },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader" ,
                exclude: /node_modules/
            },
            {
                test: /\.html$/,
                loader: "file-loader",
                exclude: /node_modules/
              },
        ]
    },
};
</code>```

index.html file :

```<code>31b0c63f79c4c085d45b3861fe75d263.html<script type="text/javascript" src="bundle.js"></script>
</code>```

hashedFile.html :

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
      <div id="root"></div>
  <script type="text/javascript" src="bundle.js"></script></body>
</html>
</code>```

答:
It's happening because you configured webpack to use file loader for html files.

The template plugin renders the file by importing it using a loader. By default, the loader returns the file contents. By using the file-loader, webpack thinks you want to obtain the url for the html file instead of it's content when the html webpack plugin renders index.html.

Maybe you can configure an include directory for the html plugin configuration for the source files, something like

```<code>{
    test: /\.html$/,
    loader: "file-loader",
    include: path.resolve(__dirname, 'src')
}
</code>```

Body:
I am using HTMLWEBPACKPLUGIN to create an html file in the dist folder. I am using the template option of the plugin so that i can add a div in the html file for the root div where my react components will be injected.

Strangely, a hashed file is created with the correct code, and another file, index.html file is created with the name of the other file and the script junction to the bundle.js file instead of having one single html file

webpack.config.js File :

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: "none",
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    plugins: [new HtmlWebpackPlugin({template: './src/index.html'})],

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                options:
                {
                    configFile: 'tsconfig.client.json'
                } ,
                exclude: /node_modules/
            },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader" ,
                exclude: /node_modules/
            },
            {
                test: /\.html$/,
                loader: "file-loader",
                exclude: /node_modules/
              },
        ]
    },
};

index.html file :

31b0c63f79c4c085d45b3861fe75d263.html

hashedFile.html :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Webpack App</title>

Body:
It's happening because you configured webpack to use file loader for html files.

The template plugin renders the file by importing it using a loader. By default, the loader returns the file contents. By using the file-loader, webpack thinks you want to obtain the url for the html file instead of it's content when the html webpack plugin renders index.html.

Maybe you can configure an include directory for the html plugin configuration for the source files, something like

{
    test: /\.html$/,
    loader: "file-loader",
    include: path.resolve(__dirname, 'src')
}


问:
Is it neccesary to make audio files public in S3 in order to play on alexa devices
I am making an alexa skill where user can listen to audio which I have uploaded in S3 but these doesn't play untill I make them public, is there any way to fix it? Why is it required to make the files public, isn't it risky?

There is one way they have suggested in javascript, they provide an api in their Utils package a function with name "getS3PreSignedURL" which will make object public for 60 seconds but what if my audio plays more than 60 seconds and I am working on Java, I am not so confident on javascript.
Have anyone faced similar issue, any thoughts will be helpful.

答:
As you mentioned, you can use an S3 presigned url. The one used in Alexa Hosted Skills imposes a limit of 60 seconds but that's enforced on the S3 side. You can configure your own S3 bucket to support this and set your custom timeout. If you check the file util.js in an Alexa Hosted skill you'll see something like this:

```<code>const AWS = require('aws-sdk');

const s3SigV4Client = new AWS.S3({
    signatureVersion: 'v4'
});

module.exports = {
    getS3PreSignedUrl(s3ObjectKey) {
        const bucketName = process.env.S3_PERSISTENCE_BUCKET;
        const s3PreSignedUrl = s3SigV4Client.getSignedUrl('getObject', {
            Bucket: bucketName,
            Key: s3ObjectKey,
            Expires: 60*1 // the Expires is capped for 1 minute
        });
        console.log(`Util.s3PreSignedUrl: ${s3ObjectKey} URL ${s3PreSignedUrl}`);
        return s3PreSignedUrl;
    }
}
</code>```

Notice that this code is using the standard AWS SDK for node.js. The S3 bucket is taken from the environment process.env.S3_PERSISTENCE_BUCKET and is the one that imposes the 60 sec timeout. If you change the Expires property to more than 60 secs you'll basically fail to retrieve the pre signed url if you try after 1 minute. But, if you pass your own bucket there (and assign it to bucketName) which is properly configured to support pre signed urls and timeouts greater than 60 secs, then nothing prevents you from reusing this code (or equivalent code in Java) and get a pre signed url with any expiration you want. The parameter s3ObjectKey is the relative path of the file in the bucket. To do this in Java you'll have to use this SDK instead.

Body:
As you mentioned, you can use an S3 presigned url. The one used in Alexa Hosted Skills imposes a limit of 60 seconds but that's enforced on the S3 side. You can configure your own S3 bucket to support this and set your custom timeout. If you check the file util.js in an Alexa Hosted skill you'll see something like this:

const AWS = require('aws-sdk');

const s3SigV4Client = new AWS.S3({
    signatureVersion: 'v4'
});

module.exports = {
    getS3PreSignedUrl(s3ObjectKey) {
        const bucketName = process.env.S3_PERSISTENCE_BUCKET;
        const s3PreSignedUrl = s3SigV4Client.getSignedUrl('getObject', {
            Bucket: bucketName,
            Key: s3ObjectKey,
            Expires: 60*1 // the Expires is capped for 1 minute
        });
        console.log(`Util.s3PreSignedUrl: ${s3ObjectKey} URL ${s3PreSignedUrl}`);
        return s3PreSignedUrl;
    }
}

Notice that this code is using the standard AWS SDK for node.js. The S3 bucket is taken from the environment process.env.S3_PERSISTENCE_BUCKET and is the one that imposes the 60 sec timeout. If you change the Expires property to more than 60 secs you'll basically fail to retrieve the pre signed url if you try after 1 minute. But, if you pass your own bucket there (and assign it to bucketName) which is properly configured to support pre signed urls and timeouts greater than 60 secs, then nothing prevents you from reusing this code (or equivalent code in Java) and get a pre signed url with any expiration you want. The parameter s3ObjectKey is the relative path of the file in the bucket. To do this in Java you'll have to use this SDK instead.


问:
How do we replace a column in a tibble with another vector of identical length without changing the variable name?
I have a large data frame that I coerced as a tibble to be able to use the dplyr package. I wanted to know if there was a way to "replace" a column in the tibble with the same variable in a different notation.

I have tried the mutate() function but I don't want to add a new column to the tibble, just replace a column with a vector of the same length.

答:
If I understand your question correctly, I think the answer is mutate()!

```<code>> library(dplyr)
> d <- tibble(x=1:3,y=2:4)
> d <- d %>% mutate(x=8:10) ## replace column x
> d
# A tibble: 3 x 2
      x     y
  <int> <int>
1     8     2
2     9     3
3    10     4
</code>```

Body:
If I understand your question correctly, I think the answer is mutate()!

> library(dplyr)
> d <- tibble(x=1:3,y=2:4)
> d <- d %>% mutate(x=8:10) ## replace column x
> d
# A tibble: 3 x 2
      x     y
  <int> <int>
1     8     2
2     9     3
3    10     4


问:
How to add user to another table after user registration in laravel?
I am developing an e-commerce project in Laravel 5.6 in which I have two tables for users :

Users for passwords and some other stuff and

UserDetails table for storing user address, phone, city, pin code, etc.

While registering a user with storing credentials in the Users table I want to make a column in the UserDetails table with the same user_id that has been generated while adding to Users table.

Below is my migrations :

```<code>Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

Schema::create('user_details', function (Blueprint $table) {
            $table->increments('id');
            $table->string('phone')->nullable();
            $table->string('city')->nullable();
            $table->string('pincode')->nullable();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
</code>```

I had tried to add following in the create function in RegisterController

```<code>protected function create(array $data)
    {
        User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        UserDetails::create([
            'user_id' => Auth::user()->id
        ]);

        return;
    }
</code>```

But it doesn't work and shows

Trying to get property 'id' of non-object".

Help me through this.

答:
The answer of @MateusJunges is correct but the error you got after doing is that

"Add [user_id] to fillable property to allow mass assignment on
  [App\UserDetails]."

In order to resolve this error I have to add this code to my UserDetails model :

```<code>protected $fillable = [
        'user_id'
    ];
</code>```

You can refer here.

After that all the code of @MateusJunges is correct.

Body:
I am developing an e-commerce project in Laravel 5.6 in which I have two tables for users :

Users for passwords and some other stuff and

UserDetails table for storing user address, phone, city, pin code, etc.

While registering a user with storing credentials in the Users table I want to make a column in the UserDetails table with the same user_id that has been generated while adding to Users table.

Below is my migrations :

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

Schema::create('user_details', function (Blueprint $table) {
            $table->increments('id');
            $table->string('phone')->nullable();
            $table->string('city')->nullable();
            $table->string('pincode')->nullable();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });

I had tried to add following in the create function in RegisterController

protected function create(array $data)
    {
        User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        UserDetails::create([
            'user_id' => Auth::user()->id
        ]);

        return;
    }

But it doesn't work and shows

Trying to get property 'id' of non-object".

Help me through this.

Body:
The answer of @MateusJunges is correct but the error you got after doing is that

"Add [user_id] to fillable property to allow mass assignment on
  [App\UserDetails]."

In order to resolve this error I have to add this code to my UserDetails model :

protected $fillable = [
        'user_id'
    ];

You can refer here.

After that all the code of @MateusJunges is correct.


问:
How should I store ~400 key-value pairs for my Android app?
What would be the best way to store ~400 key-value pairs for an Android app? These values would be set on initial setup of the app and changed extremely infrequently after that. However they are used once per app use as a template to create a set of other objects which are then manipulated.

In the previous iteration of the app I stored these values in a separate sql table. I am now transitioning to using the room model and reworking a lot of the code, which part of that is evaluating previous decisions.

How the previous code worked was that I would import the ID and boolean value pair into a list of objects. The user when then add additional info to those objects and then I would re-store those objects data back into a separate, but related sql table.

Should I keep the values in the table? Would it be too much or inefficient to use SharedPreferences? Is there a better way that I am unaware of?

Here is the format of the two tables. The first is keeping track of which carts are currently in rotation whereas the second table is a daily historical record of each cart.

```<code>(cartID int NOT NULL PRIMARY KEY,
in_rotation boolean NOT NULL) ");

database.execSQL("create table " + cartlistTable + "
(checksheetID string NOT NULL,
cartID int NOT NULL,
in_rotation boolean NOT NULL,
checked boolean default 0,
overdue boolean default 0,
maintenance boolean default 0,
FOREIGN KEY(checksheetID) REFERENCES checksheet(checksheetID),
FOREIGN KEY(cartID) REFERENCES carts(cartID))");
</code>```

答:
I would suggest you to keep away from shared preference if you are working with large amount of data, because the maximum amount of data that can be stored in shared Preference is 1428.51 kb.

Also shared preference is stored in xml file and it lacks the strong transaction support from SQlite or Room. Shared preferences loads all the data reads that entire XML file's contents into memory.

Comparing room and shared preferences, for information like 400 items, You can go with room.

Body:
What would be the best way to store ~400 key-value pairs for an Android app? These values would be set on initial setup of the app and changed extremely infrequently after that. However they are used once per app use as a template to create a set of other objects which are then manipulated.

In the previous iteration of the app I stored these values in a separate sql table. I am now transitioning to using the room model and reworking a lot of the code, which part of that is evaluating previous decisions.

How the previous code worked was that I would import the ID and boolean value pair into a list of objects. The user when then add additional info to those objects and then I would re-store those objects data back into a separate, but related sql table.

Should I keep the values in the table? Would it be too much or inefficient to use SharedPreferences? Is there a better way that I am unaware of?

Here is the format of the two tables. The first is keeping track of which carts are currently in rotation whereas the second table is a daily historical record of each cart.

(cartID int NOT NULL PRIMARY KEY,
in_rotation boolean NOT NULL) ");

database.execSQL("create table " + cartlistTable + "
(checksheetID string NOT NULL,
cartID int NOT NULL,
in_rotation boolean NOT NULL,
checked boolean default 0,
overdue boolean default 0,
maintenance boolean default 0,
FOREIGN KEY(checksheetID) REFERENCES checksheet(checksheetID),
FOREIGN KEY(cartID) REFERENCES carts(cartID))");


答:
You just need to set the name of your variable inside the mutate. For example, if you want to divide by 100:</p>

```<code>mutate(var = var/100)
</code>```

Title: How do we replace a column in a tibble with another vector of identical length without changing the variable name?

Body:
I have a large data frame that I coerced as a tibble to be able to use the dplyr package. I wanted to know if there was a way to "replace" a column in the tibble with the same variable in a different notation.

I have tried the mutate() function but I don't want to add a new column to the tibble, just replace a column with a vector of the same length.

Body:
You just need to set the name of your variable inside the mutate. For example, if you want to divide by 100:

mutate(var = var/100)


问:
Letsencrypt certificate upgrade issue
On Ubuntu 16.04.2 LTS, I am trying to upgrade letsencrypt certificate by using
./letsencrypt-auto renew --dry-run and its giving below error </p>

```<code>Error: couldn't get currently installed version for /root/.local/share/letsencrypt/bin/letsencrypt:
Traceback (most recent call last):
  File "/root/.local/share/letsencrypt/bin/letsencrypt", line 7, in <module>
    from certbot.main import main
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/certbot/main.py", line 13, in <module>
    from acme import jose
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/acme/jose/__init__.py", line 37, in <module>
    from acme.jose.interfaces import JSONDeSerializable
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/acme/jose/interfaces.py", line 9, in <module>
    from acme.jose import util
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/acme/jose/util.py", line 4, in <module>
    from cryptography.hazmat.primitives.asymmetric import rsa
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py", line 14, in <module>
    from cryptography.hazmat.backends.interfaces import RSABackend
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/cryptography/hazmat/backends/__init__.py", line 7, in <module>
    import pkg_resources
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 36, in <module>
    import plistlib
  File "/usr/lib/python2.7/plistlib.py", line 62, in <module>
    import datetime
ImportError: No module named datetime
</code>```

<p>Can you please help here </p>

答:
This works for me (Linux Debian 3.16.64-2):

mv /opt/eff.org/certbot /opt/eff.org/certbot.old

certbot-auto

Title: Letsencrypt certificate upgrade issue

Body:
On Ubuntu 16.04.2 LTS, I am trying to upgrade letsencrypt certificate by using
./letsencrypt-auto renew --dry-run and its giving below error

Error: couldn't get currently installed version for /root/.local/share/letsencrypt/bin/letsencrypt:
Traceback (most recent call last):
  File "/root/.local/share/letsencrypt/bin/letsencrypt", line 7, in <module>
    from certbot.main import main
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/certbot/main.py", line 13, in <module>
    from acme import jose
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/acme/jose/__init__.py", line 37, in <module>
    from acme.jose.interfaces import JSONDeSerializable
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/acme/jose/interfaces.py", line 9, in <module>
    from acme.jose import util
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/acme/jose/util.py", line 4, in <module>
    from cryptography.hazmat.primitives.asymmetric import rsa
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py", line 14, in <module>
    from cryptography.hazmat.backends.interfaces import RSABackend
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/cryptography/hazmat/backends/__init__.py", line 7, in <module>
    import pkg_resources
  File "/root/.local/share/letsencrypt/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 36, in <module>
    import plistlib
  File "/usr/lib/python2.7/plistlib.py", line 62, in <module>
    import datetime
ImportError: No module named datetime

Can you please help here


问:
Restart container within pod
I have a pod test-1495806908-xn5jn with 2 containers. I'd like to restart one of them called container-test. Is it possible to restart a single container within a pod and how? If not, how do I restart the pod?

The pod was created using a deployment.yaml with:

```<code>kubectl create -f deployment.yaml
</code>```

答:
All the above answers have mentioned deleting the pod...but if you have many pods of the same service then it would be tedious to delete each one of them...

Therefore, I propose the following solution, restart:

1) Set scale to zero :

```<code> kubectl scale deployment <<name>> --replicas=0 -n service
</code>```

The above command will terminate all your pods with the name <<name>>

2) To start the pod again, set the replicas to more than 0

```<code>kubectl scale deployment <<name>> --replicas=2 -n service
</code>```

The above command will start your pods again with 2 replicas.

Title: Restart container within pod

Body:
I have a pod test-1495806908-xn5jn with 2 containers. I'd like to restart one of them called container-test. Is it possible to restart a single container within a pod and how? If not, how do I restart the pod?

The pod was created using a deployment.yaml with:

kubectl create -f deployment.yaml

Body:
All the above answers have mentioned deleting the pod...but if you have many pods of the same service then it would be tedious to delete each one of them...

Therefore, I propose the following solution, restart:

1) Set scale to zero :

 kubectl scale deployment <<name>> --replicas=0 -n service

The above command will terminate all your pods with the name <<name>>

2) To start the pod again, set the replicas to more than 0

kubectl scale deployment <<name>> --replicas=2 -n service

The above command will start your pods again with 2 replicas.


问:
Factory pattern with unique_ptr
I have abstract class Agent, and few derived: Predator, Prey etc. I would like to make a factory, that gives me unique_ptr which I can store in vector of base class.

Problem is, when I have:

```<code>using creatorFunctionType = std::unique_ptr<Agent>(*)();
</code>```

this part is ok, but in map I cannot use lambda with:

```<code>return std::make_unique<Predator>();
</code>```

But when I am trying to use template:

```<code>template <class T>
using creatorFunctionType = std::unique_ptr<T>(*)();
</code>```

The rest of functions doesn't compile. I am nearby sure, I missed something important about templates, but no idea what. Can you give me some hints?

Posting full code, may be helpful

AgentFactory.h

```<code>#include "Interfaces/Agent.h"
#include "Enums.h"
#include <map>
#include <memory>

class AgentFactory
{
public:
    template <class T>
    using creatorFunctionType = std::unique_ptr<T>(*)();

    AgentFactory();
    std::unique_ptr<Agent> createAgent(Enums::AgentType agentType);
private:
    void registerAgentType(Enums::AgentType agentType, creatorFunctionType
    creatorFunction);

    std::map<Enums::AgentType, creatorFunctionType> factoryRegister;
};
</code>```

AgentFactory.cpp

```<code>#include "AgentFactory.h"
#include "Predator.h"
#include "Prey.h"

AgentFactory::AgentFactory()
{
    registerAgentType(Enums::AgentType::Predator, []() { return
    std::make_unique<Predator>(); });
    registerAgentType(Enums::AgentType::Prey, []() { return
    std::make_unique<Prey>(); });
}

std::unique_ptr<Agent> AgentFactory::createAgent(Enums::AgentType
agentType)
{
    if (auto it = factoryRegister.find(agentType); it !=
    factoryRegister.end()) {
        return it->second();
    }

    return nullptr;
}

void AgentFactory::registerAgentType(Enums::AgentType agentType,
creatorFunctionType creatorFunction)
{
    factoryRegister.insert(std::pair<Enums::AgentType,
    creatorFunctionType>(agentType, creatorFunction));
}
</code>```

Compilation errors:

```<code>1>d:\predator-prey\predator-prey\agentfactory.h(15): error C2955: 'AgentFactory::creatorFunctionType': use of alias template requires template argument list
1>d:\predator-prey\predator-prey\agentfactory.h(10): note: see declaration of 'AgentFactory::creatorFunctionType'
1>d:\predator-prey\predator-prey\agentfactory.h(17): error C3203: 'creatorFunctionType': unspecialized alias template can't be used as a template argument for template parameter '_Ty', expected a real type
1>d:\predator-prey\predator-prey\agentfactory.cpp(14): error C2064: term does not evaluate to a function taking 0 arguments
1>d:\predator-prey\predator-prey\agentfactory.cpp(22): error C3203: 'creatorFunctionType': unspecialized alias template can't be used as a template argument for template parameter '_Ty2', expected a real type
1>d:\predator-prey\predator-prey\agentfactory.cpp(22): fatal error C1903: unable to recover from previous error(s); stopping compilation
</code>```

答:
When creatorFunctionType is defined as

```<code>using creatorFunctionType = std::unique_ptr<Agent>(*)();
</code>```

creatorFunctionType is a pointer-to-function that expects functions which return a std::unique_ptr<Agent>.

However, your lambdas do not have explicit return types, so the compiler deduces their return types as std::unique_ptr<Predator> and std::unique_ptr<Prey>, respectively, based on their return statements.

A non-capturing lambda is implicitly convertible to a pointer-to-function, which is what you want in this case, however your lambdas do not return std::unique_ptr<Agent>, so they cannot be assigned to creatorFunctionType.  The types simply do not match.

You need to be explicit about the return type of your lambdas so they match the correct signature that creatorFunctionType is expecting, eg:

```<code>AgentFactory::AgentFactory()
{
    registerAgentType(Enums::AgentType::Predator,
        []() -> std::unique_ptr<Agent> { return std::make_unique<Predator>(); }
    );
    registerAgentType(Enums::AgentType::Prey,
        []() -> std::unique_ptr<Agent> { return std::make_unique<Prey>(); }
    );
}
</code>```

With the above code, the lambdas will now return std::unique_ptr<Agent>, satisfying what creatorFunctionType expects.  And the return statements still work as-is because std::unique_ptr<T> can be initialized with a std::unique_ptr as long as U derives from T, which is true in your case since Predator and Prey derive from Agent.

Title: Factory pattern with unique_ptr

Body:
I have abstract class Agent, and few derived: Predator, Prey etc. I would like to make a factory, that gives me unique_ptr which I can store in vector of base class.

Problem is, when I have:

using creatorFunctionType = std::unique_ptr<Agent>(*)();

this part is ok, but in map I cannot use lambda with:

return std::make_unique<Predator>();

But when I am trying to use template:

template <class T>
using creatorFunctionType = std::unique_ptr<T>(*)();

The rest of functions doesn't compile. I am nearby sure, I missed something important about templates, but no idea what. Can you give me some hints?

Posting full code, may be helpful

AgentFactory.h

#include "Interfaces/Agent.h"
#include "Enums.h"
#include <map>
#include <memory>

class AgentFactory
{
public:
    template <class T>
    using creatorFunctionType = std::unique_ptr<T>(*)();

    AgentFactory();
    std::unique_ptr<Agent> createAgent(Enums::AgentType agentType);
private:
    void registerAgentType(Enums::AgentType agentType, creatorFunctionType
    creatorFunction);

    std::map<Enums::AgentType, creatorFunctionType> factoryRegister;
};

AgentFactory.cpp

#include "AgentFactory.h"
#include "Predator.h"
#include "Prey.h"

AgentFactory::AgentFactory()
{
    registerAgentType(Enums::AgentType::Predator, []() { return
    std::make_unique<Predator>(); });
    registerAgentType(Enums::AgentType::Prey, []() { return
    std::make_unique<Prey>(); });
}

std::unique_ptr<Agent> AgentFactory::createAgent(Enums::AgentType
agentType)
{
    if (auto it = factoryRegister.find(agentType); it !=
    factoryRegister.end()) {
        return it->second();
    }

    return nullptr;
}

void AgentFactory::registerAgentType(Enums::AgentType agentType,
creatorFunctionType creatorFunction)
{
    factoryRegister.insert(std::pair<Enums::AgentType,
    creatorFunctionType>(agentType, creatorFunction));
}

Compilation errors:

1>d:\predator-prey\predator-prey\agentfactory.h(15): error C2955: 'AgentFactory::creatorFunctionType': use of alias template requires template argument list
1>d:\predator-prey\predator-prey\agentfactory.h(10): note: see declaration of 'AgentFactory::creatorFunctionType'
1>d:\predator-prey\predator-prey\agentfactory.h(17): error C3203: 'creatorFunctionType': unspecialized alias template can't be used as a template argument for template parameter '_Ty', expected a real type
1>d:\predator-prey\predator-prey\agentfactory.cpp(14): error C2064: term does not evaluate to a function taking 0 arguments
1>d:\predator-prey\predator-prey\agentfactory.cpp(22): error C3203: 'creatorFunctionType': unspecialized alias template can't be used as a template argument for template parameter '_Ty2', expected a real type
1>d:\predator-prey\predator-prey\agentfactory.cpp(22): fatal error C1903: unable to recover from previous error(s); stopping compilation

Body:
When creatorFunctionType is defined as

using creatorFunctionType = std::unique_ptr<Agent>(*)();

creatorFunctionType is a pointer-to-function that expects functions which return a std::unique_ptr<Agent>.

However, your lambdas do not have explicit return types, so the compiler deduces their return types as std::unique_ptr<Predator> and std::unique_ptr<Prey>, respectively, based on their return statements.

A non-capturing lambda is implicitly convertible to a pointer-to-function, which is what you want in this case, however your lambdas do not return std::unique_ptr<Agent>, so they cannot be assigned to creatorFunctionType.  The types simply do not match.

You need to be explicit about the return type of your lambdas so they match the correct signature that creatorFunctionType is expecting, eg:

AgentFactory::AgentFactory()
{
    registerAgentType(Enums::AgentType::Predator,
        []() -> std::unique_ptr<Agent> { return std::make_unique<Predator>(); }
    );
    registerAgentType(Enums::AgentType::Prey,
        []() -> std::unique_ptr<Agent> { return std::make_unique<Prey>(); }
    );
}

With the above code, the lambdas will now return std::unique_ptr<Agent>, satisfying what creatorFunctionType expects.  And the return statements still work as-is because std::unique_ptr<T> can be initialized with a std::unique_ptr<U> as long as U derives from T, which is true in your case since Predator and Prey derive from Agent.


问:
Execution time for a method listening from two events at one point of time c#
I have two events which are firing at the same time and calling the same method Method1(). So at one point in time,

that method will be executed two times. And inside that method, I have another method Method2() for which I have to find the execution time.

Right now I have created 2 stopwatches one when method fired from event1 and other for event2 so that they will not block each other and I can also differentiate the execution time of method2 when method1 fired from event1 or event2 and will get the accurate results.

```<code>     public void Method1()
     {
          if(event1)
          {
               Stopwatch timer = new Stopwatch();
               timer1.Start();
               Method2();
               timer1.Stop();
               Console.WriteLine("Time elapsed from event1:
               {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
          else
          {
                Stopwatch timer2 = new Stopwatch();
                timer2.Start();
                Method2();
                timer2.Stop();
                Console.WriteLine("Time elapsed from event2:
                {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
     }
</code>```

Any help so that I can create a common and generic stopwatch implementation that can run the event if one method is executing at some time from different sources and not have to create 2 stopwatches?

答:
You could write a wrapper method that takes in an Action to execute, and which returns a TimeSpan that represents the amount of time it took to execute the action:

```<code>public static TimeSpan TimeMethod(Action method)
{
    Stopwatch sw = Stopwatch.StartNew();
    method.Invoke();
    sw.Stop();
    return sw.Elapsed;
}
</code>```

Then you might call it like:

```<code>public void Method1()
{
    TimeSpan result = TimeMethod(Method2);
    string thisEvent = event1 ? "event1" : "event2";
    Console.WriteLine($"Time elapsed from {thisEvent}: {result.ToString("hh\\:mm\\:ss")}");
}
</code>```

Body:
I have two events which are firing at the same time and calling the same method Method1(). So at one point in time,

that method will be executed two times. And inside that method, I have another method Method2() for which I have to find the execution time.

Right now I have created 2 stopwatches one when method fired from event1 and other for event2 so that they will not block each other and I can also differentiate the execution time of method2 when method1 fired from event1 or event2 and will get the accurate results.

     public void Method1()
     {
          if(event1)
          {
               Stopwatch timer = new Stopwatch();
               timer1.Start();
               Method2();
               timer1.Stop();
               Console.WriteLine("Time elapsed from event1:
               {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
          else
          {
                Stopwatch timer2 = new Stopwatch();
                timer2.Start();
                Method2();
                timer2.Stop();
                Console.WriteLine("Time elapsed from event2:
                {0:hh\\:mm\\:ss}", stopwatch.Elapsed);
          }
     }

Any help so that I can create a common and generic stopwatch implementation that can run the event if one method is executing at some time from different sources and not have to create 2 stopwatches?

Body:
You could write a wrapper method that takes in an Action to execute, and which returns a TimeSpan that represents the amount of time it took to execute the action:

public static TimeSpan TimeMethod(Action method)
{
    Stopwatch sw = Stopwatch.StartNew();
    method.Invoke();
    sw.Stop();
    return sw.Elapsed;
}

Then you might call it like:

public void Method1()
{
    TimeSpan result = TimeMethod(Method2);
    string thisEvent = event1 ? "event1" : "event2";
    Console.WriteLine($"Time elapsed from {thisEvent}: {result.ToString("hh\\:mm\\:ss")}");
}


问:
Making a dynamic pivot table but without using the fiddle
I have done this:

```<code>;WITH a AS
(
    SELECT
        a.account
        ,index_num_date = 'date ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,index_num_rate = 'rate ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,ratechangedate
        ,new_noterate
    FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
    INNER JOIN
    (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> 'bk payment plan'
    ) b ON a.account = b.account
    WHERE archivedate = '5/20/2019'
)
,q1 AS
(
    SELECT DISTINCT
        account
        ,ratechangedate
        ,index_num_date
    FROM a
)
,q2 AS
(
    SELECT DISTINCT
        account
        ,new_noterate
        ,index_num_rate
    FROM a
)
,datepivot AS
(
    SELECT DISTINCT
        account
        ,[date 1]
        ,[date 2]
        ,[date 3]
        ,[date 4]
        ,[date 5]
        ,[date 6]
        ,[date 7]
        ,[date 8]
        ,[date 9]
        ,[date 10]
        ,[date 11]
        ,[date 12]
        ,[date 13]
    FROM q1
        PIVOT
        (
            MIN(ratechangedate)
            FOR index_num_date IN ( [date 1]
                ,[date 2]
                ,[date 3]
                ,[date 4]
                ,[date 5]
                ,[date 6]
                ,[date 7]
                ,[date 8]
                ,[date 9]
                ,[date 10]
                ,[date 11]
                ,[date 12]
                ,[date 13]
            )
        ) pvt1
)
,ratepivot AS
(
    SELECT DISTINCT
        account
        ,[rate 1]
        ,[rate 2]
        ,[rate 3]
        ,[rate 4]
        ,[rate 5]
        ,[rate 6]
        ,[rate 7]
        ,[rate 8]
        ,[rate 9]
        ,[rate 10]
        ,[rate 11]
        ,[rate 12]
        ,[rate 13]
    FROM q2
        PIVOT
        (
            MIN(new_noterate)
            FOR index_num_rate IN ( [rate 1]
                ,[rate 2]
                ,[rate 3]
                ,[rate 4]
                ,[rate 5]
                ,[rate 6]
                ,[rate 7]
                ,[rate 8]
                ,[rate 9]
                ,[rate 10]
                ,[rate 11]
                ,[rate 12]
                ,[rate 13]
            )
        ) pvt2
)
SELECT
    a.Account
    ,[date 1]
    ,[rate 1]
FROM datepivot a
LEFT JOIN ratepivot b ON a.Account = b.Account
</code>```

Which gives me this

But this is not dynamic and my Microsoft version 2016 does not allow me to use the Fiddle thing recommended in various posts. Thus I was recommended to use the Coalesce() function but I have no idea what to do to make the latter dynamic. Any help (not referring to some post) would really help.

Update:

Following the comment I tried this:

```<code>DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Account)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p '
</code>```

but get this error:

```<code>Msg 1056, Level 15, State 1, Line 37
The number of elements in the select list exceeds the maximum allowed number of 4096 elements.
Msg 102, Level 15, State 1, Line 43
Incorrect syntax near 'x'.
</code>```

Update:

I tried this to limit the amount

```<code>DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.RateChangeDate)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            WHERE c.ArchiveDate = '5/21/2019' AND c.AppliedDate > '1/2/2018'
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p
            pivot
            (
                min(new_noterate)
                for category in (' + @cols + ')
            )

            '

execute(@query)
</code>```

But I am getting this error:

```<code>Msg 102, Level 15, State 1, Line 52
Incorrect syntax near ')'.
</code>```

As requested here is the top 10 from the data table

答:
It would be a lot easier for you to create a cross tabs query. If you can identify the pattern, the dynamic code can be easier to code and there are multiple examples on the internet (and this site). If you don't know how to create dynamic code, I'd suggest that you stay away from it until you fully understand the do's and don'ts.

```<code>WITH a
AS (
    SELECT a.account,
        dense_rank() OVER ( PARTITION BY a.account ORDER BY ratechangedate) AS index_num,
        ratechangedate,
        new_noterate
    FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] a
    INNER JOIN (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
    WHERE archivedate = '5/20/2019'
    )
SELECT a.Account,
    MIN( CASE WHEN index_num = 1 THEN ratechangedate END) AS [date 1],
    MIN( CASE WHEN index_num = 1 THEN new_noterate END)   AS [rate 1],
    MIN( CASE WHEN index_num = 2 THEN ratechangedate END) AS [date 2],
    MIN( CASE WHEN index_num = 2 THEN new_noterate END)   AS [rate 2],
    MIN( CASE WHEN index_num = 3 THEN ratechangedate END) AS [date 3],
    MIN( CASE WHEN index_num = 3 THEN new_noterate END)   AS [rate 3],
    MIN( CASE WHEN index_num = 4 THEN ratechangedate END) AS [date 4],
    MIN( CASE WHEN index_num = 4 THEN new_noterate END)   AS [rate 4],
    MIN( CASE WHEN index_num = 5 THEN ratechangedate END) AS [date 5],
    MIN( CASE WHEN index_num = 5 THEN new_noterate END)   AS [rate 5],
    MIN( CASE WHEN index_num = 6 THEN ratechangedate END) AS [date 6],
    MIN( CASE WHEN index_num = 6 THEN new_noterate END)   AS [rate 6],
    MIN( CASE WHEN index_num = 7 THEN ratechangedate END) AS [date 7],
    MIN( CASE WHEN index_num = 7 THEN new_noterate END)   AS [rate 7],
    MIN( CASE WHEN index_num = 8 THEN ratechangedate END) AS [date 8],
    MIN( CASE WHEN index_num = 8 THEN new_noterate END)   AS [rate 8]
FROM a
GROUP BY a.Account;
</code>```

UPDATE:

I told you to read the article on how to work with dynamic SQL. I also told you to identify the pattern, you didn't. Now, there's an answer that will be much slower than what I'm suggesting and I just don't want subpar code to propagate, so here's an option.

```<code>DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX),
        @archivedate AS DATETIME = '20190520'; --Always use ISO 8601 format YYYYMMDD

WITH
E(n) AS(
    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
    SELECT a.n FROM E a, E b
),
E4(n) AS(
    SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
    SELECT TOP((SELECT TOP (1) COUNT(DISTINCT ratechangedate) datecount
                FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
                WHERE ArchiveDate = @archivedate AND AppliedDate > '1/2/2018'
                GROUP BY account
                ORDER BY datecount DESC)) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n
    FROM E4
)
SELECT @cols = (SELECT REPLACE( '
    ,MIN( CASE WHEN index_num = <<index_num>> THEN ratechangedate END) AS [date <<index_num>>]
    ,MIN( CASE WHEN index_num = <<index_num>> THEN new_noterate END)   AS [rate <<index_num>>]' , '<<index_num>>', n)
            FROM cteTally
            ORDER BY n
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')

set @query =
N'WITH a AS (
    SELECT a.account,
        dense_rank() OVER ( PARTITION BY a.account ORDER BY ratechangedate) AS index_num,
        ratechangedate,
        new_noterate
    FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] a
    INNER JOIN (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> ''bk payment plan''
        ) b ON a.account = b.account
    WHERE archivedate = @date
    )
SELECT a.Account' + @cols + N'
FROM a
GROUP BY a.Account;'

EXECUTE sp_executesql @query, N'@date datetime', @date = @archivedate;
</code>```

Body:
I have done this:

;WITH a AS
(
    SELECT
        a.account
        ,index_num_date = 'date ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,index_num_rate = 'rate ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,ratechangedate
        ,new_noterate
    FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
    INNER JOIN
    (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> 'bk payment plan'
    ) b ON a.account = b.account
    WHERE archivedate = '5/20/2019'
)
,q1 AS
(
    SELECT DISTINCT
        account
        ,ratechangedate
        ,index_num_date
    FROM a
)
,q2 AS
(
    SELECT DISTINCT
        account
        ,new_noterate
        ,index_num_rate
    FROM a
)
,datepivot AS
(
    SELECT DISTINCT
        account
        ,[date 1]
        ,[date 2]
        ,[date 3]
        ,[date 4]
        ,[date 5]
        ,[date 6]
        ,[date 7]
        ,[date 8]
        ,[date 9]
        ,[date 10]
        ,[date 11]
        ,[date 12]
        ,[date 13]
    FROM q1
        PIVOT
        (
            MIN(ratechangedate)
            FOR index_num_date IN ( [date 1]
                ,[date 2]
                ,[date 3]
                ,[date 4]
                ,[date 5]
                ,[date 6]
                ,[date 7]
                ,[date 8]
                ,[date 9]
                ,[date 10]
                ,[date 11]
                ,[date 12]
                ,[date 13]
            )
        ) pvt1
)
,ratepivot AS
(
    SELECT DISTINCT
        account
        ,[rate 1]
        ,[rate 2]
        ,[rate 3]
        ,[rate 4]
        ,[rate 5]
        ,[rate 6]
        ,[rate 7]
        ,[rate 8]
        ,[rate 9]
        ,[rate 10]
        ,[rate 11]
        ,[rate 12]
        ,[rate 13]
    FROM q2
        PIVOT
        (
            MIN(new_noterate)
            FOR index_num_rate IN ( [rate 1]
                ,[rate 2]
                ,[rate 3]
                ,[rate 4]
                ,[rate 5]
                ,[rate 6]
                ,[rate 7]
                ,[rate 8]
                ,[rate 9]
                ,[rate 10]
                ,[rate 11]
                ,[rate 12]
                ,[rate 13]
            )
        ) pvt2
)
SELECT
    a.Account
    ,[date 1]
    ,[rate 1]
FROM datepivot a
LEFT JOIN ratepivot b ON a.Account = b.Account

Which gives me this

But this is not dynamic and my Microsoft version 2016 does not allow me to use the Fiddle thing recommended in various posts. Thus I was recommended to use the Coalesce() function but I have no idea what to do to make the latter dynamic. Any help (not referring to some post) would really help.

Update:

Following the comment I tried this:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Account)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p '

but get this error:

Msg 1056, Level 15, State 1, Line 37
The number of elements in the select list exceeds the maximum allowed number of 4096 elements.
Msg 102, Level 15, State 1, Line 43
Incorrect syntax near 'x'.

Update:

I tried this to limit the amount

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.RateChangeDate)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            WHERE c.ArchiveDate = '5/21/2019' AND c.AppliedDate > '1/2/2018'
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p
            pivot
            (
                min(new_noterate)
                for category in (' + @cols + ')
            )

            '

execute(@query)

But I am getting this error:

Msg 102, Level 15, State 1, Line 52
Incorrect syntax near ')'.

As requested here is the top 10 from the data table

Body:
It would be a lot easier for you to create a cross tabs query. If you can identify the pattern, the dynamic code can be easier to code and there are multiple examples on the internet (and this site). If you don't know how to create dynamic code, I'd suggest that you stay away from it until you fully understand the do's and don'ts.

WITH a
AS (
    SELECT a.account,
        dense_rank() OVER ( PARTITION BY a.account ORDER BY ratechangedate) AS index_num,
        ratechangedate,
        new_noterate
    FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] a
    INNER JOIN (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
    WHERE archivedate = '5/20/2019'
    )
SELECT a.Account,
    MIN( CASE WHEN index_num = 1 THEN ratechangedate END) AS [date 1],
    MIN( CASE WHEN index_num = 1 THEN new_noterate END)   AS [rate 1],
    MIN( CASE WHEN index_num = 2 THEN ratechangedate END) AS [date 2],
    MIN( CASE WHEN index_num = 2 THEN new_noterate END)   AS [rate 2],
    MIN( CASE WHEN index_num = 3 THEN ratechangedate END) AS [date 3],
    MIN( CASE WHEN index_num = 3 THEN new_noterate END)   AS [rate 3],
    MIN( CASE WHEN index_num = 4 THEN ratechangedate END) AS [date 4],
    MIN( CASE WHEN index_num = 4 THEN new_noterate END)   AS [rate 4],
    MIN( CASE WHEN index_num = 5 THEN ratechangedate END) AS [date 5],
    MIN( CASE WHEN index_num = 5 THEN new_noterate END)   AS [rate 5],
    MIN( CASE WHEN index_num = 6 THEN ratechangedate END) AS [date 6],
    MIN( CASE WHEN index_num = 6 THEN new_noterate END)   AS [rate 6],
    MIN( CASE WHEN index_num = 7 THEN ratechangedate END) AS [date 7],
    MIN( CASE WHEN index_num = 7 THEN new_noterate END)   AS [rate 7],
    MIN( CASE WHEN index_num = 8 THEN ratechangedate END) AS [date 8],
    MIN( CASE WHEN index_num = 8 THEN new_noterate END)   AS [rate 8]
FROM a
GROUP BY a.Account;

UPDATE:

I told you to read the article on how to work with dynamic SQL. I also told you to identify the pattern, you didn't. Now, there's an answer that will be much slower than what I'm suggesting and I just don't want subpar code to propagate, so here's an option.

DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX),
        @archivedate AS DATETIME = '20190520'; --Always use ISO 8601 format YYYYMMDD

WITH
E(n) AS(
    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
    SELECT a.n FROM E a, E b
),
E4(n) AS(
    SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
    SELECT TOP((SELECT TOP (1) COUNT(DISTINCT ratechangedate) datecount
                FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
                WHERE ArchiveDate = @archivedate AND AppliedDate > '1/2/2018'
                GROUP BY account
                ORDER BY datecount DESC)) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n
    FROM E4
)
SELECT @cols = (SELECT REPLACE( '
    ,MIN( CASE WHEN index_num = <<index_num>> THEN ratechangedate END) AS [date <<index_num>>]
    ,MIN( CASE WHEN index_num = <<index_num>> THEN new_noterate END)   AS [rate <<index_num>>]' , '<<index_num>>', n)
            FROM cteTally
            ORDER BY n
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')

set @query =
N'WITH a AS (
    SELECT a.account,
        dense_rank() OVER ( PARTITION BY a.account ORDER BY ratechangedate) AS index_num,
        ratechangedate,
        new_noterate
    FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] a
    INNER JOIN (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> ''bk payment plan''
        ) b ON a.account = b.account
    WHERE archivedate = @date
    )
SELECT a.Account' + @cols + N'
FROM a
GROUP BY a.Account;'

EXECUTE sp_executesql @query, N'@date datetime', @date = @archivedate;


问:
How to align the icon of a marker in google map
In google map usually the center bottom of the image of the marker is the lat lng of a point that it has to mark.

Imagine my marker icon is a circle, I would like the center of it to be at the lat-lng of the given point...

Code:

```<code>var image_hotspot = 'img/icons/bank_euro.png';
var marker = new google.maps.Marker({
      map: map,
      position: placeLoc,
      icon: image_hotspot
    });
</code>```

答:
If you are using addMarker and need set the x,y coordinates using Point(x, y)</p>

```<code>let markerInstance = mapInstance.addMarker({
            lat : _lat,
            lng : _lng,
            label: '8',
            icon : {
              url :  'url_image.png',
              origin:  new google.maps.Point(0, 0),
            }
        });
</code>```

Body:
In google map usually the center bottom of the image of the marker is the lat lng of a point that it has to mark.

Imagine my marker icon is a circle, I would like the center of it to be at the lat-lng of the given point...

Code:

var image_hotspot = 'img/icons/bank_euro.png';
var marker = new google.maps.Marker({
      map: map,
      position: placeLoc,
      icon: image_hotspot
    });

Body:
If you are using addMarker and need set the x,y coordinates using Point(x, y)

let markerInstance = mapInstance.addMarker({
            lat : _lat,
            lng : _lng,
            label: '8',
            icon : {
              url :  'url_image.png',
              origin:  new google.maps.Point(0, 0),
            }
        });


问:
Javascript RegExp Matching weirdness
I have a RegExp:

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi

and some text "Champion"

somehow, this is coming back as a match, am I crazy?

```<code>0: "pio"
1: "i"
index: 4
input: "Champion"
length: 2
</code>```

the loop is here:

```<code>// contruct the pattern, dynamically
var someText = "Champion";
var phrase = ".?(NCAA|Division|I|Basketball|Champions,|1939-2011).?";
var pat = new RegExp(phrase, "gi"); // <- ends up being
var result;

while( result = pat.exec(someText) ) {
     // do stuff!
}
</code>```

There has to be something wrong with my RegExp, right?

EDIT:
The .? thing was just a quick and dirty attempt to say that I'd like to match one of those words AND/OR one of those words with a single char on either side. ex:

```<code>\sNCAA\s
NCAA
NCAA\s
\sNCAA
</code>```

GOAL:
I'm trying to do some simple hit highlighting based on some search words. I've got a function that gets all of the text nodes on a page, and I'd like to go through them all and highlight any matches to any of the terms in my phrase variable.

I think that I just need to rework how I am building my RegExp.

答:
Champion matches /.?I.?/i.

Your own output notes that it's matching the substring "pio".

Perhaps you meant to bound the expression to the start and end of the input, with ^ and $ respectively:

```<code>/^.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?$/gi
</code>```

I know you said to ignore the .?, but I can't: it's most likely wrong, and it's most likely going to continue to cause you problems. Explain why they're there and we can tell you how to do it properly. :)

Title: Javascript RegExp Matching weirdness

Body:
I have a RegExp:

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi

and some text "Champion"

somehow, this is coming back as a match, am I crazy?

0: "pio"
1: "i"
index: 4
input: "Champion"
length: 2

the loop is here:

// contruct the pattern, dynamically
var someText = "Champion";
var phrase = ".?(NCAA|Division|I|Basketball|Champions,|1939-2011).?";
var pat = new RegExp(phrase, "gi"); // <- ends up being
var result;

while( result = pat.exec(someText) ) {
     // do stuff!
}

There has to be something wrong with my RegExp, right?

EDIT:
The .? thing was just a quick and dirty attempt to say that I'd like to match one of those words AND/OR one of those words with a single char on either side. ex:

\sNCAA\s
NCAA
NCAA\s
\sNCAA

GOAL:
I'm trying to do some simple hit highlighting based on some search words. I've got a function that gets all of the text nodes on a page, and I'd like to go through them all and highlight any matches to any of the terms in my phrase variable.

I think that I just need to rework how I am building my RegExp.

Body:
Champion matches /.?I.?/i.

Your own output notes that it's matching the substring "pio".

Perhaps you meant to bound the expression to the start and end of the input, with ^ and $ respectively:

/^.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?$/gi

I know you said to ignore the .?, but I can't: it's most likely wrong, and it's most likely going to continue to cause you problems. Explain why they're there and we can tell you how to do it properly. :)


问:
How to get client side data from Kendo Grid to controller
I am trying to get Kendo Grid data which is hydrated from client side to a MVC controller method. My view contains several single fields like name, date of birth etc  and tabular field which I hooked with a Kendo Grid. Since its a new operation I have no data in the grid ( and other fields) and user enters them from client side.

I have no idea how to proceed on this. Ideally I would like to get this data to a list in my viewmodal. So that when the user hits save, I  have all other data and the grid data coming into a controller method.

I am able to successfully bind a list with kendo grid and display it. I have very little experience on JavaScript and Kendo and web programming.
If any of you can point me to the right direction, sample code would be greatly appreciated.

```<code>$("#departmet").kendoGrid({
                dataSource: dataSource,
                height: 250,
                scrollable: true,
                sortable: true,
                filterable: true,
                pageable: {
                    input: true,
                    numeric: false
                },
                columns: [
                    "DepartmentName",
                    "SubDivision"
                ]
            });
</code>```

答:
From experience I know their documentation is not easy to navigate. It seems there is the documentation and then the API.  The API is usually what you will always want to find. What you will need is the information from here https://docs.telerik.com/kendo-ui/api/javascript/ui/grid.  If I understand the question correctly.  There are several ways you can achieve posting.  You could make use of editor templates.  Click the Open in Dojo to get an idea how it looks.

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/editable.template

With this you do not have to worry about modifying the data via javascript. Assuming your grid is surrounded with a form element it will get posted when submitted. Note paging is not accounted for here. Also, this method by default can auto post after each edit.  If you don't want this behavior then you will have to have advanced knowledge of the API.....Correction on that last statement. The API is different when dealing with the data all on the client side. Click the Open in Dojo to see it all on the client side. If you are not wanting to use editor templates and want to manage the data editing yourself then you need to use the grid methods provided.

Once you have your grid created. To access the data source of the grid you will need to get the dataSource.

$('#departmet').data('kendoGrid').dataSource;

https://docs.telerik.com/kendo-ui/api/javascript/data/datasource

If you need to use a different data source(or change it) you can use the setDataSource method below(grid function).

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource

To add to the data source use the add function to add a new object.

$('#departmet').data('kendoGrid').dataSource.add({ id: 2, name: 'name'});

https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/methods/add

It is important with kendo to ALWAYS use the methods provided to change the data source so that the proper events can fire to update the UI accordingly. This includes if you need to set a property on a specific data item. In that case you need to use the set method on the item itself.

After you are done modifying your data. Within javascript get the data and either create DOM elements within a form

```<code>//JQuery sudo code example
var data = $("#departmet").data("kendoGrid").dataSource.data();
var dataLen = data.length;
var myForm = $('#my-form'); //Already within DOM
for (var i = 0; i < dataLen; i++) {
    var item = data[i];
    var idEl = $('<input type="hidden" name="userData[' + i + '].id" />');
    idEl.val(item.id);
    var nameEl = $('<input type="hidden" name="userData[' + i + '].name" />');
    nameEl.val(item.name);
    myForm.append(idEl);
    myForm.append(nameEl);
}

myForm.submit();
</code>```

This assumes your controller function(??) on the backend is expecting an array of objects with the property name of userData.

Alternatively, you can post it via ajax. For example, the ajax jquery function.  Passing your data as the data of the ajax call.

http://api.jquery.com/jquery.ajax/

Don't want to ramble.  Let me know if you need more help.

Body:
I am trying to get Kendo Grid data which is hydrated from client side to a MVC controller method. My view contains several single fields like name, date of birth etc  and tabular field which I hooked with a Kendo Grid. Since its a new operation I have no data in the grid ( and other fields) and user enters them from client side.

I have no idea how to proceed on this. Ideally I would like to get this data to a list in my viewmodal. So that when the user hits save, I  have all other data and the grid data coming into a controller method.

I am able to successfully bind a list with kendo grid and display it. I have very little experience on JavaScript and Kendo and web programming.
If any of you can point me to the right direction, sample code would be greatly appreciated.

$("#departmet").kendoGrid({
                dataSource: dataSource,
                height: 250,
                scrollable: true,
                sortable: true,
                filterable: true,
                pageable: {
                    input: true,
                    numeric: false
                },
                columns: [
                    "DepartmentName",
                    "SubDivision"
                ]
            });

Body:
From experience I know their documentation is not easy to navigate. It seems there is the documentation and then the API.  The API is usually what you will always want to find. What you will need is the information from here https://docs.telerik.com/kendo-ui/api/javascript/ui/grid.  If I understand the question correctly.  There are several ways you can achieve posting.  You could make use of editor templates.  Click the Open in Dojo to get an idea how it looks.

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/editable.template

With this you do not have to worry about modifying the data via javascript. Assuming your grid is surrounded with a form element it will get posted when submitted. Note paging is not accounted for here. Also, this method by default can auto post after each edit.  If you don't want this behavior then you will have to have advanced knowledge of the API.....Correction on that last statement. The API is different when dealing with the data all on the client side. Click the Open in Dojo to see it all on the client side. If you are not wanting to use editor templates and want to manage the data editing yourself then you need to use the grid methods provided.

Once you have your grid created. To access the data source of the grid you will need to get the dataSource.

$('#departmet').data('kendoGrid').dataSource;

https://docs.telerik.com/kendo-ui/api/javascript/data/datasource

If you need to use a different data source(or change it) you can use the setDataSource method below(grid function).

https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource

To add to the data source use the add function to add a new object.

$('#departmet').data('kendoGrid').dataSource.add({ id: 2, name: 'name'});

https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/methods/add

It is important with kendo to ALWAYS use the methods provided to change the data source so that the proper events can fire to update the UI accordingly. This includes if you need to set a property on a specific data item. In that case you need to use the set method on the item itself.

After you are done modifying your data. Within javascript get the data and either create DOM elements within a form

//JQuery sudo code example
var data = $("#departmet").data("kendoGrid").dataSource.data();
var dataLen = data.length;
var myForm = $('#my-form'); //Already within DOM
for (var i = 0; i < dataLen; i++) {
    var item = data[i];
    var idEl = $('<input type="hidden" name="userData[' + i + '].id" />');
    idEl.val(item.id);
    var nameEl = $('<input type="hidden" name="userData[' + i + '].name" />');
    nameEl.val(item.name);
    myForm.append(idEl);
    myForm.append(nameEl);
}

myForm.submit();

This assumes your controller function(??) on the backend is expecting an array of objects with the property name of userData.

Alternatively, you can post it via ajax. For example, the ajax jquery function.  Passing your data as the data of the ajax call.

http://api.jquery.com/jquery.ajax/

Don't want to ramble.  Let me know if you need more help.


问:
Counting an Occurrence in an Array (Java)
I am completely stumped. I took a break for a few hours and I can't seem to figure this one out. It's upsetting!

I know that I need to check the current element in the array and see if it appears elsewhere in the array. The idea is to output the following:

The user is asked to enter 10 integers and those integers are assigned to an array (hence the "numbers" as a paremeter for the method). Let's say I enter "1, 1, 2, 3, 3, 4, 5, 6, 7, 8." The printed results should be "1 occurs 2 times. 2 occurs 1 time. 3 occurs 2 times. 4 occurs 1 time. 5 occurs 1 time. 6 occurs 1 time. 7 occurs 1 time. 8 occurs 1 time." This printing will be done in a separate method.

Everything in my code works except for this method that I created to count the occurrences.

```<code>public static int getOccurrences(int[] numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
    {
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])
        {
            count++;
        }
    }

    return count;
}
</code>```

I know what the issue is here. I set the current integer element in the array to the variable currentInt. The if statement counts every integer element in the array, hence the output being "[I@2503dbd3 occurs 10 times."

How do I keep track of the occurrences of each element in the array?

答:
We can use java 8 Stream API to  create Frequency Map

Stream.of("apple", "orange", "banana", "apple")          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.forEach(System.out::println);

The downstream operation is itself a collector (Collectors.counting()) that operates on elements of type String
and produces a result of type Long. The result of the collect method call is a Map.

This would produce the following output:

banana=1

orange=1

apple=2

Body:
I am completely stumped. I took a break for a few hours and I can't seem to figure this one out. It's upsetting!

I know that I need to check the current element in the array and see if it appears elsewhere in the array. The idea is to output the following:

The user is asked to enter 10 integers and those integers are assigned to an array (hence the "numbers" as a paremeter for the method). Let's say I enter "1, 1, 2, 3, 3, 4, 5, 6, 7, 8." The printed results should be "1 occurs 2 times. 2 occurs 1 time. 3 occurs 2 times. 4 occurs 1 time. 5 occurs 1 time. 6 occurs 1 time. 7 occurs 1 time. 8 occurs 1 time." This printing will be done in a separate method.

Everything in my code works except for this method that I created to count the occurrences.

public static int getOccurrences(int[] numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
    {
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])
        {
            count++;
        }
    }

    return count;
}

I know what the issue is here. I set the current integer element in the array to the variable currentInt. The if statement counts every integer element in the array, hence the output being "[I@2503dbd3 occurs 10 times."

How do I keep track of the occurrences of each element in the array?


问:
Azure SQL Server Error : The elastic pool has reached its storage limit. The storage usage for the elastic pool cannot exceed (204800)
When I am trying to update or insert multiple rows from the application or directly sql server database, I am getting the error as below.

Msg 1132, Level 16, State 1, Line 1 The elastic pool has reached its
  storage limit. The storage usage for the elastic pool cannot exceed
  (204800) MBs.

I do not know how to handle this. Please help.

答:
Error when inserting data: "The elastic pool has reached its storage limit. The storage usage for the elastic pool cannot exceed (153600) MBs"

A scale up scale down of the database didn't fix the error.

Pool was scaled from 100GB to 150GB. Size stated in error is 153.6GB. Scaled the elastic pool to 250GB. Data successfully inserted. Scaled back down to 100GB, for cost purposes, and insert still worked.

A scale up of the elastic pool--beyond the limit in error message--and scale down fixed the issue.


问:
Java Mockito is hitting real method rather than using mocked method
My mockito method is hitting the real method rather than invoking the mocked method. Your inputs will be helpful

Java code.

```<code>public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final String domain){
        userDao = new UserDao(domain);
    }

    public IUser getExistingUser(){
            if (userDao == null) {
                throw new RuntimeException("userDao is null");
            }
            IUser existingUser = userDao.getExistingUser();
            if (existingUser == null) {
                throw new RuntimeException("ExistingUser is null");
            }
            return existingUser;
    }
}
</code>```

This is my JUnit test code.

```<code>    @Test
    public void testExistingUser() {
        UserDao mockUserDao = mock(UserDao.class);
        when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());
    }

    private UserDao getExistingTestUser(() {
        return ExistingUserImpl.Builder(). //withfield methods. build();
    }
</code>```

I  am creating this mock object for only testing purpose. This just return the mocked MockedExistingUserImpl  object which is implemented by IUser.

```<code>public class MockedExistingUserImpl implements IUser {
    //fields
    //overriding getter methods for all fields
    //Builder for  ExistingUserImpl
}
</code>```

When ever I call userDao.getExistingUser() in my code, I am expecting to return the mocked Existing user object but it is hitting the real method and failing the test due to domain connection. We don't establish a domain connection to run Junits. Any inputs are appreciated. Thank you !

答:
Your mistake is in broken 'Dependency injection' principle.

Don't use new operator - create UserDao at the level above and use injection.

```<code>public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final UserDao usedDao) {
        this.userDao = userDao;
    }

    public IUser getExistingUser() {
        if (userDao == null) {
            throw new RuntimeException("userDao is null");
        }
        IUser existingUser = userDao.getExistingUser();
        if (existingUser == null) {
            throw new RuntimeException("ExistingUser is null");
        }
        return existingUser;
    }
}
</code>```

Now you can test your code in the following way:

```<code>@Test
public void testExistingUser() {
    UserDao mockUserDao = mock(UserDao.class);
    when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());

    CheckUser checkUser = new CheckUser(mockUserDao);
    IUser iUser = checkUser.getExistingUser();

    // assertions here
}

private UserDao getExistingTestUser(() {
    return ExistingUserImpl.Builder(). //withfield methods. build();
}
</code>```

Body:
My mockito method is hitting the real method rather than invoking the mocked method. Your inputs will be helpful

Java code.

public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final String domain){
        userDao = new UserDao(domain);
    }

    public IUser getExistingUser(){
            if (userDao == null) {
                throw new RuntimeException("userDao is null");
            }
            IUser existingUser = userDao.getExistingUser();
            if (existingUser == null) {
                throw new RuntimeException("ExistingUser is null");
            }
            return existingUser;
    }
}

This is my JUnit test code.

    @Test
    public void testExistingUser() {
        UserDao mockUserDao = mock(UserDao.class);
        when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());
    }

    private UserDao getExistingTestUser(() {
        return ExistingUserImpl.Builder(). //withfield methods. build();
    }

I  am creating this mock object for only testing purpose. This just return the mocked MockedExistingUserImpl  object which is implemented by IUser.

public class MockedExistingUserImpl implements IUser {
    //fields
    //overriding getter methods for all fields
    //Builder for  ExistingUserImpl
}

When ever I call userDao.getExistingUser() in my code, I am expecting to return the mocked Existing user object but it is hitting the real method and failing the test due to domain connection. We don't establish a domain connection to run Junits. Any inputs are appreciated. Thank you !

Body:
Your mistake is in broken 'Dependency injection' principle.

Don't use new operator - create UserDao at the level above and use injection.

public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final UserDao usedDao) {
        this.userDao = userDao;
    }

    public IUser getExistingUser() {
        if (userDao == null) {
            throw new RuntimeException("userDao is null");
        }
        IUser existingUser = userDao.getExistingUser();
        if (existingUser == null) {
            throw new RuntimeException("ExistingUser is null");
        }
        return existingUser;
    }
}

Now you can test your code in the following way:

@Test
public void testExistingUser() {
    UserDao mockUserDao = mock(UserDao.class);
    when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());

    CheckUser checkUser = new CheckUser(mockUserDao);
    IUser iUser = checkUser.getExistingUser();

    // assertions here
}

private UserDao getExistingTestUser(() {
    return ExistingUserImpl.Builder(). //withfield methods. build();
}