问:
PowerShell Replace Specific String in File When multiple matches exist

Problem

I am trying to modify a file by replacing a very specific substring within a file; however, in this particular instance, the file contains two lines that are nearly identical.

This line is in an AssemblyInfo file and I am trying to replace the value of the AssemblyVersion. See below:

```<code>$CurrentVersion = '1.0.*'
$NewVersion = '1.0.7.1'

# Two similar lines:
// [assembly: AssemblyVersion("1.0.*")] # I want to ignore this line
[assembly: AssemblyVersion("1.0.*")] # I want to target this value
</code>```

I have been trying several different approaches to this, each with varying results.

```<code>$Assembly = 'C:\path\to\AssemblyInfo.cs'
$regex = '(?<!\/\/ \[assembly:AssemblyVersion\(")(?<=AssemblyVersion\(")[^"]*'
$regex2 = ('`n\[assembly: AssemblyVersion\("'+$CurrentVersion+'"\)\]')
</code>```

Attempt 001

```<code>(GC $Assembly) |
ForEach-Object { $_.Replace($CurrentVersion, $NewVersion) } |
Set-Content $Assembly
</code>```

This was an obvious failure. It ends up replacing both instances of '1.0.*'

Attempt 002

```<code>GC $Assembly |
Select-String -Pattern '^\[assembly' -AllMatches |
ForEach-Object { $_.Replace($CurrentVersion, $NewVersion) } |
Set-Content $Assembly
</code>```

This ended with incompatible command issues...

Attempt 003

```<code>(GC $Assembly) | ForEAch-Object {
    If ( $_ -MATCH $CurrentVersion ) {
        ForEach ($Line in $_) {
            $_.Replace($CurrentVersion, $NewVersion)
        }
    }
 } |
 Set-Content $Assembly
</code>```

This ended up removing all lines that contained // as the starting characters... which was not what I wanted...

Attempt 004

```<code>GC $Assembly |
ForEach-Object {
    $_.Replace($regex2, ('[assembly: AssemblyVersion("'+$NewVersion+'")]'))
} |
Set-Content $Assembly
</code>```

I get an error saying the file is in use... but that didn't make sense as I couldn't find anything using it...

I have tried several other paths as well, most variations of the above 4 in hopes of achieving my goal. Even going so far as to target the line using the regex line provided above and variations of it to try and grab

Question

Using PowerShell, how can I replace only the line/value of the target line (ignoring the line that begins with // ), but still keep all the lines in the file upon saving the contents?

答:
You are trying to use regex patterns but keep using the string method .Replace() which does not support it. You should be using the -replace operator. That would solve part of your issue.

Looks like you only want to replace the line that does not have anything else on it besides the assembly info.

```<code>$path = "C:\temp\test.txt"
$newVersion = "1.0.0.1"
$pattern = '^\s*?\[assembly: AssemblyVersion\("(.*)"\)\]'
(Get-Content $path) | ForEach-Object{
    if($_ -match $pattern){
        # We have found the matching line
        '[assembly: AssemblyVersion("{0}")]' -f $newVersion
    } else {
        # Output line as is
        $_
    }
} | Set-Content $path
</code>```

That would be a verbose yet simple to follow way to do what you want. It will only match if the assembly line is at the start of the line with optional spaces.

I would expect that the pattern '^[assembly: AssemblyVersion\("(.*)"\)\]' works just as well since it should appear at the start of the line anyway.

This comes from another answer about almost this exact problem except now there is more that one match possibility. Also you will see my regex pattern isolates the current version in case you need that. If that is the case looked at the linked question.

You can combine this with other options but if you know ahead of time the version you are going to use then the replacement is pretty simple as well.

```<code>$newVersion = "1.6.5.6"
(Get-Content $path -Raw) -replace '(?m)^\[assembly: AssemblyVersion\("(.*)"\)\]', ('[assembly: AssemblyFileVersion("{0}")]' -f $newVersion)  | Set-Content $path
</code>```

That reads the file in as one string and performs the replacement as long as the pattern is at the start of the line in the file. (?m) lets us treat the start of line anchor ^ as something that works at the beginning of lines in the text. Not just the start of the whole string.

Body:
Problem

I am trying to modify a file by replacing a very specific substring within a file; however, in this particular instance, the file contains two lines that are nearly identical.

This line is in an AssemblyInfo file and I am trying to replace the value of the AssemblyVersion. See below:

$CurrentVersion = '1.0.*'
$NewVersion = '1.0.7.1'

# Two similar lines:
// [assembly: AssemblyVersion("1.0.*")] # I want to ignore this line
[assembly: AssemblyVersion("1.0.*")] # I want to target this value

I have been trying several different approaches to this, each with varying results.

$Assembly = 'C:\path\to\AssemblyInfo.cs'
$regex = '(?<!\/\/ \[assembly:AssemblyVersion\(")(?<=AssemblyVersion\(")[^"]*'
$regex2 = ('`n\[assembly: AssemblyVersion\("'+$CurrentVersion+'"\)\]')

Attempt 001

(GC $Assembly) |
ForEach-Object { $_.Replace($CurrentVersion, $NewVersion) } |
Set-Content $Assembly

This was an obvious failure. It ends up replacing both instances of '1.0.*'

Attempt 002

GC $Assembly |
Select-String -Pattern '^\[assembly' -AllMatches |
ForEach-Object { $_.Replace($CurrentVersion, $NewVersion) } |
Set-Content $Assembly

This ended with incompatible command issues...

Attempt 003

(GC $Assembly) | ForEAch-Object {
    If ( $_ -MATCH $CurrentVersion ) {
        ForEach ($Line in $_) {
            $_.Replace($CurrentVersion, $NewVersion)
        }
    }
 } |
 Set-Content $Assembly

This ended up removing all lines that contained // as the starting characters... which was not what I wanted...

Attempt 004

GC $Assembly |
ForEach-Object {
    $_.Replace($regex2, ('[assembly: AssemblyVersion("'+$NewVersion+'")]'))
} |
Set-Content $Assembly

I get an error saying the file is in use... but that didn't make sense as I couldn't find anything using it...

I have tried several other paths as well, most variations of the above 4 in hopes of achieving my goal. Even going so far as to target the line using the regex line provided above and variations of it to try and grab

Question

Using PowerShell, how can I replace only the line/value of the target line (ignoring the line that begins with // ), but still keep all the lines in the file upon saving the contents?

Body:
You are trying to use regex patterns but keep using the string method .Replace() which does not support it. You should be using the -replace operator. That would solve part of your issue.

Looks like you only want to replace the line that does not have anything else on it besides the assembly info.

$path = "C:\temp\test.txt"
$newVersion = "1.0.0.1"
$pattern = '^\s*?\[assembly: AssemblyVersion\("(.*)"\)\]'
(Get-Content $path) | ForEach-Object{
    if($_ -match $pattern){
        # We have found the matching line
        '[assembly: AssemblyVersion("{0}")]' -f $newVersion
    } else {
        # Output line as is
        $_
    }
} | Set-Content $path

That would be a verbose yet simple to follow way to do what you want. It will only match if the assembly line is at the start of the line with optional spaces.

I would expect that the pattern '^[assembly: AssemblyVersion\("(.*)"\)\]' works just as well since it should appear at the start of the line anyway.

This comes from another answer about almost this exact problem except now there is more that one match possibility. Also you will see my regex pattern isolates the current version in case you need that. If that is the case looked at the linked question.

You can combine this with other options but if you know ahead of time the version you are going to use then the replacement is pretty simple as well.

$newVersion = "1.6.5.6"
(Get-Content $path -Raw) -replace '(?m)^\[assembly: AssemblyVersion\("(.*)"\)\]', ('[assembly: AssemblyFileVersion("{0}")]' -f $newVersion)  | Set-Content $path

That reads the file in as one string and performs the replacement as long as the pattern is at the start of the line in the file. (?m) lets us treat the start of line anchor ^ as something that works at the beginning of lines in the text. Not just the start of the whole string.


来源: stackexchange

问:
Xamarin.iOS does not compile - CS2011 Error opening Response File
I edited a storyboard in Xcode's Interface Builder, and assigned the View Controllers from Interface Builder.

Now when I attempt to compile the project I receive the following compiler error:

```<code>/absolute/path/to/project/MyProject.iOS/CSC: Error CS2011: Error opening response file '/absolute/path/to/project/MyProject.iOS/Views/Root/RootController.cs' (CS2011) (MyProject.iOS)
/absolute/path/to/project/MyProject.iOS/CSC: Error CS2011: Error opening response file '/absolute/path/to/project/MyProject.iOS/Views/Root/RootController.designer.cs' (CS2011) (MyProject.iOS)
</code>```

I don't know if this could be related, but when I create the ViewController from Visual Studio for Mac [Community] (7.2.2 build 11) it also creates a .xib file for the ViewController, that I just delete as I only want the ViewController.

Anyway, is there anything I should do differently when editing storyboards from Xcode? Or is there something I'm missing when creating a new UIViewController from Visual Studio?

Here is the file Visual Studio generates for the UIViewController

```<code>public partial class RootController : UIViewController
{
    public RootController() : base("RootController", null)
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        // Perform any additional setup after loading the view, typically from a nib.
    }

    public override void DidReceiveMemoryWarning()
    {
        base.DidReceiveMemoryWarning();
        // Release any cached data, images, etc that aren't in use.
    }
}
</code>```

答:
Ok, I'm going to post the answer to this as I just found out what was causing it.

In my solution I have my Views folder named @Views so it sits at the top of the folder structure. Visual Studio doesn't seem to like that name @Views specifically the @ and thus strips it out, which makes it an invalid path when when it goes to look for the file.

So it's my poor choice of naming that caused my own issue.

ContentLicense: CC BY-SA 3.0

Body:
I edited a storyboard in Xcode's Interface Builder, and assigned the View Controllers from Interface Builder.

Now when I attempt to compile the project I receive the following compiler error:

/absolute/path/to/project/MyProject.iOS/CSC: Error CS2011: Error opening response file '/absolute/path/to/project/MyProject.iOS/Views/Root/RootController.cs' (CS2011) (MyProject.iOS)
/absolute/path/to/project/MyProject.iOS/CSC: Error CS2011: Error opening response file '/absolute/path/to/project/MyProject.iOS/Views/Root/RootController.designer.cs' (CS2011) (MyProject.iOS)

I don't know if this could be related, but when I create the ViewController from Visual Studio for Mac [Community] (7.2.2 build 11) it also creates a .xib file for the ViewController, that I just delete as I only want the ViewController.

Anyway, is there anything I should do differently when editing storyboards from Xcode? Or is there something I'm missing when creating a new UIViewController from Visual Studio?

Here is the file Visual Studio generates for the UIViewController

public partial class RootController : UIViewController
{
    public RootController() : base("RootController", null)
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        // Perform any additional setup after loading the view, typically from a nib.
    }

    public override void DidReceiveMemoryWarning()
    {
        base.DidReceiveMemoryWarning();
        // Release any cached data, images, etc that aren't in use.
    }
}


