问:
React not overwriting state
I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

```<code>{
    0: {name: foo},
    1: {name: bar}
}
</code>```

If I add another element, it works just fine:

```<code>store[2] = {name: hohoho};
setState(store, console.log(this.state));
</code>```

With the code above, I end up with the expected state:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}
</code>```

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

```<code>delete store[2]
</code>```

If I console.log(store), I get:

```<code>{
    0: {name: foo},
    1: {name: bar}
}
</code>```

then:

```<code>setState(store, console.log(this.state))
</code>```

gives me:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}
</code>```

But stranger than this, is if I add another element to the store, and set the state after:

```<code>store[3] = {name: heyheyhey};
setState(store, console.log(this.state));
</code>```

I end up with the following state:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}
</code>```

Even if console.log(store) gives me the following:

```<code>{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}
</code>```

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

```<code>var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;
</code>```

But I'm still experiencing the same problem.

答:
You might use undefined instead of delete:

```<code>const changes = [
  {
    title: 'add 2',
    update: state => Object.assign({}, state, { 2: { name: 'hohoho' } }),
  },
  {
    title: 'remove 2',
    update: state => Object.assign({}, state, { 2: undefined }),
  },
  {
    title: 'add 3',
    update: state => Object.assign({}, state, { 3: { name: 'heyheyhey' } }),
  },
];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      0: { name: 'foo' },
      1: { name: 'bar' },
    };
  }

  update(step) {
    this.setState(changes[step].update);
  }

  componentDidMount() {
    setTimeout(this.update.bind(this, 0), 2000);
    setTimeout(this.update.bind(this, 1), 4000);
    setTimeout(this.update.bind(this, 2), 6000);
  }

  render() {
    return (
      ```
        {JSON.stringify(this.state, null, 2)}
      ```
    );
  }
}
</code>```

Try it here: https://jsfiddle.net/jprogd/062z1kqd/2/

BTW When you do this.setState({ a: something }) you don't actually set the whole state exactly to { a: something } but update only certain properties (in this particular case only a property will be updated).

Title: React not overwriting state

Body:
I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

{
    0: {name: foo},
    1: {name: bar}
}

If I add another element, it works just fine:

store[2] = {name: hohoho};
setState(store, console.log(this.state));

With the code above, I end up with the expected state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

delete store[2]

If I console.log(store), I get:

{
    0: {name: foo},
    1: {name: bar}
}

then:

setState(store, console.log(this.state))

gives me:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But stranger than this, is if I add another element to the store, and set the state after:

store[3] = {name: heyheyhey};
setState(store, console.log(this.state));

I end up with the following state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}

Even if console.log(store) gives me the following:

{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;

But I'm still experiencing the same problem.

Body:
You might use undefined instead of delete:

const changes = [
  {
    title: 'add 2',
    update: state => Object.assign({}, state, { 2: { name: 'hohoho' } }),
  },
  {
    title: 'remove 2',
    update: state => Object.assign({}, state, { 2: undefined }),
  },
  {
    title: 'add 3',
    update: state => Object.assign({}, state, { 3: { name: 'heyheyhey' } }),
  },
];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      0: { name: 'foo' },
      1: { name: 'bar' },
    };
  }

  update(step) {
    this.setState(changes[step].update);
  }

  componentDidMount() {
    setTimeout(this.update.bind(this, 0), 2000);
    setTimeout(this.update.bind(this, 1), 4000);
    setTimeout(this.update.bind(this, 2), 6000);
  }

  render() {
    return (
      <pre>
        {JSON.stringify(this.state, null, 2)}
      </pre>
    );
  }
}

Try it here: https://jsfiddle.net/jprogd/062z1kqd/2/

BTW When you do this.setState({ a: something }) you don't actually set the whole state exactly to { a: something } but update only certain properties (in this particular case only a property will be updated).


来源: stackexchange

问:
How to improve Golang compilation speed?
I'm trying to find a way to make the compilation of a Go program faster. It is currently about 30 seconds, which makes it slow to work with the project.

When I run go build -v, I see that most of the time is spent compiling go-sqlite3 (which links to the C sqlite lib). However, since this lib never changes, I'm wondering if it's possible to prevent the build tool from recompiling this every time?

答:
In Go 1.10 no need to run go install etc. Just use go build. The new version uses a build cache to determine which packages need to be re-compiled.

Check out: https://tip.golang.org/doc/go1.10

ContentLicense: CC BY-SA 3.0


问:
How To Have VBA Insert Formula Result as a Value
I got help last week getting my syntax and ranges correct, and thought I could just do a vlookup to finish it but apparently I was mistaken.  It just seems like when I try to research how to accomplish this, I find various examples but I don't have the background to translate it to my code.

The macro runs and does almost everything its supposed to do.  But in addition to inserting the arrays, there are 3 other cells that need values when there are blank cells in my ‘sourcerng’.

This is the logic for the cells that need values (the values are already in my worksheet, I just need to get them to these blank cells).  I tried to do an IIF statement for these but I still have no idea what I'm doing.  Would that be the best way? Should it just be another IF THEN statement?

rngBE   - IF Column Z = 0 Then copy value from corresponding row in column O.  Otherwise copy value from column Z

rngBG   - IF Column AA = "Unknown" Then copy value from corresponding row in column I.  Otherwise copy value from column AA.

rngBK   - IF Column AB = "Unknown" Then copy value from corresponding row in column N.  Otherwise copy value from column AB.

```<code>Sub AutomateAllTheThings6()
Dim arr3() As String
Dim arr11() As String
'Dim resBE As String
Dim rng3 As Range
Dim rng11 As Range
Dim rngBE As Range
Dim rngBG As Range
Dim rngBK As Range
Dim sourcerng As Range
'Dim firstRow As Long
Dim lastRow As Long
'Dim i As Long

    Call OptimizeCode_Begin
        'firstRow = 2
        lastRow = ActiveSheet.Range("D1").End(xlDown).Row
        Set rng3 = ActiveSheet.Range("BH2:BJ" & lastRow)
        Set rng11 = ActiveSheet.Range("BL2:BV" & lastRow)
        Set rngBE = ActiveSheet.Range("BE2:BE" & lastRow)
        Set rngBG = ActiveSheet.Range("BG2:BG" & lastRow)
        Set rngBK = ActiveSheet.Range("BK2:BK" & lastRow)
        Set sourcerng = ActiveSheet.Range("BE2:BE" & lastRow)
        arr3() = Split("UNKNOWN,UNKNOWN,UNKNOWN", ",")
        arr11() = Split("UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,00/00/0000, _
                         00/00/0000,00/00/0000,00/00/0000,NEEDS REVIEW", ",")
            For Each cell In sourcerng
                If IsEmpty(cell) Then
                    Intersect(rng3, ActiveSheet.Rows(cell.Row)).Value = arr3
                    Intersect(rng11, ActiveSheet.Rows(cell.Row)).Value = arr11
                    '***PLS HELP***
                    Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value = "WEEEEE"
                    Intersect(rngBG, ActiveSheet.Rows(cell.Row)).Value = "WOOOOO"
                    Intersect(rngBK, ActiveSheet.Rows(cell.Row)).Value = "WAAAAA"
                End If
            Next
        Range("BR2:BU2").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.NumberFormat = "mm/dd/yyyy"
        Columns("BF:BF").Select
        Selection.Delete Shift:=xlToLeft
    Call OptimizeCode_End
End Sub

'*********TESTING***********
'resBE      = IIf(Cells(13,Z).Value = 0, Cells(13,BE).Value = Cells(13,Z), Cells(13,BE).Value = Cells(13,O))

'***************************************
'For i = firstRow To lastRow
'           valZ = Range("Z" & i)
'           valOh = Range("O" & i)
'
'           If valZ = 0 Then
'               rngBE.Value = valOh
'               Else rngBE.Value = valZ
'           End If
</code>```

答:
There are several ways to do your task. If you're more of an "Excel" person than VBA you might consider this approach: You can inject the syntax of any "regular" formula in R1C1 Format.

So the formula mentioned above =if($Z2=0,$O2,$Z2) is .FORMULA format for any value in row 2.
But in .FORMULAR1C1 it can be inserted in ANY cell as: =IF(RC26=0,RC15,RC26) (basically no rows up or down, but always columns O (15) and Z(26).

So, your modified code would have something like this:

```<code>Intersect(rngBE, ActiveSheet.Rows(cell.Row)).FormulaR1C1 = "=IF(RC26=0,RC15,RC26)"
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value = _
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value
</code>```

Again, this is NOT the most efficient way to accomplish your task, but if you're dealing with thousandsof rows, versus tens to hundreds of thousands, I wouldn't worry about it and it gives you a new tool to use.

Body:
I got help last week getting my syntax and ranges correct, and thought I could just do a vlookup to finish it but apparently I was mistaken.  It just seems like when I try to research how to accomplish this, I find various examples but I don't have the background to translate it to my code.

The macro runs and does almost everything its supposed to do.  But in addition to inserting the arrays, there are 3 other cells that need values when there are blank cells in my ‘sourcerng’.

This is the logic for the cells that need values (the values are already in my worksheet, I just need to get them to these blank cells).  I tried to do an IIF statement for these but I still have no idea what I'm doing.  Would that be the best way? Should it just be another IF THEN statement?

rngBE   - IF Column Z = 0 Then copy value from corresponding row in column O.  Otherwise copy value from column Z

rngBG   - IF Column AA = "Unknown" Then copy value from corresponding row in column I.  Otherwise copy value from column AA.

rngBK   - IF Column AB = "Unknown" Then copy value from corresponding row in column N.  Otherwise copy value from column AB.

Sub AutomateAllTheThings6()
Dim arr3() As String
Dim arr11() As String
'Dim resBE As String
Dim rng3 As Range
Dim rng11 As Range
Dim rngBE As Range
Dim rngBG As Range
Dim rngBK As Range
Dim sourcerng As Range
'Dim firstRow As Long
Dim lastRow As Long
'Dim i As Long

    Call OptimizeCode_Begin
        'firstRow = 2
        lastRow = ActiveSheet.Range("D1").End(xlDown).Row
        Set rng3 = ActiveSheet.Range("BH2:BJ" & lastRow)
        Set rng11 = ActiveSheet.Range("BL2:BV" & lastRow)
        Set rngBE = ActiveSheet.Range("BE2:BE" & lastRow)
        Set rngBG = ActiveSheet.Range("BG2:BG" & lastRow)
        Set rngBK = ActiveSheet.Range("BK2:BK" & lastRow)
        Set sourcerng = ActiveSheet.Range("BE2:BE" & lastRow)
        arr3() = Split("UNKNOWN,UNKNOWN,UNKNOWN", ",")
        arr11() = Split("UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,00/00/0000, _
                         00/00/0000,00/00/0000,00/00/0000,NEEDS REVIEW", ",")
            For Each cell In sourcerng
                If IsEmpty(cell) Then
                    Intersect(rng3, ActiveSheet.Rows(cell.Row)).Value = arr3
                    Intersect(rng11, ActiveSheet.Rows(cell.Row)).Value = arr11
                    '***PLS HELP***
                    Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value = "WEEEEE"
                    Intersect(rngBG, ActiveSheet.Rows(cell.Row)).Value = "WOOOOO"
                    Intersect(rngBK, ActiveSheet.Rows(cell.Row)).Value = "WAAAAA"
                End If
            Next
        Range("BR2:BU2").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.NumberFormat = "mm/dd/yyyy"
        Columns("BF:BF").Select
        Selection.Delete Shift:=xlToLeft
    Call OptimizeCode_End
End Sub

'*********TESTING***********
'resBE      = IIf(Cells(13,Z).Value = 0, Cells(13,BE).Value = Cells(13,Z), Cells(13,BE).Value = Cells(13,O))

'***************************************
'For i = firstRow To lastRow
'           valZ = Range("Z" & i)
'           valOh = Range("O" & i)
'
'           If valZ = 0 Then
'               rngBE.Value = valOh
'               Else rngBE.Value = valZ
'           End If

Body:
There are several ways to do your task. If you're more of an "Excel" person than VBA you might consider this approach: You can inject the syntax of any "regular" formula in R1C1 Format.

So the formula mentioned above =if($Z2=0,$O2,$Z2) is .FORMULA format for any value in row 2.
But in .FORMULAR1C1 it can be inserted in ANY cell as: =IF(RC26=0,RC15,RC26) (basically no rows up or down, but always columns O (15) and Z(26).

So, your modified code would have something like this:

Intersect(rngBE, ActiveSheet.Rows(cell.Row)).FormulaR1C1 = "=IF(RC26=0,RC15,RC26)"
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value = _
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value

Again, this is NOT the most efficient way to accomplish your task, but if you're dealing with thousandsof rows, versus tens to hundreds of thousands, I wouldn't worry about it and it gives you a new tool to use.


问:
How to apply multiple arguments within find_all function?
Is it possible to use multiple arguments in a single soup.find_all function to find any particular item from certain elements? The process I wanna know about can easily be applied if i go for soup.select option. To be more specific: look at the below example:

```<code>from bs4 import BeautifulSoup

html_element='''
<div class="browse-movie-bottom">
    <a href="https://yts.ag/movie/logan-lucky-2017" class="browse-movie-title">Logan Lucky</a>
    <div class="browse-movie-year">2017</div>
    <div class="browse-movie-tags">
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>
    </div>
</div>
'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.find_all(class_='browse-movie-bottom')[0].find_all(class_='browse-movie-tags')[0].find_all("a"):
# for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)
</code>```

On the one hand, I parsed movie tags using soup.select() which you know can be used in such a way so that all the arguments can fit together in a single brace.

On the other hand, I did the same using soup.find_all() which required three different arguments in three different braces. The results are same though.

My question is: whether it is possible to create any expression using soup.find_all() function which will include multiple arguments in a single brace as i did with soup.select(). Something like below:

This is a faulty one but it will give you an idea as to what type of expression i'm after:

```<code>soup.find_all({'class':'browse-movie-bottom'},{'class':'browse-movie-tags'},"a")[0]
</code>```

However, the valid search results were:

```<code>Logan Lucky 720p
Logan Lucky 1080p
</code>```

答:
You should use a CSS selector:

```<code>>>> soup.select(".browse-movie-bottom .browse-movie-tags a")
[<a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>, <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>]
>>> [item.text for item in soup.select(".browse-movie-bottom .browse-movie-tags a")]
[u'Logan Lucky 720p', u'Logan Lucky 1080p']
</code>```

More info: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

Unless there's something you cannot do with CSS selectors (because not all of them are implemented), you should use select. Otherwise, use the more tedious find_all.

Example of non-implemented CSS-selector: n-th child.
selecting second child in beautiful soup with soup.select?

Body:
Is it possible to use multiple arguments in a single soup.find_all function to find any particular item from certain elements? The process I wanna know about can easily be applied if i go for soup.select option. To be more specific: look at the below example:

from bs4 import BeautifulSoup

html_element='''

    Logan Lucky

2017

        Logan Lucky 720p
        Logan Lucky 1080p

'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.find_all(class_='browse-movie-bottom')[0].find_all(class_='browse-movie-tags')[0].find_all("a"):
# for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)

On the one hand, I parsed movie tags using soup.select() which you know can be used in such a way so that all the arguments can fit together in a single brace.

On the other hand, I did the same using soup.find_all() which required three different arguments in three different braces. The results are same though.

My question is: whether it is possible to create any expression using soup.find_all() function which will include multiple arguments in a single brace as i did with soup.select(). Something like below:

This is a faulty one but it will give you an idea as to what type of expression i'm after:

soup.find_all({'class':'browse-movie-bottom'},{'class':'browse-movie-tags'},"a")[0]

However, the valid search results were:

Logan Lucky 720p
Logan Lucky 1080p

Body:
You should use a CSS selector:

>>> soup.select(".browse-movie-bottom .browse-movie-tags a")
[<a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>, <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>]
>>> [item.text for item in soup.select(".browse-movie-bottom .browse-movie-tags a")]
[u'Logan Lucky 720p', u'Logan Lucky 1080p']

More info: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

Unless there's something you cannot do with CSS selectors (because not all of them are implemented), you should use select. Otherwise, use the more tedious find_all.

Example of non-implemented CSS-selector: n-th child.
selecting second child in beautiful soup with soup.select?


问:
non-standard syntax; use '&' to create a pointer to member. Accessing boolean variable
I've been searching for a while on why this does not work.  I have not gotten a clear answer.

Can anyone explain why trying to access this boolean variable and comparing it to another boolean variable won't work?

I also tried setting the rhs of the comparison to 0, and that got rid of the boolean/int error, but I'm still getting the error.

```<code>#include <iostream>

using namespace std;

class MyClass {
public:
    MyClass() {
        setWorking(true);
    }

    //Mutator
    void setWorking(bool x) { working = x; }

    //Accessor
    bool getWorking() { return working; }

private:
    bool working;
};

int main() {

    MyClass alpha;

    if (alpha.getWorking == true) {
        cout << "its working\n";
    }
    else {
        cout << "not working\n";
    }

    return 0;
}
</code>```

答:
In main function

```<code>if (alpha.getWorking == true)
</code>```

should be

```<code>if (alpha.getWorking())
</code>```

Body:
I've been searching for a while on why this does not work.  I have not gotten a clear answer.

Can anyone explain why trying to access this boolean variable and comparing it to another boolean variable won't work?

I also tried setting the rhs of the comparison to 0, and that got rid of the boolean/int error, but I'm still getting the error.

#include <iostream>

using namespace std;

class MyClass {
public:
    MyClass() {
        setWorking(true);
    }

    //Mutator
    void setWorking(bool x) { working = x; }

    //Accessor
    bool getWorking() { return working; }

private:
    bool working;
};

int main() {

    MyClass alpha;

    if (alpha.getWorking == true) {
        cout << "its working\n";
    }
    else {
        cout << "not working\n";
    }

    return 0;
}

Body:
In main function

if (alpha.getWorking == true)

should be

if (alpha.getWorking())


问:
Replacing components in a Webpack bundle
We have a Webpack bundle exposing React components. The exposed components contain nested components from the same bundle.
We want to allow users to replace components with their own specific version.

For example, the following component structure;

```<code>class A extends React.Component {
    render() {
        return (
            <B/>
        );
    }
}

const C = require('./C');

class B extends React.Component {
    render() {
        return (
            <C/>
        );
    }
}
</code>```

from which the top-level component A is exposed in the Webpack bundle:

```<code>const A = bundle.components.A;
</code>```

Our server-side web framework relies on the exposed bundle interface to invoke the React components.

From this structure, an example use-case would be to replace the nested component C from component A.

Current options that we see for this are;

add a method to the class B (and A) to replace component C

create a registration mechanism, e.g. by using the filename or logical name of C, and a generic method to the bundle to replace a component. For example: bundle.component.replace('./C', './custom-C');

...

What would be the best way, i.e. common practice, to replace a (nested) React component in a Webpack bundle?

答: In the end we chose to use render-props, HOCs, and adding some replace functions for specific components.</p>

Body:
We have a Webpack bundle exposing React components. The exposed components contain nested components from the same bundle.
We want to allow users to replace components with their own specific version.

For example, the following component structure;

class A extends React.Component {
    render() {
        return (

        );
    }
}

const C = require('./C');

class B extends React.Component {
    render() {
        return (
            <C/>
        );
    }
}

from which the top-level component A is exposed in the Webpack bundle:

const A = bundle.components.A;

Our server-side web framework relies on the exposed bundle interface to invoke the React components.

From this structure, an example use-case would be to replace the nested component C from component A.

Current options that we see for this are;

add a method to the class B (and A) to replace component C

create a registration mechanism, e.g. by using the filename or logical name of C, and a generic method to the bundle to replace a component. For example: bundle.component.replace('./C', './custom-C');

...

What would be the best way, i.e. common practice, to replace a (nested) React component in a Webpack bundle?


问:
Character to binary function doesn't work as expected
I have made a function to translate a number to its binary form:

```<code>size_t atobin (char n)
{
    size_t bin= 0, pow;
    for (size_t c= 1; n>0; c++)
    {
        pow= 1;
        for (size_t i= 1; i<c; i++) //This loop is for getting the power of 10
            pow*= 10;
        bin+= (n%2)*pow;
        n/= 2;
    }
    return bin;
}
</code>```

It works great for numbers 1 to 127, but for greater numbers (128 to 255) the result is 0... I've tried using the type long long unsigned int for each variable but the result was the same. Someone has an idea about why?

答:
char by default in C is considered to be of signed.

char is of 8 bits(mostly). And for signed char the MSB is used for sign. As a result you can only use 7 bits.

(0111 1111)2 = (127)10 The maximum value that your fucntion can work with. (as you are passing a type of variable which can hold 127 at max).

If you use unsigned char then the MSB is not used as sign-bit. All 8 bits are used giving us a maximum possible value (1111 1111)2 = (255)10

For signed number min/max value is -127 to +127.

For unsigned number min/max value is 0 to +255.

So even if you make the type of the passed parameter unsigned char the maximum value it can hold is +255.

A bit more detail:

Q) What happens when you assign >127 values to your char parameter?

