问:
Cocoa binding to single object from an array
I previously posted this question as a comment on a related thread thinking it was simple.  That thread is here:

Cocoa binding to a particular item in an array controller

The questions relates to (and I'll more fully describe it here) a game I'm building to try and learn objective-c and cocoa. Its good enough to think of it like texas hold-em poker.  One server holds the game information and manages input from a variable number of clients (always more than one). Through cocoa bindings, it displays to each player the public information of the game which is stored in an array on the server using an array controller in IB.  Think of the five cards on the table being stored in an NSArray on the server and bound to the content field of an NSArrayController for each client.

This part works fine, like a charm.  However, each player has two cards that he needs to keep private.  Each client should display a different card depending on what was dealt to that particular player.  (Because what is really happening is I'm binding to an array of player objects

```<code>NSArray * thePlayers,
</code>```

imagine all the cards being stored on the same array).  So my question is, how do I set up bindings to a single object out of the array controller (or do I need some other controller)?  That is, how to I bind to one player of thePlayers array?'

答:
Very similar to Nick Moore's solution:

If you do want to bind to specific array indices, you could create a wrapper object. Something like this. It lets you bind to item0, item1 and so on. There is no range checking and it breaks if you change the size of the array, but you get the idea.

Interface

```<code>@interface MyArrayBinder : NSObject
@property NSMutableArray *array;
- (id)initWithMutableArray:(NSMutableArray *)theArray;
@end
</code>```

Implementation

```<code>static NSInteger _indexFromString(NSString *key) {
    return [[key stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]] integerValue];
}

@implementation MyArrayBinder

- (id)initWithMutableArray:(NSMutableArray *)theArray {
    if ( self=[super init] ) {
        _array=theArray;
    }
    return self;
}

- (id)valueForUndefinedKey:(NSString *)key {
    return _array[_indexFromString( key )];
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    _array[_indexFromString( key )] = value;
}

@end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I previously posted this question as a comment on a related thread thinking it was simple.  That thread is here:

Cocoa binding to a particular item in an array controller

The questions relates to (and I'll more fully describe it here) a game I'm building to try and learn objective-c and cocoa. Its good enough to think of it like texas hold-em poker.  One server holds the game information and manages input from a variable number of clients (always more than one). Through cocoa bindings, it displays to each player the public information of the game which is stored in an array on the server using an array controller in IB.  Think of the five cards on the table being stored in an NSArray on the server and bound to the content field of an NSArrayController for each client.

This part works fine, like a charm.  However, each player has two cards that he needs to keep private.  Each client should display a different card depending on what was dealt to that particular player.  (Because what is really happening is I'm binding to an array of player objects

NSArray * thePlayers,

imagine all the cards being stored on the same array).  So my question is, how do I set up bindings to a single object out of the array controller (or do I need some other controller)?  That is, how to I bind to one player of thePlayers array?'

Body:
Very similar to Nick Moore's solution:

If you do want to bind to specific array indices, you could create a wrapper object. Something like this. It lets you bind to item0, item1 and so on. There is no range checking and it breaks if you change the size of the array, but you get the idea.

Interface

@interface MyArrayBinder : NSObject
@property NSMutableArray *array;
- (id)initWithMutableArray:(NSMutableArray *)theArray;
@end

Implementation

static NSInteger _indexFromString(NSString *key) {
    return [[key stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]] integerValue];
}

@implementation MyArrayBinder

- (id)initWithMutableArray:(NSMutableArray *)theArray {
    if ( self=[super init] ) {
        _array=theArray;
    }
    return self;
}

- (id)valueForUndefinedKey:(NSString *)key {
    return _array[_indexFromString( key )];
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    _array[_indexFromString( key )] = value;
}

@end


来源: stackexchange

问:
I am having overflow problems when I used bootstrap
I coded a law firm website template and I made use of bootstrap but there is this vast space on the right when I finished. There’s a scroll bar which allows scrolling to the left and I can’t seemed to get rid of it. Below is the a link to the site. I would really appreciate if anyone could help me. I actually coded the site all over again but still couldn’t get what was wrong

http://warisandsons.ultihost.net/![enter image description here](https://i.stack.imgur.com/yefvj.jpg)

答:
I added the code below and it works

```<code>html, body{
    Width: 100%
    Margin: 0;
    Padding: 0;
    overflow-x: hidden
}
</code>```

Thanks to everyone

ContentLicense: CC BY-SA 4.0

Body:
I added the code below and it works

html, body{
    Width: 100%
    Margin: 0;
    Padding: 0;
    overflow-x: hidden
}

Thanks to everyone


问:
How can I plot these 3 functions within the range(-4,4) with 0.01 stepsize?
function[]=PieceWise1(x)

```<code>if x<=0 then
    root=sqrt(4-(x+2)^2)
    y1=2+root
    disp(y1)
elseif x>0
    y1=-0.5*x
    disp(y1)
end
</code>```

endfunction

function[]=PieceWise2(x)

```<code>if x<=0 then
    root=sqrt(4-(x+2)^2)
    y2=2-root
    disp(y2)
elseif x>0
    y2=0.5*x-4
    disp(y2)
end
</code>```

endfunction

function[]=PieceWise3(x)

```<code>if x<-0.12 then
    y3=-4-(x^-1)/2
    disp(y3)
elseif x>=0
    z=x-2*int(x/2)
    y3=4*(1-z)^2
    disp(y3)
else
    disp(0)
end
</code>```

endfunction

答:
```<code>function r = PieceWise1(x)
    r = -0.5*x
    s = x<=0
    if or(s), r(s) = 2 + sqrt(4-(x(s)+2).^2), end // .^ instead of ^
endfunction

function r = PieceWise2(x)
    r = 0.5*x - 4
    s = x<=0
    if or(s), r(s) = 2 - sqrt(4-(x(s)+2).^2), end
endfunction

function r = PieceWise3(x)
    r = zeros(x)
    s = x<-0.12
    if or(s), r(s) = -4 - 1./x(s)/2, end  // ./ instead of /
    s = x>=0
    if or(s), r(s) = 4*(1- x(s) + 2*int(x(s)/2)).^2, end
endfunction

x = (-4:0.01:4)';
clf
plot(x,PieceWise1, x,PieceWise2, x,PieceWise3)
</code>```

Body:
function[]=PieceWise1(x)

if x<=0 then
    root=sqrt(4-(x+2)^2)
    y1=2+root
    disp(y1)
elseif x>0
    y1=-0.5*x
    disp(y1)
end

endfunction

function[]=PieceWise2(x)

if x<=0 then
    root=sqrt(4-(x+2)^2)
    y2=2-root
    disp(y2)
elseif x>0
    y2=0.5*x-4
    disp(y2)
end

endfunction

function[]=PieceWise3(x)

if x<-0.12 then
    y3=-4-(x^-1)/2
    disp(y3)
elseif x>=0
    z=x-2*int(x/2)
    y3=4*(1-z)^2
    disp(y3)
else
    disp(0)
end

endfunction


问:
How to traverse a trie to display all the words?
Here's my declaration of a trie in C++ using unordered_map

```<code>class trie{
    public:
    unordered_map<char,trie*>m;
    bool isEnd;
};
</code>```

Here's my insert function(part of another class)

```<code> trie *root=nullptr;
    trie *getNode()
    {
        trie *tmp=new trie();
        tmp->isEnd=false;
        return tmp;
    }
    void insert(string s)
    {
        if(!root)
            root=getNode();
    trie *tmp=root;
    for(int i=0;i<s.length();i++)
    {
        if(tmp->m.find(s[i])==tmp->m.end())
            tmp->m[s[i]]=getNode();
        tmp=tmp->m[s[i]];
    }
    tmp->isEnd=true;
    }
</code>```

How to traverse this trie recursively or iteratively to display all the words.

答:
```<code>void iterate_(const trie* node, const std::string& prefix) {
  if (node->isEnd) {
    std::cout << prefix << std::endl;
  }
  for (const auto& [c, child] : node->m) {
    iterate_(child, prefix + c);
  }
}

void iterate() {
  if (root) {
    iterate_(root, "");
  }
}
</code>```

Body:
Here's my declaration of a trie in C++ using unordered_map

class trie{
    public:
    unordered_map<char,trie*>m;
    bool isEnd;
};

Here's my insert function(part of another class)

 trie *root=nullptr;
    trie *getNode()
    {
        trie *tmp=new trie();
        tmp->isEnd=false;
        return tmp;
    }
    void insert(string s)
    {
        if(!root)
            root=getNode();
    trie *tmp=root;
    for(int i=0;i<s.length();i++)
    {
        if(tmp->m.find(s[i])==tmp->m.end())
            tmp->m[s[i]]=getNode();
        tmp=tmp->m[s[i]];
    }
    tmp->isEnd=true;
    }

How to traverse this trie recursively or iteratively to display all the words.


问:
#define getting cleared between file loads?
I'm working on some open source code; I have a configure.ac, in which I've added the following:

```<code>: ${FFT_MODE=1}
AC_ARG_VAR([FFT_MODE], [1 for fftw3, 2 for kiss_fft])
AC_DEFINE_UNQUOTED([FFTMODE], [$FFT_MODE],
                   [1 for fftw3, 2 for kiss_fft])
</code>```

The idea is that (after calling autoconf --install), the user can run e.g. ./configure FFT_MODE=2 to switch modes.  Now, I thought it was working - the status check at the end of the configuration file output the correct value, and an if/elif/endif in my code showed the correct block was executing.  However - at some point I added an else, and discovered that both the if AND else blocks were running.  First I thought my compiler was possessed, then I realized the file was getting loaded twice, and the second time, for some reason, FFTMODE is unset (or set to zero or something).  I don't understand how, though.  FTR, the check is in a file fsk.h, like so:

#warning before
#if(FFTMODE == 1)
#warning FFTMODE 1
#include <fftw3.h>
#elif(FFTMODE == 2)
#warning FFTMODE 2
#include <kiss_fftr.h>
#else
#warning FFTMODE ???
#error Unsupported FFTMODE
#endif
#warning after
```
<p>The output of <code>make</code> is as follows:</p>
```make  all-recursive
make[1]: Entering directory '/home/erhannis/mods/minimodem'
Making all in src
make[2]: Entering directory '/home/erhannis/mods/minimodem/src'
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT minimodem.o -MD -MP -MF .deps/minimodem.Tpo -c -o minimodem.o minimodem.c
In file included from minimodem.c:43:
fsk.h:20:2: warning: #warning before [-Wcpp]
   20 | #warning before
      |  ^~~~~~~
fsk.h:22:2: warning: #warning FFTMODE 1 [-Wcpp]
   22 | #warning FFTMODE 1
      |  ^~~~~~~
In file included from minimodem.c:43:
fsk.h:31:2: warning: #warning after [-Wcpp]
   31 | #warning after
      |  ^~~~~~~
mv -f .deps/minimodem.Tpo .deps/minimodem.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_ascii.o -MD -MP -MF .deps/databits_ascii.Tpo -c -o databits_ascii.o databits_ascii.c
mv -f .deps/databits_ascii.Tpo .deps/databits_ascii.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_binary.o -MD -MP -MF .deps/databits_binary.Tpo -c -o databits_binary.o databits_binary.c
mv -f .deps/databits_binary.Tpo .deps/databits_binary.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_callerid.o -MD -MP -MF .deps/databits_callerid.Tpo -c -o databits_callerid.o databits_callerid.c
mv -f .deps/databits_callerid.Tpo .deps/databits_callerid.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_baudot.o -MD -MP -MF .deps/databits_baudot.Tpo -c -o databits_baudot.o databits_baudot.c
mv -f .deps/databits_baudot.Tpo .deps/databits_baudot.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT baudot.o -MD -MP -MF .deps/baudot.Tpo -c -o baudot.o baudot.c
mv -f .deps/baudot.Tpo .deps/baudot.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_uic.o -MD -MP -MF .deps/databits_uic.Tpo -c -o databits_uic.o databits_uic.c
mv -f .deps/databits_uic.Tpo .deps/databits_uic.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT uic_codes.o -MD -MP -MF .deps/uic_codes.Tpo -c -o uic_codes.o uic_codes.c
mv -f .deps/uic_codes.Tpo .deps/uic_codes.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT fsk.o -MD -MP -MF .deps/fsk.Tpo -c -o fsk.o fsk.c
In file included from fsk.c:30:
fsk.h:20:2: warning: #warning before [-Wcpp]
   20 | #warning before
      |  ^~~~~~~
fsk.h:28:2: warning: #warning FFTMODE ??? [-Wcpp]
   28 | #warning FFTMODE ???
      |  ^~~~~~~
fsk.h:29:2: error: #error Unsupported FFTMODE
   29 | #error Unsupported FFTMODE
      |  ^~~~~
fsk.h:31:2: warning: #warning after [-Wcpp]
   31 | #warning after
      |  ^~~~~~~
fsk.c: In function ‘fsk_bit_analyze’:
fsk.c:200:10: error: ‘mag_mark’ undeclared (first use in this function)
  200 |     if ( mag_mark > mag_space ) {
      |          ^~~~~~~~
fsk.c:200:10: note: each undeclared identifier is reported only once for each function it appears in
fsk.c:200:21: error: ‘mag_space’ undeclared (first use in this function)
  200 |     if ( mag_mark > mag_space ) {
      |                     ^~~~~~~~~
fsk.c:166:11: warning: unused variable ‘magscalar’ [-Wunused-variable]
  166 |     float magscalar = 2.0f / (float)bit_nsamples;
      |           ^~~~~~~~~
fsk.c: In function ‘fsk_detect_carrier’:
fsk.c:628:1: warning: control reaches end of non-void function [-Wreturn-type]
  628 | }
      | ^
make[2]: *** [Makefile:470: fsk.o] Error 1
make[2]: Leaving directory '/home/erhannis/mods/minimodem/src'
make[1]: *** [Makefile:361: all-recursive] Error 1
make[1]: Leaving directory '/home/erhannis/mods/minimodem'
make: *** [Makefile:302: all] Error 2
```

So, what's going on?  There IS one instance of #undef FFTMODE in config.h.in - but while I can guess that file's for cleaning up after the build is done, the build isn't done yet, so why's it cleaning up the definitions I'm still using?

The source code is at https://github.com/erhannis/minimodem/tree/feature/alternate_fft; the relevant file is src/fsk.h.

答:
I think you're confusing yourself with this idea that the file is getting loaded twice.  That doesn't seem to be the case, from the output you show.

Instead, the file is getting loaded one time each, in two different compile commands.  Once when compiling minimodem.c and once when compiling fsk.c.  Those are totally different compile operations.

In minimodem.c, the value of FFTMODE is 1.  In fsk.c, FFTMODE is unset.

This is easily explained: in minimodem.c you #include "config.h" before you #include "fsk.h", and so when fsk.h is parsed you have a value for FFTMODE.  In fsk.c you don't #include "config.h", so there is no value for FFTMODE.

If your fsk.h file needs values from config.h, then it may be best to #include "config.h" in fsk.h.  If you don't want to do that you need to make sure it's included by all the .c files, before fsk.h.

Body:
I'm working on some open source code; I have a configure.ac, in which I've added the following:

: ${FFT_MODE=1}
AC_ARG_VAR([FFT_MODE], [1 for fftw3, 2 for kiss_fft])
AC_DEFINE_UNQUOTED([FFTMODE], [$FFT_MODE],
                   [1 for fftw3, 2 for kiss_fft])

The idea is that (after calling autoconf --install), the user can run e.g. ./configure FFT_MODE=2 to switch modes.  Now, I thought it was working - the status check at the end of the configuration file output the correct value, and an if/elif/endif in my code showed the correct block was executing.  However - at some point I added an else, and discovered that both the if AND else blocks were running.  First I thought my compiler was possessed, then I realized the file was getting loaded twice, and the second time, for some reason, FFTMODE is unset (or set to zero or something).  I don't understand how, though.  FTR, the check is in a file fsk.h, like so:

#warning before
#if(FFTMODE == 1)
#warning FFTMODE 1
#include <fftw3.h>
#elif(FFTMODE == 2)
#warning FFTMODE 2
#include <kiss_fftr.h>
#else
#warning FFTMODE ???
#error Unsupported FFTMODE
#endif
#warning after

The output of make is as follows:

make  all-recursive
make[1]: Entering directory '/home/erhannis/mods/minimodem'
Making all in src
make[2]: Entering directory '/home/erhannis/mods/minimodem/src'
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT minimodem.o -MD -MP -MF .deps/minimodem.Tpo -c -o minimodem.o minimodem.c
In file included from minimodem.c:43:
fsk.h:20:2: warning: #warning before [-Wcpp]
   20 | #warning before
      |  ^~~~~~~
fsk.h:22:2: warning: #warning FFTMODE 1 [-Wcpp]
   22 | #warning FFTMODE 1
      |  ^~~~~~~
In file included from minimodem.c:43:
fsk.h:31:2: warning: #warning after [-Wcpp]
   31 | #warning after
      |  ^~~~~~~
mv -f .deps/minimodem.Tpo .deps/minimodem.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_ascii.o -MD -MP -MF .deps/databits_ascii.Tpo -c -o databits_ascii.o databits_ascii.c
mv -f .deps/databits_ascii.Tpo .deps/databits_ascii.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_binary.o -MD -MP -MF .deps/databits_binary.Tpo -c -o databits_binary.o databits_binary.c
mv -f .deps/databits_binary.Tpo .deps/databits_binary.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_callerid.o -MD -MP -MF .deps/databits_callerid.Tpo -c -o databits_callerid.o databits_callerid.c
mv -f .deps/databits_callerid.Tpo .deps/databits_callerid.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_baudot.o -MD -MP -MF .deps/databits_baudot.Tpo -c -o databits_baudot.o databits_baudot.c
mv -f .deps/databits_baudot.Tpo .deps/databits_baudot.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT baudot.o -MD -MP -MF .deps/baudot.Tpo -c -o baudot.o baudot.c
mv -f .deps/baudot.Tpo .deps/baudot.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT databits_uic.o -MD -MP -MF .deps/databits_uic.Tpo -c -o databits_uic.o databits_uic.c
mv -f .deps/databits_uic.Tpo .deps/databits_uic.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT uic_codes.o -MD -MP -MF .deps/uic_codes.Tpo -c -o uic_codes.o uic_codes.c
mv -f .deps/uic_codes.Tpo .deps/uic_codes.Po
gcc -DHAVE_CONFIG_H -I. -I..  -D_REENTRANT  -Wall  -g -O2 -MT fsk.o -MD -MP -MF .deps/fsk.Tpo -c -o fsk.o fsk.c
In file included from fsk.c:30:
fsk.h:20:2: warning: #warning before [-Wcpp]
   20 | #warning before
      |  ^~~~~~~
fsk.h:28:2: warning: #warning FFTMODE ??? [-Wcpp]
   28 | #warning FFTMODE ???
      |  ^~~~~~~
fsk.h:29:2: error: #error Unsupported FFTMODE
   29 | #error Unsupported FFTMODE
      |  ^~~~~
fsk.h:31:2: warning: #warning after [-Wcpp]
   31 | #warning after
      |  ^~~~~~~
fsk.c: In function ‘fsk_bit_analyze’:
fsk.c:200:10: error: ‘mag_mark’ undeclared (first use in this function)
  200 |     if ( mag_mark > mag_space ) {
      |          ^~~~~~~~
fsk.c:200:10: note: each undeclared identifier is reported only once for each function it appears in
fsk.c:200:21: error: ‘mag_space’ undeclared (first use in this function)
  200 |     if ( mag_mark > mag_space ) {
      |                     ^~~~~~~~~
fsk.c:166:11: warning: unused variable ‘magscalar’ [-Wunused-variable]
  166 |     float magscalar = 2.0f / (float)bit_nsamples;
      |           ^~~~~~~~~
fsk.c: In function ‘fsk_detect_carrier’:
fsk.c:628:1: warning: control reaches end of non-void function [-Wreturn-type]
  628 | }
      | ^
make[2]: *** [Makefile:470: fsk.o] Error 1
make[2]: Leaving directory '/home/erhannis/mods/minimodem/src'
make[1]: *** [Makefile:361: all-recursive] Error 1
make[1]: Leaving directory '/home/erhannis/mods/minimodem'
make: *** [Makefile:302: all] Error 2

So, what's going on?  There IS one instance of #undef FFTMODE in config.h.in - but while I can guess that file's for cleaning up after the build is done, the build isn't done yet, so why's it cleaning up the definitions I'm still using?

The source code is at https://github.com/erhannis/minimodem/tree/feature/alternate_fft; the relevant file is src/fsk.h.


问:
How to solve "The process has been signaled with signal 11" - Snappy Library?
I am using a Snappy PDF library in Laravel 5.7. Locally it works everything fine, but in my dev environment I get this error: The process has been signaled with signal "11". Till now I was not able to find a solution that would help me. This is my code in controller:

```<code>   public function pdfReport(Request $request){
    $pdf = \Snappy::loadView('index', compact(
                  'name', 'lname', 'date', 'address'
                  ))
                  ->setOrientation('portrait')
                  ->setOption('margin-bottom', 0)
                  ->setOption('margin-top', 0)
                  ->setOption('margin-left', 0)
                  ->setOption('margin-right', 0);
     return $pdf->download(str_replace(' ', '', $request->description) . Carbon::now()->format('dYm_His') . '.pdf');
  }
</code>```

Any help is appreciated!!!

答:
I solved it through composer.
In my case its seemed to be coming from Symfony\process\process.php:441,

```<code>    do {
        $this->checkTimeout();
        $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
        $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
    } while ($running);

    while ($this->isRunning()) {
        $this->checkTimeout();
        usleep(1000);
    }
</code>```

I followed every step but nothing worked. But after running
"composer require h4cc/wkhtmltopdf-amd64" and "composer require barryvdh/laravel-snappy" I replaced the vendor directory on the server.

Body:
I am using a Snappy PDF library in Laravel 5.7. Locally it works everything fine, but in my dev environment I get this error: The process has been signaled with signal "11". Till now I was not able to find a solution that would help me. This is my code in controller:

   public function pdfReport(Request $request){
    $pdf = \Snappy::loadView('index', compact(
                  'name', 'lname', 'date', 'address'
                  ))
                  ->setOrientation('portrait')
                  ->setOption('margin-bottom', 0)
                  ->setOption('margin-top', 0)
                  ->setOption('margin-left', 0)
                  ->setOption('margin-right', 0);
     return $pdf->download(str_replace(' ', '', $request->description) . Carbon::now()->format('dYm_His') . '.pdf');
  }

Any help is appreciated!!!

Body:
I solved it through composer.
In my case its seemed to be coming from Symfony\process\process.php:441,

    do {
        $this->checkTimeout();
        $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
        $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
    } while ($running);

    while ($this->isRunning()) {
        $this->checkTimeout();
        usleep(1000);
    }

I followed every step but nothing worked. But after running
"composer require h4cc/wkhtmltopdf-amd64" and "composer require barryvdh/laravel-snappy" I replaced the vendor directory on the server.


问:
Global Objects accessible throughout Android application
I have an application that uses a custom class. When the app is started I populate an instance of this class in the main activity with all the data it will hold.

Basic data is then shown in a ListView from which you can select a ListView item to see further information displayed in another Activity.

Currently, I am having to pass the data that is relevant to the new Activity to it by using:

```<code>intent.putExtra("NAME", value);
</code>```

I want to implement a ViewPager so the user can easily switch between ListView items. Therefore the currently use method isn't very good as I only have the data for one entry at a time and would need to get back to the original Activity to get all the data again.

Is there a way to have my class objects globally available ANYWHERE in my application? I feel my applications code is getting bloated as I am overcoming these issues in bad code methods.

I've just looked into using:

```<code>MyApp myapp = ((MyApp)context.getApplication());
</code>```

but this won't work unless I can pass the context around, which I'm not sure how to do??

In C# you'd create a static class that could handle this....

Thanks
Neil

答:
You could have:

a static class holding your data (available until the process is killed)

a local service offering access to your data

the application class holding your data

a database mechanism to persist your data (in that case you'd simply pass IDs as intent extra)

All those options are more or less valid, it also depends on what you do with your data, where it comes from, ...

ContentLicense: CC BY-SA 3.0

Body:
I have an application that uses a custom class. When the app is started I populate an instance of this class in the main activity with all the data it will hold.

Basic data is then shown in a ListView from which you can select a ListView item to see further information displayed in another Activity.

Currently, I am having to pass the data that is relevant to the new Activity to it by using:

intent.putExtra("NAME", value);

I want to implement a ViewPager so the user can easily switch between ListView items. Therefore the currently use method isn't very good as I only have the data for one entry at a time and would need to get back to the original Activity to get all the data again.

Is there a way to have my class objects globally available ANYWHERE in my application? I feel my applications code is getting bloated as I am overcoming these issues in bad code methods.

I've just looked into using:

MyApp myapp = ((MyApp)context.getApplication());

but this won't work unless I can pass the context around, which I'm not sure how to do??

In C# you'd create a static class that could handle this....

Thanks
Neil


问:
Binary Gap Program in Java
My problem statement:

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

My code:

```<code>public class Abc {

    static void decToBinary(int n) {

        int[] binaryNum = new int[1000];

        // counter for binary array
        int i = 0;
        while (n > 0) {
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
        int ctr = 0, k = 0;
        ArrayList<Integer> al = new ArrayList<Integer>();

        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--) {
            System.out.print(binaryNum[j]);
            if (binaryNum[j] == 0) {
                k = j;
                do {
                    ctr++;
                    k++;
                } while (binaryNum[k] == 0);
                al.add(ctr);
                ctr = 0;
            }
        }

        for (int ii = 0; ii < al.size(); ii++) {
            System.out.println(al.get(ii));
        }
    }

    // driver program
    public static void main(String[] args) {
        int n = 1041;
        decToBinary(n);
    }
}
</code>```

I am trying to show the output of binary gap that is stored in my ArrayList.  But the output is quite different for a given input of 1041. I  don't know why it is storing 1,2,3,4; according to my logic it should store only the gap values 5 and 3 in case of input:1041, even though 5 and 3 are also stored in the ArrayList but at some other index.

I think there is a problem in the do-while loop especially in al.add(ctr) but I haven't figured it out yet.

答:
The following code gives the 100% solution for the same problem in javascript. Also I have added console logs which show the flow and results before returning.
This problem is to return the maximum binary gap of 0's from a binary number which we obtain from decimal numbers.
Flow:

function that converts given decimal into binary equivalent number and store each value of binary into an array. then return the same array.

function to evaluate the number of gaps of 0's in the returned array.

check the maximum gap, if available then return the max number. Else return 0;

// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

function solution(N) {
    // write your code in JavaScript (Node.js 8.9.4)
    const aBi = returnBinary(N);
    var gaps = [];
    var flag = false;
    var counter = null;
    for(var digit in aBi){

        let nexdigit= parseInt(digit) + 1;
        if(aBi[digit]===1 && aBi[nexdigit] === 0 ){
            flag = true;counter=0;
        }
        if(flag === true){
            counter +=1;
          }
        if(aBi[digit]===0 && aBi[nexdigit] === 1 ){
            counter-=1;
            gaps.push(counter);
              counter = null;
        }
    }
    let max;
    if(gaps[0]!== undefined){
     max = gaps[0];
    }
    else {
    console.log(0);
         return 0;
         }
for(var i = 1; i < gaps.length;i++){
 if(max < gaps[i] ){ max = gaps[i] }
}
console.log(max);
return max;
}

function returnBinary(nDeccimal){
 var aBinary = [];
if(nDeccimal > 0){
// this will return a binary sequence of numbers of given number and will return as a string.
while(nDeccimal >= 1){
let remainder = nDeccimal % 2;
aBinary.unshift(remainder);
nDeccimal = parseInt(nDeccimal / 2);
}
}
console.log(aBinary.join(""));
return aBinary;
}
console.log("#####Test One ######");
solution(24);
console.log("######Test Two #####");
solution(98);```

Title: Binary Gap Program in Java

Body:
My problem statement:

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

My code:

public class Abc {

    static void decToBinary(int n) {

        int[] binaryNum = new int[1000];

        // counter for binary array
        int i = 0;
        while (n > 0) {
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
        int ctr = 0, k = 0;
        ArrayList<Integer> al = new ArrayList<Integer>();

        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--) {
            System.out.print(binaryNum[j]);
            if (binaryNum[j] == 0) {
                k = j;
                do {
                    ctr++;
                    k++;
                } while (binaryNum[k] == 0);
                al.add(ctr);
                ctr = 0;
            }
        }

        for (int ii = 0; ii < al.size(); ii++) {
            System.out.println(al.get(ii));
        }
    }

    // driver program
    public static void main(String[] args) {
        int n = 1041;
        decToBinary(n);
    }
}

I am trying to show the output of binary gap that is stored in my ArrayList.  But the output is quite different for a given input of 1041. I  don't know why it is storing 1,2,3,4; according to my logic it should store only the gap values 5 and 3 in case of input:1041, even though 5 and 3 are also stored in the ArrayList but at some other index.

I think there is a problem in the do-while loop especially in al.add(ctr) but I haven't figured it out yet.


问:
Read a base 64 encoded image from memory using OpenCv python library
I'm working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri's of the canvas and want to use it to do something like this:

```<code>cv2.imshow('image',img)
</code>```

The data URI looks something like this:

```<code> data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7
</code>```

So, for clarity I've shown what the image looks like so the base64 string is not broken.

```
</div>
</div>
</p>

<p>The official doc says, that <code>imread</code> accepts a file path as the argument. From this SO answer, if I do something like:</p>

``` import base64
 imgdata = base64.b64decode(imgstring) #I use imgdata as this variable itself in references below
 filename = 'some_image.jpg'
 with open(filename, 'wb') as f:
    f.write(imgdata)
```

<p>The above code snippet works and the image file gets generated properly. However I don't think so many File IO operations are feasible considering I'd be doing this for every frame of the stream. I want to be able to read the image into the memory directly creating the <code>img</code> object.</p>

<p>I have tried two solutions that seem to be working for some people.</p>

<ol>
<li><p>Using PIL reference:</p>

```pilImage = Image.open(StringIO(imgdata))
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)
```

<p>I get <code>cv</code> not defined as I have openCV3 installed which is available to me as <code>cv2</code> module. I tried <code>img = cv2.imdecode(npImage,0)</code>, this returns nothing.</p></li>
<li><p>Getting the bytes from decoded string and converting it into an numpy array of sorts</p>

```file_bytes = numpy.asarray(bytearray(imgdata), dtype=numpy.uint8)
img = cv2.imdecode(file_bytes, 0) #Here as well I get returned nothing
```

The documentation doesn't really mention what the imdecode function returns. However, from the errors that I encountered, I guess it is expecting a numpy array or a scalar as the first argument. How do I get a handle on that image in memory so that I can do cv2.imshow('image',img) and all kinds of cool stuff thereafter.

I hope I was able to make myself clear.

答:
I found this simple solution.

```<code>import cv2
import numpy as np
import base64
image = ""  # raw data with base64 encoding
decoded_data = base64.b64decode(image)
np_data = np.fromstring(decoded_data,np.uint8)
img = cv2.imdecode(np_data,cv2.IMREAD_UNCHANGED)
cv2.imshow("test", img)
cv2.waitKey(0)
</code>```

Source : https://gist.github.com/HoweChen/7cdd09b08147133d8e1fbe9b52c24768

Body:
I'm working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri's of the canvas and want to use it to do something like this:

cv2.imshow('image',img)

The data URI looks something like this:

 data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7

So, for clarity I've shown what the image looks like so the base64 string is not broken.

The official doc says, that imread accepts a file path as the argument. From this SO answer, if I do something like:

 import base64
 imgdata = base64.b64decode(imgstring) #I use imgdata as this variable itself in references below
 filename = 'some_image.jpg'
 with open(filename, 'wb') as f:
    f.write(imgdata)

The above code snippet works and the image file gets generated properly. However I don't think so many File IO operations are feasible considering I'd be doing this for every frame of the stream. I want to be able to read the image into the memory directly creating the img object.

I have tried two solutions that seem to be working for some people.

Using PIL reference:

pilImage = Image.open(StringIO(imgdata))
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)

I get cv not defined as I have openCV3 installed which is available to me as cv2 module. I tried img = cv2.imdecode(npImage,0), this returns nothing.

Getting the bytes from decoded string and converting it into an numpy array of sorts

file_bytes = numpy.asarray(bytearray(imgdata), dtype=numpy.uint8)
img = cv2.imdecode(file_bytes, 0) #Here as well I get returned nothing

The documentation doesn't really mention what the imdecode function returns. However, from the errors that I encountered, I guess it is expecting a numpy array or a scalar as the first argument. How do I get a handle on that image in memory so that I can do cv2.imshow('image',img) and all kinds of cool stuff thereafter.

I hope I was able to make myself clear.

Body:
I found this simple solution.

import cv2
import numpy as np
import base64
image = ""  # raw data with base64 encoding
decoded_data = base64.b64decode(image)
np_data = np.fromstring(decoded_data,np.uint8)
img = cv2.imdecode(np_data,cv2.IMREAD_UNCHANGED)
cv2.imshow("test", img)
cv2.waitKey(0)

Source : https://gist.github.com/HoweChen/7cdd09b08147133d8e1fbe9b52c24768


问:
Why isn't any value being pushed to the 'res' string?
Its a program to add two binary numbers stored in strings and storing the result in a string.

This is my code :

```<code>#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string a = "11", b = "1";
    int i, j, carry = 0;
    string res;
    i = a.length() - 1;
    j = b.length() - 1;

    while (i >= 0 && j >= 0)
    {

        res.push_back((char)(a[i] + b[j] + carry) % 2);
        cout << "0";
        carry = (a[i] + b[j] + carry) / 2;

        i--;
        j--;
    }

    if (i > 0)
    {
        while (i >= 0)
        {
            res.push_back((char)(a[i] + 0 + carry) % 2);
            carry = (a[i] + 0 + carry) / 2;
        }
    }

    if (j > 0)
    {
        while (j >= 0)
        {
            res.push_back((char)(0 + b[j] + carry) % 2);
            carry = (0 + b[j] + carry) / 2;
        }
    }

    if (carry)
        res.push_back(carry);
    cout << endl
         << "-1";
    cout << endl
         << res;
}
</code>```

output:

```<code>0
-1
1
</code>```

Only 1 is pushed into res by the last if(carry) block. Thanks in advance.

答:
If you look at the ASCII table, 49 is the ASCII value of char '1'. Thus it totally makes sense that the following:

```<code>res.push_back(carry);
</code>```

...inserts '1' into res because at that point, carry's value is 49 and the variable carry is an integer. Thus, C++ inserts the character with the ASCII value 49, ie, 1.

So use this instead:

```<code>res += std::to_string(carry); // std::to_string converts many basic data types to std::string
</code>```

The reason I am not using push_back here is because push_back can only insert a single character at one time. So you can use the += to add the contents of std::to_string(carry) to res.

Body:
Its a program to add two binary numbers stored in strings and storing the result in a string.

This is my code :

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string a = "11", b = "1";
    int i, j, carry = 0;
    string res;
    i = a.length() - 1;
    j = b.length() - 1;

    while (i >= 0 && j >= 0)
    {

        res.push_back((char)(a[i] + b[j] + carry) % 2);
        cout << "0";
        carry = (a[i] + b[j] + carry) / 2;

        i--;
        j--;
    }

    if (i > 0)
    {
        while (i >= 0)
        {
            res.push_back((char)(a[i] + 0 + carry) % 2);
            carry = (a[i] + 0 + carry) / 2;
        }
    }

    if (j > 0)
    {
        while (j >= 0)
        {
            res.push_back((char)(0 + b[j] + carry) % 2);
            carry = (0 + b[j] + carry) / 2;
        }
    }

    if (carry)
        res.push_back(carry);
    cout << endl
         << "-1";
    cout << endl
         << res;
}

output:

0
-1
1

Only 1 is pushed into res by the last if(carry) block. Thanks in advance.

Body:
If you look at the ASCII table, 49 is the ASCII value of char '1'. Thus it totally makes sense that the following:

res.push_back(carry);

...inserts '1' into res because at that point, carry's value is 49 and the variable carry is an integer. Thus, C++ inserts the character with the ASCII value 49, ie, 1.

So use this instead:

res += std::to_string(carry); // std::to_string converts many basic data types to std::string

The reason I am not using push_back here is because push_back can only insert a single character at one time. So you can use the += to add the contents of std::to_string(carry) to res.


问:
How to find how much bytes were sent on fetch request?
I am fetching data from different API with javascript's fetch API. But how can I find out how many bytes are sent on each request for analytics?

The request could be in any method.
I know that I can get the amount of bytes received with
response.headers["content-length"].
I need to find out a way to get the amount of bytes sent on the frontend (browser or mobile using React Native). Ideally, it would be the total size of the request, but just the size of the request body would be good enough.

答:
A quick solution that I used - a tiny middleware (I use Express):

```<code>const socketBytes = new Map();
app.use((req, res, next) => {
    req.socketProgress = getSocketProgress(req.socket);
    next();
});

/**
 * return kb read delta for given socket
 */
function getSocketProgress(socket) {
    const currBytesRead = socket.bytesRead;
    let prevBytesRead;
    if (!socketBytes.has(socket)) {
        prevBytesRead = 0;
    } else {
        prevBytesRead = socketBytes.get(socket).prevBytesRead;
    }
    socketBytes.set(socket, {prevBytesRead: currBytesRead})
    return (currBytesRead-prevBytesRead)/1024;
}
</code>```

And then you can use req.socketProgress in your middlewares.

Body:
A quick solution that I used - a tiny middleware (I use Express):

const socketBytes = new Map();
app.use((req, res, next) => {
    req.socketProgress = getSocketProgress(req.socket);
    next();
});

/**
 * return kb read delta for given socket
 */
function getSocketProgress(socket) {
    const currBytesRead = socket.bytesRead;
    let prevBytesRead;
    if (!socketBytes.has(socket)) {
        prevBytesRead = 0;
    } else {
        prevBytesRead = socketBytes.get(socket).prevBytesRead;
    }
    socketBytes.set(socket, {prevBytesRead: currBytesRead})
    return (currBytesRead-prevBytesRead)/1024;
}

And then you can use req.socketProgress in your middlewares.


问:
Transforming dataframe into some format
I have multiple csv. files in the following format

when opening as csv.

imported into R

I would like to transform the dataframe into the following format

答:
Well, it would be nice if you can use the data, but you can use something like that.</p>
```<code>library(stringr)
df = data.frame(property_type = c(1,2,3),
                tenant_id = c('1 1 1 1 1', '2 2 2 2', '3 3 3'))

df = data.frame(do.call(rbind, with(
  df, mapply(\(p, t) cbind(p, str_split(t, ' ')[[1]]), property_type, tenant_id)
)))
colnames(df) = c('property_type', 'tenant_id')
df
</code>```

Title: Transforming dataframe into some format

Body:
Well, it would be nice if you can use the data, but you can use something like that.

library(stringr)
df = data.frame(property_type = c(1,2,3),
                tenant_id = c('1 1 1 1 1', '2 2 2 2', '3 3 3'))

df = data.frame(do.call(rbind, with(
  df, mapply(\(p, t) cbind(p, str_split(t, ' ')[[1]]), property_type, tenant_id)
)))
colnames(df) = c('property_type', 'tenant_id')
df


问:
Flutter Firebase no notification shown on terminated app
I am using Firebase cloud messaging for flutter. Everything works as expected, when the app is either open or in the background. But if I close the app (terminated) no messages are received.

I send the messages with the firebase console.

I have tried two emulators, that both had play services installed.I even logged in with a google account in the emulator.

Any ideas what I might be doing wrong?

答: I set priority to high and it started working. The docs only talk about priority high in the context of data messages but it seems it is important for notifications as well then.


问:
Laravel Livewire how to redirect before render
I want to redirect if Auth::user()->id is not equal to Ad->user_id

it does not work inside the mount or hydrate method.

```<code>$this->ad = Ad::where('id', $this->ad_id);

        if ($this->ad->user_id != Auth::User()->id) {
            return redirect()->route('dashboard');
        }
</code>```

答:
I tried everything but below-mentioned trick worked for me.

Rather than routing from the livewire component we can route from the livewire blade component by adding below code.

```<code>@php
    $carts = \Cart::getContent();

    if(count($carts) == 0)
    {
        $this->redirect('/shopping-cart/bag');
    }
@endphp
</code>```

Suggestions:

Don't use "return" while redirecting otherwise you might face some Front-end issues.

Don't use "route" while redirecting otherwise the code won't work.

Body:
I want to redirect if Auth::user()->id is not equal to Ad->user_id

it does not work inside the mount or hydrate method.

$this->ad = Ad::where('id', $this->ad_id);

        if ($this->ad->user_id != Auth::User()->id) {
            return redirect()->route('dashboard');
        }

Body:
I tried everything but below-mentioned trick worked for me.

Rather than routing from the livewire component we can route from the livewire blade component by adding below code.

@php
    $carts = \Cart::getContent();

    if(count($carts) == 0)
    {
        $this->redirect('/shopping-cart/bag');
    }
@endphp

Suggestions:

Don't use "return" while redirecting otherwise you might face some Front-end issues.

Don't use "route" while redirecting otherwise the code won't work.


问:
Selecting multiple elements with querySelectorAll and applying event in JavaScript
there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :

function myFunction() {
  var x = document.getElementById("myText").value
  document.querySelectorAll(".number").innerText = x
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="uper-container">
  <p>Metric/Imperial unit conversion</p>
  <!-- *********************************************************************************************** -->
  <!-- this input will change the value of 6's span below with the class of "number" -->
  <!-- ********************************************************************************************** -->
  <input type="text" id="myText" placeholder="number here" value="20" onchange="myFunction()">
</div>
<div class="lower-container">
  <p>Length(Meter/Feet)</p>
  <p>
    <span class="number"></span> meters = <span class="d"></span>feet |
    <span class="number"></span> feet = <span class="d"></span>meters
  </p>
  <p>Volume(Liters/Gallons)
    <</p>
      <p>
        <span class="number"></span> liter = <span class="d"></span>gallon |
        <span class="number"></span> gallon = <span class="d"></span>liter
      </p>
      <p>Mass(Kilograms/Pounds)</p>
      <p>
        <span class="number"></span> kilogram = <span class="d"></span>pound |
        <span class="number"></span> pound = <span class="d"></span>kilogram
      </p>
</div></code>```

so how to make spans with the class="number" have the same value as input id="myText"?
and one thing to mention is that I use scrimba editor.

答:
Unlike jQuery, Vanilla JS will not execute innerText to every node returned by querySelectorAll with an inline call. You would need to loop through them.

The code below should work:

```<code>function myFunction() {
    var x = document.getElementById("myText").value;
    var spans = document.querySelectorAll(".number");
    for (let i = 0; i < spans.length; i++) {
        spans[i].innerText = x;
    }
}
</code>```

Body:
there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :

function myFunction() {
  var x = document.getElementById("myText").value
  document.querySelectorAll(".number").innerText = x
}

Metric/Imperial unit conversion

  <input type="text" id="myText" placeholder="number here" value="20" onchange="myFunction()">

Length(Meter/Feet)

     meters = feet |
     feet = meters

Volume(Liters/Gallons)
    <

         liter = gallon |
         gallon = liter

Mass(Kilograms/Pounds)

         kilogram = pound |
         pound = kilogram

so how to make spans with the class="number" have the same value as input id="myText"?
and one thing to mention is that I use scrimba editor.

Body:
Unlike jQuery, Vanilla JS will not execute innerText to every node returned by querySelectorAll with an inline call. You would need to loop through them.

The code below should work:

function myFunction() {
    var x = document.getElementById("myText").value;
    var spans = document.querySelectorAll(".number");
    for (let i = 0; i < spans.length; i++) {
        spans[i].innerText = x;
    }
}


问:
How do I read the image currently on the framebuffer in Qt/C?
Is there any way I can read the content of the framebuffer in Qt or anyway in C? I read it is possible to write the content of /dev/fb0 to a file and then load it. But is it possible to avoid saving it to memory and simply copy to a new memory location to use in Qt?
Thanks!</p>

答: You can look this example to take a screenshot from any window (even desktop). Example uses QScreen::grabWindow() function to take screenshot.


答:
Its ideal to also share some dummy data so that its easier for us to respond.

tidyr option using separate_rows()

```<code>library(dplyr)
df %>%
  tidyr::separate_rows(tenant_id,sep=" ") # assuming the separator is a space
</code>```

Title: Transforming dataframe into some format

Body:
I have multiple csv. files in the following format

when opening as csv.

imported into R

I would like to transform the dataframe into the following format

Body:
Its ideal to also share some dummy data so that its easier for us to respond.

tidyr option using separate_rows()

library(dplyr)
df %>%
  tidyr::separate_rows(tenant_id,sep=" ") # assuming the separator is a space


问:
Difference between getContext() , getApplicationContext() , getBaseContext() and "this"
What is the difference between getContext() , getApplicationContext() , getBaseContext() , and "this"?

Though this is simple question I am unable to understand the basic difference between them. Please give some easy examples if possible.

答:
getApplicationContext() - it's Returns the context for all activities running in application.

getBaseContext() - when you want to access Context from another context within application you can access.

getContext() - it's Returns the context view only current running activity.

this - it's refers to the current class object

This refers to the current activity class object, and activity inherits context, so this must be used where context or activity can be used.


问:
How do I avoid 'Function components cannot be given refs' when using react-router-dom?
I have the following (using Material UI)....

```<code>import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
function LinkTab(link){
    return <Tab component={NavLink}
        to={link.link}
        label={link.label}
        value={link.link}
        key={link.link}
    />;
}
</code>```

In the new versions this causes the following warning...

Warning: Function components cannot be given refs. Attempts to access
  this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of ForwardRef.
      in NavLink (created by ForwardRef)

I tried changing to...

```<code>function LinkTab(link){
    // See https://material-ui.com/guides/composition/#caveat-with-refs
    const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
    return <Tab component={MyLink}
        to={link.link}
        label={link.label}
        value={link.link}
        key={link.link}
    />;
}
</code>```

But I still get the warning. How do I resolve this issue?

答:
I just paste here skychavda solution, as it provide a ref to a child : so you can call child method or child ref from parent directly, without any warn.

source: https://github.com/reactjs/reactjs.org/issues/2120

```<code>/* Child.jsx */
import React from 'react'

class Child extends React.Component {
  componentDidMount() {
    const { childRef } = this.props;
    childRef(this);
  }
  componentWillUnmount() {
   const { childRef } = this.props;
    childRef(undefined);
  }
  alertMessage() {
    window.alert('called from parent component');
  }
  render() {
    return <h1>Hello World!</h1>
  }
}

export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';

class Parent extends React.Component {
  onClick = () => {
    this.child.alertMessage(); // do stuff
  }
  render() {
    return (
      <div>
        <Child childRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.alertMessage()</button>
      </div>
    );
  }
}
</code>```

Body:
I have the following (using Material UI)....

import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
function LinkTab(link){
    return <Tab component={NavLink}
        to={link.link}
        label={link.label}
        value={link.link}
        key={link.link}
    />;
}

In the new versions this causes the following warning...

Warning: Function components cannot be given refs. Attempts to access
  this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of ForwardRef.
      in NavLink (created by ForwardRef)

I tried changing to...

function LinkTab(link){
    // See https://material-ui.com/guides/composition/#caveat-with-refs
    const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
    return <Tab component={MyLink}
        to={link.link}
        label={link.label}
        value={link.link}
        key={link.link}
    />;
}

But I still get the warning. How do I resolve this issue?

Body:
I just paste here skychavda solution, as it provide a ref to a child : so you can call child method or child ref from parent directly, without any warn.

source: https://github.com/reactjs/reactjs.org/issues/2120

/* Child.jsx */
import React from 'react'

class Child extends React.Component {
  componentDidMount() {
    const { childRef } = this.props;
    childRef(this);
  }
  componentWillUnmount() {
   const { childRef } = this.props;
    childRef(undefined);
  }
  alertMessage() {
    window.alert('called from parent component');
  }
  render() {
    return <h1>Hello World!</h1>
  }
}

export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';

class Parent extends React.Component {
  onClick = () => {
    this.child.alertMessage(); // do stuff
  }
  render() {
    return (
      <div>
        <Child childRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.alertMessage()</button>
      </div>
    );
  }
}


问:
Adding a new column to a list of data frames and then 'unlist' with names intact?
I have a number of dfs to which I want to add a column.
For the sake of a mrp, these dfs are called df_1, df_2, df_3...

```<code>for (i in 1:10) {
assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
</code>```

I want to add another column z to each of these dfs.

```<code>z <- rep("hello",10)

</code>```

How can I accomplish this?

Using lapply I have been able to do this

```<code>q <- list()
for (i in 1:10) {
q[[i]] <-  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)
</code>```

This adds the required column, however, I don't know how to preserve the names. How can I still have df_1, df_2, etc but each with a new column z?

Thanks in advance

答:
Using `[<-`().

```<code>q <- lapply(q,`[<-`, 'z', value=rep("hello", 10))
</code>```

Gives

```<code>str(q)
# List of 10
# $ :'data.frame':  10 obs. of  3 variables:
#  ..$ x: num [1:10] 1 1 1 1 1 1 1 1 1 1
#  ..$ y: num [1:10] 2 2 2 2 2 2 2 2 2 2
#  ..$ z: chr [1:10] "hello" "hello" "hello" "hello" ...
# $ :'data.frame':  10 obs. of  3 variables:
#  ..$ x: num [1:10] 1 1 1 1 1 1 1 1 1 1
#  ..$ y: num [1:10] 2 2 2 2 2 2 2 2 2 2
#  ..$ z: chr [1:10] "hello" "hello" "hello" "hello" ...
# ...
</code>```

This works, because `[<-`(df_1, 'z', value=z) is similar to df_1[['z']] <- z. (Actually we're using base:::`[<-.data.frame()`.)

Note: You might get q a little cheaper using replicate:

```<code>n <- 3
q <- replicate(n, data.frame(x=rep(1, 3), y=rep(2, 3)), simplify=FALSE) |>
  setNames(paste0('df_', 1:n))
q
# $df_1
#   x y
# 1 1 2
# 2 1 2
# 3 1 2
#
# $df_2
#   x y
# 1 1 2
# 2 1 2
# 3 1 2
#
# $df_3
#   x y
# 1 1 2
# 2 1 2
# 3 1 2
</code>```

Body:
I have a number of dfs to which I want to add a column.
For the sake of a mrp, these dfs are called df_1, df_2, df_3...

for (i in 1:10) {
assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}

I want to add another column z to each of these dfs.

z <- rep("hello",10)

How can I accomplish this?

Using lapply I have been able to do this

q <- list()
for (i in 1:10) {
q[[i]] <-  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)

This adds the required column, however, I don't know how to preserve the names. How can I still have df_1, df_2, etc but each with a new column z?

Thanks in advance

Body:
Using `[<-`().

q <- lapply(q,`[<-`, 'z', value=rep("hello", 10))

Gives

str(q)
# List of 10
# $ :'data.frame':  10 obs. of  3 variables:
#  ..$ x: num [1:10] 1 1 1 1 1 1 1 1 1 1
#  ..$ y: num [1:10] 2 2 2 2 2 2 2 2 2 2
#  ..$ z: chr [1:10] "hello" "hello" "hello" "hello" ...
# $ :'data.frame':  10 obs. of  3 variables:
#  ..$ x: num [1:10] 1 1 1 1 1 1 1 1 1 1
#  ..$ y: num [1:10] 2 2 2 2 2 2 2 2 2 2
#  ..$ z: chr [1:10] "hello" "hello" "hello" "hello" ...
# ...

This works, because `[<-`(df_1, 'z', value=z) is similar to df_1[['z']] <- z. (Actually we're using base:::`[<-.data.frame()`.)

Note: You might get q a little cheaper using replicate:

n <- 3
q <- replicate(n, data.frame(x=rep(1, 3), y=rep(2, 3)), simplify=FALSE) |>
  setNames(paste0('df_', 1:n))
q
# $df_1
#   x y
# 1 1 2
# 2 1 2
# 3 1 2
#
# $df_2
#   x y
# 1 1 2
# 2 1 2
# 3 1 2
#
# $df_3
#   x y
# 1 1 2
# 2 1 2
# 3 1 2


问:
Angular SignalR and Windows Authentication (NTLM)
My question is pretty straightforward. I am using Windows Authentication in .NET Core. On the front end part of the app (Angular) I have a HTTP interceptor which sets
widhcredentails: true
to the all HTTP requests.

This interceptor does not work with WebSocket, so I need a solution for adding the same code from Interceptor to the SignalR service.

Here is my interceptor code:

```<code>intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
{
    request = request.clone({ withCredentials: true });
    return next.handle(request);
}
</code>```

And here is my SignalR service:

```<code>  this.requestConnection = new HubConnectionBuilder().
        withUrl(`${environment.apiUrl}/request`).
        withAutomaticReconnect([0, 2000, 30000, 60000, null]).
        build();
    this.requestConnection.
        start().
        then(() => console.log('Connection started')).
        catch(err => console.log(`Error while starting connection: ${err}`));
</code>```

Keep in mind that interceptor is added in providers array in the app.module component :

```<code>providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: WinAuthInterceptor,
        multi: true
    }

],
</code>```

SignalR service is injected in the root.

```<code>@Injectable({
    providedIn: 'root'
})
</code>```

答:
Finally, I've realized what was the problem. Since I am using Windows Authentications, there was no need to add any kind of JWT Authorization. Also, the interceptor code I've posted above, makes no difference lol. Meaning you don't need withCredetials: true either in interceptor or SignalR.

Anyway, (if you are using IIS you need to configure it by following this documentation, locally it will work perfectly, but if you are hosting/deploying your app on the IIS you need to do this prior, otherwise your Context will be NULL) you need to set anonymousAuthentication property to false in launchSettings.json (.NET Core as you backend)

```<code>  "iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
  "applicationUrl": "http://localhost:64152",
  "sslPort": 44385
}
</code>```

Long story short, Angular code looks like this:

```<code>  this.requestConnection = new HubConnectionBuilder().
        withUrl(`${environment.apiUrl}/request`).
        withAutomaticReconnect([0, 2000, 30000, 60000, null]).
        build();
    this.requestConnection.
        start().
        then(() => console.log('Connection started')).
        catch(err => console.log(`Error while starting connection: ${err}`));
</code>```

in .NET Core I've just override OnConnectAsync() class to fetch connections and do some logic:

```<code>    public override Task OnConnectedAsync()
    {
        var user = Context.User.Identity.Name.ToUpper();
        //remove domain name
        user = user[user.IndexOf("\\")..];
        //remove speacial chars, excluding .
        user = UserProvider.RemoveSpecialCharacters(user);
        var conId = Context.ConnectionId;

        if (UserProvider.UserConnections.Any(key => key.Key == user))
        {
            UserProvider.UserConnections[user] = conId;
        }
        else
        {
            UserProvider.UserConnections.Add(user, conId);
        }

        return base.OnConnectedAsync();
    }
</code>```

Body:
My question is pretty straightforward. I am using Windows Authentication in .NET Core. On the front end part of the app (Angular) I have a HTTP interceptor which sets
widhcredentails: true
to the all HTTP requests.

This interceptor does not work with WebSocket, so I need a solution for adding the same code from Interceptor to the SignalR service.

Here is my interceptor code:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
{
    request = request.clone({ withCredentials: true });
    return next.handle(request);
}

And here is my SignalR service:

  this.requestConnection = new HubConnectionBuilder().
        withUrl(`${environment.apiUrl}/request`).
        withAutomaticReconnect([0, 2000, 30000, 60000, null]).
        build();
    this.requestConnection.
        start().
        then(() => console.log('Connection started')).
        catch(err => console.log(`Error while starting connection: ${err}`));

Keep in mind that interceptor is added in providers array in the app.module component :

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: WinAuthInterceptor,
        multi: true
    }

],

SignalR service is injected in the root.

@Injectable({
    providedIn: 'root'
})

Body:
Finally, I've realized what was the problem. Since I am using Windows Authentications, there was no need to add any kind of JWT Authorization. Also, the interceptor code I've posted above, makes no difference lol. Meaning you don't need withCredetials: true either in interceptor or SignalR.

Anyway, (if you are using IIS you need to configure it by following this documentation, locally it will work perfectly, but if you are hosting/deploying your app on the IIS you need to do this prior, otherwise your Context will be NULL) you need to set anonymousAuthentication property to false in launchSettings.json (.NET Core as you backend)

  "iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
  "applicationUrl": "http://localhost:64152",
  "sslPort": 44385
}

Long story short, Angular code looks like this:

  this.requestConnection = new HubConnectionBuilder().
        withUrl(`${environment.apiUrl}/request`).
        withAutomaticReconnect([0, 2000, 30000, 60000, null]).
        build();
    this.requestConnection.
        start().
        then(() => console.log('Connection started')).
        catch(err => console.log(`Error while starting connection: ${err}`));

in .NET Core I've just override OnConnectAsync() class to fetch connections and do some logic:

    public override Task OnConnectedAsync()
    {
        var user = Context.User.Identity.Name.ToUpper();
        //remove domain name
        user = user[user.IndexOf("\\")..];
        //remove speacial chars, excluding .
        user = UserProvider.RemoveSpecialCharacters(user);
        var conId = Context.ConnectionId;

        if (UserProvider.UserConnections.Any(key => key.Key == user))
        {
            UserProvider.UserConnections[user] = conId;
        }
        else
        {
            UserProvider.UserConnections.Add(user, conId);
        }

        return base.OnConnectedAsync();
    }


问:
How to replace an element in a list with an existing variable?
I can't replace an element in a list with a variable and I'm not sure how. I've checked everywhere and I can't find it. Can someone let me know how to? Cheers</p>
```<code>import random
passcode = "x"
while passcode == "x":
  randomword = list(input("Please enter a random word: "))
  randomwordtwo = list(input("Please enter a second random word: "))
  randomwordthree = list(input("Please enter a final random word: "))
  randomword.extend(randomwordtwo)
  randomword.extend(randomwordthree)
  symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
  number = ["0","1","2","3","4","5","6","7","8","9"]
  print(randomword)
  randsymb = (random.choice(symbol))
  for i in range(len(randomword)):
    if randomword[i] == "a":
      randomword[i] = (randsymb)
</code>```

答:
There is not have replace() method for a list

But you can use str.replace() on a string.

there is an example on w3schools

Body:
I can't replace an element in a list with a variable and I'm not sure how. I've checked everywhere and I can't find it. Can someone let me know how to? Cheers

import random
passcode = "x"
while passcode == "x":
  randomword = list(input("Please enter a random word: "))
  randomwordtwo = list(input("Please enter a second random word: "))
  randomwordthree = list(input("Please enter a final random word: "))
  randomword.extend(randomwordtwo)
  randomword.extend(randomwordthree)
  symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
  number = ["0","1","2","3","4","5","6","7","8","9"]
  print(randomword)
  randsymb = (random.choice(symbol))
  for i in range(len(randomword)):
    if randomword[i] == "a":
      randomword[i] = (randsymb)


问:
Cannot overwrite model once compiled Mongoose
Not Sure what I'm doing wrong, here is my check.js

```<code>var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));

var a1= db.once('open',function(){
var user = mongoose.model('users',{
       name:String,
       email:String,
       password:String,
       phone:Number,
      _enabled:Boolean
     });

user.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere })
    });
</code>```

and here is my insert.js

```<code>var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')

var user = mongoose.model('users',{
     name:String,
     email:String,
     password: String,
     phone:Number,
     _enabled:Boolean
   });

var new_user = new user({
     name:req.body.name,
     email: req.body.email,
     password: req.body.password,
     phone: req.body.phone,
     _enabled:false
   });

new_user.save(function(err){
    if(err) console.log(err);
   });
</code>```

Whenever I'm trying to run check.js, I'm getting this error

Cannot overwrite 'users' model once compiled.

I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.

Here is what I'm getting from the client interface of my MongoDB:

```<code>MongoDB shell version: 2.4.6 connecting to: test
> use event-db
  switched to db event-db
> db.users.find()
  { "_id" : ObjectId("52457d8718f83293205aaa95"),
    "name" : "MyName",
    "email" : "myemail@me.com",
    "password" : "myPassword",
    "phone" : 900001123,
    "_enable" : true
  }
>
</code>```

答:
Make sure you are not using the same model name for two different schemas.

Example:

```<code>// course model
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
    course: {
        type: String,
        required: true,
    },
    course_category: {
        type: String,
        required: true,
    }
});
module.exports = mongoose.model("course", courseSchema);

// student model
const mongoose = require("mongoose");
const studentSchema = new mongoose.Schema({
    first_name: {
        type: String,
        required: true,
    },
    last_name: {
        type: String,
        required: true,
    }
});
module.exports = mongoose.model("course", studentSchema);
</code>```

Body:
Not Sure what I'm doing wrong, here is my check.js

var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));

var a1= db.once('open',function(){
var user = mongoose.model('users',{
       name:String,
       email:String,
       password:String,
       phone:Number,
      _enabled:Boolean
     });

user.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere })
    });

and here is my insert.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')

var user = mongoose.model('users',{
     name:String,
     email:String,
     password: String,
     phone:Number,
     _enabled:Boolean
   });

var new_user = new user({
     name:req.body.name,
     email: req.body.email,
     password: req.body.password,
     phone: req.body.phone,
     _enabled:false
   });

new_user.save(function(err){
    if(err) console.log(err);
   });

Whenever I'm trying to run check.js, I'm getting this error

Cannot overwrite 'users' model once compiled.

I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.

Here is what I'm getting from the client interface of my MongoDB:

MongoDB shell version: 2.4.6 connecting to: test
> use event-db
  switched to db event-db
> db.users.find()
  { "_id" : ObjectId("52457d8718f83293205aaa95"),
    "name" : "MyName",
    "email" : "myemail@me.com",
    "password" : "myPassword",
    "phone" : 900001123,
    "_enable" : true
  }
>

Body:
Make sure you are not using the same model name for two different schemas.

Example:

// course model
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
    course: {
        type: String,
        required: true,
    },
    course_category: {
        type: String,
        required: true,
    }
});
module.exports = mongoose.model("course", courseSchema);

// student model
const mongoose = require("mongoose");
const studentSchema = new mongoose.Schema({
    first_name: {
        type: String,
        required: true,
    },
    last_name: {
        type: String,
        required: true,
    }
});
module.exports = mongoose.model("course", studentSchema);


问:
How to Unit Test Method Calling IConfiguration.Get<T> extension
I have this very simple method that I need to unit test.

```<code>public static class ValidationExtensions
{
    public static T GetValid<T>(this IConfiguration configuration)
    {
        var obj = configuration.Get<T>();
        Validator.ValidateObject(obj, new ValidationContext(obj), true);
        return obj;
    }
}
</code>```

The problem is that configuration.Get<T> is a static extension method and doesn't belong to IConfiguration. I can't change the implementation of that static method.

I'm thinking, perhaps the simplest way is to create a Memory Configuration Provider? But I don't know if I can create one without binding it to a web host.

答:
Most of mocking libraries(Moq, FakeItEasy, etc) can't mock extension methods.

So, you have to 'fill' your IConfiguration in a way that a IConfiguration.Get<T> returns an instance of T. Nkoski answer works for a lot of scenarios, but not if you need to test a code that calls IConfiguration.Get<T> you can use the example bellow:

```<code>using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Xunit;

public class TestClass {
    public class Movie
    {
        public string Name { get; set; }
        public decimal Rating { get; set; }
        public IList<string> Stars { get; set; } //it works with collections
    }

    [Fact]
    public void MyTest()
    {
        var movie = new Movie {
            Name = "Some Movie",
            Rating = 9,
            Stars = new List<string>{"Some actress", "Some actor"}
        };

        var movieAsJson = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(movie));
        using(var stream = new MemoryStream(movieAsJson))
        {
            var config = new ConfigurationBuilder().AddJsonStream(stream).Build();
            var movieFromConfig = config.Get<Movie>();
            //var sut = new SomeService(config).SomeMethodThatCallsConfig.Get<Movie>()
        }
    }
}
</code>```

Body:
I have this very simple method that I need to unit test.

public static class ValidationExtensions
{
    public static T GetValid<T>(this IConfiguration configuration)
    {
        var obj = configuration.Get<T>();
        Validator.ValidateObject(obj, new ValidationContext(obj), true);
        return obj;
    }
}

The problem is that configuration.Get<T> is a static extension method and doesn't belong to IConfiguration. I can't change the implementation of that static method.

I'm thinking, perhaps the simplest way is to create a Memory Configuration Provider? But I don't know if I can create one without binding it to a web host.

Body:
Most of mocking libraries(Moq, FakeItEasy, etc) can't mock extension methods.

So, you have to 'fill' your IConfiguration in a way that a IConfiguration.Get<T> returns an instance of T. Nkoski answer works for a lot of scenarios, but not if you need to test a code that calls IConfiguration.Get<T> you can use the example bellow:

using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Xunit;

public class TestClass {
    public class Movie
    {
        public string Name { get; set; }
        public decimal Rating { get; set; }
        public IList<string> Stars { get; set; } //it works with collections
    }

    [Fact]
    public void MyTest()
    {
        var movie = new Movie {
            Name = "Some Movie",
            Rating = 9,
            Stars = new List<string>{"Some actress", "Some actor"}
        };

        var movieAsJson = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(movie));
        using(var stream = new MemoryStream(movieAsJson))
        {
            var config = new ConfigurationBuilder().AddJsonStream(stream).Build();
            var movieFromConfig = config.Get<Movie>();
            //var sut = new SomeService(config).SomeMethodThatCallsConfig.Get<Movie>()
        }
    }
}


问:
React Table - new order after filtering
I have a table made with React Table. I want it to have a fresh order after each filtering. So far, I have achieved only one order which is created at render.

Here is the Table component:

```<code>import React, { useEffect } from "react";
import { Table as BTable } from "react-bootstrap";
import { useTable, useSortBy, useGlobalFilter } from "react-table";