问:
When cloning a MySQL db, does the "current database" name need to be changed for the new website?
When doing a mysqldump of a MySQL database, it includes the following at the top of the .sql file:

```<code>Host: localhost    Database: myaccount_mydb
</code>```

The cloned database will have a different name (myaccount_mynewdb), in this example. Does myaccount_mydb need to be renamed in the .sql file prior to it being loaded in the new name? Or does this command line take care of it:

```<code>mysql --one-database myaccount_mynewdb < myaccount_mydb.sql -p
</code>```

Does the mysql command ignore Database: myaccount_mydb entirely?

答: The host and database line is inside a comment (line starts with '-- '), so the line will be ignored by the MySQL command-line tool. It is information only.</p>

Body:
When doing a mysqldump of a MySQL database, it includes the following at the top of the .sql file:

Host: localhost    Database: myaccount_mydb

The cloned database will have a different name (myaccount_mynewdb), in this example. Does myaccount_mydb need to be renamed in the .sql file prior to it being loaded in the new name? Or does this command line take care of it:

mysql --one-database myaccount_mynewdb < myaccount_mydb.sql -p

Does the mysql command ignore Database: myaccount_mydb entirely?


问:
Avoid lexicographic ordering of numerical values with Python min() max()
I have a script to pull random numbers from a set of values. However, it broke today because min() and max() sort values by lexicographic order (so 200 is considered greater than 10000). How can I avoid lexicographic order here? Len key is on the right track but not quite right. I couldn't find any other key(s) that would help.

```<code>data_set = 1600.csv, 2405.csv, 6800.csv, 10000.csv, 21005.csv
</code>```

First try:

```<code>highest_value = os.path.splitext(max(data_set))[0]
lowest_value = os.path.splitext(min(data_set))[0]
</code>```

returns: lowest_value = 10000 highest_value = 6800

Second try:

```<code>highest_value = os.path.splitext(max(data_set,key=len))[0]
lowest_value = os.path.splitext(min(data_set,key=len))[0]
</code>```

returns: lowest_value = 1600 highest_value = 10000

Thanks.

答:
You were close. Rather than using the result of splittext with the len function, use the int function instead:

```<code>>>> from os.path import splitext
>>> data_set = ['1600.csv', '2405.csv', '6800.csv', '10000.csv', '21005.csv']
>>> def convert_to_int(file_name):
        return int(splitext(file_name)[0])

>>> min(data_set, key=convert_to_int)
'1600.csv'
>>> max(data_set, key=convert_to_int)
'21005.csv'
</code>```

Of course, this solution assumes that your file name will consist solely of numerical values.

Body:
I have a script to pull random numbers from a set of values. However, it broke today because min() and max() sort values by lexicographic order (so 200 is considered greater than 10000). How can I avoid lexicographic order here? Len key is on the right track but not quite right. I couldn't find any other key(s) that would help.

data_set = 1600.csv, 2405.csv, 6800.csv, 10000.csv, 21005.csv

First try:

highest_value = os.path.splitext(max(data_set))[0]
lowest_value = os.path.splitext(min(data_set))[0]

returns: lowest_value = 10000 highest_value = 6800

Second try:

highest_value = os.path.splitext(max(data_set,key=len))[0]
lowest_value = os.path.splitext(min(data_set,key=len))[0]

returns: lowest_value = 1600 highest_value = 10000

Thanks.

Body:
You were close. Rather than using the result of splittext with the len function, use the int function instead:

>>> from os.path import splitext
>>> data_set = ['1600.csv', '2405.csv', '6800.csv', '10000.csv', '21005.csv']
>>> def convert_to_int(file_name):
        return int(splitext(file_name)[0])

>>> min(data_set, key=convert_to_int)
'1600.csv'
>>> max(data_set, key=convert_to_int)
'21005.csv'

Of course, this solution assumes that your file name will consist solely of numerical values.


问:
Getting a variable value into a jQuery UI call
I'm using the HTML/CSS/JavaScript/jQuery to create a UI palette for a Sketchup plug-in. There are numerous instances within the palette which require an input box with an associated slider, so I've decided to make a "class" using JavaScript so I can stamp them out. The HTML for one of the input box/slider combos looks like this:

```<code><span>H: <input type="text" class="InputBox" id="reg_panel_spacing_h"></span>
<div class="SliderSpan" id="reg_panel_spacing_h_slider"></div><br/>
</code>```

The relevant portion of the JavaScript looks like this:

```<code>$(document).ready(function() {

    function InputBoxJS (id, mi, ma, numtype, slider) {

        this.current_val = mi;
        this.element_id = id;
        this.minimum = mi;
        this.maximum = ma;

        var self = this;

        // string for selecting element using jquery
        jq_id = "#" + this.element_id;

        // slider code (if input box has associated slider)
        if(slider = true) {
            slider_jq_id = jq_id + "_slider" // id for selecting slider; assumes it's input id + "_slider"

            $(slider_jq_id).slider({
                min: mi,
                max: ma,
                value: self.current_val,
                slide: function(event,ui) {
                    $(jq_id).val(ui.value); // PROBLEMATIC LINE
                    call_ruby("manipulate_data", self.element_id);
                }
            });
        } // if slider = true
    }

    // create script objects for two input boxes
    var reg_panel_spacing_h = new InputBoxJS("reg_panel_spacing_h", 500, 50000, 0, true);
    var reg_panel_spacing_v = new InputBoxJS("reg_panel_spacing_v", 500, 50000, 0, true);

});
</code>```

The problem I'm having is that when I create two input boxes using this class (as shown in the above code), both sliders end up associated with the second input box. Specifically, the jq_id variable flagged in the above code as problematic ends up being set to "reg_panel_spacing_v" for both input boxes. What's bizarre is that jq_id is used a few lines above the "problematic line" to set slider_jq_id, and performs as expected when used there.

Basically what seems to be happening is that the function which contains the "problematic line" is getting associated with the slide event of ALL of the sliders when it's created, and it only uses the jq_id of the most recently-created input box. If change the "problematic line" like so:

```<code>$(("#" + self.element_id)).val(ui.value);
</code>```

the problem is fixed. So, I have a workaround. I'm just hoping that someone would be able to explain to me exactly what's going on.

Many thanks!

Josh

答:
Try making the variable local, like this:

```<code>var jq_id = "#" + this.element_id;
</code>```

I suspect that without making it local it get global scope that explain the "bizarre" behaviour.

ContentLicense: CC BY-SA 2.5

Body:
I'm using the HTML/CSS/JavaScript/jQuery to create a UI palette for a Sketchup plug-in. There are numerous instances within the palette which require an input box with an associated slider, so I've decided to make a "class" using JavaScript so I can stamp them out. The HTML for one of the input box/slider combos looks like this:

H: <input type="text" class="InputBox" id="reg_panel_spacing_h">

The relevant portion of the JavaScript looks like this:

$(document).ready(function() {

    function InputBoxJS (id, mi, ma, numtype, slider) {

        this.current_val = mi;
        this.element_id = id;
        this.minimum = mi;
        this.maximum = ma;

        var self = this;

        // string for selecting element using jquery
        jq_id = "#" + this.element_id;

        // slider code (if input box has associated slider)
        if(slider = true) {
            slider_jq_id = jq_id + "_slider" // id for selecting slider; assumes it's input id + "_slider"

            $(slider_jq_id).slider({
                min: mi,
                max: ma,
                value: self.current_val,
                slide: function(event,ui) {
                    $(jq_id).val(ui.value); // PROBLEMATIC LINE
                    call_ruby("manipulate_data", self.element_id);
                }
            });
        } // if slider = true
    }

    // create script objects for two input boxes
    var reg_panel_spacing_h = new InputBoxJS("reg_panel_spacing_h", 500, 50000, 0, true);
    var reg_panel_spacing_v = new InputBoxJS("reg_panel_spacing_v", 500, 50000, 0, true);

});

The problem I'm having is that when I create two input boxes using this class (as shown in the above code), both sliders end up associated with the second input box. Specifically, the jq_id variable flagged in the above code as problematic ends up being set to "reg_panel_spacing_v" for both input boxes. What's bizarre is that jq_id is used a few lines above the "problematic line" to set slider_jq_id, and performs as expected when used there.

Basically what seems to be happening is that the function which contains the "problematic line" is getting associated with the slide event of ALL of the sliders when it's created, and it only uses the jq_id of the most recently-created input box. If change the "problematic line" like so:

$(("#" + self.element_id)).val(ui.value);

the problem is fixed. So, I have a workaround. I'm just hoping that someone would be able to explain to me exactly what's going on.

Many thanks!

Josh

Body:
Try making the variable local, like this:

var jq_id = "#" + this.element_id;

I suspect that without making it local it get global scope that explain the "bizarre" behaviour.


问:
Camera Image is too small
From the last few days, I am suffering from the problem of Camera Image which is too small with the size of 120 x 160.

The Scenario is when I capture the image from camera and convert that image to byte[], it becomes too small.

Below is the code which I am using:

```<code> Bitmap unscaledBitmap  = (Bitmap) data.getExtras().get("data");
 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
 unscaledBitmap  .compress(Bitmap.CompressFormat.PNG, 30, bytes);
 byte[] bytesDoc1 = bytes.toByteArray();
</code>```

Don't have any idea about it but I have tried many solutions given on SO but all not worked for me.

Please help me.

答:
Not sure if it is too late to help you out on this issue. I faced this issue as well and just figured out why that photo is so small.
The reason was because on some phones (LG Tribute 5), the default picture size is somehow using the lowest one (160x120). In order to fix this bug, you have to get the supported picture sizes list from the camera.
Something like camera.getParameters.getSupportedPictureSizes(), and try to pick the minimum resolution you want, then setPictureSize to the best matched size you have picked.
That would fix the issue for sure.

Title: Camera Image is too small

Body:
From the last few days, I am suffering from the problem of Camera Image which is too small with the size of 120 x 160.

The Scenario is when I capture the image from camera and convert that image to byte[], it becomes too small.

Below is the code which I am using:

 Bitmap unscaledBitmap  = (Bitmap) data.getExtras().get("data");
 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
 unscaledBitmap  .compress(Bitmap.CompressFormat.PNG, 30, bytes);
 byte[] bytesDoc1 = bytes.toByteArray();

Don't have any idea about it but I have tried many solutions given on SO but all not worked for me.

Please help me.


问:
how do I add an azure role using a json within the azure cli?
I am using the Azure CLI 2.0 and don't see any documentation on adding a custom role via a json document. Can someone help?

I assume it starts out like this: $  az role create .. but that doesn't exist, apparently.

答:
Create a custom role in Azure Role-Based Access Control (RBAC) if none of the built-in roles meet your specific access needs. Custom roles can be created using Azure PowerShell, Azure Command-Line Interface (CLI), and the REST API.