It is signed char by default. It is of 8 bits. But it can't hold it. So what will happen?

The result is implementation defined. But

Suppose the value is 130. In binary it is 10000010. In most of the cases this returns -126. So that will be the value of n.
n>0; fails. Loop is never entered. And it returns 0.

Now if we make it unsigned char then it can hold values between 0 and 255 (inclusive). And that is what you want to have here.

Note:

Q) What happens when >255 values are stored in unsigned char?

The value is reduced to modulo of (max value unsigned char can hold+1) which is
  256.

So apply modulo operation and put the result. That will be stored in
  unsigned char.

Body:
I have made a function to translate a number to its binary form:

size_t atobin (char n)
{
    size_t bin= 0, pow;
    for (size_t c= 1; n>0; c++)
    {
        pow= 1;
        for (size_t i= 1; i<c; i++) //This loop is for getting the power of 10
            pow*= 10;
        bin+= (n%2)*pow;
        n/= 2;
    }
    return bin;
}

It works great for numbers 1 to 127, but for greater numbers (128 to 255) the result is 0... I've tried using the type long long unsigned int for each variable but the result was the same. Someone has an idea about why?


问:
Can I make a pull request on a gist on GitHub?
Can I make a pull request on some else's gist on GitHub?

I'm aware of the fork, clone and commit workflow for a gist I own. I'd like to know if I can request to update someone else's gist with my fork.