function Table({ data, columns, variant, filter = "" }) {
  const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter,
    useSortBy
  );

  const { globalFilter } = state;

  useEffect(() => {
    setGlobalFilter(filter);
    // eslint-disable-next-line
  }, []);
  return (
    <>
      <span>Search: </span>
      <input
        value={globalFilter}
        onChange={(e) => setGlobalFilter(e.target.value)}
        onMouseMove={(e) => setGlobalFilter(e.target.value)}
      ></input>
      <hr></hr>
      <BTable striped bordered hover variant={variant} {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th
                  width={column.width}
                  {...column.getHeaderProps(column.getSortByToggleProps())}
                >
                  {column.render("Header")}
                  <span>
                    {column.isSorted
                      ? column.isSortedDesc
                        ? " "
                        : " "
                      : ""}
                  </span>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </BTable>
    </>
  );
}

export default Table;
</code>```

And implementation:

```<code>const columns = React.useMemo(
    () => [
      {
        Header: "#",
        Cell: (row) => {
          return <div>{Number(row.row.id) + 1}</div>;
        },
      },
      {
        Header: "ID",
        accessor: "id",
      },
      {
        Header: "Added By",
        accessor: "addedBy",
      },
      { Header: "Date of creation", accessor: "dateOfCreation", width: "10%" },
      {
        Header: "Ordertaker",
        accessor: "orderTaker",
        width: "5%",
      },
      {
        Header: "Customer",
        accessor: "customer",
        width: "20%",
      },
      {
        Header: "Description",
        accessor: "description",
        disableSortBy: "true",
        width: "30%",
      },
      {
        Header: "Status",
        accessor: "status",
        disableSortBy: "true",
        width: "10%",
      },
    ],
  );