To create a custom role using JSON, use the following cmdlet:

azure role create --inputfile

For more details, refer "Create a custom role"

Manage user roles for access control with Azure Active Directory and service principals, refer "az role".


问:
AutoHotkey: trigger hotkey just with Alt and Window
I want a hotkey to trigger when I press only ALT+WIN, and then release.  So if I use those keys to modify a different hotkey (for example, !#A), I do NOT want it to trigger. Only if I press !# then release without another keypress.

I tried !# UP::DoMyThing(), but that didn't work.

Is this possible?

答:
Unlike Control/Alt/Shift, there is no generic/neutral "Win" key because the OS does not support it. (See Modifier_keys)

Furthermore "#" is the modifier symbol for the windows key. Modifier symbols are used only in key-combinations in order to modify other keys.

Try also

```<code> !LWin UP::DoMyThing()
</code>```

or

```<code> !RWin UP::DoMyThing()
</code>```

Body:
Unlike Control/Alt/Shift, there is no generic/neutral "Win" key because the OS does not support it. (See Modifier_keys)

Furthermore "#" is the modifier symbol for the windows key. Modifier symbols are used only in key-combinations in order to modify other keys.

Try also

 !LWin UP::DoMyThing()

or

 !RWin UP::DoMyThing()


问:
Confusing "duplicate identifier" Typescript error message
Why am I getting this and many more errors of this kind? I am adding a link to the repo as well as key code snippets below. I think I have a basic misunderstanding of how the dependency and "include" chaining works.

```<code>csvproc(master)> tsc
node_modules/typescript/bin/lib.core.d.ts(83,5): error TS2300: Duplicate identifier 'configurable'.
node_modules/typescript/bin/lib.core.d.ts(84,5): error TS2300: Duplicate identifier 'enumerable'.
node_modules/typescript/bin/lib.core.d.ts(85,5): error TS2300: Duplicate identifier 'value'.
node_modules/typescript/bin/lib.core.d.ts(86,5): error TS2300: Duplicate identifier 'writable'.
</code>```

All code can be found here.

My tsconfig.json:

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": false,
        "outDir": "built/",
        "sourceMap": true,
        "target": "es5"
    }
}
</code>```

My tsd.json:

```<code>{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "node/node-0.10.d.ts": {
      "commit": "6387999eb899d0ba02d37dd8697647718caca230"
    },
    "should/should.d.ts": {
      "commit": "e1182d56ccb192379eade6055d9ba3fb6a0bacc4"
    }
  }
}
</code>```

My tsd.d.ts:

```<code>{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "node/node-0.10.d.ts": {
      "commit": "6387999eb899d0ba02d37dd8697647718caca230"
    },
    "should/should.d.ts": {
      "commit": "e1182d56ccb192379eade6055d9ba3fb6a0bacc4"
    }
  }
}
</code>```

答:
It can be because of having both typing and dependency in your node folder.
so first check what you have in your @types folder and if you have them in dependencies, remove the duplicate.
for me it was core.js</p>

Body:
Why am I getting this and many more errors of this kind? I am adding a link to the repo as well as key code snippets below. I think I have a basic misunderstanding of how the dependency and "include" chaining works.

csvproc(master)> tsc
node_modules/typescript/bin/lib.core.d.ts(83,5): error TS2300: Duplicate identifier 'configurable'.
node_modules/typescript/bin/lib.core.d.ts(84,5): error TS2300: Duplicate identifier 'enumerable'.
node_modules/typescript/bin/lib.core.d.ts(85,5): error TS2300: Duplicate identifier 'value'.
node_modules/typescript/bin/lib.core.d.ts(86,5): error TS2300: Duplicate identifier 'writable'.

All code can be found here.

My tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": false,
        "outDir": "built/",
        "sourceMap": true,
        "target": "es5"
    }
}

My tsd.json:

{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "node/node-0.10.d.ts": {
      "commit": "6387999eb899d0ba02d37dd8697647718caca230"
    },
    "should/should.d.ts": {
      "commit": "e1182d56ccb192379eade6055d9ba3fb6a0bacc4"
    }
  }
}

My tsd.d.ts:

{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "node/node-0.10.d.ts": {
      "commit": "6387999eb899d0ba02d37dd8697647718caca230"
    },
    "should/should.d.ts": {
      "commit": "e1182d56ccb192379eade6055d9ba3fb6a0bacc4"
    }
  }
}


问:
Case insensitive Predicate in WHERE clause without Changing Collation
Say I want to get all the people with the surname Smith

```<code>SELECT *
FROM   Person
WHERE  LastName = 'Smith'
</code>```

The above is fine. However, as my Database Collation is CS, a LastName value like SmItH, smith or SMITH will not be included in the results above.

I could do

```<code>SELECT *
FROM   Person
WHERE  UPPER(LastName) = 'SMITH'
</code>```

Which would work, however the query isn't then SARGable. However, the rub is that this will cause a table / index scan rather than a seek.

I know I can change the column or database collation but is there a way I can make the query SARGable without making any database changes?

答:
You can change the collation in your query by placing it after the where clause.  You can also mix the collations used within a where clause.  (The following example is pointless beyond demonstrating using two different collations.)

```<code>SELECT  *
  FROM  sys.objects AS o
  WHERE UPPER( o.name ) = o.name COLLATE SQL_Latin1_General_CP1_CS_AS
        AND o.name = o.name COLLATE SQL_Latin1_General_CP1_CI_AS
</code>```

The collation test can also be used in a case statement.

```<code>SELECT  o.name,
        CASE
          WHEN UPPER( o.name ) = o.name COLLATE SQL_Latin1_General_CP1_CS_AS
            THEN 'Upper Case'
          WHEN LOWER( o.name ) = o.name COLLATE SQL_Latin1_General_CP1_CS_AS
            THEN 'Lower Case'
          ELSE 'Mixed Case'
        END
  FROM  sys.objects AS o
  WHERE o.is_ms_shipped = 0
;
</code>```

Note the use of UPPER/LOWER was only to demonstrate the case sensitive nature once the collations were included.

Body:
Say I want to get all the people with the surname Smith

SELECT *
FROM   Person
WHERE  LastName = 'Smith'

The above is fine. However, as my Database Collation is CS, a LastName value like SmItH, smith or SMITH will not be included in the results above.

I could do

SELECT *
FROM   Person
WHERE  UPPER(LastName) = 'SMITH'

Which would work, however the query isn't then SARGable. However, the rub is that this will cause a table / index scan rather than a seek.

I know I can change the column or database collation but is there a way I can make the query SARGable without making any database changes?

Body:
You can change the collation in your query by placing it after the where clause.  You can also mix the collations used within a where clause.  (The following example is pointless beyond demonstrating using two different collations.)

SELECT  *
  FROM  sys.objects AS o
  WHERE UPPER( o.name ) = o.name COLLATE SQL_Latin1_General_CP1_CS_AS
        AND o.name = o.name COLLATE SQL_Latin1_General_CP1_CI_AS

The collation test can also be used in a case statement.

SELECT  o.name,
        CASE
          WHEN UPPER( o.name ) = o.name COLLATE SQL_Latin1_General_CP1_CS_AS
            THEN 'Upper Case'
          WHEN LOWER( o.name ) = o.name COLLATE SQL_Latin1_General_CP1_CS_AS
            THEN 'Lower Case'
          ELSE 'Mixed Case'
        END
  FROM  sys.objects AS o
  WHERE o.is_ms_shipped = 0
;

Note the use of UPPER/LOWER was only to demonstrate the case sensitive nature once the collations were included.


问:
Uncaught RangeError: Maximum call stack size exceeded - Error with Post to Ruby API from Preact Frontend
My browser ends up freezing and then giving me this error when I try to sign up. This is my first time working using a preact frontend with a rails api (also my first time posting on stackoverflow). Let me know if you need anymore information.

```<code>import { h, Component } from 'preact';
import $ from 'jquery';

class Signup extends Component {
    handleClick = (e) => {
      e.preventDefault();
      // console.log(this.password.value)
       var firstName = this.first_name;
       var lastName = this.last_name;
       var userName = this.userName;
       var email = this.email;
       var password = this.password;

      $.ajax({
        url: 'http://localhost:3000/users',
        type: 'POST',
        data: { user: { first_name: firstName, last_name: lastName, userName: userName, email: email, password: password } },
        success: (response) => {
          console.log('it worked!', response);
        },
        error: (response) => {
          console.log('it failed', response);
        }
        });
      }

      render() {
        return (
          <div className="sign-up">
            <br></br>
            <br/>
            <h2>Sign Up</h2>
            <br/>
            <form onSubmit={this.handleClick} method="get">
            <ul>
              <li> First name: <input ref={a => this.first_name = a} type="text" name="first_name"/> </li> <br/>
              <li> Last name: <input ref={b => this.last_name = b} type="text" name="last_name"/> </li> <br/>
              <li> Username: <input ref={ c => this.username = c} type="text" name="userName"/> </li> <br/>
              <li> Email: <input ref={d => this.email = d} type="text" name="email"/> </li> <br/>
              <li> Password: <input ref={e => this.password = e} type="password" name="password"/> </li> <br/>
            <input type="submit" value="Sign Up"/>
            </ul>
            </form>
          </div>
          )
        }
}

export default Signup;
</code>```

Picture of Error coming from Chrome Dev Tools

答:
I ended up changing a bunch of code and using fetch instead of jquery. Check it out below. Thanks to everybody for your comments.

```<code>import { h, Component } from 'preact';
</code>```

// import $ from 'jquery';
import axios from 'axios';

```<code>class Signup extends Component {
  handleClick = (e) => {
    e.preventDefault();
    var url = 'http://localhost:3000/users',
      data= JSON.stringify({
        user: {
          first_name: this.firstName.value,
          last_name: this.lastName.value,
          username: this.userName.value,
          email: this.email.value,
          password: this.password.value,
        }
      });

    fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: data
    })
    .then( res => res.json())
    .then( jsonRes => window.location = "/login")
    .catch( err => console.log(err))
}

render() {
  return (
    <div className="sign-up">
      <br></br>
      <br/>
      <h2>Sign Up</h2>
      <br/>
      <form onSubmit={this.handleClick} method="get">
      <ul>
        <li> First name: <input ref={a => this.firstName = a} type="text"/> </li> <br/>
        <li> Last name: <input ref={b => this.lastName = b} type="text"/> </li> <br/>
        <li> Username: <input ref={ c => this.userName = c} type="text"/> </li> <br/>
        <li> Email: <input ref={d => this.email = d} type="text"/> </li> <br/>
        <li> Password: <input ref={e => this.password = e} type="password"/> </li> <br/>
        <input type="submit" value="Sign Up"/>
      </ul>
      </form>
    </div>
  )
}
}