答:
I don't think it is appropriate to have pull request on gists. The intent of gist.github.com was to improve upon the pastebin concept commonly used in IRC and forums. They chose to call the service "gist" because as vocabulary.com describes it...

When you need a quick summary of the essentials, rather than the whole story or a thorough explanation, you're looking for the gist.

However I will concede that github is missing a very important feature. The ability to create a full github repo out of a gist and keep metadata about its origins.

That would solve most of what people need. At that point, the only form of "request" that someone would need to submit is "hey, won't you make a full repo out of this." And that can be done in the comments. By NOT allowing pull requests, issues, etc. on gists, it allows the author to reply to such a comment with, "nah, it was just a hack I threw together and don't intend to support."

```<code>StackOverflow won't let you link to pastebin without including a code block. Done.
</code>```

Body:
I don't think it is appropriate to have pull request on gists. The intent of gist.github.com was to improve upon the pastebin concept commonly used in IRC and forums. They chose to call the service "gist" because as vocabulary.com describes it...

When you need a quick summary of the essentials, rather than the whole story or a thorough explanation, you're looking for the gist.

However I will concede that github is missing a very important feature. The ability to create a full github repo out of a gist and keep metadata about its origins.

That would solve most of what people need. At that point, the only form of "request" that someone would need to submit is "hey, won't you make a full repo out of this." And that can be done in the comments. By NOT allowing pull requests, issues, etc. on gists, it allows the author to reply to such a comment with, "nah, it was just a hack I threw together and don't intend to support."

StackOverflow won't let you link to pastebin without including a code block. Done.


问:
How to add dependency JAR in java azure functions
Is there a way to add third party jars  to Azure functions using JAVA. I would need to have the json-simple jar and jackson-databind jars to be available for the function at run time. Right now, My code throws a runtime exception(ClassNotFound Exception) as the function is not able to reference the jar during runtime because it is unavailable.

I tried using maven-shade-plugin. It does create an executable jar including the external jars but the deployment still takes the original jar.

Please suggest.

Thanks.

POM.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sce.api.learning</groupId>
    <artifactId>myApi</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Azure Java Functions</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <functionAppName>mckapi-http-nov2</functionAppName>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-functions-java-core</artifactId>
            <version>1.0.0-beta-1</version>
        </dependency>

        <!-- Adding GSON dependancy -->
        <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.4</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20171018</version>
</dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <groupId>com.microsoft.azure</groupId>
                    <artifactId>azure-functions-maven-plugin</artifactId>
                    <version>0.1.4</version>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>
            <plugin>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-functions-maven-plugin</artifactId>
                <configuration>
                    <resourceGroup>java-functions-group</resourceGroup>
                    <appName>${functionAppName}</appName>
                    <region>westus2</region>
                    <appSettings>
                        <property>
                            <name>FUNCTIONS_EXTENSION_VERSION</name>
                            <value>beta</value>
                        </property>
                    </appSettings>
                </configuration>
                <executions>
                    <execution>
                        <id>package-functions</id>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <overwrite>true</overwrite>
                            <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${project.basedir}</directory>
                                    <includes>
                                        <include>host.json</include>
                                        <include>local.settings.json</include>
                                        **<include>**/*.jar</include>**<!-- This includes the jar files in the target/lib folder -->
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                        <overwrite>true</overwrite>
                            <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}
                            </outputDirectory>
              <shadedArtifactAttached>false</shadedArtifactAttached>
            </configuration>
                    </execution>
                </executions>
                <configuration>
                    <finalName>${artifactId}-${version}</finalName>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>
</code>```

答:
I had the same problem and I figured out how to arrange a solution.

First of all, start from a brand new Maven project following the straightforward guide at this link.

Assume <project_root_path> as the folder where you will create the project.

Once you have generated your maven project, just add this maven-assembly-plugin plugin on your <project_root_path>/pom.xml within <build><plugins>...</plugins></build>:

```<code><plugin>
   <artifactId>maven-assembly-plugin</artifactId>
   <configuration>
      <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}</outputDirectory>
      <appendAssemblyId>false</appendAssemblyId>
      <descriptorRefs>
         <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
      <archive />
   </configuration>
   <executions>
      <execution>
         <id>make-assembly</id>
         <phase>package</phase>
         <goals>
            <goal>assembly</goal>
         </goals>
      </execution>
   </executions>
</plugin>
</code>```

Compiling and packaging the Azure Function with command mvn clean compile package will produce a jar on path <project_root_path>/target/<project_name>.jar containing all the external libraries listed under the <dependencies></dependencies> of the pom.xml.

Note 1: if you didn't modify the standard pom.xml, <project_name> will be generated according to <artifactId>_<version>.jar.

Note 2: if you don't use the <appendAssemblyId>false</appendAssemblyId> directive on the above snippet, the <project_name> will be <artifactId>_<version>-<descriptorRef>.jar. Consider this for the following instructions.

So, now you should have your complete <project_root_path>/target/<project_name>.jar, but before using it you have to copy it under <project_root_path>/target/azure-functions/<azure_function_name>/ where <azure_function_name> is the name you gave to your function during the creation progress documented on the above link.

Now you can test it using the Azure Maven plugins:

Running the Azure Function on your machine locally: mvn azure-functions:run

Deploying the Azure Function on your subscription: mvn azure-functions:deploy

At the end, the key point is moving the jar generated with maven-assembly-plugin into the right place where the Azure Maven plugin will look during the run/deploy process. I wish I could find a more automatic way using standard Maven commands.

Hope this helps.

Ciao
IP

Edit (17/11/17)

Adding <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}</outputDirectory> within the  <configuration> POM tag and changing <goal> tag to assembly, it makes Maven to automatically copy the final JAR in the Azure Function staging directory. This allows the mvn azure-functions:run and mvn azure-functions:deploy commands to directly use the correct JAR file containing all dependency. No manual actions are requested anymore.

The above POM have been updated accordingly.

Edit (21/11/17)

In case you want to use the Maven Shade Plugin instead of the Maven Assembly Plugin, replace the above XML snippet with this one:

```<code><plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-shade-plugin</artifactId>
   <version>3.1.0</version>
   <configuration>
      <shadedArtifactAttached>false</shadedArtifactAttached>
      <outputFile>${project.build.directory}/azure-functions/${functionAppName}/${project.artifactId}-${project.version}.jar</outputFile>
      <filters>
         <filter>
            <artifact>*:*</artifact>
            <excludes>
               <exclude>META-INF/*.SF</exclude>
               <exclude>META-INF/*.DSA</exclude>
               <exclude>META-INF/*.RSA</exclude>
            </excludes>
         </filter>
      </filters>
   </configuration>
   <executions>
      <execution>
         <phase>package</phase>
         <goals>
            <goal>shade</goal>
         </goals>
      </execution>
   </executions>
</plugin>
</code>```

It will work using the same standard Maven commands mentioned before.

Body:
Is there a way to add third party jars  to Azure functions using JAVA. I would need to have the json-simple jar and jackson-databind jars to be available for the function at run time. Right now, My code throws a runtime exception(ClassNotFound Exception) as the function is not able to reference the jar during runtime because it is unavailable.

I tried using maven-shade-plugin. It does create an executable jar including the external jars but the deployment still takes the original jar.

Please suggest.

Thanks.

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sce.api.learning</groupId>
    <artifactId>myApi</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Azure Java Functions</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <functionAppName>mckapi-http-nov2</functionAppName>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-functions-java-core</artifactId>
            <version>1.0.0-beta-1</version>
        </dependency>

        <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.4</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20171018</version>
</dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <groupId>com.microsoft.azure</groupId>
                    <artifactId>azure-functions-maven-plugin</artifactId>
                    <version>0.1.4</version>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>
            <plugin>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-functions-maven-plugin</artifactId>
                <configuration>
                    <resourceGroup>java-functions-group</resourceGroup>
                    <appName>${functionAppName}</appName>
                    <region>westus2</region>
                    <appSettings>
                        <property>
                            <name>FUNCTIONS_EXTENSION_VERSION</name>
                            <value>beta</value>
                        </property>
                    </appSettings>
                </configuration>
                <executions>
                    <execution>
                        <id>package-functions</id>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <overwrite>true</overwrite>
                            <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${project.basedir}</directory>
                                    <includes>
                                        <include>host.json</include>
                                        <include>local.settings.json</include>
                                        **<include>**/*.jar</include>**
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                        <overwrite>true</overwrite>
                            <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}
                            </outputDirectory>
              <shadedArtifactAttached>false</shadedArtifactAttached>
            </configuration>
                    </execution>
                </executions>
                <configuration>
                    <finalName>${artifactId}-${version}</finalName>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>

Body:
I had the same problem and I figured out how to arrange a solution.

First of all, start from a brand new Maven project following the straightforward guide at this link.

Assume <project_root_path> as the folder where you will create the project.

Once you have generated your maven project, just add this maven-assembly-plugin plugin on your <project_root_path>/pom.xml within <build><plugins>...</plugins></build>:

<plugin>
   <artifactId>maven-assembly-plugin</artifactId>
   <configuration>
      <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}</outputDirectory>
      <appendAssemblyId>false</appendAssemblyId>
      <descriptorRefs>
         <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
      <archive />
   </configuration>
   <executions>
      <execution>
         <id>make-assembly</id>
         <phase>package</phase>
         <goals>
            <goal>assembly</goal>
         </goals>
      </execution>
   </executions>
</plugin>

Compiling and packaging the Azure Function with command mvn clean compile package will produce a jar on path <project_root_path>/target/<project_name>.jar containing all the external libraries listed under the <dependencies></dependencies> of the pom.xml.

Note 1: if you didn't modify the standard pom.xml, <project_name> will be generated according to <artifactId>_<version>.jar.

Note 2: if you don't use the <appendAssemblyId>false</appendAssemblyId> directive on the above snippet, the <project_name> will be <artifactId>_<version>-<descriptorRef>.jar. Consider this for the following instructions.

So, now you should have your complete <project_root_path>/target/<project_name>.jar, but before using it you have to copy it under <project_root_path>/target/azure-functions/<azure_function_name>/ where <azure_function_name> is the name you gave to your function during the creation progress documented on the above link.

Now you can test it using the Azure Maven plugins:

Running the Azure Function on your machine locally: mvn azure-functions:run

Deploying the Azure Function on your subscription: mvn azure-functions:deploy

At the end, the key point is moving the jar generated with maven-assembly-plugin into the right place where the Azure Maven plugin will look during the run/deploy process. I wish I could find a more automatic way using standard Maven commands.

Hope this helps.

Ciao
IP

Edit (17/11/17)

Adding <outputDirectory>${project.build.directory}/azure-functions/${functionAppName}</outputDirectory> within the  <configuration> POM tag and changing <goal> tag to assembly, it makes Maven to automatically copy the final JAR in the Azure Function staging directory. This allows the mvn azure-functions:run and mvn azure-functions:deploy commands to directly use the correct JAR file containing all dependency. No manual actions are requested anymore.

The above POM have been updated accordingly.

Edit (21/11/17)