return (
            <Table
              data={data} // data is fetched from firebase
              columns={columns}
              variant="dark"
            />
  );

</code>```

"#" column has number from 1 for each row. What I want is to reset order in "#" column after each filtering to start with 1. Any ideas how can it be done?

答: I found the solution on the internet. Here`s the link</p>

Title: React Table - new order after filtering

Body:
I have a table made with React Table. I want it to have a fresh order after each filtering. So far, I have achieved only one order which is created at render.

Here is the Table component:

import React, { useEffect } from "react";
import { Table as BTable } from "react-bootstrap";
import { useTable, useSortBy, useGlobalFilter } from "react-table";

function Table({ data, columns, variant, filter = "" }) {
  const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter,
    useSortBy
  );

  const { globalFilter } = state;

  useEffect(() => {
    setGlobalFilter(filter);
    // eslint-disable-next-line
  }, []);
  return (
    <>
      Search:
      <input
        value={globalFilter}
        onChange={(e) => setGlobalFilter(e.target.value)}
        onMouseMove={(e) => setGlobalFilter(e.target.value)}
      ></input>

      <BTable striped bordered hover variant={variant} {...getTableProps()}>

          {headerGroups.map((headerGroup) => (

              {headerGroup.headers.map((column) => (

                  {column.render("Header")}

                    {column.isSorted
                      ? column.isSortedDesc
                        ? " "
                        : " "
                      : ""}

              ))}

          ))}

          {rows.map((row, i) => {
            prepareRow(row);
            return (

                {row.cells.map((cell) => {
                  return (
                    {cell.render("Cell")}
                  );
                })}

            );
          })}

      </BTable>
    </>
  );
}