export default Signup;
</code>```

Body:
My browser ends up freezing and then giving me this error when I try to sign up. This is my first time working using a preact frontend with a rails api (also my first time posting on stackoverflow). Let me know if you need anymore information.

import { h, Component } from 'preact';
import $ from 'jquery';

class Signup extends Component {
    handleClick = (e) => {
      e.preventDefault();
      // console.log(this.password.value)
       var firstName = this.first_name;
       var lastName = this.last_name;
       var userName = this.userName;
       var email = this.email;
       var password = this.password;

      $.ajax({
        url: 'http://localhost:3000/users',
        type: 'POST',
        data: { user: { first_name: firstName, last_name: lastName, userName: userName, email: email, password: password } },
        success: (response) => {
          console.log('it worked!', response);
        },
        error: (response) => {
          console.log('it failed', response);
        }
        });
      }

      render() {
        return (

Sign Up

            <form onSubmit={this.handleClick} method="get">

 First name: <input ref={a => this.first_name = a} type="text" name="first_name"/>

 Last name: <input ref={b => this.last_name = b} type="text" name="last_name"/>

 Username: <input ref={ c => this.username = c} type="text" name="userName"/>

 Email: <input ref={d => this.email = d} type="text" name="email"/>

 Password: <input ref={e => this.password = e} type="password" name="password"/>

            <input type="submit" value="Sign Up"/>

            </form>

          )
        }
}

export default Signup;

Picture of Error coming from Chrome Dev Tools

Body:
I ended up changing a bunch of code and using fetch instead of jquery. Check it out below. Thanks to everybody for your comments.

import { h, Component } from 'preact';

// import $ from 'jquery';
import axios from 'axios';

class Signup extends Component {
  handleClick = (e) => {
    e.preventDefault();
    var url = 'http://localhost:3000/users',
      data= JSON.stringify({
        user: {
          first_name: this.firstName.value,
          last_name: this.lastName.value,
          username: this.userName.value,
          email: this.email.value,
          password: this.password.value,
        }
      });

    fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: data
    })
    .then( res => res.json())
    .then( jsonRes => window.location = "/login")
    .catch( err => console.log(err))
}

render() {
  return (
    <div className="sign-up">
      <br></br>
      <br/>
      <h2>Sign Up</h2>
      <br/>
      <form onSubmit={this.handleClick} method="get">
      <ul>
        <li> First name: <input ref={a => this.firstName = a} type="text"/> </li> <br/>
        <li> Last name: <input ref={b => this.lastName = b} type="text"/> </li> <br/>
        <li> Username: <input ref={ c => this.userName = c} type="text"/> </li> <br/>
        <li> Email: <input ref={d => this.email = d} type="text"/> </li> <br/>
        <li> Password: <input ref={e => this.password = e} type="password"/> </li> <br/>
        <input type="submit" value="Sign Up"/>
      </ul>
      </form>
    </div>
  )
}
}

export default Signup;


问:
Sorting a list of ten numbers with selection sort in assembly language
sorting a list of ten numbers with selection sort in assembly language.
How does i convert this bubble sort method into  selection sort method </p>

```<code>`[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
swap: db 0
start: mov bx, 0 ; initialize array index to zero
mov byte [swap], 0 ; rest swap flag to no swaps
loop1: mov ax, [data+bx] ; load number in ax
cmp ax, [data+bx+2] ; compare with next number
jbe noswap ; no swap if already in order
mov dx, [data+bx+2] ; load second element in dx
mov [data+bx+2], ax ; store first number in second
mov [data+bx], dx ; store second number in first
mov byte [swap], 1 ; flag that a swap has been done
noswap: add bx, 2 ; advance bx to next index
cmp bx, 18 ; are we at last index
jne loop1 ; if not compare next two
cmp byte [swap], 1 ; check if a swap has been done
je start ; if yes make another pass
mov ax, 0x4c00 ;  terminate program
int 0x21`
</code>```

答:
Maybe this will be helpfull. I wrote this a long time ago. Realmode intel assembler.

MAIN.ASM

```<code>SSTACK SEGMENT PARA STACK 'STACK'
    DW 128 DUP(?)
SSTACK ENDS

DSEG SEGMENT PUBLIC 'DATA'

    S LABEL BYTE
    ARR DB 'IHGFED27182392JASKD1O12312345CBA'
    LEN EQU ($-S)

    PUBLIC TMP
    PUBLIC MIN
    TMP DW ?
    MIN DW ?

DSEG ENDS

CSEG SEGMENT 'CODE'
    ASSUME CS:CSEG, SS:SSTACK, DS:DSEG

        EXTRN OUTPUT:NEAR
        EXTRN SORT:NEAR

START:      MOV AX, DSEG
        MOV DS, AX

        MOV BX, OFFSET ARR
        MOV CX, LEN
        CALL OUTPUT

        MOV AX, 60

        CMP AX, 0
        JZ NO_SORT
        CMP AX, 1
        JZ NO_SORT

        MOV BX, OFFSET ARR
        MOV CX, LEN
        CALL SORT

NO_SORT:    MOV BX, OFFSET ARR
        MOV CX, LEN
        CALL OUTPUT

        MOV AH, 4CH
        MOV AL, 0
        INT 21H

CSEG ENDS
     END START
</code>```

SORT.ASM

```<code>DSEG SEGMENT PUBLIC 'DATA'

    EXTRN TMP:WORD
    EXTRN MIN:WORD

DSEG ENDS

CSEG SEGMENT 'CODE'
    ASSUME CS:CSEG, DS:DSEG

    PUBLIC SORT

SORT PROC;              (AX - N, BX - ARRAY ADDRESS, CX - ARRAY LENGTH)

        PUSH SI
        PUSH DI
        PUSH DX

        CALL COMPARE_MIN

        DEC CX
        MOV AX, CX

        XOR SI, SI
        XOR DI, DI

 L1:
        PUSH CX
        MOV MIN, SI

        MOV TMP, DI
        INC DI

        MOV CX, AX

        L2:

        MOV DH, BYTE PTR[BX+DI]

        PUSH SI
        MOV SI, MIN
        MOV DL, BYTE PTR[BX+SI]
        POP SI

        CMP DH, DL
        JA OLD_MIN

NEW_MIN:    MOV MIN, DI

OLD_MIN:    INC DI
            DEC CX

        CMP CX, TMP
        JNZ L2

SWAP:       PUSH DI
        MOV DI, MIN

        MOV DL, BYTE PTR[BX+DI]
        MOV DH, BYTE PTR[BX+SI]

        MOV BYTE PTR [BX+SI], DL
        MOV BYTE PTR [BX+DI], DH

        POP DI

        INC SI
        MOV DI, SI

   POP CX
   LOOP L1

    POP DX
    POP DI
    POP DI

    RET

SORT ENDP

COMPARE_MIN PROC;   (AX - A, CX - B     CX - MIN)

        PUSH AX

        CMP AX, CX
        JB B__A
        JA A__B

A__B:       MOV CX, CX
        JMP EX

B__A:       MOV CX, AX
        JMP EX

EX:     POP AX
        RET

COMPARE_MIN ENDP

CSEG ENDS

     END
</code>```

OUTPUT.ASM

```<code>CSEG SEGMENT 'CODE'
    ASSUME CS:CSEG

    PUBLIC OUTPUT

OUTPUT PROC ; (BX - ARRAY ADDRESS, CX - ARRAY LENGTH)

    PUSH DX
    PUSH SI
    PUSH AX

    XOR SI, SI

    MOV AH, 02H

OUTARR: MOV DL,[BX+SI]
    INT 21H

    INC SI

        LOOP OUTARR

    MOV DL, 10
    INT 21H

    POP AX
    POP SI
    POP DX

    RET

OUTPUT ENDP
CSEG ENDS
     END
