问:
AWS.Transfer is not a constructor
I'm setting up a SFTP process using AWS Transfer for SFTP API in Lambda. I've followed the example in the documentation and the limited examples I've found online, but only receive the "AWS.Transfer is not a constructor" error message. Here's a simple example:

const AWS = require('aws-sdk')

const transfer = new AWS.Transfer({
    apiVersion: '2018-11-05',
    region: `us-west-2`
});

const params = {
    ServerId: 'hlaoslloesses' /* required */
};

transfer.describeServer(params, (err, data) => {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});```
</div>
</div>
</p>

<p>The error message:</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-html lang-html prettyprint-override"><code>Response:
{
  "errorMessage": "AWS.Transfer is not a constructor",
  "errorType": "TypeError",
  "stackTrace": [
    "Module._compile (module.js:652:30)",
    "Object.Module._extensions..js (module.js:663:10)",
    "Module.load (module.js:565:32)",
    "tryModuleLoad (module.js:505:12)",
    "Function.Module._load (module.js:497:3)",
    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)"
  ]
}

Request ID:
"ced0c74a-d81a-42b0-94a1-3e667921f7c4"

Function Logs:
START RequestId: ced0c74a-d81a-42b0-94a1-3e667921f7c4 Version: $LATEST
module initialization error: TypeError
    at Object.<anonymous> (/var/task/index.js:3:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
END RequestId: ced0c74a-d81a-42b0-94a1-3e667921f7c4
REPORT RequestId: ced0c74a-d81a-42b0-94a1-3e667921f7c4 Duration: 79.81 ms Billed Duration: 100 ms  Memory Size: 128 MB Max Memory Used: 67 MB
module initialization error
TypeError</code>```

I've tried modifying the example from the API and the SDK docs, but still get the same result. Has anyone gotten this to work?

答:
AWS Transfer is relatively new.  The Node 8.10 Lambda runtime is running version 2.290.0 of the SDK, which doesn't include AWS.Transfer.

You can either deploy your function on the Node10.x runtime, which currently runs 2.437.0, or package a newer version of the JS SDK along with your function code.

Here's a link for future reference: https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html

Title: AWS.Transfer is not a constructor

Body:
I'm setting up a SFTP process using AWS Transfer for SFTP API in Lambda. I've followed the example in the documentation and the limited examples I've found online, but only receive the "AWS.Transfer is not a constructor" error message. Here's a simple example:

const AWS = require('aws-sdk')

const transfer = new AWS.Transfer({
    apiVersion: '2018-11-05',
    region: `us-west-2`
});

const params = {
    ServerId: 'hlaoslloesses' /* required */
};

transfer.describeServer(params, (err, data) => {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});

The error message:

Response:
{
  "errorMessage": "AWS.Transfer is not a constructor",
  "errorType": "TypeError",
  "stackTrace": [
    "Module._compile (module.js:652:30)",
    "Object.Module._extensions..js (module.js:663:10)",
    "Module.load (module.js:565:32)",
    "tryModuleLoad (module.js:505:12)",
    "Function.Module._load (module.js:497:3)",
    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)"
  ]
}

Request ID:
"ced0c74a-d81a-42b0-94a1-3e667921f7c4"