export default Table;

And implementation:

const columns = React.useMemo(
    () => [
      {
        Header: "#",
        Cell: (row) => {
          return
{Number(row.row.id) + 1}
;
        },
      },
      {
        Header: "ID",
        accessor: "id",
      },
      {
        Header: "Added By",
        accessor: "addedBy",
      },
      { Header: "Date of creation", accessor: "dateOfCreation", width: "10%" },
      {
        Header: "Ordertaker",
        accessor: "orderTaker",
        width: "5%",
      },
      {
        Header: "Customer",
        accessor: "customer",
        width: "20%",
      },
      {
        Header: "Description",
        accessor: "description",
        disableSortBy: "true",
        width: "30%",
      },
      {
        Header: "Status",
        accessor: "status",
        disableSortBy: "true",
        width: "10%",
      },
    ],
  );

return (

  );

"#" column has number from 1 for each row. What I want is to reset order in "#" column after each filtering to start with 1. Any ideas how can it be done?


问:
REST URL structure advice
I'm trying to finalise on a restful url structure for the wishlist section of a site I'm working on. It's a pretty simple model, a user can have many wishlists and each wishlist can contain many products.

Currently I have the obvious CRUD URLs to manipulate the wishlist itself :

```<code>GET account/wishlists.json
GET account/wishlists/{id}.json
POST account/wishlists.json?name=My%20Wishlist
POST account/wishlists/{id}.json?name=My%20New%20Name
DELETE account/wishlists/{id}.json
</code>```