</code>```

Body:
sorting a list of ten numbers with selection sort in assembly language.
How does i convert this bubble sort method into  selection sort method

`[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
swap: db 0
start: mov bx, 0 ; initialize array index to zero
mov byte [swap], 0 ; rest swap flag to no swaps
loop1: mov ax, [data+bx] ; load number in ax
cmp ax, [data+bx+2] ; compare with next number
jbe noswap ; no swap if already in order
mov dx, [data+bx+2] ; load second element in dx
mov [data+bx+2], ax ; store first number in second
mov [data+bx], dx ; store second number in first
mov byte [swap], 1 ; flag that a swap has been done
noswap: add bx, 2 ; advance bx to next index
cmp bx, 18 ; are we at last index
jne loop1 ; if not compare next two
cmp byte [swap], 1 ; check if a swap has been done
je start ; if yes make another pass
mov ax, 0x4c00 ;  terminate program
int 0x21`

Body:
Maybe this will be helpfull. I wrote this a long time ago. Realmode intel assembler.

MAIN.ASM

SSTACK SEGMENT PARA STACK 'STACK'
    DW 128 DUP(?)
SSTACK ENDS

DSEG SEGMENT PUBLIC 'DATA'

    S LABEL BYTE
    ARR DB 'IHGFED27182392JASKD1O12312345CBA'
    LEN EQU ($-S)

    PUBLIC TMP
    PUBLIC MIN
    TMP DW ?
    MIN DW ?

DSEG ENDS

CSEG SEGMENT 'CODE'
    ASSUME CS:CSEG, SS:SSTACK, DS:DSEG

        EXTRN OUTPUT:NEAR
        EXTRN SORT:NEAR

START:      MOV AX, DSEG
        MOV DS, AX

        MOV BX, OFFSET ARR
        MOV CX, LEN
        CALL OUTPUT

        MOV AX, 60

        CMP AX, 0
        JZ NO_SORT
        CMP AX, 1
        JZ NO_SORT

        MOV BX, OFFSET ARR
        MOV CX, LEN
        CALL SORT

NO_SORT:    MOV BX, OFFSET ARR
        MOV CX, LEN
        CALL OUTPUT

        MOV AH, 4CH
        MOV AL, 0
        INT 21H

CSEG ENDS
     END START

SORT.ASM

DSEG SEGMENT PUBLIC 'DATA'

    EXTRN TMP:WORD
    EXTRN MIN:WORD

DSEG ENDS

CSEG SEGMENT 'CODE'
    ASSUME CS:CSEG, DS:DSEG

    PUBLIC SORT

SORT PROC;              (AX - N, BX - ARRAY ADDRESS, CX - ARRAY LENGTH)

        PUSH SI
        PUSH DI
        PUSH DX

        CALL COMPARE_MIN

        DEC CX
        MOV AX, CX

        XOR SI, SI
        XOR DI, DI

 L1:
        PUSH CX
        MOV MIN, SI

        MOV TMP, DI
        INC DI

        MOV CX, AX

        L2:

        MOV DH, BYTE PTR[BX+DI]

        PUSH SI
        MOV SI, MIN
        MOV DL, BYTE PTR[BX+SI]
        POP SI

        CMP DH, DL
        JA OLD_MIN

NEW_MIN:    MOV MIN, DI

OLD_MIN:    INC DI
            DEC CX

        CMP CX, TMP
        JNZ L2

SWAP:       PUSH DI
        MOV DI, MIN

        MOV DL, BYTE PTR[BX+DI]
        MOV DH, BYTE PTR[BX+SI]

        MOV BYTE PTR [BX+SI], DL
        MOV BYTE PTR [BX+DI], DH

        POP DI

        INC SI
        MOV DI, SI

   POP CX
   LOOP L1

    POP DX
    POP DI
    POP DI

    RET

SORT ENDP

COMPARE_MIN PROC;   (AX - A, CX - B     CX - MIN)

        PUSH AX

        CMP AX, CX
        JB B__A
        JA A__B

A__B:       MOV CX, CX
        JMP EX

B__A:       MOV CX, AX
        JMP EX

EX:     POP AX
        RET

COMPARE_MIN ENDP

CSEG ENDS

     END

OUTPUT.ASM

CSEG SEGMENT 'CODE'
    ASSUME CS:CSEG

    PUBLIC OUTPUT

OUTPUT PROC ; (BX - ARRAY ADDRESS, CX - ARRAY LENGTH)

    PUSH DX
    PUSH SI
    PUSH AX

    XOR SI, SI

    MOV AH, 02H

OUTARR: MOV DL,[BX+SI]
    INT 21H

    INC SI

        LOOP OUTARR

    MOV DL, 10
    INT 21H

    POP AX
    POP SI
    POP DX

    RET

OUTPUT ENDP
CSEG ENDS
     END


问:
Update start date by one day until end date as relevant data for each day within date range is recorded
I'm trying to update a date and simultaneously record each individual date and its respective z score on a separate worksheet. My excel file is is already set up so that as the date changes, the corresponding z scores for the day updates. Can anyone help me write VBA code that compiles the date with corresponding data for each day within the date range? Ideally, I want the code to adjust for a start date and end date when it is changed directly on the excel sheet. Unfortunately, I can't seem to update the date by one day without presetting it to a specific day, as an objected required error occurs for the "nextday" part of the code. </p>

```<code>Sub compliedataloop()

Dim wb As Workbook
Set wb = ActiveWorkbook

Dim wsprecip As Worksheet
Set wsprecip = wb.Worksheets("Precip")

Dim wshistoricaldata As Worksheet
Set wshistoricaldata = wb.Worksheets("Historical Data")

Dim nextday As String
Set nextday = wb.wsprecip.Range("CJ4")

wb.wshistoricaldata.Range("C4").Activate
wb.wsprecip.Range("CJ4").Activate
ActiveCell.Copy
wb.wshitoricaldata.Activate
ActiveCell.PasteSpecial
ActiveCell.Offset(1, 0).Activate
wb.wsprecip.Range("CN37").Activate
ActiveCell.Copy
wb.wshistoricaldata.Activate
ActiveCell.PasteSpecial
ActiveCell.Offset(-1, 1).Activate
wb.wsprecip.Range("CJ4").Activate
nextday.DateAdd = ("d")

Do While Enddate = False

'select, copy and paste first Date from cell CJ5 in "precip" Worksheet to "historicaldata" worksheet
wb.wsprecip.Range(CJ4).Activate
ActiveCell.Copy
wb.wshistoricaldata.Activate
ActiveCell.PasteSpecial
ActiveCell.Offset(1, 0).Activate
wb.wsprecip.Range("CJ4").Activate
nextday.DateAdd = ("d")
'copy new z-score for new date and paste data into "historicaldata" worksheet
wbs.wsprecip.Range("CN37").Activate
ActiveCell.Copy
wb.wshistoricaldata.Activate
ActiveCell.Offset(0, 1).Activate
ActiveCell.PasteSpecial
'reset positioning for next day's date in one cell above and to the right
ActiveCell.Offset(-1, 1).Activate

If Enddate = 2 / 28 / 2018 Then
Enddate = True
End If

End Sub
</code>```

答:
I don't know where to begin...

Make sure that you have Option Explicit as the first line in the module.  It will require you to define all of your variables, which stops you from randomly mistyping (wbs) or using variables (Enddate) that haven't been assigned a value.

PS please you capital letters at the start of each word in variable names, so that you can read them easier i.e. NextDay

You defined nextday as a string.  A string is not an object, hence why the " object required error occurs".

If all that you are doing is adding a day, you don't need the DateAdd function, just add 1.

You don't need to use any .Activate, .copy or .PasteSpecial to just copy a value from one cell to another.

I can't exactly figure out what you are doing; specifically with your end date. Are you trying to make this run once a day and keep writing to the next column?  If so, you need to fine the last column with something like this:

```<code>Public Function LastColumn(Optional Row As Integer = 1, Optional Sheet As Excel.Worksheet) As Long
    If Sheet Is Nothing Then Set Sheet = Application.ActiveSheet
    LastColumn = Sheet.Cells(Row, Sheet.Columns.Count).End(xlLeft).Row
End Function
</code>```

Set cell to the empty cell (Offset) after the last cell in row 4:

```<code>Set cell = LastColumn(4, wb.wsHistoricalData).offset(0,1)
</code>```

Anyway, here is what your code roughly looks like when fixed...

```<code>Option Explicit

Sub ComplieDataLoop()
Dim wb As Workbook
Dim wsPrecip As Worksheet
Dim wsHistoricalData As Worksheet
Dim NextDay As Date
'Dim EndDate As Date???
Dim cell As Range

    Set wb = ActiveWorkbook
    Set wsPrecip = wb.Worksheets("Precip")
    Set wsHistoricalData = wb.Worksheets("Historical Data")
    NextDay = wb.wsPrecip.Range("CJ4")
    'EndDate = ???
    Set cell = wb.wsHistoricalData.Range("C4")

    Do While EndDate < DateSerial( 2018, 2, 28)
        cell = wb.wsPrecip.Range("CJ4")
        Set cell = Offset(-1, 0)
        cell = wb.wsPrecip.Range("CN37")
        'reset positioning for next day's date in one cell above and to the right
        Set cell = Offset(-1, 1)
        'EndDate = ???
    Loop
End Sub
</code>```

Body:
I'm trying to update a date and simultaneously record each individual date and its respective z score on a separate worksheet. My excel file is is already set up so that as the date changes, the corresponding z scores for the day updates. Can anyone help me write VBA code that compiles the date with corresponding data for each day within the date range? Ideally, I want the code to adjust for a start date and end date when it is changed directly on the excel sheet. Unfortunately, I can't seem to update the date by one day without presetting it to a specific day, as an objected required error occurs for the "nextday" part of the code.

Sub compliedataloop()

Dim wb As Workbook
Set wb = ActiveWorkbook

Dim wsprecip As Worksheet
Set wsprecip = wb.Worksheets("Precip")

Dim wshistoricaldata As Worksheet
Set wshistoricaldata = wb.Worksheets("Historical Data")

Dim nextday As String
Set nextday = wb.wsprecip.Range("CJ4")

wb.wshistoricaldata.Range("C4").Activate
wb.wsprecip.Range("CJ4").Activate
ActiveCell.Copy
wb.wshitoricaldata.Activate
ActiveCell.PasteSpecial
ActiveCell.Offset(1, 0).Activate
wb.wsprecip.Range("CN37").Activate
ActiveCell.Copy
wb.wshistoricaldata.Activate
ActiveCell.PasteSpecial
ActiveCell.Offset(-1, 1).Activate
wb.wsprecip.Range("CJ4").Activate
nextday.DateAdd = ("d")

Do While Enddate = False

'select, copy and paste first Date from cell CJ5 in "precip" Worksheet to "historicaldata" worksheet
wb.wsprecip.Range(CJ4).Activate
ActiveCell.Copy
wb.wshistoricaldata.Activate
ActiveCell.PasteSpecial
ActiveCell.Offset(1, 0).Activate
wb.wsprecip.Range("CJ4").Activate
nextday.DateAdd = ("d")
'copy new z-score for new date and paste data into "historicaldata" worksheet
wbs.wsprecip.Range("CN37").Activate
ActiveCell.Copy
wb.wshistoricaldata.Activate
ActiveCell.Offset(0, 1).Activate
ActiveCell.PasteSpecial
'reset positioning for next day's date in one cell above and to the right
ActiveCell.Offset(-1, 1).Activate

If Enddate = 2 / 28 / 2018 Then
Enddate = True
End If

End Sub

Body:
I don't know where to begin...

Make sure that you have Option Explicit as the first line in the module.  It will require you to define all of your variables, which stops you from randomly mistyping (wbs) or using variables (Enddate) that haven't been assigned a value.

PS please you capital letters at the start of each word in variable names, so that you can read them easier i.e. NextDay

You defined nextday as a string.  A string is not an object, hence why the " object required error occurs".

If all that you are doing is adding a day, you don't need the DateAdd function, just add 1.

You don't need to use any .Activate, .copy or .PasteSpecial to just copy a value from one cell to another.

I can't exactly figure out what you are doing; specifically with your end date. Are you trying to make this run once a day and keep writing to the next column?  If so, you need to fine the last column with something like this:

Public Function LastColumn(Optional Row As Integer = 1, Optional Sheet As Excel.Worksheet) As Long
    If Sheet Is Nothing Then Set Sheet = Application.ActiveSheet
    LastColumn = Sheet.Cells(Row, Sheet.Columns.Count).End(xlLeft).Row
End Function

Set cell to the empty cell (Offset) after the last cell in row 4:

Set cell = LastColumn(4, wb.wsHistoricalData).offset(0,1)

Anyway, here is what your code roughly looks like when fixed...

Option Explicit

Sub ComplieDataLoop()
Dim wb As Workbook
Dim wsPrecip As Worksheet
Dim wsHistoricalData As Worksheet
Dim NextDay As Date
'Dim EndDate As Date???
Dim cell As Range

    Set wb = ActiveWorkbook
    Set wsPrecip = wb.Worksheets("Precip")
    Set wsHistoricalData = wb.Worksheets("Historical Data")
    NextDay = wb.wsPrecip.Range("CJ4")
    'EndDate = ???
    Set cell = wb.wsHistoricalData.Range("C4")

    Do While EndDate < DateSerial( 2018, 2, 28)
        cell = wb.wsPrecip.Range("CJ4")
        Set cell = Offset(-1, 0)
        cell = wb.wsPrecip.Range("CN37")
        'reset positioning for next day's date in one cell above and to the right
        Set cell = Offset(-1, 1)
        'EndDate = ???
    Loop
End Sub


问:
AllowAnyOrigin Cors Not working Axios Vuejs
I have a server that I have set up, running in production, we have tons of applications calling this web server. The code below is to demonstrate that it allows any origin requests.

```<code> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");

        app.UseStaticFiles();

        app.UseCors(builder =>
        {
            builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
        });
</code>```

This works for all servers currently set up. It's on our internal network, and other servers internally will use this service.

I am creating a proof of concept to try and modernize our Applications slowly by using Vue. Except this axios request is getting an error. The other servers that call this method are using .net as well, but it should build the same request.

Here is the error.

Failed to load https://{server}/api/application/36626: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

This is obviously crazy talk by axios. I allow for any origin. I can't imagine we only want to use 'simple-requests' so the w3 standard for simple requests might not work. I thought maybe this could be an incorrect error considering this is an octet-stream returned from the server. The code is below.

```<code><script>
import axios from 'axios'

export default {
  name: 'AppList',
  data () {
    return {
      applist: [],
      errors: []
    }
  },
  created: function() {
    axios.get('https://{server}/api/application/36626')
      .then(r => { console.log(response); })
      .catch(ex => {
        this.errors.push(ex);
      })
  }
}
</script>
</code>```

EDIT I have full rights to this machine, I have confirmed I can use a Postman GET request from my local machine with no problem.

Edit 2 Working curl command curl -X GET --header 'Accept: application/octet-stream' 'https://{server}/api/Application/36626'

答:
It turns out the .Net Core Server was not set up right, it wasn't until I was trying to use the browser on my local machine did the CORS problem crop up.

I'm not sure if the CORS implementation changed and I was not aware, or if I just wasn't doing it right from the start, but I was sure I followed guides.

The first thing I changed was ensuring that the Cors Policy was added before configuring the app to use MVC.

The second thing I did, and I suspect this is optional, but best practice, I also moved the policy logic to the ConfigureServices method.

My final code looked below. I'm keeping as much in tact to preserve the order.

```<code> public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
            services.AddOptions();
            services.AddSwaggerGen();
            ///Authentication configuration went here.
            services.AddSingleton<IConfiguration>(Configuration);
            services.AddMvc();

        }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");
        app.UseStaticFiles();
        app.UseCors("CorsPolicy");

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger((httpRequest, swaggerDoc) =>
        {
            swaggerDoc.Host = httpRequest.Host.Value;

        });
        app.UseSwaggerUi(swaggerUrl: "/{appname}/swagger/v1/swagger.json");