Function Logs:
START RequestId: ced0c74a-d81a-42b0-94a1-3e667921f7c4 Version: $LATEST
module initialization error: TypeError
    at Object.<anonymous> (/var/task/index.js:3:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
END RequestId: ced0c74a-d81a-42b0-94a1-3e667921f7c4
REPORT RequestId: ced0c74a-d81a-42b0-94a1-3e667921f7c4 Duration: 79.81 ms Billed Duration: 100 ms  Memory Size: 128 MB Max Memory Used: 67 MB
module initialization error
TypeError

I've tried modifying the example from the API and the SDK docs, but still get the same result. Has anyone gotten this to work?


来源: stackexchange

问:
Graphql custom scalar, parseLiteral not called for null values?
I have a custom scalar

```<code>export const GraphQLObjectId = new GraphQLScalarType({
    name: "GraphQLObjectId",
    description: "whatever",

    ...

    parseValue(value) {
        console.log("parseValue");
        console.log(value);
        ...
    },

    parseLiteral(ast) {
        console.log("parseLiteral");
        console.log(ast);
        ...
    }
});
</code>```

And a mutation like this

```<code>mutation {
  updateInstrument(
    input: {
      _id: "558ba89433d865236cb94bd5"
      name: "whatnot"
      issuerId: null
    }
  ) {
    _id
  }
}
</code>```

where both _id and issuerId is of type GraphQLObjectId.

But only _id goes trough the parseLiteral function and not issuerId.
If I change issuerId to "000000000000000000000000", it will also go trough parseLiteral(),
but I intended to handle null in parseLiteral(), but it never ends up there.

What am I doing wrong?

答:
This is expected behavior. null is conceptually a different kind of value in GraphQL than scalars or other types. All object fields and arguments normally accept null instead of an actual value -- that is, you may provide one or the other.

For example, the spec outlines these rules for coercing input object fields:

If the value null was provided for an input object field, and the field’s type is not a non‐null type, an entry in the coerced unordered map is given the value null...

If a literal value is provided for an input object field, an entry in the coerced unordered map is given the result of coercing that value according to the input coercion rules for the type of that field.

In other words, the input is never coerced (parsed) if a null value is provided. The same applies to scalars:

For all types below, with the exception of Non‐Null, if the explicit value null is provided, then the result of input coercion is null.

The whole idea of a null value is tightly intertwined with GraphQL's rules for nullability. Null values are meant to be handled using the available types (namely, the Non-null type) -- trying to handle them inside a scalar's coercion logic is inadvisable.

ContentLicense: CC BY-SA 4.0

Body:
I have a custom scalar

export const GraphQLObjectId = new GraphQLScalarType({
    name: "GraphQLObjectId",
    description: "whatever",

    ...

    parseValue(value) {
        console.log("parseValue");
        console.log(value);
        ...
    },

    parseLiteral(ast) {
        console.log("parseLiteral");
        console.log(ast);
        ...
    }
});

And a mutation like this

mutation {
  updateInstrument(
    input: {
      _id: "558ba89433d865236cb94bd5"
      name: "whatnot"
      issuerId: null
    }
  ) {
    _id
  }
}

where both _id and issuerId is of type GraphQLObjectId.

But only _id goes trough the parseLiteral function and not issuerId.
If I change issuerId to "000000000000000000000000", it will also go trough parseLiteral(),
but I intended to handle null in parseLiteral(), but it never ends up there.

What am I doing wrong?


问:
How to access namespaced Vuex getters in Mocha unit test
I am building a new Vue component that uses a namespaced Vuex getter to access a list of column names. The actual component compiles and runs.

In my Mocha unit tests, I created a mocked getter that returns a list of strings called "allColumns". When I run the unit tests, during ShallowMount, the component's methods try to access this.allColumns during initialization, but the value is always undefined. I can see the value I want in this.$store.getters.allColumns, but it is not getting mapped to this.allColumns like it does when I open the page in a browser.

There is a lot of information out there about how to mock getters in a test and how to use mapGetters with a namespace, but I have not found any documentation about namespaced getters in a Mocha test.

test.spec.js

```<code>  let propsData;
  let getters;
  let store;

  beforeEach(() => {
    debugger;
    propsData = {
      players: samplePlayerObject,
      metadata: sampleMetadataObject
    };

    getters = {
      allColumns: () => ["playerid","last","first","birthday","height"]
    }

    store = new Vuex.Store({
      getters
    });
  })

  it('initializes the component', () => {
    const wrapper = shallowMount(PlayerFilterTable, { propsData, localVue, store });
  });
</code>```

vue component

```<code>
<template>
  <div class="player-filter-table">
    <table>
      <tr>
         <th v-for="(key, index) in GetColumns()"
            v-bind:id="'header-' + key"
            v-bind:key="index"
            @click="HeaderClick(key)"
          >...</th>
      </tr>
    </table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
  computed: {
    ...mapGetters({
      allColumns: 'playerFilter/allColumns'
    })
  },
GetColumns() {
  // this.allColumns is defined when running in browser, but undefined when loaded from a Mocha test
  return this.allColumns.filter(column => [*some filter criteria*]);
}
</script>
</code>```

When shallowMount runs in test.spec.js, I expect the component to load successfully and then continue on to run my tests, but instead I get an error that says TypeError: Cannot read property 'filter' of undefined because this.allColumns is not defined.

答:
Use modules with namespaced: true:

import { createLocalVue, shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import PlayerFilterTable from '~/whatever';

const localVue = createLocalVue();
localVue.use(Vuex);

let propsData, getters, store, wrapper, consoleSpy;

describe('PlayerFilterTable', () => {

  beforeEach(() => {
    consoleSpy = jest.spyOn(console, 'error');
    propsData = {
      players: samplePlayerObject,
      metadata: sampleMetadataObject
    };
    getters = {
      allColumns: () => ["playerid", "last", "first", "birthday", "height"]
    };
    store = new Vuex.Store({
      modules: {
        playerFilter: {
          namespaced: true,
          getters
        }
      }
    });
    wrapper = shallowMount(PlayerFilterTable, {
      propsData,
      localVue,
      store
    });
  });

  afterEach(() => {
    expect(consoleSpy).not.toHaveBeenCalled();
  });

  it('should render correctly', () => {
    expect(wrapper.is(PlayerFilterTable)).toBe(true);
    expect(wrapper.html()).toMatchSnapshot();
  })
})
```

If you use getters from more than one module you could group them up under different props of getters and assign to each module accordingly.

Body:
I am building a new Vue component that uses a namespaced Vuex getter to access a list of column names. The actual component compiles and runs.

In my Mocha unit tests, I created a mocked getter that returns a list of strings called "allColumns". When I run the unit tests, during ShallowMount, the component's methods try to access this.allColumns during initialization, but the value is always undefined. I can see the value I want in this.$store.getters.allColumns, but it is not getting mapped to this.allColumns like it does when I open the page in a browser.

There is a lot of information out there about how to mock getters in a test and how to use mapGetters with a namespace, but I have not found any documentation about namespaced getters in a Mocha test.

test.spec.js

  let propsData;
  let getters;
  let store;

  beforeEach(() => {
    debugger;
    propsData = {
      players: samplePlayerObject,
      metadata: sampleMetadataObject
    };

    getters = {
      allColumns: () => ["playerid","last","first","birthday","height"]
    }

    store = new Vuex.Store({
      getters
    });
  })

  it('initializes the component', () => {
    const wrapper = shallowMount(PlayerFilterTable, { propsData, localVue, store });
  });

vue component

<template>

         ...

</template>

When shallowMount runs in test.spec.js, I expect the component to load successfully and then continue on to run my tests, but instead I get an error that says TypeError: Cannot read property 'filter' of undefined because this.allColumns is not defined.

Body:
Use modules with namespaced: true:

import { createLocalVue, shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import PlayerFilterTable from '~/whatever';

const localVue = createLocalVue();
localVue.use(Vuex);

let propsData, getters, store, wrapper, consoleSpy;

describe('PlayerFilterTable', () => {

  beforeEach(() => {
    consoleSpy = jest.spyOn(console, 'error');
    propsData = {
      players: samplePlayerObject,
      metadata: sampleMetadataObject
    };
    getters = {
      allColumns: () => ["playerid", "last", "first", "birthday", "height"]
    };
    store = new Vuex.Store({
      modules: {
        playerFilter: {
          namespaced: true,
          getters
        }
      }
    });
    wrapper = shallowMount(PlayerFilterTable, {
      propsData,
      localVue,
      store
    });
  });

  afterEach(() => {
    expect(consoleSpy).not.toHaveBeenCalled();
  });

  it('should render correctly', () => {
    expect(wrapper.is(PlayerFilterTable)).toBe(true);
    expect(wrapper.html()).toMatchSnapshot();
  })
})

If you use getters from more than one module you could group them up under different props of getters and assign to each module accordingly.


问:
Determining if VBA If Then Statement is necessary to code and how to fix Compile Error
Trying to set a Range ("headers") that is from a cell containing "Period" to cell containing "Agent Split". At the end of the code I select all of these ranges to make sure it's working properly.

I had tweaked the following code that contained a For loop

```<code>Sub Rangeheaders_test()

 Dim r As Long
 Dim endRow As Long
 Dim endCell As Range
 Dim headers As Range

  With ActiveSheet

    endRow = 500
 For r = 1 To endRow

    If .Cells(r, "A").Value = "Period" Then
       Set endCell = .Rows(r).Find(What:="Agent Split", LookIn:=xlValues,_
    LookAt:=xlPart, After:=.Cells(r, "A"))

       Set headers = .Range(.Cells(r, "A"), endCell)
    End If
  Next r
   End With

    headers.Select

End Sub
</code>```

However this code ran through the ranges and only selected the last when I wish to select them ALL in order to test it. So I deleted the loop which left me with the following

```<code>  With ActiveSheet
   endRow = 500

  r = 1 To endRow

    If .Cells(r, "A").Value = "Period" Then
       Set endCell = .Rows(r).Find(What:="Agent Split", LookIn:=xlValues,_
    LookAt:=xlPart, After:=.Cells(r, "A"))

       Set headers = .Range(.Cells(r, "A"), endCell)
    End If
  End With

    headers.Select
</code>```

But now I'm either getting a Syntax Error or Compile error for Unexpected With or If close and I'm stuck. Do I need to define the Then condition? Is the If Then statement even necessary? Is there another way i can set the conditions?

答:
I realized from @Jun 's insightful comment that i was trying to store multiple ranges in one variable and that's where i was going wrong.

After some research i found the Union method where I'm able to combine my ranges after i specify them -- which i did using the .Findnext method

```<code>Sub findheader()

Dim startcell As Range
Dim rng As Range
    Set rng = Range("A1:A500")
    Set startcell = rng.Find(what:="Period", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)

Dim header1, header2, header3 As Range
    Set header1 = Range(startcell, startcell.End(xlToRight))

        Set startcell = rng.FindNext(startcell)
        Set header2 = Range(startcell, startcell.End(xlToRight))

             Set startcell = rng.FindNext(startcell)
             Set header3 = Range(startcell, startcell.End(xlToRight))

Dim headers As Range
    Set headers = Union(header1, header2, header3)

headers.Select

End Sub
</code>```

Body:
Trying to set a Range ("headers") that is from a cell containing "Period" to cell containing "Agent Split". At the end of the code I select all of these ranges to make sure it's working properly.

I had tweaked the following code that contained a For loop

Sub Rangeheaders_test()

 Dim r As Long
 Dim endRow As Long
 Dim endCell As Range
 Dim headers As Range

  With ActiveSheet

    endRow = 500
 For r = 1 To endRow

    If .Cells(r, "A").Value = "Period" Then
       Set endCell = .Rows(r).Find(What:="Agent Split", LookIn:=xlValues,_
    LookAt:=xlPart, After:=.Cells(r, "A"))

       Set headers = .Range(.Cells(r, "A"), endCell)
    End If
  Next r
   End With

    headers.Select

End Sub

However this code ran through the ranges and only selected the last when I wish to select them ALL in order to test it. So I deleted the loop which left me with the following

  With ActiveSheet
   endRow = 500

  r = 1 To endRow

    If .Cells(r, "A").Value = "Period" Then
       Set endCell = .Rows(r).Find(What:="Agent Split", LookIn:=xlValues,_
    LookAt:=xlPart, After:=.Cells(r, "A"))

       Set headers = .Range(.Cells(r, "A"), endCell)
    End If
  End With

    headers.Select

But now I'm either getting a Syntax Error or Compile error for Unexpected With or If close and I'm stuck. Do I need to define the Then condition? Is the If Then statement even necessary? Is there another way i can set the conditions?

Body:
I realized from @Jun 's insightful comment that i was trying to store multiple ranges in one variable and that's where i was going wrong.

After some research i found the Union method where I'm able to combine my ranges after i specify them -- which i did using the .Findnext method

Sub findheader()

Dim startcell As Range
Dim rng As Range
    Set rng = Range("A1:A500")
    Set startcell = rng.Find(what:="Period", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)

Dim header1, header2, header3 As Range
    Set header1 = Range(startcell, startcell.End(xlToRight))

        Set startcell = rng.FindNext(startcell)
        Set header2 = Range(startcell, startcell.End(xlToRight))

             Set startcell = rng.FindNext(startcell)
             Set header3 = Range(startcell, startcell.End(xlToRight))

Dim headers As Range
    Set headers = Union(header1, header2, header3)

headers.Select

End Sub


问:
Getopts default case bash script
I want to use getopts but the default case doesn't work.

The code that I tried is:

while getopts "sdp" arg; do
case "$arg" in
s)
    echo "1"
;;
p)
    echo "2"
;;
d)
   echo "3"
;;
*)
   echo "default"
;;
esac
```

when I run the process: ./myTask

I didn't receive any output

答:
That's the default of the case statement, but it means something specific in the context of getopts: That you have an option defined but no clause to handle it.

If you run ./myTask -z, for example, you will see the output of "default" as @that_other_guy states in another answer here.

If you want to output something that indicates that no option was supplied:

Then after the while getopts block but before the shift $(($OPTIND - 1)) line, do this (with whatever processing you want inside the if block:

```<code>if ((OPTIND == 1))
then
    echo "No options specified"
fi
</code>```

Note that this does not indicate that no arguments were specified (e.g. ./myTask as in your question). To do something with that, add this after the shift line:

```<code>if (($# == 0))
then
    echo "No positional arguments specified"
fi
</code>```

Please see a reference implementation of a getopts function in my answer here.

Title: Getopts default case bash script

Body:
I want to use getopts but the default case doesn't work.

The code that I tried is:

while getopts "sdp" arg; do
case "$arg" in
s)
    echo "1"
;;
p)
    echo "2"
;;
d)
   echo "3"
;;
*)
   echo "default"
;;
esac

when I run the process: ./myTask

I didn't receive any output

Body:
That's the default of the case statement, but it means something specific in the context of getopts: That you have an option defined but no clause to handle it.

If you run ./myTask -z, for example, you will see the output of "default" as @that_other_guy states in another answer here.

If you want to output something that indicates that no option was supplied:

Then after the while getopts block but before the shift $(($OPTIND - 1)) line, do this (with whatever processing you want inside the if block:

if ((OPTIND == 1))
then
    echo "No options specified"
fi

Note that this does not indicate that no arguments were specified (e.g. ./myTask as in your question). To do something with that, add this after the shift line:

if (($# == 0))
then
    echo "No positional arguments specified"
fi

Please see a reference implementation of a getopts function in my answer here.


问:
Prompt coming before print statement when executing a c program in git-bash
```<code>For example :
#include<stdio.h>
int main ()
{
int i,N;
printf("Enter row no.\n");
scanf("%d",&N);
for(i=0;i<N;i++)
printf("%d\n",i);
return 1;
}
</code>```

In command prompt the execution is in sequence but when I execute this in git bash, first i need to enter the row number then the 'Enter row no' text is displayed followed by the rest of the output of a pattern.
I just dont get why scanf is getting executed before printf in git.

答:
You could try defining a macro named "eprint" to add a flush() after calling printf(...) and I just use the eprint macro below:

```<code>#define eprintf(...) printf(__VA_ARGS__); \
                     fflush(stdout);      \
</code>```

Sample code:

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

#define eprintf(...) printf(__VA_ARGS__); \
                     fflush(stdout);      \

int main(void) {
    int a;

    eprintf("a=");

    scanf("%d",&a);

    eprintf("I've read value %d.\n",a);

    return EXIT_SUCCESS;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example :
#include<stdio.h>
int main ()
{
int i,N;
printf("Enter row no.\n");
scanf("%d",&N);
for(i=0;i<N;i++)
printf("%d\n",i);
return 1;
}

In command prompt the execution is in sequence but when I execute this in git bash, first i need to enter the row number then the 'Enter row no' text is displayed followed by the rest of the output of a pattern.
I just dont get why scanf is getting executed before printf in git.

Body:
You could try defining a macro named "eprint" to add a flush() after calling printf(...) and I just use the eprint macro below:

#define eprintf(...) printf(__VA_ARGS__); \
                     fflush(stdout);      \

Sample code:

#include <stdio.h>
#include <stdlib.h>

#define eprintf(...) printf(__VA_ARGS__); \
                     fflush(stdout);      \

int main(void) {
    int a;

    eprintf("a=");

    scanf("%d",&a);

    eprintf("I've read value %d.\n",a);

    return EXIT_SUCCESS;
}


问:
C# Multiply Each row of array by set of factors
I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.

Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }

and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}

to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }

I've tried to use .Length within a for loop using the example code.

```<code>double [] factors = {0.5, 0.4, 0, 0.8};

int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};

double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
    output[i] = myarray[i] * factors;
</code>```

I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.

答:
You can get the length of each dimension by using the method GetLength:

```<code>double[,] output = new double[myarray.GetLength(0), myarray.GetLength(1)];
for (int i = 0; i < myarray.GetLength(0); i++)
{
    for (int j = 0; j < myarray.GetLength(1); j++)
    {
        output[i, j] = myarray[i, j] * factors[j];
    }
}
</code>```

In case your array is huge, you can speed up the calculation by using all processors/cores of your PC:

```<code>Parallel.For(0, myarray.GetLength(0), i =>
{
    for (int j = 0; j < myarray.GetLength(1); j++)
    {
        output[i, j] = myarray[i, j] * factors[j];
    }
});
</code>```

Body:
I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.

Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }

and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}

to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }

I've tried to use .Length within a for loop using the example code.

double [] factors = {0.5, 0.4, 0, 0.8};

int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};

double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
    output[i] = myarray[i] * factors;

I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.

Body:
You can get the length of each dimension by using the method GetLength:

double[,] output = new double[myarray.GetLength(0), myarray.GetLength(1)];
for (int i = 0; i < myarray.GetLength(0); i++)
{
    for (int j = 0; j < myarray.GetLength(1); j++)
    {
        output[i, j] = myarray[i, j] * factors[j];
    }
}

In case your array is huge, you can speed up the calculation by using all processors/cores of your PC:

Parallel.For(0, myarray.GetLength(0), i =>
{
    for (int j = 0; j < myarray.GetLength(1); j++)
    {
        output[i, j] = myarray[i, j] * factors[j];
    }
});


问:
RegEx for replacing a JavaScript pattern
I have tons of html files with expression like this:

```<code>eval('enterData.style.pixelTop=' + y);
</code>```

and I want to eliminate the eval expression and just execute the code, in other words change it to:

```<code>enterData.style.pixelTop =  y;
</code>```

Can anybody help me with this. Im breaking my head trying to get a solution but i only know how to eliminate the eval with:

```<code>Regex: eval\('(.*)'\)
Replace: $1
</code>```

Im using java for regex.

答:
I know nothing about Javascript, but this is what I see.

You need to escape your ' characters and to put them in non-matching groups using :?

```<code>Regex: eval\(((?:\')(.*)(?:\').*)\)
Replace: $1
</code>```

Check out regex101 for prototyping regular expressions.

Body:
I have tons of html files with expression like this:

eval('enterData.style.pixelTop=' + y);

and I want to eliminate the eval expression and just execute the code, in other words change it to:

enterData.style.pixelTop =  y;

Can anybody help me with this. Im breaking my head trying to get a solution but i only know how to eliminate the eval with:

Regex: eval\('(.*)'\)
Replace: $1

Im using java for regex.

Body:
I know nothing about Javascript, but this is what I see.

You need to escape your ' characters and to put them in non-matching groups using :?