However, I don't think I know how to structure the URLs that would add/remove a product to a wishlist :(

Here are my current choices :

1) Have the product to add as part of the URL and use the HTTP verb to define my action

```<code>POST account/wishlist/{id}/product/{product_id}.json
DELETE account/wishlist/{id}/product/{product_id}.json
</code>```

or

2) Have the action as part of the URL and the product id as part of the payload

```<code>POST account/wishlist/{id}/add.json?product_id={product_id}
POST account/wishlist/{id}/remove.json?product_id={product_id}
</code>```

(1) is clean and, as far as I can tell it's pretty RESTful but doesn't allow things like adding multiple products easily etc.

I'm also a bit concerned about using the DELETE verb - I'm not deleting the product or the wishlist, I'm just removing one from the other.

(2) is more explicit but veers away from REST - I wouldn't be just referring to the resource in the url, I would be referring to an operation on that resource :(

Any advice on which of the above would be more correct would be very helpful! (If there's a third option that's better than mine, feel free to correct me!)

答:
As noted by other responses, the first option is clearly the RESTful approach.  The approach to deleting products from the wishlist looks fine - after all you would be doing a DELETE on product/{product_id} to remove the product itself.

For adding products, you might wish to consider a POST to account/wishlist/{id}/product/ the body of which could contain a list of product IDs.