</code>```

Body:
I have a server that I have set up, running in production, we have tons of applications calling this web server. The code below is to demonstrate that it allows any origin requests.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");

        app.UseStaticFiles();

        app.UseCors(builder =>
        {
            builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
        });

This works for all servers currently set up. It's on our internal network, and other servers internally will use this service.

I am creating a proof of concept to try and modernize our Applications slowly by using Vue. Except this axios request is getting an error. The other servers that call this method are using .net as well, but it should build the same request.

Here is the error.

Failed to load https://{server}/api/application/36626: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

This is obviously crazy talk by axios. I allow for any origin. I can't imagine we only want to use 'simple-requests' so the w3 standard for simple requests might not work. I thought maybe this could be an incorrect error considering this is an octet-stream returned from the server. The code is below.

EDIT I have full rights to this machine, I have confirmed I can use a Postman GET request from my local machine with no problem.

Edit 2 Working curl command curl -X GET --header 'Accept: application/octet-stream' 'https://{server}/api/Application/36626'

Body:
It turns out the .Net Core Server was not set up right, it wasn't until I was trying to use the browser on my local machine did the CORS problem crop up.

I'm not sure if the CORS implementation changed and I was not aware, or if I just wasn't doing it right from the start, but I was sure I followed guides.

The first thing I changed was ensuring that the Cors Policy was added before configuring the app to use MVC.

The second thing I did, and I suspect this is optional, but best practice, I also moved the policy logic to the ConfigureServices method.

My final code looked below. I'm keeping as much in tact to preserve the order.

 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
            services.AddOptions();
            services.AddSwaggerGen();
            ///Authentication configuration went here.
            services.AddSingleton<IConfiguration>(Configuration);
            services.AddMvc();

        }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");
        app.UseStaticFiles();
        app.UseCors("CorsPolicy");

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger((httpRequest, swaggerDoc) =>
        {
            swaggerDoc.Host = httpRequest.Host.Value;

        });
        app.UseSwaggerUi(swaggerUrl: "/{appname}/swagger/v1/swagger.json");


问:
how to read a specific position in the last line using python
I have a txt file that is too large and has several similar lines, like this:

word1 word2 word3 word4 -553.75

I am interested in the position [4] "the value", that of the last line -553.75

my file text:

```<code>.
.
word1 word2 word3 word4 -553.20
.
.
.
word1 word2 word3 word4 -553.25
.
.
.
word1 word2 word3 word4 -553.75
.
.
.
</code>```

my script :

```<code>def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
    text = f.readlines()
    for line in text:
        if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4':
      oTE_list.append(line[4])

    # Change Lists To Number Format
    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

if __name__ == '__main__':
    main()
</code>```

but I do not know why it does not work with me!

thank you in advance.

答:
way don't you use re and read from the end of the file</p>

```<code>import re
with open("file1.txt","r") as f:
    for line in reversed(f.readlines()):
        if re.search('word1.*word2.*word3.*word4',line):
            print(line.split(' ')[-1])
            break
</code>```

Body:
I have a txt file that is too large and has several similar lines, like this:

word1 word2 word3 word4 -553.75

I am interested in the position [4] "the value", that of the last line -553.75

my file text:

.
.
word1 word2 word3 word4 -553.20
.
.
.
word1 word2 word3 word4 -553.25
.
.
.
word1 word2 word3 word4 -553.75
.
.
.

my script :

def main():
    oTE_list = []
    oTE = []

    with open("file.txt","r") as f:
    text = f.readlines()
    for line in text:
        if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4':
      oTE_list.append(line[4])

    # Change Lists To Number Format
    for idx, item in enumerate(oTE_list):
        if idx == len(oTE_list) - 1:
            print(item)

if __name__ == '__main__':
    main()

but I do not know why it does not work with me!

thank you in advance.

Body:
way don't you use re and read from the end of the file

import re
with open("file1.txt","r") as f:
    for line in reversed(f.readlines()):
        if re.search('word1.*word2.*word3.*word4',line):
            print(line.split(' ')[-1])
            break


问:
DDD: Referencing MediatR interface from the domain project
I'm just getting started with DDD. I'm putting domain events into a CQRS application and I'm stumbling on a fundamental task: How to use the MediatR.INotification marker interface within the domain project without creating a domain dependency on infrastructure.

My solution is organized in four projects as follows:

```<code>MyApp.Domain
    - Domain events
    - Aggregates
    - Interfaces (IRepository, etc), etc.
MyApp.ApplicationServices
    - Commands
    - Command Handlers, etc.
MyApp.Infrastructure
    - Repository
    - Emailer, etc.
MyApp.Web
    - Startup
    - MediatR NuGet packages and DI here
    - UI, etc.
</code>```

I currently have the MediatR and MediatR .net Core DI packages installed in the UI project and they are added to DI using .AddMediatR(), with the command

```<code>services.AddMediatR(typeof(MyApp.AppServices.Commands.Command).Assembly);
</code>```

which scans and registers command handlers from the AppServices project.

The problem comes when I want to define an event. For MediatR to work with my domain events, they need to be marked with the MediatR.INotification interface.

```<code>namespace ObApp.Domain.Events
{
    public class NewUserAdded : INotification
    {
        ...
    }
</code>```

What is the proper way to mark my events in this situation so they can be used by MediatR? I can create my own marker interface for events, but MediatR won't recognize those without some way to automatically cast them to MediatR.INotification.

Is this just a shortcoming of using multiple projects? Even if I was using a single project, though, I would be putting an "external" interface in the domain if I used MediatR.INotification from within the domain section.

I've run into the same issue when my User entity inherited from EF's IdentityUser. In that case the web consensus seems to say be pragmatic and go ahead and allow the minor pollution to save a lot of headaches. Is this another similar case? I don't mind sacrificing purity for pragmatism, but not just to be lazy.

This is a fundamental issue that will occur with other packages I use, so I look forward to solving this.

Thank you!

答: It is best that your domain layer doesn't depend on any infrastructure but that is hard to obtain in CQRS because of the bindings. I can tell you from my experience. You can, however, minimize that dependency.  One way to do that is to make your own EventInterface that extends MediatR.INotification and use that interface all over the domain code. In this way, if you ever want to change the infrastructure, you need to change only in one place.

Body:
I'm just getting started with DDD. I'm putting domain events into a CQRS application and I'm stumbling on a fundamental task: How to use the MediatR.INotification marker interface within the domain project without creating a domain dependency on infrastructure.

My solution is organized in four projects as follows:

MyApp.Domain
    - Domain events
    - Aggregates
    - Interfaces (IRepository, etc), etc.
MyApp.ApplicationServices
    - Commands
    - Command Handlers, etc.
MyApp.Infrastructure
    - Repository
    - Emailer, etc.
MyApp.Web
    - Startup
    - MediatR NuGet packages and DI here
    - UI, etc.

I currently have the MediatR and MediatR .net Core DI packages installed in the UI project and they are added to DI using .AddMediatR(), with the command

services.AddMediatR(typeof(MyApp.AppServices.Commands.Command).Assembly);

which scans and registers command handlers from the AppServices project.

The problem comes when I want to define an event. For MediatR to work with my domain events, they need to be marked with the MediatR.INotification interface.

namespace ObApp.Domain.Events
{
    public class NewUserAdded : INotification
    {
        ...
    }

What is the proper way to mark my events in this situation so they can be used by MediatR? I can create my own marker interface for events, but MediatR won't recognize those without some way to automatically cast them to MediatR.INotification.

Is this just a shortcoming of using multiple projects? Even if I was using a single project, though, I would be putting an "external" interface in the domain if I used MediatR.INotification from within the domain section.

I've run into the same issue when my User entity inherited from EF's IdentityUser. In that case the web consensus seems to say be pragmatic and go ahead and allow the minor pollution to save a lot of headaches. Is this another similar case? I don't mind sacrificing purity for pragmatism, but not just to be lazy.

This is a fundamental issue that will occur with other packages I use, so I look forward to solving this.

Thank you!


问:
geom_vline on R not working for adding vertical line on a ggplot graph
I'm having a problem to draw a graph with multiple lines on R.
I'm trying to add some vertical lines on a plot, but it's not working.

I'm using the following code.

```<code>library(ggplot2)
library("ggthemes")
library("scales")
dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  #frequency = c(3, 8, 20, 26, 30, 38,29, 27, 13, 1)
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30),
  frequency_performance = c(3, 7, 20, 22, 19, 29, 18, 15, 16, 18),
  frequency_correctness = c(0, 1, 1, 2, 1, 6, 5, 9, 1, 4),
  frequency_fault = c(0, 0, 2, 4, 6, 2, 6, 7, 2, 8)
)