Regex: eval\(((?:\')(.*)(?:\').*)\)
Replace: $1

Check out regex101 for prototyping regular expressions.


问:
reverse a list without copying (recursive method)
I need a little help about the move of the listhead ..<br>
this is my prof method and it works but i couldn't understand this point.
I think that every call changed the listhead  but in the pratic it moves and points to the last element .. any help about this  ?
thanks a lot  </p>

```<code>    void reverserecv2(pt* listhead){
       pt curr=*listhead,suiv;
       if(curr && curr->next){
         suiv=curr->next;
         reverse(&(curr->next));
         suiv->next=curr;
        *listhead=curr->next;
         suiv->next->next=NULL;
        }
      }
   // my  structure :

         typedef struct node{
            int data;
            struct node* next;
            }node;
            typedef node* pt ;
</code>```

答:
If you print out a little data, it might help you see what it is doing; where *listhead is assigned, put in the line:

```<code>printf(“*(%p) = %p\n”, listhead, curr->next);
</code>```

I did for a len 4 list:

```<code>*(0x79628344) = 0x79628320
*(0x79628354) = 0x79628320
*(0x79628364) = 0x79628320
*(0xbff92bd0) = 0x79628320
</code>```

What we see is that listhead itself has several different values; and when we look at the recursive invocation, this makes sense.  Each time it is being called using the next as the listhead, so that each node is updated.   You can see from mine that the address that isn’t contiguous with the rest is a stack address where the final listhead is.

Body:
I need a little help about the move of the listhead ..

this is my prof method and it works but i couldn't understand this point.
I think that every call changed the listhead  but in the pratic it moves and points to the last element .. any help about this  ?
thanks a lot

    void reverserecv2(pt* listhead){
       pt curr=*listhead,suiv;
       if(curr && curr->next){
         suiv=curr->next;
         reverse(&(curr->next));
         suiv->next=curr;
        *listhead=curr->next;
         suiv->next->next=NULL;
        }
      }
   // my  structure :

         typedef struct node{
            int data;
            struct node* next;
            }node;
            typedef node* pt ;

Body:
If you print out a little data, it might help you see what it is doing; where *listhead is assigned, put in the line:

printf(“*(%p) = %p\n”, listhead, curr->next);

I did for a len 4 list:

*(0x79628344) = 0x79628320
*(0x79628354) = 0x79628320
*(0x79628364) = 0x79628320
*(0xbff92bd0) = 0x79628320

What we see is that listhead itself has several different values; and when we look at the recursive invocation, this makes sense.  Each time it is being called using the next as the listhead, so that each node is updated.   You can see from mine that the address that isn’t contiguous with the rest is a stack address where the final listhead is.


问:
Redirect 401 Error in React Redux Actions File
So I'm trying to redirect the user if the server responds with a 401 Unauthorized response based on the user authentication backend I've established. Currently I'm sending a request to the server to check if the user matches with the item I'm checking against. IF they don't match, a 401 Unauthorized response is returned. But I cannot properly redirect them in my .catch(err) statement in my actions file.

I've tried several different solutions, stackoverflow searches, google searches, tutorials, and still cannot get the results I want. I've also tried installing different packages to no avail.

Here is my actions file. The .catch(err) is where I'd like to redirect the user to if a 401 error comes back.

// Get Single Score
export const getScore = (id, history) => dispatch => {
    dispatch(setScoreLoading());
    axios
        .get(`score/${id}`)
        .then(res =>
            dispatch({
                type: GET_SCORE,
                payload: res.data
            })
        )
        .catch(err =>
            dispatch({
                type: SCORE_NOT_FOUND,
                payload: err.response.data
            })
            history.push('/not-authorized')
        );
}```

Any help is greatly appreciated.

答:
i think the problem is your arrow function . you use => directly that will return your dispatch but never touch your history.push

.catch(err => {dispatch({
                type: SCORE_NOT_FOUND,
                payload: err.response.data
            })
            return history.push('/not-authorized')
        )}
Hope this help.
Btw use history.replace is better in this case in my opinion

Body:
So I'm trying to redirect the user if the server responds with a 401 Unauthorized response based on the user authentication backend I've established. Currently I'm sending a request to the server to check if the user matches with the item I'm checking against. IF they don't match, a 401 Unauthorized response is returned. But I cannot properly redirect them in my .catch(err) statement in my actions file.

I've tried several different solutions, stackoverflow searches, google searches, tutorials, and still cannot get the results I want. I've also tried installing different packages to no avail.

Here is my actions file. The .catch(err) is where I'd like to redirect the user to if a 401 error comes back.

// Get Single Score
export const getScore = (id, history) => dispatch => {
    dispatch(setScoreLoading());
    axios
        .get(`score/${id}`)
        .then(res =>
            dispatch({
                type: GET_SCORE,
                payload: res.data
            })
        )
        .catch(err =>
            dispatch({
                type: SCORE_NOT_FOUND,
                payload: err.response.data
            })
            history.push('/not-authorized')
        );
}

Any help is greatly appreciated.


问:
I need help adding input fields from a div to another div on a button click
I need help adding the input from the fields in my newContainer div to my container div on a button click. This is the extra credit assignment description:
- Create a form somewhere on the page and style it.
- The Form needs to contain fields for Name, Phone, Email and Address and a submit button.
- When the user clicks the submit button a new student needs to be added to the list, and the search needs to reset and show all students.

I included my HTML below.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Assignment 6</title>
  <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
    <div class="newContainer">
        <div>
          <p><input id="name" type="text" placeholder="Enter New Name"/></p>
          <p><input id="phone" type="text" placeholder="Enter Phone #"/></p>
          <p><input id="email" type="text" placeholder="Enter Email"/></p>
          <p><input id="address" type="text" placeholder="Enter Address"/></p>
          <button type="button" id="btn1">Add New</button>
        </div>
        <div class="newStudent"></div>
    </div>
    <div class="container">
      <div>
        <input class="search" type="text" placeholder="Enter Name"/>
      </div>
      <div class="students"></div>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.2/handlebars.js"></script>
<script src="index.js"></script>
</body>
</html>
</code>```

jQuery:

```<code>     const searchElement = document.querySelector('.search');
    const studentsElement = document.querySelector('.students');
    const newContainer = document.querySelector('.newContainer');

    let students= [];
    console.log(students);

    $("#newContainer").click(contents().appendTo('#container').end().fadeOut());

    let template = `
        {{#each students}}
        <div class="student">
            <p>{{name}}</p>
            <a href="mailto:{{email}}">{{email}}</a>
            <br />
            <a href="tel:{{phone}}">{{phone}}</a>
            <p>{{address}}</p>
            <button class="remove" onclick="removeStudent({{ @index }})">Remove</button>
        </div>
        {{/each}}
    `;

    /**
     * Renders the template with the given data.
     * @param context The date to render.
     */
    function render(context) {
      let compiled = Handlebars.compile(template);
      studentsElement.innerHTML = compiled(context);
    }

    function searchHandler(event) {
      //TODO: 5
      let val = searchElement.value;
      render(template);
      // TODO: 6
        console.log(val);
      let filteredStudents = students.students.filter(function (student) {
          console.log(student.name);
        return student.name.toLowerCase().includes(val.toLowerCase());
    })

      let dataCopy = {
        students: filteredStudents
      };

      render(dataCopy);
    }

    $.ajax({
      url: 'https://my-json-server.typicode.com/it238-sp-2019/db-test/students',
      method: 'GET'
     // TODO: 1
    }).done(function (resp) {
      console.log(resp);
      students = {students : resp}
      render(students);
    });
    function removeStudent(index) {
      // TODO: 7
        students.students.splice(index, 1);
      console.log(index);
        searchHandler();

      console.log(students);
    }
// TODO: 4
searchElement.addEventListener('input', searchHandler);
</code>```

So far this is what I have. It's working almost perfect expect I don't want it to loop I want it to only run once so it looks like the other students (attached screenshot). student

```<code>var s = $(".students");
$(document).on("click", "#btn1", function() {
  $(".newContainer input").val(function() {
    let n = $("#name");
    let p = $("#phone");
    let e = $("#email");
    let a = $("#address");
    s.append("<div class='student'><p>" + n.val() + "</p><a href='mailto:" + e.val() + "'>" + e.val() + "</a><br /><a href='tel:" + p.val() + "'>" + p.val() + "</a><p>" + a.val() + "</p><button class='remove' onclick='removeStudent()'>Remove</button></div>");
  });
});
</code>```

Template:

```<code>{{#each students}}
    <div class="student">
        <p>{{name}}</p>
        <a href="mailto:{{email}}">{{email}}</a>
        <br />
        <a href="tel:{{phone}}">{{phone}}</a>
        <p>{{address}}</p>
        <button class="remove" onclick="removeStudent({{ @index }})">Remove</button>
    </div>
    {{/each}}
</code>```

Screenshot:

答:
$(".newContainer").html() will grab all the content inside the entire div as HTML.

To grab all the field contents only, each input has to be referenced to grab their values using .val(). Assuming you want to grab all the inputs in the container, .each() can iterate over the set of selected elements.

Edit: Updated to fill in a template per student instead of iterating through each arbitrary field.

$(document).on("click", "#btn1", function() {
  let n = $('#name').val(),
    p = $('#phone').val(),
    e = $('#email').val(),
    a = $('#address').val();

  $(".students").append("

" + n + "
" + e + "
" + p + "
" + a + "
<button class='remove' onclick='removeStudent(" + e + ")'>Remove</button>
");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="newContainer">
  <div>
    <p><input id="name" type="text" placeholder="Enter New Name" /></p>
    <p><input id="phone" type="text" placeholder="Enter Phone #" /></p>
    <p><input id="email" type="text" placeholder="Enter Email" /></p>
    <p><input id="address" type="text" placeholder="Enter Address" /></p>
    <button type="button" id="btn1">Add New</button>
  </div>
  <div class="newStudent"></div>
</div>
<div class="container">
  <div>
    <input class="search" type="text" placeholder="Enter Name" />
  </div>
  <div class="students"></div>
</div></code>```

A few hopefully helpful tips from updating your attempted code to the working solution:

Declarations (let, var, const) can use commas to declare multiple variables. This helps save space on JS files and keeps code cleaner.

$(".newContainer input") was only needed when iterating to reference each input element under the .newContainer element. It is not needed when referencing each element directly by their unique id.

It is more efficient to call .val() once per element during the variable declaration than multiple times during the append. General refactoring and performance consideration.

It's unclear from your code how you intend to implement removeStudent(). I'll leave that for you to give it a shot first. Though I did give you a hint here about using an unique identifier that's readily available ;)

Body:
I need help adding the input from the fields in my newContainer div to my container div on a button click. This is the extra credit assignment description:
- Create a form somewhere on the page and style it.
- The Form needs to contain fields for Name, Phone, Email and Address and a submit button.
- When the user clicks the submit button a new student needs to be added to the list, and the search needs to reset and show all students.

I included my HTML below.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Assignment 6</title>
  <link rel="stylesheet" type="text/css" href="index.css">

<input id="name" type="text" placeholder="Enter New Name"/>

<input id="phone" type="text" placeholder="Enter Phone #"/>

<input id="email" type="text" placeholder="Enter Email"/>

<input id="address" type="text" placeholder="Enter Address"/>

          <button type="button" id="btn1">Add New</button>

        <input class="search" type="text" placeholder="Enter Name"/>

jQuery:

     const searchElement = document.querySelector('.search');
    const studentsElement = document.querySelector('.students');
    const newContainer = document.querySelector('.newContainer');

    let students= [];
    console.log(students);

    $("#newContainer").click(contents().appendTo('#container').end().fadeOut());

    let template = `
        {{#each students}}

{{name}}

            {{email}}

            {{phone}}

{{address}}

            <button class="remove" onclick="removeStudent({{ @index }})">Remove</button>

        {{/each}}
    `;

    /**
     * Renders the template with the given data.
     * @param context The date to render.
     */
    function render(context) {
      let compiled = Handlebars.compile(template);
      studentsElement.innerHTML = compiled(context);
    }

    function searchHandler(event) {
      //TODO: 5
      let val = searchElement.value;
      render(template);
      // TODO: 6
        console.log(val);
      let filteredStudents = students.students.filter(function (student) {
          console.log(student.name);
        return student.name.toLowerCase().includes(val.toLowerCase());
    })

      let dataCopy = {
        students: filteredStudents
      };

      render(dataCopy);
    }

    $.ajax({
      url: 'https://my-json-server.typicode.com/it238-sp-2019/db-test/students',
      method: 'GET'
     // TODO: 1
    }).done(function (resp) {
      console.log(resp);
      students = {students : resp}
      render(students);
    });
    function removeStudent(index) {
      // TODO: 7
        students.students.splice(index, 1);
      console.log(index);
        searchHandler();

      console.log(students);
    }
// TODO: 4
searchElement.addEventListener('input', searchHandler);

So far this is what I have. It's working almost perfect expect I don't want it to loop I want it to only run once so it looks like the other students (attached screenshot). student

var s = $(".students");
$(document).on("click", "#btn1", function() {
  $(".newContainer input").val(function() {
    let n = $("#name");
    let p = $("#phone");
    let e = $("#email");
    let a = $("#address");
    s.append("

" + n.val() + "
" + e.val() + "
" + p.val() + "
" + a.val() + "
<button class='remove' onclick='removeStudent()'>Remove</button>
");
  });
});

Template:

{{#each students}}

{{name}}

        {{email}}

        {{phone}}

{{address}}

        <button class="remove" onclick="removeStudent({{ @index }})">Remove</button>

    {{/each}}

Screenshot:

Body:
$(".newContainer").html() will grab all the content inside the entire div as HTML.

To grab all the field contents only, each input has to be referenced to grab their values using .val(). Assuming you want to grab all the inputs in the container, .each() can iterate over the set of selected elements.

Edit: Updated to fill in a template per student instead of iterating through each arbitrary field.

$(document).on("click", "#btn1", function() {
  let n = $('#name').val(),
    p = $('#phone').val(),
    e = $('#email').val(),
    a = $('#address').val();

  $(".students").append("<div class='student'><p>" + n + "</p><a href='mailto:" + e + "'>" + e + "</a><br /><a href='tel:" + p + "'>" + p + "</a><p>" + a + "</p><button class='remove' onclick='removeStudent(" + e + ")'>Remove</button></div>");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="newContainer">
  <div>
    <p><input id="name" type="text" placeholder="Enter New Name" /></p>
    <p><input id="phone" type="text" placeholder="Enter Phone #" /></p>
    <p><input id="email" type="text" placeholder="Enter Email" /></p>
    <p><input id="address" type="text" placeholder="Enter Address" /></p>
    <button type="button" id="btn1">Add New</button>
  </div>
  <div class="newStudent"></div>
</div>
<div class="container">
  <div>
    <input class="search" type="text" placeholder="Enter Name" />
  </div>
  <div class="students"></div>
</div>

A few hopefully helpful tips from updating your attempted code to the working solution:

Declarations (let, var, const) can use commas to declare multiple variables. This helps save space on JS files and keeps code cleaner.

$(".newContainer input") was only needed when iterating to reference each input element under the .newContainer element. It is not needed when referencing each element directly by their unique id.

It is more efficient to call .val() once per element during the variable declaration than multiple times during the append. General refactoring and performance consideration.

It's unclear from your code how you intend to implement removeStudent(). I'll leave that for you to give it a shot first. Though I did give you a hint here about using an unique identifier that's readily available ;)


问:
Android - How to know, in the host activity, the navigation has come to end
I'm thinking about a new architecture for my application
and I'm implementing something new to an app that already exists.

So, basically my new module has a flow, using navigation component, and when this comes to end my app need to know to call the old flow.

How do I know that?
Can host activity knows when navigation end?

答:
Your host activity can call addOnDestinationChangedListener so that it is aware of the current fragment in the navigation flow. If my understanding is correct, you could do something like this in your host activity's onCreate:

```<code>navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
   @Override
   public void onDestinationChanged(@NonNull NavController controller,
           @NonNull NavDestination destination, @Nullable Bundle arguments) {
       // if you have reached the end of your navigation flow, do something
       if(destination.getId() == R.id.end_dest) {
           // add code calling your old flow here
       }
   }
});
</code>```

Body:
Your host activity can call addOnDestinationChangedListener so that it is aware of the current fragment in the navigation flow. If my understanding is correct, you could do something like this in your host activity's onCreate:

navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
   @Override
   public void onDestinationChanged(@NonNull NavController controller,
           @NonNull NavDestination destination, @Nullable Bundle arguments) {
       // if you have reached the end of your navigation flow, do something
       if(destination.getId() == R.id.end_dest) {
           // add code calling your old flow here
       }
   }
});


问:
Generic IDisposable wrapper for stream - alternative to catching all exceptions
So I've just written this implementation for a type that abstracts a file and implements IDisposable over the stream that it contains.  It is intended to be used in any project:

```<code>public void Dispose()
{
  if (_contentStream == null)
    return;
  lock (_contentStreamLocker)
  {
    if (_contentStream == null)
      return;

    try
    {
      _contentStream.Dispose();
    }
    catch (Exception)
    {
      //legitimate? - don't let any exception prevent
      //us from successfully disposing?
    }
    _contentStream = null;
  }
}
</code>```

So I feel dirty, obviously, because:

I'm catching Exception

I'm doing nothing with Exception

But since I can't guarantee the behaviour of the underlying stream (also accounting for custom implementations) - i.e. if it's already disposed or if it's in a state where the implementation decides disposal is impossible - I can't really see what else to do.

Obviously I shouldn't be hiding bad implementations of Stream's Dispose(); but I think there is a half-way-house here.

In particular is the fact that this object doesn't necessarily 'own' the stream, and therefore won't have to be always responsible for Dispose()ing.  It should therefore be tolerant to when the stream has been disposed by somebody else.

Clearly, in most cases this won't be an issue; get a file in a using block perhaps, read it, do something with it and then dispose of it.  But there's those edge-cases; and they bother me!

Initially I wrote it as catch(ObjectDisposedException){ } - but that's only an informal pattern that can't be relied upon either.

What should I do?  Keep it as this, despite the fact that exception gulping is bad karma? Gulp only ObjectDisposedException, even though that's not much better?  Or should I just not have any exception gulping or handling at all?

I can see merits in all cases; just can't figure out which of them wins.

答: I suggest that you want to implement your dispose pattern according to the Microsoft guidelines, If the client of your wrapper has "pulled the rug" on the base stream you should let the exception get to them so they can deal with it or, at least know about it.</p>

Body:
So I've just written this implementation for a type that abstracts a file and implements IDisposable over the stream that it contains.  It is intended to be used in any project:

public void Dispose()
{
  if (_contentStream == null)
    return;
  lock (_contentStreamLocker)
  {
    if (_contentStream == null)
      return;

    try
    {
      _contentStream.Dispose();
    }
    catch (Exception)
    {
      //legitimate? - don't let any exception prevent
      //us from successfully disposing?
    }
    _contentStream = null;
  }
}

So I feel dirty, obviously, because:

I'm catching Exception

I'm doing nothing with Exception

But since I can't guarantee the behaviour of the underlying stream (also accounting for custom implementations) - i.e. if it's already disposed or if it's in a state where the implementation decides disposal is impossible - I can't really see what else to do.

Obviously I shouldn't be hiding bad implementations of Stream's Dispose(); but I think there is a half-way-house here.

In particular is the fact that this object doesn't necessarily 'own' the stream, and therefore won't have to be always responsible for Dispose()ing.  It should therefore be tolerant to when the stream has been disposed by somebody else.

Clearly, in most cases this won't be an issue; get a file in a using block perhaps, read it, do something with it and then dispose of it.  But there's those edge-cases; and they bother me!

Initially I wrote it as catch(ObjectDisposedException){ } - but that's only an informal pattern that can't be relied upon either.

What should I do?  Keep it as this, despite the fact that exception gulping is bad karma? Gulp only ObjectDisposedException, even though that's not much better?  Or should I just not have any exception gulping or handling at all?

I can see merits in all cases; just can't figure out which of them wins.


问:
Where is Episerver Salesforce connector configuration saved?
Working with a site running Episerver with the Salesforce add-on to tie episerver forms to Salesforce. I enter username/password/token for my salesforce user in the salesforce connector configuration screen in episerver backend and it saves my credentials. I navigate to forms and can now see my salesforce fields to map the form fields to.

The issue is that the salesforce connection config keeps disappearing. After some time when returning to the salesforce connector config in the episerver admin, or going to a form and attempting to map fields, the salesforce connection is gone and my fields are no longer mapped. If I re-add the connection the field mappings return. Where is this configuration saved in the database and what could be causing it to overridden? Is there a way to configure default values in a web config instead?

Relevant Package Details:

EPiServer.CMS - v11.11.3

EPiServer.MarketingAutomationIntegration.Salesforce - v4.2.0

EPiServer.Marketing.Automation.Forms - v2.1.0

EDIT:
It looks like the salesforce connector setting gets saved to dbo.tblBigTable and dbo.tblBigTableReference. Those records get cleared on startup of the project when I run it locally, still not sure why. I can restart the dev server without these records being cleared:
Running something like the following shows where the connector name portion is saved. There are likely other entries in these tables for the other fields configured there.

```<code>select * from dbo.tblBigTable where String01 like '%my-connector-name%'
</code>```

```<code>StoreName | ItemType | String01 | String02
Marketing_Automation_Connector_Credentials |
Episerver.Marketing.Connector.Framework.Data.ConnectorCredentialStoreData, Episerver.Marketing.Connector, Version=5.4.0.0, Culture=neutral, PublicKeyToken=null |
my-connector-name |
!!=!encrypt!=!!0...
</code>```

select * from dbo.tblBigTableReference where StringValue like '%my-connector-name%'

```<code>Type | PropertyName | CollectionType | ElementType | StringValue

3 | ActiveConnectors |
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 |
System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 |
my-connector-name
</code>```

答:
Cause of issue:

I ended up having to decompile Episerver's source code to find the issue. It turns out the issue is in EPiServer's Episerver.Marketing.Connector.Framework.MarketingConnectorManager.GetConnectorCredentials method, so this might not be specific to the Salesforce connector but any marketing connector. The problem is that when the credentials were created in our DEV environment they get encrypted in the database. When the credentials are then fetched later on in our Local instance there is an attempt to decrypt the credentials. If the credentials cannot be decrypted, EPiServer deletes them rather than throwing an error or saying no valid credentials found.

Workaround:

To get around this problem, you can add a machineKey tag to your web.config so that the decryptionKey is shared between local and dev environments:

```<code><system.web>
        <machineKey validationKey="YOUR_VALIDATION_KEY_HERE" decryptionKey="YOUR_ENCRYPTION_KEY_HERE" validation="SHA1" decryption="AES" />
        ....
</system.web>
</code>```

Body:
Working with a site running Episerver with the Salesforce add-on to tie episerver forms to Salesforce. I enter username/password/token for my salesforce user in the salesforce connector configuration screen in episerver backend and it saves my credentials. I navigate to forms and can now see my salesforce fields to map the form fields to.

The issue is that the salesforce connection config keeps disappearing. After some time when returning to the salesforce connector config in the episerver admin, or going to a form and attempting to map fields, the salesforce connection is gone and my fields are no longer mapped. If I re-add the connection the field mappings return. Where is this configuration saved in the database and what could be causing it to overridden? Is there a way to configure default values in a web config instead?

Relevant Package Details:

EPiServer.CMS - v11.11.3

EPiServer.MarketingAutomationIntegration.Salesforce - v4.2.0

EPiServer.Marketing.Automation.Forms - v2.1.0

EDIT:
It looks like the salesforce connector setting gets saved to dbo.tblBigTable and dbo.tblBigTableReference. Those records get cleared on startup of the project when I run it locally, still not sure why. I can restart the dev server without these records being cleared:
Running something like the following shows where the connector name portion is saved. There are likely other entries in these tables for the other fields configured there.

select * from dbo.tblBigTable where String01 like '%my-connector-name%'

StoreName | ItemType | String01 | String02
Marketing_Automation_Connector_Credentials |
Episerver.Marketing.Connector.Framework.Data.ConnectorCredentialStoreData, Episerver.Marketing.Connector, Version=5.4.0.0, Culture=neutral, PublicKeyToken=null |
my-connector-name |
!!=!encrypt!=!!0...

select * from dbo.tblBigTableReference where StringValue like '%my-connector-name%'

Type | PropertyName | CollectionType | ElementType | StringValue

3 | ActiveConnectors |
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 |
System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 |
my-connector-name

Body:
Cause of issue:

I ended up having to decompile Episerver's source code to find the issue. It turns out the issue is in EPiServer's Episerver.Marketing.Connector.Framework.MarketingConnectorManager.GetConnectorCredentials method, so this might not be specific to the Salesforce connector but any marketing connector. The problem is that when the credentials were created in our DEV environment they get encrypted in the database. When the credentials are then fetched later on in our Local instance there is an attempt to decrypt the credentials. If the credentials cannot be decrypted, EPiServer deletes them rather than throwing an error or saying no valid credentials found.

Workaround:

To get around this problem, you can add a machineKey tag to your web.config so that the decryptionKey is shared between local and dev environments:

<system.web>
        <machineKey validationKey="YOUR_VALIDATION_KEY_HERE" decryptionKey="YOUR_ENCRYPTION_KEY_HERE" validation="SHA1" decryption="AES" />
        ....
</system.web>


问:
How do you sort using a dynamic number of sorting keys?
I need to sort data in VBA using multiple columns as keys, but the number of columns is not known ahead of time.

I tried using the sheets.sort method and using .sortfields.add witin a for loop, but this did not have any effect.

Here is the code used to sort the data:

```<code>For sh = 1 To 2
        Sheets(sh).Sort.SortFields.Clear
        For i = 1 To idSize
            Sheets(sh).Sort.SortFields.Add Key:=Sheets(sh).UsedRange.Columns(idList(sh)(i)) _
                , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        Next i
        With Sheets(sh).Sort
         .Header = xlYes
         .MatchCase = False
         .Orientation = xlTopToBottom
         .Apply
        End With
    Next sh
</code>```

where sh iterates through the sheets in the workbook, and the numerical index of each column to be used as a key is in idList. For example, idList(2)(1) represents the index of the column from sheet 2 that should be the primary sort key.

This code results in no sorting happening at all.

答:
Try something like this.  It's just an example how to loop thru your sheets and columsn, you might want to change the intenal logic of sort order.</p>

```<code>Dim intCols As Integer
Dim rng As Range
Dim sht As Worksheet

For Each sht In Sheets
    With sht

        Set rng = .Range("A1").CurrentRegion

        intCols = rng.Columns.Count

        .Sort.SortFields.Clear
        For i = 1 To intCols
            .Sort.SortFields.Add Key:=Columns(i), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        Next

        With .Sort
            .SetRange rng
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With

Next
</code>```

Body:
I need to sort data in VBA using multiple columns as keys, but the number of columns is not known ahead of time.

I tried using the sheets.sort method and using .sortfields.add witin a for loop, but this did not have any effect.

Here is the code used to sort the data:

For sh = 1 To 2
        Sheets(sh).Sort.SortFields.Clear
        For i = 1 To idSize
            Sheets(sh).Sort.SortFields.Add Key:=Sheets(sh).UsedRange.Columns(idList(sh)(i)) _
                , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        Next i
        With Sheets(sh).Sort
         .Header = xlYes
         .MatchCase = False
         .Orientation = xlTopToBottom
         .Apply
        End With
    Next sh

where sh iterates through the sheets in the workbook, and the numerical index of each column to be used as a key is in idList. For example, idList(2)(1) represents the index of the column from sheet 2 that should be the primary sort key.

This code results in no sorting happening at all.

Body:
Try something like this.  It's just an example how to loop thru your sheets and columsn, you might want to change the intenal logic of sort order.

Dim intCols As Integer
Dim rng As Range
Dim sht As Worksheet

For Each sht In Sheets
    With sht

        Set rng = .Range("A1").CurrentRegion

        intCols = rng.Columns.Count

        .Sort.SortFields.Clear
        For i = 1 To intCols
            .Sort.SortFields.Add Key:=Columns(i), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        Next

        With .Sort
            .SetRange rng
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With

Next


问:
How to use frame to set x position in loop on Swift
I have an array that count is between 1 to 3 varies.
I want to frame them in the middle of the screen with a certain distance
Also the width of the labels is fixed

```<code>let array = ["some1", "some2", "some3"]

func setLabel(){
  var i = -1
  for text in array{
      i += 1
      let label = UILabel()
      label.fram = CGRect(x: screenWidth/2 - (CGFloat(i)*50) + 25, y: 100, width: 50 , height: 20)
      label.text = text
      addSubview(label)
  }
}
</code>```

答:
The really easy way to do this is to put the labels (one, two, or three of them) into a centered UIStackView. You would still need to know the desired fixed width of a label and apply a width constraint to each label, but everything else will just take care of itself.

Just as a demonstration, I used an arbitrary width of 100, with the text for all three labels being just "UILabel" as in your image. Here's what it looks like with one label:

Here's what it looks like with three labels:

Here's the code I used (sv is the stack view, which has already been configured in the storyboard; n is how many labels we want):

```<code>    for _ in 1...n {
        let lab = UILabel()
        lab.text = "UILabel"
        lab.textAlignment = .center
        lab.translatesAutoresizingMaskIntoConstraints = false
        lab.widthAnchor.constraint(equalToConstant: 100).isActive = true
        sv.addArrangedSubview(lab)
    }
</code>```

So all you really need to do is get the right text from your array as we loop, and you're done. The point is that you don't need to think about frames at all! The UIStackView imposes the correct the frames for us.

NOTE Although I said above that the stack view was "configured in the storyboard", that has nothing to do with the answer. You can create and configure the stack view in code just as well, without changing anything about my answer. The point is that the stack view already knows how to receive an arbitrary number of views, space them out evenly, and center them as a whole. That is what it is for. So if, as your question implies, you can't manage the arithmetic to assign the views a frame yourself, why not let the stack view do it for you?

Body:
I have an array that count is between 1 to 3 varies.
I want to frame them in the middle of the screen with a certain distance
Also the width of the labels is fixed

let array = ["some1", "some2", "some3"]

func setLabel(){
  var i = -1
  for text in array{
      i += 1
      let label = UILabel()
      label.fram = CGRect(x: screenWidth/2 - (CGFloat(i)*50) + 25, y: 100, width: 50 , height: 20)
      label.text = text
      addSubview(label)
  }
}

Body:
The really easy way to do this is to put the labels (one, two, or three of them) into a centered UIStackView. You would still need to know the desired fixed width of a label and apply a width constraint to each label, but everything else will just take care of itself.

Just as a demonstration, I used an arbitrary width of 100, with the text for all three labels being just "UILabel" as in your image. Here's what it looks like with one label:

Here's what it looks like with three labels:

Here's the code I used (sv is the stack view, which has already been configured in the storyboard; n is how many labels we want):

    for _ in 1...n {
        let lab = UILabel()
        lab.text = "UILabel"
        lab.textAlignment = .center
        lab.translatesAutoresizingMaskIntoConstraints = false
        lab.widthAnchor.constraint(equalToConstant: 100).isActive = true
        sv.addArrangedSubview(lab)
    }

So all you really need to do is get the right text from your array as we loop, and you're done. The point is that you don't need to think about frames at all! The UIStackView imposes the correct the frames for us.

NOTE Although I said above that the stack view was "configured in the storyboard", that has nothing to do with the answer. You can create and configure the stack view in code just as well, without changing anything about my answer. The point is that the stack view already knows how to receive an arbitrary number of views, space them out evenly, and center them as a whole. That is what it is for. So if, as your question implies, you can't manage the arithmetic to assign the views a frame yourself, why not let the stack view do it for you?


问:
Why if clicking button twice setInterval method is shorter then declared
I want to execute function FindNext() every second with setInterval method.
It works excellent if I click the button once, but if I click the button twice or more the interval starts to be shorter then declared - shorter then one second.I do not know how to make the time interval independent of button clicking number ?</p>

```<code><button id="search-next">Find - next</button>

$('#search-next').click(function() {
setInterval(function()  {
FindNext();
}, 1000);
});
</code>```

答:
Becuase it's setting another interval. So now you have two loops. If you click one button 500 milliseconds after clicking another, it will start each at 500 milliseconds.

I suggest using clearInterval(myIntervalVariable);

You can do var myIntervalVariable = setInterval(stuff);

Body:
I want to execute function FindNext() every second with setInterval method.
It works excellent if I click the button once, but if I click the button twice or more the interval starts to be shorter then declared - shorter then one second.I do not know how to make the time interval independent of button clicking number ?

<button id="search-next">Find - next</button>

$('#search-next').click(function() {
setInterval(function()  {
FindNext();
}, 1000);
});


问:
How to get app information like app version, device os version in ios using Appium?
I am testing the app using appium and integrating the test output in testrail. I need to add the device and app information in the testrail. In android i am able to get app and device information like device model, device version and app version using adb command like following:

```<code>adb -s 012313gasda shell getprop ro.product.model
adb -s 012313gasda shell getprop ro.build.version.release
adb -s 012313gasda shell dumpsys package com.test.app |grep versionName
</code>```

How can i achieve the same information for ios? using following command will return you the device name and OS version as set in desired capabilities

```<code>driver.getCapabilities().getCapability("deviceName").toString();
driver.getCapabilities().getCapability("CapabilityType.VERSION").toString();
</code>```

Is there anyway to get device and app information for ios?

答:
You can do something similar to adb using ideviceinfo such as in this SO post
https://stackoverflow.com/a/55028994/8016330

```<code>PRODUCT_NAME=$(ideviceinfo --udid $DEVICE_UDID --key ProductName)
PRODUCT_TYPE=$(ideviceinfo --udid $DEVICE_UDID --key ProductType)
PRODUCT_VERSION=$(ideviceinfo --udid $DEVICE_UDID --key ProductVersion)
</code>```

HTH

James

Body:
I am testing the app using appium and integrating the test output in testrail. I need to add the device and app information in the testrail. In android i am able to get app and device information like device model, device version and app version using adb command like following:

adb -s 012313gasda shell getprop ro.product.model
adb -s 012313gasda shell getprop ro.build.version.release
adb -s 012313gasda shell dumpsys package com.test.app |grep versionName

How can i achieve the same information for ios? using following command will return you the device name and OS version as set in desired capabilities

driver.getCapabilities().getCapability("deviceName").toString();
driver.getCapabilities().getCapability("CapabilityType.VERSION").toString();

Is there anyway to get device and app information for ios?

Body:
You can do something similar to adb using ideviceinfo such as in this SO post
https://stackoverflow.com/a/55028994/8016330

PRODUCT_NAME=$(ideviceinfo --udid $DEVICE_UDID --key ProductName)
PRODUCT_TYPE=$(ideviceinfo --udid $DEVICE_UDID --key ProductType)
PRODUCT_VERSION=$(ideviceinfo --udid $DEVICE_UDID --key ProductVersion)

HTH

James


问:
How to silence 'The last statement should return a value' warning?
Sun Studio 12.1 prints the warning

```<code>Warning: The last statement should return a value.
</code>```

frequently for functions like that:

```<code>int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}
</code>```

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

```<code>// Silence a compiler warning
return 42;
</code>```

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

答:
Perhaps encapsulate the contents in a do { } while (false); construct:

```<code>int my_function()
{
  int result = DEFAULT_VALUE;
  do
  {
     result = /*...*/
     // Whatever
     if (error)
     {
       throw std::runtime_error("Error ...");
     }
   } while (false);
   return result;
}
</code>```

The idea is for normal operation to set the result value then let the execution flow to the end or use a break to jump to the return statement.

Body:
Sun Studio 12.1 prints the warning

Warning: The last statement should return a value.

frequently for functions like that:

int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

// Silence a compiler warning
return 42;

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

Body:
Perhaps encapsulate the contents in a do { } while (false); construct:

int my_function()
{
  int result = DEFAULT_VALUE;
  do
  {
     result = /*...*/
     // Whatever
     if (error)
     {
       throw std::runtime_error("Error ...");
     }
   } while (false);
   return result;
}

The idea is for normal operation to set the result value then let the execution flow to the end or use a break to jump to the return statement.


问:
Extracting array of numbers from an array of dictionaries
I have the following 2x2 array of dictionaries:

```<code>a = np.array([[{'x_id':0, 'y_id':0},{'x_id':1, 'y_id':1}],[{'x_id':2, 'y_id':0},{'x_id':3, 'y_id':1}]])
</code>```

I would like to get a 2x2 array of numbers corresponding to the values of the key 'x_id', [[0, 1], [2, 3]], i.e.:

```<code>0  1
2  3
</code>```

Is there a way other than a double for loop? That is:

```<code>numbers = [[a[i,j]['x_id'] for j in range(2)] for i in range(2)]
</code>```

答:
If you are talking about explicit for loop within the code, you can flatten your array and get the job done using a single for loop, followed by a reshape of your final array

```<code>numbers = np.array([i['x_id'] for i in a.flatten()]).reshape(a.shape)
# array([[0, 1],
#        [2, 3]])
</code>```

An alternate solution would be using itemgetter on a flattened array as

```<code>import operator
numbers = np.array(list(map(operator.itemgetter('x_id'), a.flatten()))).reshape(a.shape)
</code>```

Performance: Both the methods take similar times

```<code>%timeit np.array([i['x_id'] for i in a.flatten()]).reshape(a.shape)
# 4.16 µs ± 676 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.array(list(map(operator.itemgetter('x_id'), a.flatten()))).reshape(a.shape)
# 4.9 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Body:
I have the following 2x2 array of dictionaries:

a = np.array([[{'x_id':0, 'y_id':0},{'x_id':1, 'y_id':1}],[{'x_id':2, 'y_id':0},{'x_id':3, 'y_id':1}]])

I would like to get a 2x2 array of numbers corresponding to the values of the key 'x_id', [[0, 1], [2, 3]], i.e.:

0  1
2  3

Is there a way other than a double for loop? That is:

numbers = [[a[i,j]['x_id'] for j in range(2)] for i in range(2)]

Body:
If you are talking about explicit for loop within the code, you can flatten your array and get the job done using a single for loop, followed by a reshape of your final array

numbers = np.array([i['x_id'] for i in a.flatten()]).reshape(a.shape)
# array([[0, 1],
#        [2, 3]])

An alternate solution would be using itemgetter on a flattened array as

import operator
numbers = np.array(list(map(operator.itemgetter('x_id'), a.flatten()))).reshape(a.shape)

Performance: Both the methods take similar times

%timeit np.array([i['x_id'] for i in a.flatten()]).reshape(a.shape)
# 4.16 µs ± 676 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.array(list(map(operator.itemgetter('x_id'), a.flatten()))).reshape(a.shape)
# 4.9 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
Groovy not in collection
The idiomatic way to check if a list contains something in Groovy is to use in.

```<code>if ('b' in ['a', 'b', 'c'])
</code>```

But how do you nicely check if something is not in a collection?

```<code>if (!('g' in ['a', 'b', 'c']))
</code>```

Using logical not seems messy and the ! is hidden to the casual glance. Is there a more idiomatic way to do this in Groovy?

Thanks!

答:
The contains(string) method is nice and simple to read if something is contained or not contained in the list to be checked against. Take a look the example below for more insight.

EXAMPLE

```<code>//Any data you are looking to filter
List someData = ['a', 'f', 'b', 'c', 'o', 'o']

//A filter/conditions to not match or match against
List myFilter = ['a', 'b', 'c']

//Some variables for this example
String filtered, unfiltered

//Loop the data and filter for not contains or contains
someData.each {
   if (!myFilter.contains(it)){
      unfiltered += it
   } else {
      filtered += it
   }
}

assert unfiltered = "foo"
assert filtered = "abc"
</code>```

CONTAINS( )

Parameters: text - a String to look for.

Returns: true if this string contains the given text

source

Title: Groovy not in collection

Body:
The idiomatic way to check if a list contains something in Groovy is to use in.

if ('b' in ['a', 'b', 'c'])

But how do you nicely check if something is not in a collection?

if (!('g' in ['a', 'b', 'c']))

Using logical not seems messy and the ! is hidden to the casual glance. Is there a more idiomatic way to do this in Groovy?

Thanks!

Body:
The contains(string) method is nice and simple to read if something is contained or not contained in the list to be checked against. Take a look the example below for more insight.

EXAMPLE

//Any data you are looking to filter
List someData = ['a', 'f', 'b', 'c', 'o', 'o']

//A filter/conditions to not match or match against
List myFilter = ['a', 'b', 'c']

//Some variables for this example
String filtered, unfiltered

//Loop the data and filter for not contains or contains
someData.each {
   if (!myFilter.contains(it)){
      unfiltered += it
   } else {
      filtered += it
   }
}

assert unfiltered = "foo"
assert filtered = "abc"

CONTAINS( )

Parameters: text - a String to look for.

Returns: true if this string contains the given text

source


问:
Azure timer Function output binding record set in a queue
I have a timer azure function which calls a stored proc and the proc returns a record set. What is the best way to grab a value from record set and push it in the queue using output binding on the signature of the timer function.

I need to be able to go through the contents of the table and push one column value to the queue. If there are 50 records in the record set, there will be 50 entries in the queue.

Here is my code

```<code>public static void FieldDevicePollingStatusDispatch_Run ([TimerTrigger("%ScheduleDispatch%")]TimerInfo myTimer,
             [Queue("%DispatchQueueName%", Connection = "AVStorageAccessKey")] out string msg, //output binding
            ILogger log)
        {
            oConnect.Open();
            DataTable oDataTable = new DataTable();
            SqlCommand objCommand = new SqlCommand("CallProc", oConnect);
            objCommand.CommandType = CommandType.StoredProcedure;
            objCommand.Connection = oConnect;

            SqlDataAdapter oDataAdapter = new SqlDataAdapter(objCommand);
            oDataAdapter.Fill(oDataTable);

            msg = // Content from the table, need one column from table.

        }
</code>```

答:
You can use the return attribute:

```<code>[StorageAccount("AzureWebJobsStorage")]
public static class QueueFunctions
{
    [FunctionName("QueueOutput")]
    [return: Queue("myqueue-items")]
    public static string QueueOutput([HttpTrigger] dynamic input,  ILogger log)
    {
        log.LogInformation($"C# function processed: {input.Text}");
        return input.Text;
    }
}
</code>```

Body:
I have a timer azure function which calls a stored proc and the proc returns a record set. What is the best way to grab a value from record set and push it in the queue using output binding on the signature of the timer function.

I need to be able to go through the contents of the table and push one column value to the queue. If there are 50 records in the record set, there will be 50 entries in the queue.

Here is my code

public static void FieldDevicePollingStatusDispatch_Run ([TimerTrigger("%ScheduleDispatch%")]TimerInfo myTimer,
             [Queue("%DispatchQueueName%", Connection = "AVStorageAccessKey")] out string msg, //output binding
            ILogger log)
        {
            oConnect.Open();
            DataTable oDataTable = new DataTable();
            SqlCommand objCommand = new SqlCommand("CallProc", oConnect);
            objCommand.CommandType = CommandType.StoredProcedure;
            objCommand.Connection = oConnect;

            SqlDataAdapter oDataAdapter = new SqlDataAdapter(objCommand);
            oDataAdapter.Fill(oDataTable);

            msg = // Content from the table, need one column from table.

        }

Body:
You can use the return attribute:

[StorageAccount("AzureWebJobsStorage")]
public static class QueueFunctions
{
    [FunctionName("QueueOutput")]
    [return: Queue("myqueue-items")]
    public static string QueueOutput([HttpTrigger] dynamic input,  ILogger log)
    {
        log.LogInformation($"C# function processed: {input.Text}");
        return input.Text;
    }
}


问:
How to fix a compile error with this code?
This is the link to the tutorial
https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/

```<code>Sub AttachMultipleFilesToEmail()
Dim outlookApp As Outlook.Application
Dim myMail As Outlook.MailItem

Set outlookApp = New Outlook.Application
Set myMail = outlookApp.CreateItem(olMailItem)

For i = 2 To 5
  source_file = "C:\Work Files\" & Cells(i, 3)
  myMail.Attachments.Add source_file
Next i
End Sub
</code>```

Where the error occurs

The error code

This is the big picture of what I am trying to do. Got this image from https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/ but the files and directory exist and correct. What could be the problem?

答:
At a guess, I'd say that you don't have a reference to the outlook dll.

Try clicking on the Tools menu in the VBA editor, and selecting References...

Then scroll down the list until you find Microsoft Outlook XX Object Library, and select it.  XX is just the version number.

For future questions, please always tell us the line of code where the error occurs, and the exact error message. Otherwise we are just guessing.

Regarding your revised question:

I ran your code and it works fine. I did however make sure to have the sheet with the filenames as the active sheet, otherwise you will get errors.

I suggest you explictly reference the sheet with the data, rather than just use Cells(i,3) as that is shorthand for using the active sheet.

Here is one way to do it:

```<code>Sub AttachMultipleFilesToEmail()
    Dim outlookApp As Outlook.Application
    Dim myMail As Outlook.MailItem
    Dim sheet As Worksheet 'declare an object to point to the sheet with the data

    Set outlookApp = New Outlook.Application
    Set myMail = outlookApp.CreateItem(olMailItem)
    Set sheet = Worksheets("Sheet1") 'set the object to the correct sheet

    For i = 1 To 2
        source_file = "C:\Work Files\" & sheet.Cells(i, 3) 'use the sheet object to ensure the correct cells are used.
        myMail.Attachments.Add source_file
    Next i
End Sub
</code>```

Body:
This is the link to the tutorial
https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/

Sub AttachMultipleFilesToEmail()
Dim outlookApp As Outlook.Application
Dim myMail As Outlook.MailItem

Set outlookApp = New Outlook.Application
Set myMail = outlookApp.CreateItem(olMailItem)

For i = 2 To 5
  source_file = "C:\Work Files\" & Cells(i, 3)
  myMail.Attachments.Add source_file
Next i
End Sub

Where the error occurs

The error code

This is the big picture of what I am trying to do. Got this image from https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/ but the files and directory exist and correct. What could be the problem?

Body:
At a guess, I'd say that you don't have a reference to the outlook dll.

Try clicking on the Tools menu in the VBA editor, and selecting References...

Then scroll down the list until you find Microsoft Outlook XX Object Library, and select it.  XX is just the version number.

For future questions, please always tell us the line of code where the error occurs, and the exact error message. Otherwise we are just guessing.

Regarding your revised question:

I ran your code and it works fine. I did however make sure to have the sheet with the filenames as the active sheet, otherwise you will get errors.

I suggest you explictly reference the sheet with the data, rather than just use Cells(i,3) as that is shorthand for using the active sheet.

Here is one way to do it:

Sub AttachMultipleFilesToEmail()
    Dim outlookApp As Outlook.Application
    Dim myMail As Outlook.MailItem
    Dim sheet As Worksheet 'declare an object to point to the sheet with the data

    Set outlookApp = New Outlook.Application
    Set myMail = outlookApp.CreateItem(olMailItem)
    Set sheet = Worksheets("Sheet1") 'set the object to the correct sheet

    For i = 1 To 2
        source_file = "C:\Work Files\" & sheet.Cells(i, 3) 'use the sheet object to ensure the correct cells are used.
        myMail.Attachments.Add source_file
    Next i
End Sub


问:
How would you go about where a user types in {prefix}reddit {subreddit} (then replies a random image from that subreddit)
So far I got this that pulls images from set subreddits using random-puppy.
I will change meme to reddit for the cmd. Plus how would you go about restricting people from pulling images from 18+ subreddit if the channel is not marked NSFW</p>

```<code>const randomPuppy = require('random-puppy');

exports.run = async (client, message, args) => {

  let reddit = [
    "meme",
    "animemes",
    "MemesOfAnime",
    "animememes",
    "AnimeFunny",
    "dankmemes",
    "dankmeme",
    "wholesomememes",
    "MemeEconomy",
    "techsupportanimals",
    "meirl",
    "me_irl",
    "2meirl4meirl",
    "AdviceAnimals"
  ]

  let subreddit = reddit[Math.floor(Math.random() * reddit.length)];

  message.channel.startTyping();

  randomPuppy(subreddit).then(async url => {
    await message.channel.send({
      files: [{
        attachment: url,
        name: 'meme.png'
      }]
    }).then(() => message.channel.stopTyping());
  }).catch(err => console.error(err));

};
exports.help = {
    name: 'meme',
    aliases: [],
    description: 'What can I say ͡°-͜ʖ-͡°',
    usage: 'meme'
};
</code>```

答:
Instead of defining an array of subreddits and selecting a random one, you can simply use the user provided argument.

const randomPuppy = require('random-puppy');

exports.run = async (client, message, args) => {
  // Assuming args[1] is the name of the subreddit.
  try {
    if (!args[1]) {
      // Insert your code for choosing from a random subreddit.
    } else {
      if (args[2]) return await message.channel.send('Too many arguments.');

      const imgURL = await randomPuppy(args[1]);

      await message.channel.send({
        files: [{
          attachment: imgURL,
          name: 'image.png'
        }];
      });
    }
  } catch(err) {
    console.error(err);
  }
};

exports.help = {
  name: 'reddit',
  aliases: [],
  description: 'Retrieve a random picture from a subreddit',
  usage: 'meme'
};
```

<p>As for the restriction of NSFW content, you'd probably have to scan the image with some sort of nudity/NSFW detection system. To check if the channel is marked as NSFW, you can use...</p>

<pre class="lang-js prettyprint-override"><code>if (message.channel.nsfw === false) console.log('Not an NSFW channel');
</code>```

Body:
So far I got this that pulls images from set subreddits using random-puppy.
I will change meme to reddit for the cmd. Plus how would you go about restricting people from pulling images from 18+ subreddit if the channel is not marked NSFW

const randomPuppy = require('random-puppy');

exports.run = async (client, message, args) => {

  let reddit = [
    "meme",
    "animemes",
    "MemesOfAnime",
    "animememes",
    "AnimeFunny",
    "dankmemes",
    "dankmeme",
    "wholesomememes",
    "MemeEconomy",
    "techsupportanimals",
    "meirl",
    "me_irl",
    "2meirl4meirl",
    "AdviceAnimals"
  ]

  let subreddit = reddit[Math.floor(Math.random() * reddit.length)];

  message.channel.startTyping();

  randomPuppy(subreddit).then(async url => {
    await message.channel.send({
      files: [{
        attachment: url,
        name: 'meme.png'
      }]
    }).then(() => message.channel.stopTyping());
  }).catch(err => console.error(err));

};
exports.help = {
    name: 'meme',
    aliases: [],
    description: 'What can I say ͡°-͜ʖ-͡°',
    usage: 'meme'
};

Body:
Instead of defining an array of subreddits and selecting a random one, you can simply use the user provided argument.

const randomPuppy = require('random-puppy');

exports.run = async (client, message, args) => {
  // Assuming args[1] is the name of the subreddit.
  try {
    if (!args[1]) {
      // Insert your code for choosing from a random subreddit.
    } else {
      if (args[2]) return await message.channel.send('Too many arguments.');

      const imgURL = await randomPuppy(args[1]);

      await message.channel.send({
        files: [{
          attachment: imgURL,
          name: 'image.png'
        }];
      });
    }
  } catch(err) {
    console.error(err);
  }
};

exports.help = {
  name: 'reddit',
  aliases: [],
  description: 'Retrieve a random picture from a subreddit',
  usage: 'meme'
};

As for the restriction of NSFW content, you'd probably have to scan the image with some sort of nudity/NSFW detection system. To check if the channel is marked as NSFW, you can use...

if (message.channel.nsfw === false) console.log('Not an NSFW channel');


答:
It's not shorter. You simply have multiple timers running.

You could do something like this to check if there already is a timer running:

```<code>var myTimer = null;

$('#search-next').click(function() {
  if (myTimer === null) {
    myTimer = setInterval(function() {
      FindNext();
    }, 1000);
  }
});
</code>```

or maybe use clearInterval before starting a new timer:

```<code>var myTimer = null;

$('#search-next').click(function() {
  if (myTimer !== null) {
    clearInterval(myTimer);
  }

  myTimer = setInterval(function() {
    FindNext();
  }, 1000);
});
</code>```

Title: Why if clicking button twice setInterval method is shorter then declared

Body:
It's not shorter. You simply have multiple timers running.

You could do something like this to check if there already is a timer running:

var myTimer = null;

$('#search-next').click(function() {
  if (myTimer === null) {
    myTimer = setInterval(function() {
      FindNext();
    }, 1000);
  }
});

or maybe use clearInterval before starting a new timer:

var myTimer = null;

$('#search-next').click(function() {
  if (myTimer !== null) {
    clearInterval(myTimer);
  }

  myTimer = setInterval(function() {
    FindNext();
  }, 1000);
});


问:
Reading between the lines (perl or awk)
Hey all, sorry for posting this here I could not find an answer anywhere and my solution is not working. I have a log file being written in the following fashion (don't ask):

```<code>=============================

04-12-2011 11:37:10 SOMETHING_GOES_HERE

Variable1

Something Goes Here

=============================

04-12-2011 11:37:20 SOMETHING_GOES_HERE

Variable2

Anything different may be here

=============================

04-12-2011 11:37:30 SOMETHING_GOES_HERE

Variable3

is altogether different here

=============================
</code>```

What I'd like to do (either in perl or awk as this is an RTOS) is:

Take a look at the file, if Variable1 exists, then start at Variable2 and print everything between the equal signs:

E.g.

```<code>=============================
04-12-2011 11:37:10 SOMETHING_GOES_HERE

Variable1

Mary had a little lamb

=============================
04-12-2011 11:37:20 SOMETHING_GOES_HERE

Variable2

The cow jumped over the moon
=============================
</code>```

awk '/Mary had/{getline;getline;getline;print}'

will only print

```<code>04-12-2011 11:37:20 SOMETHING_GOES_HERE
</code>```

but what I need is everything between the equal signs. I tried butchering up a perl script which isn't working either. Any thoughts?

Alright, this worked (sort of)

```<code>#!perl -w
use strict;

my $LOGFILE = "/home/mydir/MyTestFile";
open my $fh, "<$LOGFILE" or die("could not open log file: $!");
my $in = 0;

while(<$fh>)
{
    $in = 1 if /Variable1/i;
    print if($in);
    $in = 0 if /Variable2/i;
}
</code>```

In the sense that a lot was stripped out. Now another q I have is selective printing a-la awk. Typically, I can get the line before something using:

```<code>echo "
test
hello
foo
bar" | awk '/foo/{print x};{x=$0}'
</code>```

Will print test, however haven't found a way to get the word test (will always be a different word, but the word foo will always remain). Any takers (by the way many thanks in advance)

Title: Reading between the lines (perl or awk)

Body:
Hey all, sorry for posting this here I could not find an answer anywhere and my solution is not working. I have a log file being written in the following fashion (don't ask):

=============================

04-12-2011 11:37:10 SOMETHING_GOES_HERE

Variable1

Something Goes Here

=============================

04-12-2011 11:37:20 SOMETHING_GOES_HERE

Variable2

Anything different may be here

=============================

04-12-2011 11:37:30 SOMETHING_GOES_HERE

Variable3

is altogether different here

=============================

What I'd like to do (either in perl or awk as this is an RTOS) is:

Take a look at the file, if Variable1 exists, then start at Variable2 and print everything between the equal signs:

E.g.

=============================
04-12-2011 11:37:10 SOMETHING_GOES_HERE

Variable1

Mary had a little lamb

=============================
04-12-2011 11:37:20 SOMETHING_GOES_HERE

Variable2

The cow jumped over the moon
=============================

awk '/Mary had/{getline;getline;getline;print}'

will only print

04-12-2011 11:37:20 SOMETHING_GOES_HERE

but what I need is everything between the equal signs. I tried butchering up a perl script which isn't working either. Any thoughts?

Alright, this worked (sort of)

#!perl -w
use strict;

my $LOGFILE = "/home/mydir/MyTestFile";
open my $fh, "<$LOGFILE" or die("could not open log file: $!");
my $in = 0;

while(<$fh>)
{
    $in = 1 if /Variable1/i;
    print if($in);
    $in = 0 if /Variable2/i;
}

In the sense that a lot was stripped out. Now another q I have is selective printing a-la awk. Typically, I can get the line before something using:

echo "
test
hello
foo
bar" | awk '/foo/{print x};{x=$0}'

Will print test, however haven't found a way to get the word test (will always be a different word, but the word foo will always remain). Any takers (by the way many thanks in advance)

Body:
local $/ = "\n=============================\n";
while (<>) {
   chomp;
   ...
}

Alternative:

my $rec = '';
while (<>) {
   if (!/^=============================$/) {
      $rec .= $_;
      next;
   }

   ...

   $rec = '';
}

$/, chomp