Title: REST URL structure advice

Body:
I'm trying to finalise on a restful url structure for the wishlist section of a site I'm working on. It's a pretty simple model, a user can have many wishlists and each wishlist can contain many products.

Currently I have the obvious CRUD URLs to manipulate the wishlist itself :

GET account/wishlists.json
GET account/wishlists/{id}.json
POST account/wishlists.json?name=My%20Wishlist
POST account/wishlists/{id}.json?name=My%20New%20Name
DELETE account/wishlists/{id}.json

However, I don't think I know how to structure the URLs that would add/remove a product to a wishlist :(

Here are my current choices :

1) Have the product to add as part of the URL and use the HTTP verb to define my action

POST account/wishlist/{id}/product/{product_id}.json
DELETE account/wishlist/{id}/product/{product_id}.json

or

2) Have the action as part of the URL and the product id as part of the payload

POST account/wishlist/{id}/add.json?product_id={product_id}
POST account/wishlist/{id}/remove.json?product_id={product_id}

(1) is clean and, as far as I can tell it's pretty RESTful but doesn't allow things like adding multiple products easily etc.

I'm also a bit concerned about using the DELETE verb - I'm not deleting the product or the wishlist, I'm just removing one from the other.

(2) is more explicit but veers away from REST - I wouldn't be just referring to the resource in the url, I would be referring to an operation on that resource :(