p <- ggplot(data=dat, aes(x=time)) + #, y=frequency, group=1)) +
   theme(aspect.ratio=.4,text = element_text(size=13),
          panel.grid.major = element_line(colour = "grey"),
          panel.border = element_rect( fill = NA),
          panel.background = element_rect(fill = "white", colour = "grey")) +
  geom_line(aes(y=frequency, colour="slateblue"),group=1, size=1.5) +
  geom_line(aes(y=frequency_performance, colour="darkgoldenrod"),group=1, size=1.5) +
  geom_line(aes(y=frequency_correctness, colour="darkgreen"),group=1, size=1.5) +
  geom_line(aes(y=frequency_fault, colour="chocolate"),group=1, size=1.5) +
  xlab("Year") + ylab("Number of publications") + # Set axis labels
  scale_color_discrete(name = "Category", labels = c("Fault tolerance", "Performance", "Correctness", "All papers")) +
  ggtitle("")

p +   geom_vline(xintercept=c(2010,2012,2014,2016), linetype="dotted", color="red")
</code>```

I tried using another format with this code, but it also didn't worked.

```<code>dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30, 3, 7, 20, 22, 19, 29, 18, 15, 16, 18, 0, 1, 1, 2, 1, 6, 5, 9, 1, 4, 0, 0, 2, 4, 6, 2, 6, 7, 2, 8),
  group = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4)
)

p<- ggplot(data=dat, aes(x=time, y=frequency,group=group, color=as.factor(group) )) +
  geom_line() +
  geom_point() +
  scale_color_manual(breaks = c("1", "2", "3", "4"),
                     values=c("slateblue", "darkgoldenrod", "darkgreen", "chocolate")) +
  xlab("Year") + ylab("Number of publications") + theme_bw() +

guides(shape = FALSE, linetype = FALSE,
       colour = guide_legend(override.aes =  list(shape = c(16, 16, 16,  16),
                                                  linetype = c("solid","solid","solid", "solid"),
                                                  labels= c("All articles","Performance","Correctness","Fault tolerance"),
                                                  title = "Category"
       )))

p +   geom_vline(xintercept=as.numeric(2012), linetype="dotted", color="red", size=3)
</code>```

There are other problems that I have with both codes (that's why I have two different codes), like not being able to order the legend on the first code, or the color is wrong for some reason. The second graph I can't replace the legend text for some reason, but the vertical line is the main problem right now.

答:
```<code>p +   geom_vline(xintercept=which(dat$time %in% c('2010', '2012', '2014', '2016')), linetype="dotted", color="red")
</code>```

Body:
I'm having a problem to draw a graph with multiple lines on R.
I'm trying to add some vertical lines on a plot, but it's not working.

I'm using the following code.

library(ggplot2)
library("ggthemes")
library("scales")
dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  #frequency = c(3, 8, 20, 26, 30, 38,29, 27, 13, 1)
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30),
  frequency_performance = c(3, 7, 20, 22, 19, 29, 18, 15, 16, 18),
  frequency_correctness = c(0, 1, 1, 2, 1, 6, 5, 9, 1, 4),
  frequency_fault = c(0, 0, 2, 4, 6, 2, 6, 7, 2, 8)
)

p <- ggplot(data=dat, aes(x=time)) + #, y=frequency, group=1)) +
   theme(aspect.ratio=.4,text = element_text(size=13),
          panel.grid.major = element_line(colour = "grey"),
          panel.border = element_rect( fill = NA),
          panel.background = element_rect(fill = "white", colour = "grey")) +
  geom_line(aes(y=frequency, colour="slateblue"),group=1, size=1.5) +
  geom_line(aes(y=frequency_performance, colour="darkgoldenrod"),group=1, size=1.5) +
  geom_line(aes(y=frequency_correctness, colour="darkgreen"),group=1, size=1.5) +
  geom_line(aes(y=frequency_fault, colour="chocolate"),group=1, size=1.5) +
  xlab("Year") + ylab("Number of publications") + # Set axis labels
  scale_color_discrete(name = "Category", labels = c("Fault tolerance", "Performance", "Correctness", "All papers")) +
  ggtitle("")

p +   geom_vline(xintercept=c(2010,2012,2014,2016), linetype="dotted", color="red")

I tried using another format with this code, but it also didn't worked.

dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30, 3, 7, 20, 22, 19, 29, 18, 15, 16, 18, 0, 1, 1, 2, 1, 6, 5, 9, 1, 4, 0, 0, 2, 4, 6, 2, 6, 7, 2, 8),
  group = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4)
)

p<- ggplot(data=dat, aes(x=time, y=frequency,group=group, color=as.factor(group) )) +
  geom_line() +
  geom_point() +
  scale_color_manual(breaks = c("1", "2", "3", "4"),
                     values=c("slateblue", "darkgoldenrod", "darkgreen", "chocolate")) +
  xlab("Year") + ylab("Number of publications") + theme_bw() +

guides(shape = FALSE, linetype = FALSE,
       colour = guide_legend(override.aes =  list(shape = c(16, 16, 16,  16),
                                                  linetype = c("solid","solid","solid", "solid"),
                                                  labels= c("All articles","Performance","Correctness","Fault tolerance"),
                                                  title = "Category"
       )))

p +   geom_vline(xintercept=as.numeric(2012), linetype="dotted", color="red", size=3)

There are other problems that I have with both codes (that's why I have two different codes), like not being able to order the legend on the first code, or the color is wrong for some reason. The second graph I can't replace the legend text for some reason, but the vertical line is the main problem right now.


问:
Equality in definitions (decidable equality? e.g. replace elements in list)
I am trying to learn lean and want to define a replace function, which takes two elements x and y and replaces every occurrence of x with y in a given list.

I tried to define it like this:

```<code>def replace {α : Type}: α -> α -> list α -> list α
| a b [] := []
| a b (x::xs) := (if a = x then b else x) :: replace a b xs
</code>```

This gives me the following error:

```<code>error: failed to synthesize type class instance for
α : Type,
replace : α → α → list α → list α,
a b x : α,
xs : list α
⊢ decidable (a = x)
</code>```

My problem is that I cannot use equality for type α, so I guess I need to restrict α to be of some kind of type class where equality is decidable (like I would in Haskell). How can I do this?

My current workaround is to take the equality function as a parameter:

```<code>def replace {α : Type}: (α -> α -> bool) -> α -> α -> list α -> list α
| eq a b [] := []
| eq a b (x::xs) := (if eq a x then b else x) :: replace eq a b xs
</code>```

答:
You can take the decidable equality of α as a type class argument, like this:

```<code>def replace {α : Type} [decidable_eq α] : α -> α -> list α -> list α
| a b [] := []
| a b (x::xs) := (if a = x then b else x) :: replace a b xs

#eval replace 2 3 [2, 2, 5, 6, 3, 2]
</code>```

The square brackets denote that an instance of the type class should be inferred by type class resolution.

Body:
I am trying to learn lean and want to define a replace function, which takes two elements x and y and replaces every occurrence of x with y in a given list.

I tried to define it like this:

def replace {α : Type}: α -> α -> list α -> list α
| a b [] := []
| a b (x::xs) := (if a = x then b else x) :: replace a b xs

This gives me the following error:

error: failed to synthesize type class instance for
α : Type,
replace : α → α → list α → list α,
a b x : α,
xs : list α
⊢ decidable (a = x)

My problem is that I cannot use equality for type α, so I guess I need to restrict α to be of some kind of type class where equality is decidable (like I would in Haskell). How can I do this?

My current workaround is to take the equality function as a parameter:

def replace {α : Type}: (α -> α -> bool) -> α -> α -> list α -> list α
| eq a b [] := []
| eq a b (x::xs) := (if eq a x then b else x) :: replace eq a b xs

Body:
You can take the decidable equality of α as a type class argument, like this:

def replace {α : Type} [decidable_eq α] : α -> α -> list α -> list α
| a b [] := []
| a b (x::xs) := (if a = x then b else x) :: replace a b xs

#eval replace 2 3 [2, 2, 5, 6, 3, 2]

The square brackets denote that an instance of the type class should be inferred by type class resolution.


问:
Javascript Express Checkout - are they IPN compatible?
I'm currently using PayPal buttons on a site. When the transaction completes, my backend system gets an IPN with the details to process and dispatch the purchased item.

The javascript-driven express checkout looks nice and fancy, but I'm confused by the mixed statements and documentation. Do I need to implement WebHooks to achieve the same with the newer express checkout? Or do I still receive IPNs?

I also have subscription buttons that won't use the express checkout yet. So I need to know if I can use IPNs to process both purchase types, or if JS-express checkouts only send webhooks and not IPNs.

I want to avoid signing up to webhooks and then receiving both webhooks and IPNs for the same order.

答:
Found out I can actually test this in the sandbox by creating a sandbox merchant account, logging in on sandbox.paypal.com, and setting up IPNs there.

Yes, IPNs are still sent for the Javascript Express Checkout functionality. Webhooks are optional.


问:
WHM/cPanel: Create New Account ERROR
When creating a new account in WHM I get this error instantly when I click the Create button: 'A fatal error or timeout occurred while processing this directive'. It says 'show' for more info but its not clickable. Certain the entered information is correct. Any suggestions?

.

CENTOS 6.9 v66.0.29, Load Averages: 0.05 0.06 0.02

答: After much research and time wasting this proved to be a server side issue. The host rebooted the server and reset VPS quotas and all works good now. I would recommend contacting your host first if you have the same problem.</p>

Title: WHM/cPanel: Create New Account ERROR


问:
merge arrays and convert to JSON string
I have two arrays consist of strings
["25","36","32"] and ["GradeA", "GradeB", "GradeC"]

I want to merge them all together and want to produce JSON string something like this:

{"GradeA" : "25", "GradeB" : "36", "GradeC": "32"}

How do I do this in js?

答:
Using Array#reduce and Object#assign to add a property and it's value to the object on each iteration:

const keys = ["GradeA", "GradeB", "GradeC"];
const values = ["25","36","32"];

const result = keys.reduce((obj, key, i) => Object.assign(obj, { [key]: values[i] }), {});

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

<p>Using Array#map, to create a series of object with one property each, then combining them to a single object with Object#assign, and spread:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const keys = ["GradeA", "GradeB", "GradeC"];
const values = ["25","36","32"];

const result = Object.assign(...keys.map((key, i) => ({ [key]: values[i] })));

console.log(result);</code>```

Title: merge arrays and convert to JSON string

Body:
Using Array#reduce and Object#assign to add a property and it's value to the object on each iteration:

const keys = ["GradeA", "GradeB", "GradeC"];
const values = ["25","36","32"];

const result = keys.reduce((obj, key, i) => Object.assign(obj, { [key]: values[i] }), {});

console.log(result);

Using Array#map, to create a series of object with one property each, then combining them to a single object with Object#assign, and spread:

const keys = ["GradeA", "GradeB", "GradeC"];
const values = ["25","36","32"];

const result = Object.assign(...keys.map((key, i) => ({ [key]: values[i] })));

console.log(result);


问:
How to turn potential loop query to set based?
I have something like this currently -