In case you want to use the Maven Shade Plugin instead of the Maven Assembly Plugin, replace the above XML snippet with this one:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-shade-plugin</artifactId>
   <version>3.1.0</version>
   <configuration>
      <shadedArtifactAttached>false</shadedArtifactAttached>
      <outputFile>${project.build.directory}/azure-functions/${functionAppName}/${project.artifactId}-${project.version}.jar</outputFile>
      <filters>
         <filter>
            <artifact>*:*</artifact>
            <excludes>
               <exclude>META-INF/*.SF</exclude>
               <exclude>META-INF/*.DSA</exclude>
               <exclude>META-INF/*.RSA</exclude>
            </excludes>
         </filter>
      </filters>
   </configuration>
   <executions>
      <execution>
         <phase>package</phase>
         <goals>
            <goal>shade</goal>
         </goals>
      </execution>
   </executions>
</plugin>

It will work using the same standard Maven commands mentioned before.


问:
javascript counter using for loop
I've created a simple counter using javascript but there is a problem Field "display" starts from 1, but it should start from 100 and goes low. The console logs shows values correctly from 100 to 1.
I have to use loops to do this tasks, so please not replace it using recursion :) Also the timeout is for sure does not equal to 100ms, it's more

function wyswietlLiczbe(j) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, 100);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="display"></p></code>```

答:
Since the loop executes immediately, you need to wait an increasing amount of time for each number.  This will queue up the innerHTML modifications.

As it is now, after a 100ms wait all 100 wyswietlLiczbe are executed in rapid succession.

function wyswietlLiczbe(j, waitTime) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, waitTime);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i, (101 - i) * 100);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="display"></p></code>```

Title: javascript counter using for loop

Body:
Since the loop executes immediately, you need to wait an increasing amount of time for each number.  This will queue up the innerHTML modifications.

As it is now, after a 100ms wait all 100 wyswietlLiczbe are executed in rapid succession.

function wyswietlLiczbe(j, waitTime) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, waitTime);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i, (101 - i) * 100);
}

<p id="display"></p>


问:
Is there any way to hide the sensitive information when i click the dynamic link in browser
I just created a short dynamic link for this url https://m.example.com/invitation?gameid=1234&referrer=555.
It  is working fine, but when i click the shortlink in browser it is directing to my page but it is showing all the sensitive information like gameId and referrer in browser address bar. I don't want to show that.
Is there any way to show short link even when i click the shortlink in browser also or anyway to hide the sensitive information.

答:
Firebase Dynamic Links do not provide mechanism to hide link data from person who have access to the link. In addition to exposing the link content in browser address bar (as you already found out), any person can get link details by going to link debug page https://firebase.google.com/docs/dynamic-links/debug . Append ?d=1 or &d=1 to the link to get here.

If you need to hide information, you can consider encrypting the information, like https://m.example.com/invitation?encrypted_data=<base64 data here>

Another option is to store data in database and having only data identifier in your link, like https://m.example.com/invitation?data_id=<identifier>

If you think your use case is important or widely used, feel free to open Firebase support ticket. We always open to feature requests and suggestions how to improve our product.


问:
firebase downloading an image url encode error
I'm storing some images in firebase, firebase gives me an url to download the image like this one:

```<code>https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%2F1000%2Falicate%20cortante%20electronica.jpg?alt=media&token=f2d54a3b-0526-4b9a-99ff-4c38c468757c
</code>```

the permissions to download the images are full open

I want to upload the images through a rest api in another server from MercadoLibre (api.mercadolibre.com)

to upload the images I have to send the pictures like this

```<code>{"source":"https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%2F1000%2Falicate%20cortante%20electronica.jpg?alt=media&token=f2d54a3b-0526-4b9a-99ff-4c38c468757c"}
</code>```

via POST

The problem is that the server from mercadolibre encodes the url, and broke the url and the server tries to download the images from this url

```<code>https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%252F1000%252Falicate%2520cortante%2520electronica.jpg%3Falt%3Dmedia%26token%3Df2d54a3b-0526-4b9a-99ff-4c38c468757c
</code>```

notice the %25

this link gives the following error

```<code>{
  "error": {
    "code": 404,
    "message": "Not Found.  Could not get object"
  }
}
</code>```

so in python i tried to decode the first url

```<code>https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures/1000/alicate cortante electronica.jpg?alt=media&token=f2d54a3b-0526-4b9a-99ff-4c38c468757c
</code>```

(this link gives the following error)

```<code>{
  "error": {
    "code": 400,
    "message": "Invalid HTTP method/URL pair."
  }
}
</code>```

with the idea that when the mercadolibre server encodes the url i get the original, but the problem is that only the "/" after "/o/" should be converted to %2F

I have no control over the url encoding (which is automatic in the mercadolibre server), what can i do to send a url that after is encoded i get the original url in a valid format??

thanks.

答:
As a workaround i shortered the url using the google api goo.gl
this works for mercadolibre, facebook or any other api that requires an url to upload a picture.

greetings.

Body:
I'm storing some images in firebase, firebase gives me an url to download the image like this one:

https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%2F1000%2Falicate%20cortante%20electronica.jpg?alt=media&token=f2d54a3b-0526-4b9a-99ff-4c38c468757c

the permissions to download the images are full open

I want to upload the images through a rest api in another server from MercadoLibre (api.mercadolibre.com)

to upload the images I have to send the pictures like this

{"source":"https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%2F1000%2Falicate%20cortante%20electronica.jpg?alt=media&token=f2d54a3b-0526-4b9a-99ff-4c38c468757c"}

via POST

The problem is that the server from mercadolibre encodes the url, and broke the url and the server tries to download the images from this url

https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures%252F1000%252Falicate%2520cortante%2520electronica.jpg%3Falt%3Dmedia%26token%3Df2d54a3b-0526-4b9a-99ff-4c38c468757c

notice the %25

this link gives the following error

{
  "error": {
    "code": 404,
    "message": "Not Found.  Could not get object"
  }
}

so in python i tried to decode the first url

https://firebasestorage.googleapis.com/v0/b/afel-orders-mirror.appspot.com/o/stock_pictures/1000/alicate cortante electronica.jpg?alt=media&token=f2d54a3b-0526-4b9a-99ff-4c38c468757c

(this link gives the following error)

{
  "error": {
    "code": 400,
    "message": "Invalid HTTP method/URL pair."
  }
}

with the idea that when the mercadolibre server encodes the url i get the original, but the problem is that only the "/" after "/o/" should be converted to %2F

I have no control over the url encoding (which is automatic in the mercadolibre server), what can i do to send a url that after is encoded i get the original url in a valid format??

thanks.


问:
Portability of binary serialization of double/float type in C++
The C++ standard does not discuss the underlying layout of float and double types, only the range of values they should represent.  (This is also true for signed types, is it two's compliment or something else)

My question is: What the are techniques used to serialize/deserialize POD types such as double and float in a portable manner? At the moment it seems the only way to do this is to have the value represented literally(as in "123.456"), The ieee754 layout for double is not standard on all architectures.

答: Just write the binary IEEE754 representation to disk, and document this as your storage format (along with is endianness). Then it's up to the implementation to convert this to its internal representation if necessary.</p>

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

ContentLicense: CC BY-SA 2.5


问:
Java jks keystore with CA, intermediate and website cert on tomcat in docker on AWS gives "Peer's Certificate issuer is not recognised"
I have put together a jks keystore and Java 1.8 cacerts with a certificate from my company's certificate provider for internal use only, and build it into my app's docker build with tomcat, deployed it and successfully started the server and connected to it via Chrome and Edge, but Firefox on Windows 10 is not connecting, giving SEC_ERROR_UNKNOWN_ISSUER "Your connection is not secure" and "Peer's Certificate issuer is not recognised".

This is what I've done:

I created my private key and certificate request using the Java 1.8 keytool.

Obtained a root certificate .cer, an intermediate .cer and a website .cer file

I put the root cert into java's cacerts:

keytool -importcert -alias app-cert1 -file AD1GXECA001-SHA2-Root.cer -v -keystore c:/dev/tools/Java/jdk1.8.0_131/jre/lib/security/cacer
```

<p>ts</p>

<ol start="4">
<li><p>I also concatenated them together into a pem file in this order:</p>

```1. website cert
2. intermediate cert
3. company cert
```</li>
<li>and inserted them into the jks with keytool:</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>keytool -import -alias app-cert1 -file chain.pem -v -keystore my-app.jks
</code>```

and I build them into my docker image which runs a Spring boot fat jar with tomcat and the app inside:

CMD -Dlogging.file=/logs/my-app.log
    -Djava.security.auth.login.config=/config/login.conf
    -Djava.security.krb5.conf=/config/krb5.conf
    -Djavax.net.ssl.trustStore=/config/cacerts
    -Djavax.net.ssl.trustStorePassword=changeit
    -Djavax.net.debug=ssl
    -jar /my-app.jar
```

<p>and the Spring config:</p>

<pre class="lang-sh prettyprint-override"><code>server.ssl.key-alias=app-cert1
server.ssl.key-password=changeit
server.ssl.key-store=file:/config/my-app.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS
</code>```

I see no errors in the build or the tomcat logging.

Where is my problem? Firefox? Windows 10? Docker?

Are Chrome and Edge really not having problems? Does that mean it must be firefox?

答:
The error message simply means that Firefox cannot establish a chain starting from a trusted certificate in its certificate store (usually the root CA) down to the website certificate.

As you have imported the complete chain (excluding the root CA) in Tomcat's SSL keystore, Tomcat will deliver those certificates to the client. So, you are fine on the server side. But on the client side (Firefox in this case) you need a trust anchor, so you have to import the root certificate into Firefox.

The reason you are getting different results with Chrome/Edge is that Firefox has its own certificate store, whereas Chrome and Edge use the Windows store.

Body:
I have put together a jks keystore and Java 1.8 cacerts with a certificate from my company's certificate provider for internal use only, and build it into my app's docker build with tomcat, deployed it and successfully started the server and connected to it via Chrome and Edge, but Firefox on Windows 10 is not connecting, giving SEC_ERROR_UNKNOWN_ISSUER "Your connection is not secure" and "Peer's Certificate issuer is not recognised".

This is what I've done:

I created my private key and certificate request using the Java 1.8 keytool.

Obtained a root certificate .cer, an intermediate .cer and a website .cer file

I put the root cert into java's cacerts:

keytool -importcert -alias app-cert1 -file AD1GXECA001-SHA2-Root.cer -v -keystore c:/dev/tools/Java/jdk1.8.0_131/jre/lib/security/cacer

ts

I also concatenated them together into a pem file in this order:

1. website cert
2. intermediate cert
3. company cert

and inserted them into the jks with keytool:

keytool -import -alias app-cert1 -file chain.pem -v -keystore my-app.jks

and I build them into my docker image which runs a Spring boot fat jar with tomcat and the app inside:

CMD -Dlogging.file=/logs/my-app.log
    -Djava.security.auth.login.config=/config/login.conf
    -Djava.security.krb5.conf=/config/krb5.conf
    -Djavax.net.ssl.trustStore=/config/cacerts
    -Djavax.net.ssl.trustStorePassword=changeit
    -Djavax.net.debug=ssl
    -jar /my-app.jar

and the Spring config:

server.ssl.key-alias=app-cert1
server.ssl.key-password=changeit
server.ssl.key-store=file:/config/my-app.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

I see no errors in the build or the tomcat logging.

Where is my problem? Firefox? Windows 10? Docker?

Are Chrome and Edge really not having problems? Does that mean it must be firefox?


问:
Printing a python object doesn't yield the expected <__main__.myclass ...> output
When I create a Class like this

```<code>class Node(object):
    def __init__(self):
        pass

node = Node()
print node
</code>```

prints <__main__.Task object at 0x7fc9be21cd0>.
However, I was using a library and wanted to print an object, which yielded the following:

```<code>foo.node(path="/test/1/2", value='Text')
</code>```

how is this being constructed? value doesn't seem to be member variable or anything accessible? I was expecting something like <__main__.foo object at ...

答:
As I was expecting a more explanatory answer, I found the answer in the Book "Fluent Python"  Basically the author of the library implemented the __repr__

```<code>class Node:
    def __init__(self, path=0, value=0):
        self.path = path
        self.value = value

    def __repr__(self):
        return "foo.node(path="{0}", value='{1}')".format(self.path, self.value)
</code>```

The repr special method is called by the repr built-in to get string representation
  of the object for inspection. If we did not implement repr, vector instances would
  be shown in the console like <Vector object at 0x10e100070>

Body:
When I create a Class like this

class Node(object):
    def __init__(self):
        pass

node = Node()
print node

prints <__main__.Task object at 0x7fc9be21cd0>.
However, I was using a library and wanted to print an object, which yielded the following:

foo.node(path="/test/1/2", value='Text')

how is this being constructed? value doesn't seem to be member variable or anything accessible? I was expecting something like <__main__.foo object at ...

Body:
As I was expecting a more explanatory answer, I found the answer in the Book "Fluent Python"  Basically the author of the library implemented the __repr__

class Node:
    def __init__(self, path=0, value=0):
        self.path = path
        self.value = value

    def __repr__(self):
        return "foo.node(path="{0}", value='{1}')".format(self.path, self.value)

The repr special method is called by the repr built-in to get string representation
  of the object for inspection. If we did not implement repr, vector instances would
  be shown in the console like <Vector object at 0x10e100070>


问:
Unable to import Google Cloud Storage library in ML Engine
As a quick solution to get some images processed in batch within ML Engine I am using the Cloud Storage Python library to download the images.

Unfortunately it seems that when the job is sent to ML Engine, the library import fails with the following stack trace:

Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/root/.local/lib/python2.7/site-packages/trainer/task.py", line 1, in <module> from google.cloud import storage ImportError: cannot import name storage

I am pretty sure that the library is included within the ML engine image (it would be weird if it wasn't) so I am at a loss here, the program runs fine locally.

答:
The container does not contain this package because typically you use TensorFlow's file_io module, which works with GCS.

Two options. Assuming you already know how to use and/or have code for google.cloud.storage, you can just add it as a requirement in your setup.py file (instructions), for example:

```<code>from setuptools import find_packages
from setuptools import setup

REQUIRED_PACKAGES = ['google-cloud-storage']

setup(
    name='trainer',
    version='0.1',
    install_requires=REQUIRED_PACKAGES,
    packages=find_packages(),
    include_package_data=True,
    description='My trainer application package.'
)
</code>```

Or, you can use file_io, which is especially useful if you don't actually need copies of the data but want to read them directly:

```<code>import tensorflow as tf
from tensorflow.python.lib.io import file_io

# Copy
file_io.copy("gs://my-bucket/myfiles/*", "/tmp")

# Glob and read
for file in file_io.get_matching_files("gs://my-bucket/myfiles/*"):
  with file_io.FileIO(file) as f:
    # Do something
</code>```

Finally, note that if you're using TensorFlow operations, TensorFlow's readers already know how to read from GCS and so there is no need to manually manipulate the files.

Body:
The container does not contain this package because typically you use TensorFlow's file_io module, which works with GCS.

Two options. Assuming you already know how to use and/or have code for google.cloud.storage, you can just add it as a requirement in your setup.py file (instructions), for example:

from setuptools import find_packages
from setuptools import setup

REQUIRED_PACKAGES = ['google-cloud-storage']

setup(
    name='trainer',
    version='0.1',
    install_requires=REQUIRED_PACKAGES,
    packages=find_packages(),
    include_package_data=True,
    description='My trainer application package.'
)

Or, you can use file_io, which is especially useful if you don't actually need copies of the data but want to read them directly:

import tensorflow as tf
from tensorflow.python.lib.io import file_io

# Copy
file_io.copy("gs://my-bucket/myfiles/*", "/tmp")

# Glob and read
for file in file_io.get_matching_files("gs://my-bucket/myfiles/*"):
  with file_io.FileIO(file) as f:
    # Do something

Finally, note that if you're using TensorFlow operations, TensorFlow's readers already know how to read from GCS and so there is no need to manually manipulate the files.


问:
find variable Declaration reference Abstract syntax tree eclipse cdt C code
I have a c code like this
int x;
x = 5;

I used eclipse cdt to generate the AST, and traverse on it, so this is the code of the traversed class

```<code>public class RuleChk extends AbstractRule {
    public RuleChk(IASTTranslationUnit ast) {
        super("RuleChk", false, ast);
        shouldVisitDeclarations = true;
        shouldVisitParameterDeclarations = true;
    }

    @Override
    public int visit(IASTSimpleDeclaration simpleDecl) {
        //if this node has init, e.g: x = 5, do business
        if(VisitorUtil.containNode(simpleDecl, CASTExpressionStatement){
           // Now I have the x = 5 node,
           // I want to get the reference node of it's declaration
           // I mean (int x;) node
           IASTNode declNode = ?????
        }
        return super.visit(parameterDeclaration);
    }
}
</code>```

what I want to visit the node that only has assignation(Initialization) and get the reference of declaration node for that varaiable.

答:
I'm not sure how VisitorUtil works (it's not from the CDT code), but I assume it gives you a way to access the the found node. So:

Given the IASTExpressionStatement node that was found, use IASTExpression.getExpression() to get the contained expression.

See if it's an IASTBinaryExpression, and that is getOperator() is IASTBinaryExpression.op_assign.

Use IASTBinaryExpression.getOperand1() to get the assignment expression's left subexpression. Check that it's an IASTIdExpression, and get the variable it names via IASTIdExpression.getName().

Now that you have the name, use IASTName.resolveBinding() to get the variable's binding. This is the variable's representation in the semantic program model.

To find the variable's definition, use IASTTranslationUnit.getDefinitionsInAST(IBinding) if you only want it to look in the current file, or IASTTranslationUnit.getDefinitions(IBinding) if you want it to look in included header files as well (the latter requires the project to be indexed). The IASTTranslationUnit can be obtained from any IASTNode via IASTNode.getTranslationUnit().

Body:
I have a c code like this
int x;
x = 5;

I used eclipse cdt to generate the AST, and traverse on it, so this is the code of the traversed class

public class RuleChk extends AbstractRule {
    public RuleChk(IASTTranslationUnit ast) {
        super("RuleChk", false, ast);
        shouldVisitDeclarations = true;
        shouldVisitParameterDeclarations = true;
    }

    @Override
    public int visit(IASTSimpleDeclaration simpleDecl) {
        //if this node has init, e.g: x = 5, do business
        if(VisitorUtil.containNode(simpleDecl, CASTExpressionStatement){
           // Now I have the x = 5 node,
           // I want to get the reference node of it's declaration
           // I mean (int x;) node
           IASTNode declNode = ?????
        }
        return super.visit(parameterDeclaration);
    }
}

what I want to visit the node that only has assignation(Initialization) and get the reference of declaration node for that varaiable.


问:
Noty: Do not execute callback when closed by timeout
I am using Noty to display messages to the user. When a notification is clicked, the user is redirected to a page that displays further details about the notification. For this I am using the onClose() callback.

I would also like to hide the notifications after a short period of time. I am utilizing the timeout property for this.

The problem is that the onClose() callback gets executed even if the notification gets closed by the timeout. But since there is no onClick() or a similar callback available I believe that using the current approach is the best I can do.

Is anybody aware of a way to solve this or some sort of workaround? Any help is appreciated!

答:
In Noty v2 is looks like they have a new onCloseClick callback you can use. Seems like its only called when the user clicks the noty to close it. On timeout it will still close the noty without triggering that callback.

Here is an example:

noty({
  text: 'Alert: I am an error!',
  timeout: 3000,
  progressBar: true,
  callback:{
   onCloseClick: function() {
     console.log("you closed with a click");
     // redirect user here
   }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/noty@2.4.1/js/noty/packaged/jquery.noty.packaged.min.js"></script></code>```

Body:
In Noty v2 is looks like they have a new onCloseClick callback you can use. Seems like its only called when the user clicks the noty to close it. On timeout it will still close the noty without triggering that callback.

Here is an example:

noty({
  text: 'Alert: I am an error!',
  timeout: 3000,
  progressBar: true,
  callback:{
   onCloseClick: function() {
     console.log("you closed with a click");
     // redirect user here
   }
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/noty@2.4.1/js/noty/packaged/jquery.noty.packaged.min.js"></script>


问:
scrollHeight not resetting after programmatically changing content
I am trying to learn a few things without jQuery. Here is one of the challenges I'm facing.

I have a fixed contenteditable div that when adding text to the div, if the scrollHeight exceeds the clientHeight I shrink the font until content fits the div.

Occasionally I "rebuild" the text which replaces the innerHTML programmatically. Or the user can delete text which should reduce the scrollHeight, but in both cases, the scrollHeight remains the maximum value. I need some way to increase the font size to "fit" the div again. (that ideally isn't super expensive)

Example:

My clientHeight = 142, and the scrollHeight = 158. A loop reduces the font size, until scrollHeight is 142.
Then, the user deletes a line of text, but the scrollHeight is still 142, no change.

code to reduce/increase height:

```<code>    var textBox = document.getElementById('text');
    var current, min = 6, max = 14;
    current = textBox.style.fontSize.substr(0, textBox.style.fontSize.length - 2);
    current = parseInt(current);
    if (textBox.clientHeight < textBox.scrollHeight) {
        while (textBox.clientHeight < textBox.scrollHeight) {
            current--;
            if (current < min) break;
            textBox.style.fontSize = '' + current + 'pt';
        }
    } else if (textBox.clientHeight > textBox.scrollHeight) {
        while (textBox.clientHeight > textBox.scrollHeight) {
            current++;
            if (current > max) break;
            textBox.style.fontSize = '' + current + 'pt';
        }
    }
</code>```

html (incase it matters):

```<code><div id="text" contenteditable="true"></div>
</code>```

css (incase it matters):

```<code>#text {
    position: relative;
    border: 1px solid blue;
    top: 180px;
    left: 31px;
    width: 300px;
    height: 132px;
    padding: 5px;
    font-family: 'mplantin';
    font-size: 14pt;
    font-weight: 200;
}
</code>```

答:
both answers from @nixahn and @jeff are working for me (chrome,ff)</p>

```<code>iframe.style.height ="0"; // or "auto"
iframe.contentWindow.document.open();
iframe.contentWindow.document.write('<style>'+css+'</style>');
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
</code>```

Body:
I am trying to learn a few things without jQuery. Here is one of the challenges I'm facing.

I have a fixed contenteditable div that when adding text to the div, if the scrollHeight exceeds the clientHeight I shrink the font until content fits the div.

Occasionally I "rebuild" the text which replaces the innerHTML programmatically. Or the user can delete text which should reduce the scrollHeight, but in both cases, the scrollHeight remains the maximum value. I need some way to increase the font size to "fit" the div again. (that ideally isn't super expensive)

Example:

My clientHeight = 142, and the scrollHeight = 158. A loop reduces the font size, until scrollHeight is 142.
Then, the user deletes a line of text, but the scrollHeight is still 142, no change.

code to reduce/increase height:

    var textBox = document.getElementById('text');
    var current, min = 6, max = 14;
    current = textBox.style.fontSize.substr(0, textBox.style.fontSize.length - 2);
    current = parseInt(current);
    if (textBox.clientHeight < textBox.scrollHeight) {
        while (textBox.clientHeight < textBox.scrollHeight) {
            current--;
            if (current < min) break;
            textBox.style.fontSize = '' + current + 'pt';
        }
    } else if (textBox.clientHeight > textBox.scrollHeight) {
        while (textBox.clientHeight > textBox.scrollHeight) {
            current++;
            if (current > max) break;
            textBox.style.fontSize = '' + current + 'pt';
        }
    }

html (incase it matters):

css (incase it matters):

#text {
    position: relative;
    border: 1px solid blue;
    top: 180px;
    left: 31px;
    width: 300px;
    height: 132px;
    padding: 5px;
    font-family: 'mplantin';
    font-size: 14pt;
    font-weight: 200;
}

Body:
both answers from @nixahn and @jeff are working for me (chrome,ff)

iframe.style.height ="0"; // or "auto"
iframe.contentWindow.document.open();
iframe.contentWindow.document.write('<style>'+css+'</style>');
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();


问:
Changing the name of the method called dynamically in java
I have an object "JudgesSubmission" with the following methods:

```<code>public String getInnovationGrade1() {
    return innovationGrade1;
}
public String getInnovationGrade2() {
    return innovationGrade2;
}
public String getInnovationGrade3() {
    return innovationGrade3;
}
public String getInnovationGrade4() {
    return innovationGrade4;
}
</code>```

Now, when calling these methods, I want to put them in a loop where the called method name gets the index of the loop attached to its end changing the method called. Is this possible?
For example, the following code would never work, but I am writing it to explain what I need:

```<code>judgesSubmission metricScores= new judgesSubmission;
int metricSum=0;
for (int i=0;i<4;i++){
metricSum=metricSum
      Integer.parseInt(metricScores.getInnovationGrade+"i"());
}
</code>```

Is there a way to do that or do I always have the full method name written?

答:
What you want to do is not possible... but with reflection such as :

```<code>MyObject.class.getMethod("mymethod"+i);
</code>```

Without reflection you could use a Supplier<String> :

```<code>public void process(Supplier<String>... suppliers){

    judgesSubmission metricScores= new judgesSubmission;
    int metricSum=0;
    for (Supplier<String> supplier : suppliers){
          Integer.parseInt(supplier.get());
    }
}
</code>```

And call it such as :

```<code>MyObject myObject = new MyObject();
process(()->myObject.getInnovationGrade1(),
    ()->myObject.getInnovationGrade2(),
    ()->myObject.getInnovationGrade3(),
    ()->myObject.getInnovationGrade4());
</code>```

Body:
I have an object "JudgesSubmission" with the following methods:

public String getInnovationGrade1() {
    return innovationGrade1;
}
public String getInnovationGrade2() {
    return innovationGrade2;
}
public String getInnovationGrade3() {
    return innovationGrade3;
}
public String getInnovationGrade4() {
    return innovationGrade4;
}

Now, when calling these methods, I want to put them in a loop where the called method name gets the index of the loop attached to its end changing the method called. Is this possible?
For example, the following code would never work, but I am writing it to explain what I need:

judgesSubmission metricScores= new judgesSubmission;
int metricSum=0;
for (int i=0;i<4;i++){
metricSum=metricSum
      Integer.parseInt(metricScores.getInnovationGrade+"i"());
}

Is there a way to do that or do I always have the full method name written?

Body:
What you want to do is not possible... but with reflection such as :

MyObject.class.getMethod("mymethod"+i);

Without reflection you could use a Supplier<String> :

public void process(Supplier<String>... suppliers){

    judgesSubmission metricScores= new judgesSubmission;
    int metricSum=0;
    for (Supplier<String> supplier : suppliers){
          Integer.parseInt(supplier.get());
    }
}

And call it such as :

MyObject myObject = new MyObject();
process(()->myObject.getInnovationGrade1(),
    ()->myObject.getInnovationGrade2(),
    ()->myObject.getInnovationGrade3(),
    ()->myObject.getInnovationGrade4());


问:
Service identity incorrect when set with Service resource
I have a DSC configuration which includes this resource:

```<code>Service SQL {
    Name = 'SQLSERVERAGENT'
    StartupType = 'Manual'
    State = 'Running'
    Credential = $c
}
</code>```

When I run this configuration, the service identity is correct in services.msc but kerberos fails because the SPN is assigned to the new user and the service is still running under whatever the old identity is. When I restart the service, it functions correctly. I don't want to have to make a custom resource with a registry flag to mark it for no further resets, etc.

Can I use this resource to make my service restart only once in order to assume the correct identity?

答: I have written a script resource that restarts the service and then creates a registry key.</p>

Body:
I have a DSC configuration which includes this resource:

Service SQL {
    Name = 'SQLSERVERAGENT'
    StartupType = 'Manual'
    State = 'Running'
    Credential = $c
}

When I run this configuration, the service identity is correct in services.msc but kerberos fails because the SPN is assigned to the new user and the service is still running under whatever the old identity is. When I restart the service, it functions correctly. I don't want to have to make a custom resource with a registry flag to mark it for no further resets, etc.

Can I use this resource to make my service restart only once in order to assume the correct identity?


问:
Error in file(file, "rt") : cannot open the connection
I'm new to R,  and after researching this error extensively, I'm still not able to find a solution for it. Here's the code. I've checked my working directory, and made sure the files are in the right directory. Appreciate it. Thanks

```<code>pollutantmean <- function(directory, pollutant = "nitrate", id= 1:332)
{                 if(grep("specdata",directory) ==1)
            {
                    directory <- ("./specdata")
            }
            mean_polldata <- c()
            specdatafiles <- as.character(list.files(directory))
            specdatapaths <- paste(directory, specdatafiles, sep="")
                            for(i in id)
                    {
                    curr_file <- read.csv(specdatapaths[i], header=T, sep=",")
                    head(curr_file)
                    pollutant
                    remove_na <- curr_file[!is.na(curr_file[, pollutant]), pollutant]
                    mean_polldata <- c(mean_polldata, remove_na)
                    }
            {
                    mean_results <- mean(mean_polldata)
                    return(round(mean_results, 3))
            }
}
</code>```

The error I'm getting is below:

```<code>Error in file(file, "rt") : cannot open the connection

file(file, "rt")

read.table(file = file, header = header, sep = sep, quote = quote,
    dec = dec, fill = fill, comment.char = comment.char, ...)

read.csv(specdatapaths[i], header = T, sep = ",")

pollutantmean3("specdata", "sulfate", 1:10)

In addition: Warning message:
In file(file, "rt") :
  cannot open file './specdata001.csv': No such file or directory
</code>```

答: I got this same error message and fixed it in the easiest way I could.  I put my .csv file into a file folder on my desktop, opened desktop in the window next to console on RStudio, and then opened my file there, and checked the box next to my .csv file, then I used the "more" pull down menu at the top of this window to set this as my working directory...probably the easiest thing for SUPER beginners like me :)</p>

Body:
I'm new to R,  and after researching this error extensively, I'm still not able to find a solution for it. Here's the code. I've checked my working directory, and made sure the files are in the right directory. Appreciate it. Thanks

pollutantmean <- function(directory, pollutant = "nitrate", id= 1:332)
{                 if(grep("specdata",directory) ==1)
            {
                    directory <- ("./specdata")
            }
            mean_polldata <- c()
            specdatafiles <- as.character(list.files(directory))
            specdatapaths <- paste(directory, specdatafiles, sep="")
                            for(i in id)
                    {
                    curr_file <- read.csv(specdatapaths[i], header=T, sep=",")
                    head(curr_file)
                    pollutant
                    remove_na <- curr_file[!is.na(curr_file[, pollutant]), pollutant]
                    mean_polldata <- c(mean_polldata, remove_na)
                    }
            {
                    mean_results <- mean(mean_polldata)
                    return(round(mean_results, 3))
            }
}

The error I'm getting is below:

Error in file(file, "rt") : cannot open the connection

file(file, "rt")

read.table(file = file, header = header, sep = sep, quote = quote,
    dec = dec, fill = fill, comment.char = comment.char, ...)

read.csv(specdatapaths[i], header = T, sep = ",")

pollutantmean3("specdata", "sulfate", 1:10)

In addition: Warning message:
In file(file, "rt") :
  cannot open file './specdata001.csv': No such file or directory


问:
jQuery form validation check returns 'undefined'
I am having some trouble with a form I am trying to submit using jquery $.post, I am using this validation plugin to validate the form, but when I try to check the form with $("#form").validationEngine('validate') I constantly get undefined and then the page reloads, here is the code:

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

        $("#form").validationEngine();

        $("#submit").live('click',function(){
            var valid = $("#form").validationEngine('validate');
            var vars = $("#form").serialize();

            if(valid == true){

                //disable submit button
                $("#submit").attr('disabled','disabled');

                $.post('thank_you.php',vars,function(data){
                    alert(data);
                });

            }else{
                $("#form").validationEngine();
            }
        });
});
</code>```

the HTML:

```<code><form id="form">
    <div>
        <label for='province'>Select your current province </label>
        <select id='province' name='province' class='validate[required] text-input'>
            <option value=''>Select one</option>
            <option>province1</option>
            <option>province2</option>
        </select>
    </div>
    <br />
    <div>
        <label for="city">Select your current city</label><br />
        <select id="city" name="city" class="validate[required] text-input">
            <option value="">Select one</option>
            <option>city1</option>
            <option>city2</option>
        </select>
    </div>
    <br />
    <div>
        <label for="name_surname">Name & Surname</label><br />
        <input type="text" id="name_surname" name="name_surname" class="validate[required] text-input" />
    </div>
    <br />
    <div>
        <label for="email">Email Address</label><br />
        <input type="text" id="email" name="email" class="validate[required,custom[email]] text-input" />
    </div>
    <div>
        <input type="image" src="images/solar_38.gif" width="82" height="32" alt"submit" id="submit" />
    </div>
</form>
</code>```

I have had a look on the plugin's site, and have found nothing that could indicate why I am getting this, is there anything in my code that could be causing me to get undefined when I try to validate the form?

答:
Looking at the documentation I think the $("#form").validationEngine();  line is wrong - should it be

```<code>$("#form").validationEngine('attach');
</code>```

From the documentation:

Instantiation The validator is
  typically instantiated by using a call
  of the following form:

```<code>$("#form.id").validationEngine(action or options);
</code>```

The method takes one or
  several optional parameters, either an
  action (and parameters) or a list of
  options to customize the behavior of
  the engine.

Here comes a glimpse: say you have a
  form is this kind

The following code would instance the validation engine:

```<code> <script>
 $(document).ready(function(){
     $("#formID").validationEngine('attach');

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

Body:
I am having some trouble with a form I am trying to submit using jquery $.post, I am using this validation plugin to validate the form, but when I try to check the form with $("#form").validationEngine('validate') I constantly get undefined and then the page reloads, here is the code:

$(document).ready(function() {

        $("#form").validationEngine();

        $("#submit").live('click',function(){
            var valid = $("#form").validationEngine('validate');
            var vars = $("#form").serialize();

            if(valid == true){

                //disable submit button
                $("#submit").attr('disabled','disabled');

                $.post('thank_you.php',vars,function(data){
                    alert(data);
                });

            }else{
                $("#form").validationEngine();
            }
        });
});

the HTML:

<form id="form">

        Select your current province
        <select id='province' name='province' class='validate[required] text-input'>
            <option value=''>Select one</option>
            <option>province1</option>
            <option>province2</option>
        </select>

        Select your current city

        <select id="city" name="city" class="validate[required] text-input">
            <option value="">Select one</option>
            <option>city1</option>
            <option>city2</option>
        </select>

        Name & Surname

        <input type="text" id="name_surname" name="name_surname" class="validate[required] text-input" />

        Email Address

        <input type="text" id="email" name="email" class="validate[required,custom[email]] text-input" />

        <input type="image" src="images/solar_38.gif" width="82" height="32" alt"submit" id="submit" />

</form>

I have had a look on the plugin's site, and have found nothing that could indicate why I am getting this, is there anything in my code that could be causing me to get undefined when I try to validate the form?

Body:
Looking at the documentation I think the $("#form").validationEngine();  line is wrong - should it be

$("#form").validationEngine('attach');

From the documentation:

Instantiation The validator is
  typically instantiated by using a call
  of the following form:

$("#form.id").validationEngine(action or options);

The method takes one or
  several optional parameters, either an
  action (and parameters) or a list of
  options to customize the behavior of
  the engine.

Here comes a glimpse: say you have a
  form is this kind

The following code would instance the validation engine:

 <script>
 $(document).ready(function(){
     $("#formID").validationEngine('attach');

    });
 </script>


问:
Fetch event not receiving request headers
It seems that fetch event inside service worker isn't receiving request headers, although it is stated in MDN documentation:

You can retrieve a lot of information about each request by calling parameters of the Request object returned by the FetchEvent:

event.request.url

  event.request.method

  event.request.headers

  event.request.body

Code for fetching resource from main thread:

```<code>fetch(`${companyConfig.base}ticket-scanner/config`, {
    headers: {
        'X-Nsft-Locale' : `en`,
        'X-Nsft-Id': `1`,
    },
}).then((response) => {
    return response.json();
}).then((data) => {...})
</code>```

Fetch event handler inside SW file:

```<code>self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request, {cacheName : CACHE_NAME})
        .then(function(response) {
            if(response) {
                return response;
            }
            console.log(event.request.headers); //Log out headers
            return fetch(event.request).then(function(response){
                return response;
            }).catch(function(err){
                console.error(err);
            })
        })
    )
});
</code>```

Logging headers for every fetch event gives me empty object:

Headers {}

This is preventing me to cache this specific request which requires only these two headers. Credentials aren't required. Am I missing something?

答:
The Headers interface is iterable, supports a .get() accessor, and a .has() existence check.

You could take advantage of any of that to read the values you care about.

const request = new Request('https://example.com', {
  headers: {
    'x-header-1': 'header 1 value',
    'x-header-2': 'header 2 value',
  }
});

for (const [header, value] of request.headers) {
  console.log(`${header}: ${value} (via iterator)`);
}

console.log(`'x-header-1' is ${request.headers.get('x-header-1')}`);

console.log(`'x-header-2' ${request.headers.has('x-header-2') ? 'exists' : 'does not exist'}`);```

Body:
It seems that fetch event inside service worker isn't receiving request headers, although it is stated in MDN documentation:

You can retrieve a lot of information about each request by calling parameters of the Request object returned by the FetchEvent:

event.request.url

  event.request.method

  event.request.headers

  event.request.body

Code for fetching resource from main thread:

fetch(`${companyConfig.base}ticket-scanner/config`, {
    headers: {
        'X-Nsft-Locale' : `en`,
        'X-Nsft-Id': `1`,
    },
}).then((response) => {
    return response.json();
}).then((data) => {...})

Fetch event handler inside SW file:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request, {cacheName : CACHE_NAME})
        .then(function(response) {
            if(response) {
                return response;
            }
            console.log(event.request.headers); //Log out headers
            return fetch(event.request).then(function(response){
                return response;
            }).catch(function(err){
                console.error(err);
            })
        })
    )
});

Logging headers for every fetch event gives me empty object:

Headers {}

This is preventing me to cache this specific request which requires only these two headers. Credentials aren't required. Am I missing something?