Any advice on which of the above would be more correct would be very helpful! (If there's a third option that's better than mine, feel free to correct me!)


问:
AWS SAM Local vs Serverless-offline
We are a Terraform shop for standing up our infrastructure on AWS and I am using AWS SAM Local to:

Test AWS Lambdas locally without having to deploy on the cloud.

I can also run integration tests on locally running lambda function as it will call downstream services that are running in the cloud.

I am curious about serverless-offline. I don't have much experience with the npm serverless library and wondering if others have any experience how it compares to SAM Local? Does it have same capabilities that I am able to accomplish with AWS SAM Local?

答:
The sam local cli command and the Serverless Offline plugin work in similar ways. Both run a Docker instance and emulate API Gateway and Lambda. Additionally, Serverless Framework supports other platforms, unlike SAM Local.

The biggest advantage of using one or another is the ability to test your Serveless functions locally with the tool that you are currently using. So if you are using AWS SAM, the sam local will be the best option, similar if you are using the Serverless Framework, as the best option will be using the Serverless-offline plugin.

Serverless Framework included offline testing long before SAM Local arrived, so maybe you can find options that are not available yet using SAM local. sam local can have some advantages, such as template validation.

Both systems use Node.js and support API Gateway and Lambda, but neither currently supports DynamoDB execution, so you need to work in a way to make your DynamoDb available locally.