```<code>declare @thisDate smalldatetime

create table #theseDates (thisDate smalldatetime)
insert into #theseDates(thisDate)
values ('11/1/2016', '5/1/2017', '9/30/2017)

create table #someData (productid int, productname varchar(32), productprice float, productsolddate smalldatetime)

declare date_cursor cursor for
select thisDate from #theseDates

open date_cursor
fetch next for date_cursor into @thisDate

while @@fetch_status = 0
begin
   insert into #someData(soldid, productid, productname, productprice, productsolddate)
   select soldid, productid, productname, productprice, productsolddate
   from soldproducts
   where productsolddate between @thisDate and getdate()

   fetch next from date_cursor into @thisDate
end

close date_cursor
deallocate date_cursor
</code>```

How do I change this from a cursor to a set-based solution?
NOTE: added fetch line

答:
You don't need a cursor to solve this OP. Use CROSS Join instead

This way faster than Cursor.

See below.

FYI. the mydates table is just a random date example because I don't want type them

```<code>declare @myproducts table (prodid int, proddesc varchar(30), prodprice money, solddate date)

insert into @myproducts
values
(1,'prod 1',1,dateadd(day,-1,getdate())),
(2,'prod 2',10,dateadd(day,-10,getdate())),
(3,'prod 3',100,dateadd(day,-5,getdate())),
(1,'prod 1',1.5,dateadd(day,-6,getdate())),
(2,'prod 2',8.99,dateadd(day,-20,getdate())),
(3,'prod 3',95,dateadd(day,-15,getdate())),
(1,'prod 1',0.89,dateadd(day,-2,getdate()))

select * from @myproducts

declare @mydates table (mydate date)

/* reporting datefrom */

insert into @mydates
values (dateadd(day,-11,getdate())),(dateadd(day,-20,getdate())),(dateadd(day,-3,getdate()))

select * from @mydates

/* apply cross join to distribute the datefrom but should only be to data where solddate is between datefrom and today */

-- insert statement to dump all qualified data or not
select p.*,d.mydate [DateFrom] from @myproducts p
cross join @mydates d
where solddate between mydate and cast(getdate() as date)
</code>```

Body:
I have something like this currently -

declare @thisDate smalldatetime

create table #theseDates (thisDate smalldatetime)
insert into #theseDates(thisDate)
values ('11/1/2016', '5/1/2017', '9/30/2017)

create table #someData (productid int, productname varchar(32), productprice float, productsolddate smalldatetime)

declare date_cursor cursor for
select thisDate from #theseDates

open date_cursor
fetch next for date_cursor into @thisDate

while @@fetch_status = 0
begin
   insert into #someData(soldid, productid, productname, productprice, productsolddate)
   select soldid, productid, productname, productprice, productsolddate
   from soldproducts
   where productsolddate between @thisDate and getdate()

   fetch next from date_cursor into @thisDate
end

close date_cursor
deallocate date_cursor

How do I change this from a cursor to a set-based solution?
NOTE: added fetch line

Body:
You don't need a cursor to solve this OP. Use CROSS Join instead

This way faster than Cursor.

See below.

FYI. the mydates table is just a random date example because I don't want type them

declare @myproducts table (prodid int, proddesc varchar(30), prodprice money, solddate date)

insert into @myproducts
values
(1,'prod 1',1,dateadd(day,-1,getdate())),
(2,'prod 2',10,dateadd(day,-10,getdate())),
(3,'prod 3',100,dateadd(day,-5,getdate())),
(1,'prod 1',1.5,dateadd(day,-6,getdate())),
(2,'prod 2',8.99,dateadd(day,-20,getdate())),
(3,'prod 3',95,dateadd(day,-15,getdate())),
(1,'prod 1',0.89,dateadd(day,-2,getdate()))

select * from @myproducts

declare @mydates table (mydate date)

/* reporting datefrom */

insert into @mydates
values (dateadd(day,-11,getdate())),(dateadd(day,-20,getdate())),(dateadd(day,-3,getdate()))

select * from @mydates

/* apply cross join to distribute the datefrom but should only be to data where solddate is between datefrom and today */

-- insert statement to dump all qualified data or not
select p.*,d.mydate [DateFrom] from @myproducts p
cross join @mydates d
where solddate between mydate and cast(getdate() as date)


问:
Embedded Matlab - testing for bottlenecks
I have an embedded Matlab function that itself calls other embedded Matlab functions and which also calls mex functions.  Where can I find information about how to test blocks of this code for the time it takes to execute?  Ideally there is something like tic toc that I can stick before and after a block in order to determine how long it takes to execute.  And perhaps tic toc even works, but I don't know if I should trust it.

答:
Use the built in profiler:

http://www.mathworks.com/help/techdoc/ref/profile.html


问:
How to send mails from outlook using R RDCOMClient using latest Version?
When i am using latest version R RDCOMClient package for sending outlook Emails, It is showing up an error :
 "[[<- defined for objects of type "S4" only for subclasses of environment"

Code for the same:

```<code>    library(RDCOMClient)
    ## init com api
    OutApp <- COMCreate("Outlook.Application")
    ## create an email
    outMail = OutApp$CreateItem(0)

    outMail$GetInspector()

    signature = outMail[["HTMLBody"]]
    ## configure  email parameter
    outMail[["To"]] = "some@outlook.com"
    outMail[["CC"]] <- "Some@outlook.com"
    outMail[["subject"]] = "some subject"
    outMail[["body"]] = "some body"
    outMail[["Attachments"]]$Add("C:\\Users\\Some\\Desktop\\file.csv")

    outMail[["HTMLBody"]] = paste0('<p>some body', signature, '</p>')
    ## send it
    outMail$Send()

**Error:**
 signature = outMail[["HTMLBody"]]
Error in mget(plabels[hasSubclass], env) : invalid first argument
## configure  email parameter
outMail[["To"]] = "some@outlook.com"
Error in `[[<-`(`*tmp*`, "To", value = "some@outlook.com") :
  [[<- defined for objects of type "S4" only for subclasses of environment
</code>```

答:
I think the below code should work for you. You may have to define body of the email separately as I have done and then paste it at outMail[["HTMLbody"]] = paste0("
", body, "
", Signature) as seen below. This code works without any errors provided you have installed the RDCOMClient package. I have tested this code using the latest version of R (V3.4.2), RDCOMClient and RStudio. Let me know if this helps you.

```<code>library(RDCOMClient)

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)

# Get signature from outlook
# GetInspector renders the message in html format.
# Note that if you have not created any signatures, this will return blank
outMail$GetInspector()
Signature <- outMail[["HTMLbody"]]

# Define the body of you email separately
body <- "Define your body here."

outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "TEST EMAIL"

# Paste the body and signatures into the email body
outMail[["HTMLbody"]] = paste0("<p>", body, "</p>", Signature)

# Add your attachment
outMail[["Attachments"]]$Add("C:\\Users\\Some\\Desktop\\file.csv")

outMail$Send()
</code>```

Body:
When i am using latest version R RDCOMClient package for sending outlook Emails, It is showing up an error :
 "[[<- defined for objects of type "S4" only for subclasses of environment"

Code for the same:

    library(RDCOMClient)
    ## init com api
    OutApp <- COMCreate("Outlook.Application")
    ## create an email
    outMail = OutApp$CreateItem(0)

    outMail$GetInspector()

    signature = outMail[["HTMLBody"]]
    ## configure  email parameter
    outMail[["To"]] = "some@outlook.com"
    outMail[["CC"]] <- "Some@outlook.com"
    outMail[["subject"]] = "some subject"
    outMail[["body"]] = "some body"
    outMail[["Attachments"]]$Add("C:\\Users\\Some\\Desktop\\file.csv")

    outMail[["HTMLBody"]] = paste0('
some body', signature, '
')
    ## send it
    outMail$Send()

**Error:**
 signature = outMail[["HTMLBody"]]
Error in mget(plabels[hasSubclass], env) : invalid first argument
## configure  email parameter
outMail[["To"]] = "some@outlook.com"
Error in `[[<-`(`*tmp*`, "To", value = "some@outlook.com") :
  [[<- defined for objects of type "S4" only for subclasses of environment

Body:
I think the below code should work for you. You may have to define body of the email separately as I have done and then paste it at outMail[["HTMLbody"]] = paste0("<p>", body, "</p>", Signature) as seen below. This code works without any errors provided you have installed the RDCOMClient package. I have tested this code using the latest version of R (V3.4.2), RDCOMClient and RStudio. Let me know if this helps you.

library(RDCOMClient)

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)

# Get signature from outlook
# GetInspector renders the message in html format.
# Note that if you have not created any signatures, this will return blank
outMail$GetInspector()
Signature <- outMail[["HTMLbody"]]

# Define the body of you email separately
body <- "Define your body here."

outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "TEST EMAIL"

# Paste the body and signatures into the email body
outMail[["HTMLbody"]] = paste0("<p>", body, "</p>", Signature)

# Add your attachment
outMail[["Attachments"]]$Add("C:\\Users\\Some\\Desktop\\file.csv")

outMail$Send()


问:
RxJava/RxKotlin split stream depending on subtype
I have a stream of ResponseMessage which can be of different subtypes. I would like to split the stream into streams where I can handle each type in its own stream.

My first try resulted in this which I can not see working out.

```<code>file.readLines()
        .toObservable()
        .map { mapper.readValue(it, ResponseMessage::class.java) }
        .groupBy { when(it) {
            is MarketChangeMessage -> it::class
            else -> it::class
        }}
        .map { it.????? } //How can possible this work?
</code>```

My question is now:
What is the idiomatic way to divide a stream into streams on one specific sub type?

答:
You could use the ofType operator:

ofType( ) — emit only those items from the source Observable that are of a particular class.

Example:

```<code>val messages = file.readLines()
    .toObservable()
    .map { mapper.readValue(it, ResponseMessage::class.java) }
    .share() // <-- or other multicasting operator

messages
    .ofType(MarketChangeMessage::class)
    .subscribe()

messages
    .ofType(Other::class)
    .subscribe()
</code>```

Body:
I have a stream of ResponseMessage which can be of different subtypes. I would like to split the stream into streams where I can handle each type in its own stream.

My first try resulted in this which I can not see working out.

file.readLines()
        .toObservable()
        .map { mapper.readValue(it, ResponseMessage::class.java) }
        .groupBy { when(it) {
            is MarketChangeMessage -> it::class
            else -> it::class
        }}
        .map { it.????? } //How can possible this work?

My question is now:
What is the idiomatic way to divide a stream into streams on one specific sub type?

Body:
You could use the ofType operator:

ofType( ) — emit only those items from the source Observable that are of a particular class.

Example:

val messages = file.readLines()
    .toObservable()
    .map { mapper.readValue(it, ResponseMessage::class.java) }
    .share() // <-- or other multicasting operator

messages
    .ofType(MarketChangeMessage::class)
    .subscribe()

messages
    .ofType(Other::class)
    .subscribe()