If you want to decide if the best option for you is the AWS SAM or the Serveless Framework, you can take a look in comparison like this one: Comparing AWS SAM with the Serverless framework.

Title: AWS SAM Local vs Serverless-offline


问:
Observable emits no value
I am new to Observables. I am using a switchMap to loop through an array of Observables from firestore, retriving two streams, combining the outputs of the streams into a new Observable Array.

```<code>createSuperPolicy( product:VehicleProducts, vehicle:Vehicle, id:String, policyCertID:String) : Observable<SuperVehiclePolicy>{

    var temp = new SuperVehiclePolicy;

      temp.policyID =  id,
      temp.vendor =  product.vendor,
      temp.title  = product.title,
      temp.premium = product.premium,
      temp.offer = product.offer,
      temp.reg = vehicle.registrationNumber ,
      temp.benefits = product.Benefits,
      temp.policyCertID =  policyCertID

    return of(temp)
  }

  populateVehiclePolicyList = this.vehiclePolicyService.getPolicies().pipe(
       switchMap((policies:VehiclePolicy[]) => {
         var policyList$: Observable<SuperVehiclePolicy>[] = [];
         policies.forEach(policy => {
          var product$: Observable<VehicleProducts> = this.vehicleProductService.getProductByID(policy.vehicleProductID)
          var vehicle$: Observable<Vehicle> = this.vehicleService.getVehicleByID(policy.vehicleID)
          var id$ = of(policy.id)
          var certID$ = of(policy.policyCertID)

          combineLatest(product$, vehicle$, id$,certID$)
          .pipe(map(([product, vehicle, pid,certID]) => this.createSuperPolicy(product,vehicle, pid, certID)))
          .subscribe((val) => policyList$.push(val));
         });

         console.log(policyList$)
         return forkJoin(policyList$);
       })
     )

</code>```

Calling viewing the contents of the new Array of Observables(policyList$) displays the contents of the array.

Now when I subscribe to populateVehiclePolicyList, as below,

```<code>
this.displayService.populateVehiclePolicyList.subscribe(((policy: SuperVehiclePolicy[]) => {console.log(policy)}))
</code>```

Console.log(policy) returns neither a value nor an error.
I am confused as to what is happening.
How can I successfully subscribe to populateVehiclePolicyList, so as to consume the output?

答:
there are few issues in your code so before I share the proper code, let me explain them a lil bit:

```<code>return  temp as unknown as Observable<SuperVehiclePolicy>
</code>```

as keyword doesn't actually cast to different types, it just tells typescript to treat one thing as something other so you can't cast a variable of type SuperVehiclePolicy into Observable<SuperVehiclePolicy> like this, typescript won't complain as you are using as but you'll get problems in runtime, for this purposes rxjs provides an operator called of that you did use inside that switchMap

you are first converting your object to unknown so that you can then convert it to Observable<SuperVehiclePolicy>, that's just wrong cuz by doing this, you're basically hiding the symptoms instead of curing the disease.

```<code>var policyList$: Observable<SuperVehiclePolicy>[] = [];
</code>```

don't use var, it's dead, use either let or const, read this

```<code>combineLatest(product$, vehicle$, id$,certID$)
      .pipe(map(([product, vehicle, pid,certID]) => this.createSuperPolicy(product,vehicle, pid, certID)))
      .subscribe((val) => policyList$.push(val));

</code>```

you are subscribing manually inside switchMap, don't do that, generally don't subscribe inside an rxjs operator as most of the time this is not what you actually want to do.

now why doesn't console.log(policy) logs anything?
you are providingforkJoin(policyList$); to your switchMap which is good but because you subscribing manually to above mentioned combineLatest, switchMap didn't wait for it and by the time you started pushing inside policyList$, your switchMap was already done. Hope this helps you understand why subscribing inside an operator is sometimes not what you actually want.

Ok lets jump onto the right code:

class DisplayService {
    createSuperPolicy(product: VehicleProducts, vehicle: Vehicle, id: String, policyCertID: String): SuperVehiclePolicy {
        const temp = new SuperVehiclePolicy();

        temp.policyID = id;
        temp.vendor = product.vendor;
        temp.title = product.title;
        temp.premium = product.premium;
        temp.offer = product.offer;
        temp.reg = vehicle.registrationNumber;
        temp.benefits = product.Benefits;
        temp.policyCertID = policyCertID;

        return temp;
    }

    populateVehiclePolicyList = this.vehiclePolicyService.getPolicies().pipe(
        switchMap((policies: VehiclePolicy[]) => {
            const policyList$: Observable<SuperVehiclePolicy>[] = policies.map(policy => {
                const product$: Observable<VehicleProducts> = this.vehicleProductService.getProductByID(policy.vehicleProductID);
                const vehicle$: Observable<Vehicle> = this.vehicleService.getVehicleByID(policy.vehicleID);

                // build super policy for current policy and return it in an observable
                return forkJoin([product$, vehicle$]).pipe(
                    map((product, vehicle) => this.createSuperPolicy(product, vehicle, policy.id, policy.policyCertID))
                );
            });

            return forkJoin(policyList$).pipe(
                tap(superPolicies => {
                    console.log("Super policies: ", superPolicies);
                })
            );
        })
    );
}
```

notice that you don't need to return Observable<SuperVehiclePolicy> from createSuperPolicy

let me know if you have any doubt regarding above code, Happy coding!

Title: Observable emits no value

Body:
I am new to Observables. I am using a switchMap to loop through an array of Observables from firestore, retriving two streams, combining the outputs of the streams into a new Observable Array.

createSuperPolicy( product:VehicleProducts, vehicle:Vehicle, id:String, policyCertID:String) : Observable<SuperVehiclePolicy>{

    var temp = new SuperVehiclePolicy;

      temp.policyID =  id,
      temp.vendor =  product.vendor,
      temp.title  = product.title,
      temp.premium = product.premium,
      temp.offer = product.offer,
      temp.reg = vehicle.registrationNumber ,
      temp.benefits = product.Benefits,
      temp.policyCertID =  policyCertID

    return of(temp)
  }

  populateVehiclePolicyList = this.vehiclePolicyService.getPolicies().pipe(
       switchMap((policies:VehiclePolicy[]) => {
         var policyList$: Observable<SuperVehiclePolicy>[] = [];
         policies.forEach(policy => {
          var product$: Observable<VehicleProducts> = this.vehicleProductService.getProductByID(policy.vehicleProductID)
          var vehicle$: Observable<Vehicle> = this.vehicleService.getVehicleByID(policy.vehicleID)
          var id$ = of(policy.id)
          var certID$ = of(policy.policyCertID)

          combineLatest(product$, vehicle$, id$,certID$)
          .pipe(map(([product, vehicle, pid,certID]) => this.createSuperPolicy(product,vehicle, pid, certID)))
          .subscribe((val) => policyList$.push(val));
         });

         console.log(policyList$)
         return forkJoin(policyList$);
       })
     )

Calling viewing the contents of the new Array of Observables(policyList$) displays the contents of the array.

Now when I subscribe to populateVehiclePolicyList, as below,

this.displayService.populateVehiclePolicyList.subscribe(((policy: SuperVehiclePolicy[]) => {console.log(policy)}))

Console.log(policy) returns neither a value nor an error.
I am confused as to what is happening.
How can I successfully subscribe to populateVehiclePolicyList, so as to consume the output?

Body:
there are few issues in your code so before I share the proper code, let me explain them a lil bit:

return  temp as unknown as Observable<SuperVehiclePolicy>

as keyword doesn't actually cast to different types, it just tells typescript to treat one thing as something other so you can't cast a variable of type SuperVehiclePolicy into Observable<SuperVehiclePolicy> like this, typescript won't complain as you are using as but you'll get problems in runtime, for this purposes rxjs provides an operator called of that you did use inside that switchMap

you are first converting your object to unknown so that you can then convert it to Observable<SuperVehiclePolicy>, that's just wrong cuz by doing this, you're basically hiding the symptoms instead of curing the disease.

var policyList$: Observable<SuperVehiclePolicy>[] = [];

don't use var, it's dead, use either let or const, read this

combineLatest(product$, vehicle$, id$,certID$)
      .pipe(map(([product, vehicle, pid,certID]) => this.createSuperPolicy(product,vehicle, pid, certID)))
      .subscribe((val) => policyList$.push(val));

you are subscribing manually inside switchMap, don't do that, generally don't subscribe inside an rxjs operator as most of the time this is not what you actually want to do.

now why doesn't console.log(policy) logs anything?
you are providingforkJoin(policyList$); to your switchMap which is good but because you subscribing manually to above mentioned combineLatest, switchMap didn't wait for it and by the time you started pushing inside policyList$, your switchMap was already done. Hope this helps you understand why subscribing inside an operator is sometimes not what you actually want.

Ok lets jump onto the right code:

class DisplayService {
    createSuperPolicy(product: VehicleProducts, vehicle: Vehicle, id: String, policyCertID: String): SuperVehiclePolicy {
        const temp = new SuperVehiclePolicy();

        temp.policyID = id;
        temp.vendor = product.vendor;
        temp.title = product.title;
        temp.premium = product.premium;
        temp.offer = product.offer;
        temp.reg = vehicle.registrationNumber;
        temp.benefits = product.Benefits;
        temp.policyCertID = policyCertID;

        return temp;
    }

    populateVehiclePolicyList = this.vehiclePolicyService.getPolicies().pipe(
        switchMap((policies: VehiclePolicy[]) => {
            const policyList$: Observable<SuperVehiclePolicy>[] = policies.map(policy => {
                const product$: Observable<VehicleProducts> = this.vehicleProductService.getProductByID(policy.vehicleProductID);
                const vehicle$: Observable<Vehicle> = this.vehicleService.getVehicleByID(policy.vehicleID);

                // build super policy for current policy and return it in an observable
                return forkJoin([product$, vehicle$]).pipe(
                    map((product, vehicle) => this.createSuperPolicy(product, vehicle, policy.id, policy.policyCertID))
                );
            });

            return forkJoin(policyList$).pipe(
                tap(superPolicies => {
                    console.log("Super policies: ", superPolicies);
                })
            );
        })
    );
}

notice that you don't need to return Observable<SuperVehiclePolicy> from createSuperPolicy

let me know if you have any doubt regarding above code, Happy coding!