问:
What does Redis do when it runs out of memory?
This might be easy question but I am having a hard time finding the answer. How does Redis 2.0 handle running out of maximum allocated memory? How does it decide which data to remove or which data to keep in memory?</p>

答:
Update redis 4.0

```<code>127.0.0.1:6379> MEMORY HELP
1) "MEMORY DOCTOR                        - Outputs memory problems report"
2) "MEMORY USAGE <key> [SAMPLES <count>] - Estimate memory usage of key"
3) "MEMORY STATS                         - Show memory usage details"
4) "MEMORY PURGE                         - Ask the allocator to release memory"
5) "MEMORY MALLOC-STATS                  - Show allocator internal stats"
</code>```

/usr/local/etc/redis.conf

```<code>############################## MEMORY MANAGEMENT ################################

# Set a memory usage limit to the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected (see maxmemory-policy).
#
# If Redis can't remove keys according to the policy, or if the policy is
# set to 'noeviction', Redis will start to reply with errors to commands
# that would use more memory, like SET, LPUSH, and so on, and will continue
# to reply to read-only commands like GET.
#
# This option is usually useful when using Redis as an LRU or LFU cache, or to
# set a hard memory limit for an instance (using the 'noeviction' policy).
#
# WARNING: If you have slaves attached to an instance with maxmemory on,
# the size of the output buffers needed to feed the slaves are subtracted
# from the used memory count, so that network problems / resyncs will
# not trigger a loop where keys are evicted, and in turn the output
# buffer of slaves is full with DELs of keys evicted triggering the deletion
# of more keys, and so forth until the database is completely emptied.
#
# In short... if you have slaves attached it is suggested that you set a lower
# limit for maxmemory so that there is some free RAM on the system for slave
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory <bytes>

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones with an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
# Note: with any of the above policies, Redis will return an error on write
#       operations, when there are no suitable keys for eviction.
#
#       At the date of writing these commands are: set setnx setex append
#       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
#       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
#       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
#       getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction

# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can tune it for speed or
# accuracy. For default Redis will check five keys and pick the one that was
# used less recently, you can change the sample size using the following
# configuration directive.
#
# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs more CPU. 3 is faster but not very accurate.
#
# maxmemory-samples 5
</code>```

Body:
Update redis 4.0

127.0.0.1:6379> MEMORY HELP
1) "MEMORY DOCTOR                        - Outputs memory problems report"
2) "MEMORY USAGE <key> [SAMPLES <count>] - Estimate memory usage of key"
3) "MEMORY STATS                         - Show memory usage details"
4) "MEMORY PURGE                         - Ask the allocator to release memory"
5) "MEMORY MALLOC-STATS                  - Show allocator internal stats"

/usr/local/etc/redis.conf

############################## MEMORY MANAGEMENT ################################

# Set a memory usage limit to the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected (see maxmemory-policy).
#
# If Redis can't remove keys according to the policy, or if the policy is
# set to 'noeviction', Redis will start to reply with errors to commands
# that would use more memory, like SET, LPUSH, and so on, and will continue
# to reply to read-only commands like GET.
#
# This option is usually useful when using Redis as an LRU or LFU cache, or to
# set a hard memory limit for an instance (using the 'noeviction' policy).
#
# WARNING: If you have slaves attached to an instance with maxmemory on,
# the size of the output buffers needed to feed the slaves are subtracted
# from the used memory count, so that network problems / resyncs will
# not trigger a loop where keys are evicted, and in turn the output
# buffer of slaves is full with DELs of keys evicted triggering the deletion
# of more keys, and so forth until the database is completely emptied.
#
# In short... if you have slaves attached it is suggested that you set a lower
# limit for maxmemory so that there is some free RAM on the system for slave
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory <bytes>

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones with an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
# Note: with any of the above policies, Redis will return an error on write
#       operations, when there are no suitable keys for eviction.
#
#       At the date of writing these commands are: set setnx setex append
#       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
#       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
#       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
#       getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction

# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can tune it for speed or
# accuracy. For default Redis will check five keys and pick the one that was
# used less recently, you can change the sample size using the following
# configuration directive.
#
# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs more CPU. 3 is faster but not very accurate.
#
# maxmemory-samples 5


来源: stackexchange

问:
C++ how to use a pointer to circular shift array element
```<code>#include <iostream>
using namespace std;

void RotateLeft(unsigned char* in)
{
    unsigned int* q= (unsigned int*)in;
    *q = (*q >> 8)|((*q & 0xff) << 24);
}
int main() {
    unsigned char temp[4] = {'a', 'b', 'c', 'd'};
    RotateLeft(temp);
    for (int i=0; i<4; i++) {
        cout<<temp[i]<<endl;
    }
}
</code>```

the output is: b c d a.

Could you explain how does this line work:

```<code>*q = (*q >> 8)|((*q & 0xff) << 24);
</code>```

?

答:
It's just deferencing the pointer, which returns an int, and performing all the bit operations on that. It's effectively the same as:

```<code>unsigned int val = *q;
val = (val >> 8)|((val & 0xff) << 24);
*q = val;
</code>```

The program itself has undefined behavior. You can't access a char array through an unsigned int* pointer. It also assumes that sizeof (unsigned int) is 4, the array has no padding between elements, and a particular endianness of the CPU.

ContentLicense: CC BY-SA 3.0

Body:
#include <iostream>
using namespace std;

void RotateLeft(unsigned char* in)
{
    unsigned int* q= (unsigned int*)in;
    *q = (*q >> 8)|((*q & 0xff) << 24);
}
int main() {
    unsigned char temp[4] = {'a', 'b', 'c', 'd'};
    RotateLeft(temp);
    for (int i=0; i<4; i++) {
        cout<<temp[i]<<endl;
    }
}

the output is: b c d a.

Could you explain how does this line work:

*q = (*q >> 8)|((*q & 0xff) << 24);

?

Body:
It's just deferencing the pointer, which returns an int, and performing all the bit operations on that. It's effectively the same as:

unsigned int val = *q;
val = (val >> 8)|((val & 0xff) << 24);
*q = val;

The program itself has undefined behavior. You can't access a char array through an unsigned int* pointer. It also assumes that sizeof (unsigned int) is 4, the array has no padding between elements, and a particular endianness of the CPU.


问:
Julia 0.6 pmap function
I want to paralelize a decomposition algorithm for optimization named Progressive Hedging. This optimization is stored on a function named PH which recieve arguments for the model, some arguments are matrix but PH needs just a vector from that matrix in this way.

```<code>for s = 1:nS
    res = PH(k,s,data,Lines,Ag,Gx,Pmax[:,s],Prmax[:,s],COpe[:,s])
    push!(data,res)
end
</code>```

So PH needs just a vector from Pmax, Prmax and COpe.

To paralelize I try to do this.

```<code> pmap(s -> PH(k,s,data,Lines,Ag,Gx,Pmax[:,s],Prmax[:,s],COpe[:,]),1:nS)
</code>```

But I get this:

```<code>The applicable method may be too new: running in world age 21846, while current world is 21965.
</code>```

I'm using Julia 0.6 maybe the way i'm programming is from a older version.

Any idea?

答:
I recently had a similar issue with pmap() in 0.6. Try to assign the argument f in pmap(f,c...) to a concrete function, i.e.,

```<code>createPH(s) = PH(k,s,data,Lines,Ag,Gx,Pmax[:,s],Prmax[:,s],COpe[:,])
pmap(createPH,1:nS)
</code>```

This fixed the issue for me. (Also note that in 0.6.0 a warning is generated, and not a world age error)

Title: Julia 0.6 pmap function

Body:
I want to paralelize a decomposition algorithm for optimization named Progressive Hedging. This optimization is stored on a function named PH which recieve arguments for the model, some arguments are matrix but PH needs just a vector from that matrix in this way.

for s = 1:nS
    res = PH(k,s,data,Lines,Ag,Gx,Pmax[:,s],Prmax[:,s],COpe[:,s])
    push!(data,res)
end

So PH needs just a vector from Pmax, Prmax and COpe.

To paralelize I try to do this.

 pmap(s -> PH(k,s,data,Lines,Ag,Gx,Pmax[:,s],Prmax[:,s],COpe[:,]),1:nS)

But I get this:

The applicable method may be too new: running in world age 21846, while current world is 21965.

I'm using Julia 0.6 maybe the way i'm programming is from a older version.

Any idea?

Body:
I recently had a similar issue with pmap() in 0.6. Try to assign the argument f in pmap(f,c...) to a concrete function, i.e.,

createPH(s) = PH(k,s,data,Lines,Ag,Gx,Pmax[:,s],Prmax[:,s],COpe[:,])
pmap(createPH,1:nS)

This fixed the issue for me. (Also note that in 0.6.0 a warning is generated, and not a world age error)


问:
Catch multiple exceptions at once?
It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecessary repetitive code, for example:

```<code>try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}
</code>```

I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?

The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

答:
This is a classic problem every C# developer faces eventually.

Let me break your question into 2 questions.  The first,

Can I catch multiple exceptions at once?

In short, no.

Which leads to the next question,

How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?

Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:

Initialize WebId to the fall-back value.

Construct a new Guid in a temporary variable.

Set WebId to the fully constructed temporary variable.  Make this the final statement of the try{} block.

So the code looks like:

```<code>try
{
    WebId = Guid.Empty;
    Guid newGuid = new Guid(queryString["web"]);
    // More initialization code goes here like
    // newGuid.x = y;
    WebId = newGuid;
}
catch (FormatException) {}
catch (OverflowException) {}
</code>```

If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.

If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:

```<code>try
{
    WebId = new Guid(queryString["web"]);
    // More initialization code goes here.
}
catch (FormatException) {
    Reset(WebId);
}
catch (OverflowException) {
    Reset(WebId);
}
</code>```

OwnerDisplayName: Michael Stum

ContentLicense: CC BY-SA 4.0

Title: Catch multiple exceptions at once?

Body:
It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecessary repetitive code, for example:

try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}

I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?

The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

LastEditorDisplayName: Michael Stum

Body:
This is a classic problem every C# developer faces eventually.

Let me break your question into 2 questions.  The first,

Can I catch multiple exceptions at once?

In short, no.

Which leads to the next question,

How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?

Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:

Initialize WebId to the fall-back value.

Construct a new Guid in a temporary variable.

Set WebId to the fully constructed temporary variable.  Make this the final statement of the try{} block.

So the code looks like:

try
{
    WebId = Guid.Empty;
    Guid newGuid = new Guid(queryString["web"]);
    // More initialization code goes here like
    // newGuid.x = y;
    WebId = newGuid;
}
catch (FormatException) {}
catch (OverflowException) {}

If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.

If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:

try
{
    WebId = new Guid(queryString["web"]);
    // More initialization code goes here.
}
catch (FormatException) {
    Reset(WebId);
}
catch (OverflowException) {
    Reset(WebId);
}


问:
Last 8 used rows in excel. Powershell
I've looked all over and I can't seem to find an answer for this.  Instead of selecting from A1 to G8, I just want it to select the last 8 USED rows in the import it creates.  Not sure what to use here.      </p>

```<code>$pathtsv = "C:\xxxxxx.mdf"
$pathxlsx = "C:\xxxxxxxxxxxxxx.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true

$Workbook = $Excel.Workbooks.Open($pathxlsx)
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv)

$temp = $excel.Workbooks.Item(2)
$temp = $temp.Worksheets.Item(1)
$CopyRange = $temp.Range("A1:G8")
$CopyRange.Copy()
</code>```

<p>Thanks in advance.  </p>

答:
I'd recommend using the ImportExcel module by Doug Finke rather than using Excel as a COM Object. Then the Excel document can be easily imported as a PowerShell object which can then be filtered by Select-Object -Last 8 or $ImportedExcelObject[-8..-1] then reexported in what I assume a Tab Delimited format.

```<code>Install-Module ImportExcel

$pathtsv = "C:\xxxxxx.mdf"
$pathxlsx = "C:\xxxxxxxxxxxxxx.xlsx"

Import-Excel $pathxlsx | Select-Object -Last 8 | Export-CSV $pathtsv -Delimiter "`t"
</code>```

Note: The Install-Module command is included by default in PowerShell 5+.

Here is the updated code for going the opposite way from a tsv to a a specific row and column in an Excel document using the Export-Excel cmdlet from the ImportExcel Module.

```<code>Install-Module ImportExcel

$pathtsv = 'C:\xxxxxx.mdf'
$templatexls = 'C:\yyyyyyyyyy.xlsx'
$pathxlsx = 'C:\xxxxxxxxxxxxxx.xlsx'

Copy-Item $templatexls $pathxlsx
Import-CSV $pathtsv -Delimiter "`t" | Select-Object -Last 8 | Export-Excel -Path $pathxlsx -WorksheetName 'Sheet1' -Show -StartRow 3 -StartColumn 1 -NoHeader
</code>```

Title: Last 8 used rows in excel. Powershell

Body:
I've looked all over and I can't seem to find an answer for this.  Instead of selecting from A1 to G8, I just want it to select the last 8 USED rows in the import it creates.  Not sure what to use here.

$pathtsv = "C:\xxxxxx.mdf"
$pathxlsx = "C:\xxxxxxxxxxxxxx.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true

$Workbook = $Excel.Workbooks.Open($pathxlsx)
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv)

$temp = $excel.Workbooks.Item(2)
$temp = $temp.Worksheets.Item(1)
$CopyRange = $temp.Range("A1:G8")
$CopyRange.Copy()

Thanks in advance.

Body:
I'd recommend using the ImportExcel module by Doug Finke rather than using Excel as a COM Object. Then the Excel document can be easily imported as a PowerShell object which can then be filtered by Select-Object -Last 8 or $ImportedExcelObject[-8..-1] then reexported in what I assume a Tab Delimited format.

Install-Module ImportExcel

$pathtsv = "C:\xxxxxx.mdf"
$pathxlsx = "C:\xxxxxxxxxxxxxx.xlsx"

Import-Excel $pathxlsx | Select-Object -Last 8 | Export-CSV $pathtsv -Delimiter "`t"

Note: The Install-Module command is included by default in PowerShell 5+.

Here is the updated code for going the opposite way from a tsv to a a specific row and column in an Excel document using the Export-Excel cmdlet from the ImportExcel Module.

Install-Module ImportExcel

$pathtsv = 'C:\xxxxxx.mdf'
$templatexls = 'C:\yyyyyyyyyy.xlsx'
$pathxlsx = 'C:\xxxxxxxxxxxxxx.xlsx'

Copy-Item $templatexls $pathxlsx
Import-CSV $pathtsv -Delimiter "`t" | Select-Object -Last 8 | Export-Excel -Path $pathxlsx -WorksheetName 'Sheet1' -Show -StartRow 3 -StartColumn 1 -NoHeader


问:
[Rspec/Capybara]How can I detect page's content while it's loading by Visit method
I'm quite new to Rspec/Capybara.

I want to test how fast I can load my main content in my page before the page is fully loaded by visit method.

If I do this

```<code>starts = Time.now
visit "/"
pp Time.now - starts ******(this will start after visit "/" fully loaded)
test_time = Time.now - starts
test_time.should < 10
</code>```

The output in console would be 10.xxxx (10 seconds) because it does pp method after it finishes loading my home page (fully load all contents in page).

Is there anyway I can do something like this?

```<code>starts = Time.now
visit "/" do (visit and do something while it is loading)
  break if page.has_content("Main content appeared now !!") (Detect if the page has content "Main content appeared now !!" then break and stop loading page
end
pp Time.now - starts
test_time = Time.now - starts
test_time.should < 10
</code>```

and the result would be something like 2.12342 (because we stop visit to stop loading when it detects content

Or any way else I can detect content while page is loading.

答:
I don't think you can do this with capybara. Try using Selenium-Webdriver, though Selenium does not wait until page is completely loaded.</p>

```<code>driver = Selenium::WebDriver.for :chrome
driver.navigate.to url
while driver.find_elements(:id, 'element_id').size > 0
    sleep 0.1
end
test_time = Time.now - starts
p "#{test_time} seconds"
driver.quit
expect(test_time).to be < 10
</code>```

Body:
I'm quite new to Rspec/Capybara.

I want to test how fast I can load my main content in my page before the page is fully loaded by visit method.

If I do this

starts = Time.now
visit "/"
pp Time.now - starts ******(this will start after visit "/" fully loaded)
test_time = Time.now - starts
test_time.should < 10

The output in console would be 10.xxxx (10 seconds) because it does pp method after it finishes loading my home page (fully load all contents in page).

Is there anyway I can do something like this?

starts = Time.now
visit "/" do (visit and do something while it is loading)
  break if page.has_content("Main content appeared now !!") (Detect if the page has content "Main content appeared now !!" then break and stop loading page
end
pp Time.now - starts
test_time = Time.now - starts
test_time.should < 10

and the result would be something like 2.12342 (because we stop visit to stop loading when it detects content

Or any way else I can detect content while page is loading.

Body:
I don't think you can do this with capybara. Try using Selenium-Webdriver, though Selenium does not wait until page is completely loaded.

driver = Selenium::WebDriver.for :chrome
driver.navigate.to url
while driver.find_elements(:id, 'element_id').size > 0
    sleep 0.1
end
test_time = Time.now - starts
p "#{test_time} seconds"
driver.quit
expect(test_time).to be < 10


问:
How to use ImageBackground to set background image for screen in react-native
When I use  in react-native it gives warning that using  with children is deprecated and will be error in future. User  instead.

So,
If I use  it doesn't give expected result which I was getting using

Here is the code I wrote for using

```<code><ImageBackground source={require('../../img/splash/splash_bg.png')} style={styles.backgroundImage} >
        </ImageBackground>
</code>```

And style code is

```<code>const styles = StyleSheet.create({
backgroundImage: {
    flex: 1,
    // width: undefined,
    // height: undefined,
    // flexDirection: 'column',
    // backgroundColor:'transparent',
    // justifyContent: 'flex-start',

},}
</code>```

<img src="https://i.stack.imgur.com/dgTPz.jpg" alt="Expected result: getting when using <Image>">
<img src="https://i.stack.imgur.com/XdEVZ.jpg" alt="Result using <ImageBackground>">

答:
You can use "ImageBackground" component on React Native.</p>

```<code><ImageBackground
  source={yourSourceFile}
  style={{width: '100%', height: '100%'}}
>
    <....yourContent...>
</ImageBackground>
</code>```

Body:
When I use  in react-native it gives warning that using  with children is deprecated and will be error in future. User  instead.

So,
If I use  it doesn't give expected result which I was getting using

Here is the code I wrote for using

<ImageBackground source={require('../../img/splash/splash_bg.png')} style={styles.backgroundImage} >
        </ImageBackground>

And style code is

const styles = StyleSheet.create({
backgroundImage: {
    flex: 1,
    // width: undefined,
    // height: undefined,
    // flexDirection: 'column',
    // backgroundColor:'transparent',
    // justifyContent: 'flex-start',

},}

<img src="https://i.stack.imgur.com/dgTPz.jpg" alt="Expected result: getting when using <Image>">
<img src="https://i.stack.imgur.com/XdEVZ.jpg" alt="Result using <ImageBackground>">

Body:
You can use "ImageBackground" component on React Native.

<ImageBackground
  source={yourSourceFile}
  style={{width: '100%', height: '100%'}}
>
    <....yourContent...>
</ImageBackground>


问:
Killing processes opened with popen()?
I'm opening a long-running process with popen().  For debugging, I'd like to terminate the process before it has completed.  Calling pclose() just blocks until the child completes.

How can I kill the process?  I don't see any easy way to get the pid out of the resource that popen() returns so that I can send it a signal.

I suppose I could do something kludgey and try to fudge the pid into the output using some sort of command-line hackery...

答:
Well, landed on a solution: I switched back to proc_open() instead of popen().  Then it's as simple as:

```<code>$s = proc_get_status($p);
posix_kill($s['pid'], SIGKILL);
proc_close($p);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Killing processes opened with popen()?

Body:
Well, landed on a solution: I switched back to proc_open() instead of popen().  Then it's as simple as:

$s = proc_get_status($p);
posix_kill($s['pid'], SIGKILL);
proc_close($p);


问:
How do I concatenate two System.IO.Stream instances into one?
Let's imagine I want to stream three files to a user all in a row, but instead of him handing me a Stream object to push bytes down, I have to hand him a Stream object he'll pull bytes from. I'd like to take my three FileStream objects (or even cleverer, an IEnumerable<Stream>) and return a new ConcatenatedStream object that would pull from the source streams on demand.

答:
Edit: Made it clear this is a seekable option.

Here is an option that supports seeking which is necessary in many situations. It is missing some functionality for disposing the underlying streams and could be a little more efficient if you were willing to assume that the underlying streams do not change length. Total length and stream offsets could then be calculated once.

```<code>public sealed class SeekableConcatenatedStream : Stream
{
    List<Stream> streams;
    private long _Position { get; set; }

    public SeekableConcatenatedStream(List<Stream> streams)
    {
        foreach (var s in streams)
        {
          if (!s.CanSeek)
              throw new ArgumentException($"All provided streams must be be seekable to create a {nameof(SeekableConcatenatedStream)}");
        }

        this.streams = streams;
        Seek(0, SeekOrigin.Begin);
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        if (streams.Count == 0)
            return 0;

        var startStream = 0;
        var cumulativeCapacity = 0L;
        for (var i = 0; i < streams.Count; i++)
        {
            cumulativeCapacity += streams[i].Length;
            if (_Position < cumulativeCapacity)
            {
                startStream = i;
                break;
            }
        }

        var bytesRead = 0;
        var curStream = startStream;

        while (_Position < Length && bytesRead < count && curStream < streams.Count)
        {
            var r = streams[curStream].Read(buffer, offset + bytesRead, count - bytesRead);
            bytesRead += r;
            Seek(_Position + r, SeekOrigin.Begin);
            curStream++;
        }

        return bytesRead;
    }

    public override bool CanSeek
    {
        get { return true; }
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void Flush()
    {
        throw new NotImplementedException();
    }

    public override long Length
    {
        get {
            long length = 0;
            for (var i = 0; i < streams.Count; i++)
            {
                length += streams[i].Length;
            }
            return length;
        }
    }

    public override long Position
    {
        get
        {
            return _Position;
        }
        set
        {
            Seek(value, SeekOrigin.Begin);
        }
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        if (origin == SeekOrigin.Begin)
        {
            _Position = offset;

            var prevLength = 0L;
            var cumulativeLength = 0L;
            for (var i = 0; i < streams.Count; i++)
            {
                cumulativeLength += streams[i].Length;
                if (offset < cumulativeLength)
                {
                    streams[i].Seek(offset - prevLength, SeekOrigin.Begin);
                    return _Position;
                }
                prevLength = cumulativeLength;
            }
        }

        if (origin == SeekOrigin.Current)
        {
            var newAbs = _Position + offset;
            return Seek(newAbs, SeekOrigin.Begin);
        }
        else if(origin == SeekOrigin.End)
        {
            var newAbs = Length - offset;
            return Seek(newAbs, SeekOrigin.Begin);
        }

        throw new NotImplementedException();
    }

    public override void SetLength(long value)
    {
        throw new NotImplementedException();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
Edit: Made it clear this is a seekable option.

Here is an option that supports seeking which is necessary in many situations. It is missing some functionality for disposing the underlying streams and could be a little more efficient if you were willing to assume that the underlying streams do not change length. Total length and stream offsets could then be calculated once.

public sealed class SeekableConcatenatedStream : Stream
{
    List<Stream> streams;
    private long _Position { get; set; }

    public SeekableConcatenatedStream(List<Stream> streams)
    {
        foreach (var s in streams)
        {
          if (!s.CanSeek)
              throw new ArgumentException($"All provided streams must be be seekable to create a {nameof(SeekableConcatenatedStream)}");
        }

        this.streams = streams;
        Seek(0, SeekOrigin.Begin);
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        if (streams.Count == 0)
            return 0;

        var startStream = 0;
        var cumulativeCapacity = 0L;
        for (var i = 0; i < streams.Count; i++)
        {
            cumulativeCapacity += streams[i].Length;
            if (_Position < cumulativeCapacity)
            {
                startStream = i;
                break;
            }
        }

        var bytesRead = 0;
        var curStream = startStream;

        while (_Position < Length && bytesRead < count && curStream < streams.Count)
        {
            var r = streams[curStream].Read(buffer, offset + bytesRead, count - bytesRead);
            bytesRead += r;
            Seek(_Position + r, SeekOrigin.Begin);
            curStream++;
        }

        return bytesRead;
    }

    public override bool CanSeek
    {
        get { return true; }
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void Flush()
    {
        throw new NotImplementedException();
    }

    public override long Length
    {
        get {
            long length = 0;
            for (var i = 0; i < streams.Count; i++)
            {
                length += streams[i].Length;
            }
            return length;
        }
    }

    public override long Position
    {
        get
        {
            return _Position;
        }
        set
        {
            Seek(value, SeekOrigin.Begin);
        }
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        if (origin == SeekOrigin.Begin)
        {
            _Position = offset;

            var prevLength = 0L;
            var cumulativeLength = 0L;
            for (var i = 0; i < streams.Count; i++)
            {
                cumulativeLength += streams[i].Length;
                if (offset < cumulativeLength)
                {
                    streams[i].Seek(offset - prevLength, SeekOrigin.Begin);
                    return _Position;
                }
                prevLength = cumulativeLength;
            }
        }

        if (origin == SeekOrigin.Current)
        {
            var newAbs = _Position + offset;
            return Seek(newAbs, SeekOrigin.Begin);
        }
        else if(origin == SeekOrigin.End)
        {
            var newAbs = Length - offset;
            return Seek(newAbs, SeekOrigin.Begin);
        }

        throw new NotImplementedException();
    }

    public override void SetLength(long value)
    {
        throw new NotImplementedException();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new NotImplementedException();
    }
}


问:
How to add more objects to my file every time i run my program?
This is my saveTable button which saves one row of my table and than puts it into my Auto.auto file,but i can only save one object(row) of Auto type. Every time i save another line(row) it replaces the old one whith the new one so at the end i have only one object(row of table) in my file after clicking save button for like 5 times while my program is running. How can I solve this?

```<code>        saveTable.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = Integer.parseInt(textField.getText());
            getText.getAuto(row);
            File tabel = new File("C:\\Users\\Jovan\\Desktop\\Auto.auto");
            try {
                if (!(tabel.exists())) {
                    tabel.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(tabel);
                ObjectOutputStream oos1 = new ObjectOutputStream(fos);
                oos1.writeObject(getText.getAuto(row));
                oos1.close();

                ObjectOutputStream os2 = new ObjectOutputStream(new FileOutputStream(tabel, true)) {
                    protected void writeStreamHeader() throws IOException {
                        reset();
                    }
                };

                os2.writeObject(getText.getAuto(row));
                os2.close();

            } catch (IOException  error) {
                error.printStackTrace();
            }
        }

    });
</code>```

答:
```<code>new FileOutputStream(tabel, true)
</code>```

The second parameter means that you will append to that file instead of overwriting it

public FileOutputStream(File file,
                  boolean append)
                   throws FileNotFoundException

Creates a file output stream to write to the file represented by the specified File object.
  If the second argument is true, then bytes will be written to the end
  of the file rather than the beginning. A new FileDescriptor object is
  created to represent this file connection. First, if there is a
  security manager, its checkWrite method is called with the path
  represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does
  not exist but cannot be created, or cannot be opened for any other
  reason then a FileNotFoundException is thrown.

Reference here

Body:
This is my saveTable button which saves one row of my table and than puts it into my Auto.auto file,but i can only save one object(row) of Auto type. Every time i save another line(row) it replaces the old one whith the new one so at the end i have only one object(row of table) in my file after clicking save button for like 5 times while my program is running. How can I solve this?

        saveTable.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = Integer.parseInt(textField.getText());
            getText.getAuto(row);
            File tabel = new File("C:\\Users\\Jovan\\Desktop\\Auto.auto");
            try {
                if (!(tabel.exists())) {
                    tabel.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(tabel);
                ObjectOutputStream oos1 = new ObjectOutputStream(fos);
                oos1.writeObject(getText.getAuto(row));
                oos1.close();

                ObjectOutputStream os2 = new ObjectOutputStream(new FileOutputStream(tabel, true)) {
                    protected void writeStreamHeader() throws IOException {
                        reset();
                    }
                };

                os2.writeObject(getText.getAuto(row));
                os2.close();

            } catch (IOException  error) {
                error.printStackTrace();
            }
        }

    });

Body:
new FileOutputStream(tabel, true)

The second parameter means that you will append to that file instead of overwriting it

public FileOutputStream(File file,
                  boolean append)
                   throws FileNotFoundException

Creates a file output stream to write to the file represented by the specified File object.
  If the second argument is true, then bytes will be written to the end
  of the file rather than the beginning. A new FileDescriptor object is
  created to represent this file connection. First, if there is a
  security manager, its checkWrite method is called with the path
  represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does
  not exist but cannot be created, or cannot be opened for any other
  reason then a FileNotFoundException is thrown.

Reference here


问:
Python 2.X : Regex to find all company names ending in ".inc"
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

```<code>aa = re.findall('inc\.,? (.*?inc\.)', text)
</code>```

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

答:
Bit late to the party since an answer has already been accepted, but anyway, here's a solution that uses Python's built-in re module rather than the third-party regex module.

Your attempt correctly anchors the end of the company name on inc. but you need some way to capture the start of the name. Let's define a company name as:

A word starting with a capital letter or a number, followed by,

Optionally one or more additional words, since a firm may have a one-word name. These need not start with an uppercase letter. Then, finally,

inc.

Further, we'll define a word as a string of letters and/or numbers possibly containing one or more hyphens. Normally we would use \w to represent a word character, but that doesn't include hyphens, so we'll need to match that separately.

So:

A word starting with a capital letter or a number: [A-Z0-9](?:\w|-)*

Zero or more additional words, each denoted as: (?:\w|-)+

inc\.

Words are separated by white space, which we will denote as \s+. So for #2's "optional one or more words" we must create a group that includes one or more word characters (including hyphen) followed by one or more space characters, and repeat that group zero or more times: (?:(?:\w|-)+\s+)*

So, putting it all together and adding \b at the start make sure it starts with a whole word:

```<code>re.findall(r"\b[A-Z0-9](?:\w|-)*\s+(?:(?:\w|-)+\s+)*inc\.", text)
</code>```

To extend this so you can also catch names ending with Ltd. or Sons and to also catch capitalized Inc. and make the period optional:

```<code>re.findall(r"\b[A-Z0-9](?:\w|-)*\s+(?:(?:\w|-)+\s+)*(?:[Ii]nc?|[Ll]td|[Ss]ons)(?:\.|\b)?", text)
</code>```

Body:
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

aa = re.findall('inc\.,? (.*?inc\.)', text)

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

Body:
Bit late to the party since an answer has already been accepted, but anyway, here's a solution that uses Python's built-in re module rather than the third-party regex module.

Your attempt correctly anchors the end of the company name on inc. but you need some way to capture the start of the name. Let's define a company name as:

A word starting with a capital letter or a number, followed by,

Optionally one or more additional words, since a firm may have a one-word name. These need not start with an uppercase letter. Then, finally,

inc.

Further, we'll define a word as a string of letters and/or numbers possibly containing one or more hyphens. Normally we would use \w to represent a word character, but that doesn't include hyphens, so we'll need to match that separately.

So:

A word starting with a capital letter or a number: [A-Z0-9](?:\w|-)*

Zero or more additional words, each denoted as: (?:\w|-)+

inc\.

Words are separated by white space, which we will denote as \s+. So for #2's "optional one or more words" we must create a group that includes one or more word characters (including hyphen) followed by one or more space characters, and repeat that group zero or more times: (?:(?:\w|-)+\s+)*

So, putting it all together and adding \b at the start make sure it starts with a whole word:

re.findall(r"\b[A-Z0-9](?:\w|-)*\s+(?:(?:\w|-)+\s+)*inc\.", text)

To extend this so you can also catch names ending with Ltd. or Sons and to also catch capitalized Inc. and make the period optional:

re.findall(r"\b[A-Z0-9](?:\w|-)*\s+(?:(?:\w|-)+\s+)*(?:[Ii]nc?|[Ll]td|[Ss]ons)(?:\.|\b)?", text)


问:
Call an event listener from angular 4 service
Let's say I have a component like this :

```<code>@Component({
  selector: 'app-root',

  template: `
  <button class="btn btn-primary"
  (click)="buttonClicked()">testbutton</button>`,

  styleUrls: ['./app.component.css']
})

export class AppComponent {
   constructor(private testService : TestService) {
      // some code
    }
    buttonClicked(){
       console.log("clicked");
    }
}
</code>```

Now, there is a service called TestService. Is it possible to add another event listener(clickEvent listener) to the same button in TestService?

I am trying add two event listeners, but one being in the component file, other in service file.

For example, it is possible if done in jquery like :

```<code>$(document).on('click', 'button', function(){
     console.log("button clicked outside of component");
}
</code>```

答:
Update Based on your Use Case comment, I don't think there's a good way to listen to every button click without modifying component files. The clearest design is to call the service's method from every click event.

The only other hacky way I know of is to put a click event on your app component element and use the passed $event to decide to log or not.

app.component.html

```<code><div class="template page-container" (click)="onClicked($event)">
   <router-outlet></router-outlet>
</div>
</code>```

app.component.ts

```<code>onClicked(e: any) {
  console.log(e);
  let pointerEvent = e as PointerEvent;
  if (pointerEvent) {
    let target = pointerEvent.target as HTMLButtonElement;
    if (target) {
      let isButtonClick = !target.disabled;
      if(isButtonClick) {
         //do something
      }
    }
  }
}
</code>```

Original
I don't know what your use case is for doing it, but Angular lets you call two methods for an event.

Edit: You should expose the private service in a public property so the template can access it.

```<code>@Component({
  selector: 'app-root',

  template: `
  <button class="btn btn-primary"
  (click)="buttonClicked(); myTestService.buttonClicked()">testbutton</button>`,

  styleUrls: ['./app.component.css']
})
export class AppComponent {
   constructor(private testService : TestService) {
      // some code
    }

    get myTestService() {
       return this.testService;
    }

    buttonClicked(){
       console.log("clicked");
    }
}
</code>```

Can you say why? There is probably a better way to do what you need.

Body:
Let's say I have a component like this :

@Component({
  selector: 'app-root',

  template: `
  <button class="btn btn-primary"
  (click)="buttonClicked()">testbutton</button>`,

  styleUrls: ['./app.component.css']
})

export class AppComponent {
   constructor(private testService : TestService) {
      // some code
    }
    buttonClicked(){
       console.log("clicked");
    }
}

Now, there is a service called TestService. Is it possible to add another event listener(clickEvent listener) to the same button in TestService?

I am trying add two event listeners, but one being in the component file, other in service file.

For example, it is possible if done in jquery like :

$(document).on('click', 'button', function(){
     console.log("button clicked outside of component");
}

Body:
Update Based on your Use Case comment, I don't think there's a good way to listen to every button click without modifying component files. The clearest design is to call the service's method from every click event.

The only other hacky way I know of is to put a click event on your app component element and use the passed $event to decide to log or not.

app.component.html

<div class="template page-container" (click)="onClicked($event)">
   <router-outlet></router-outlet>
</div>

app.component.ts

onClicked(e: any) {
  console.log(e);
  let pointerEvent = e as PointerEvent;
  if (pointerEvent) {
    let target = pointerEvent.target as HTMLButtonElement;
    if (target) {
      let isButtonClick = !target.disabled;
      if(isButtonClick) {
         //do something
      }
    }
  }
}

Original
I don't know what your use case is for doing it, but Angular lets you call two methods for an event.

Edit: You should expose the private service in a public property so the template can access it.

@Component({
  selector: 'app-root',

  template: `
  <button class="btn btn-primary"
  (click)="buttonClicked(); myTestService.buttonClicked()">testbutton</button>`,

  styleUrls: ['./app.component.css']
})
export class AppComponent {
   constructor(private testService : TestService) {
      // some code
    }

    get myTestService() {
       return this.testService;
    }

    buttonClicked(){
       console.log("clicked");
    }
}

Can you say why? There is probably a better way to do what you need.


问:
How to convert strings with even or odd numbers to 0 or 1?
Starting with the data of this form:

```<code>    col_1   col_2
0   a1      a6
1   a3      a7
2   a4      a2
3   a5      a8
</code>```

Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame:

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

How I can approach this?

答:
Using str.extract</p>

```<code>df = df.apply(lambda x: ((x.str.extract('(\d+)', expand = False)).astype(int) % 2 != 0).astype(int))

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

Body:
Starting with the data of this form:

    col_1   col_2
0   a1      a6
1   a3      a7
2   a4      a2
3   a5      a8

Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame:

    col_1   col_2
0   1       0
1   1       1
2   0       0
3   1       0

How I can approach this?

Body:
Using str.extract

df = df.apply(lambda x: ((x.str.extract('(\d+)', expand = False)).astype(int) % 2 != 0).astype(int))

    col_1   col_2
0   1       0
1   1       1
2   0       0
3   1       0


问:
Get diffuse map RGB data from Qt3D PickEvent
I am developing an application using Qt3D's Scene3D components. I have loaded a mesh obj into the Scene3D and applying a PNG image as diffuse map via QDiffuseMapMaterial. Great so far, object renders with map correct.

Now, I need to get the RGB properties for a picked vertex using a QPickEvent. I aquire a few vertex properties like so:

```<code>ESEctoPoint ES3DAnalysisEntity::getVertexDataFromIndex(quint32 idx)
{
    ESEctoPoint vData;
    vData.vIndex = idx;

    const QGeometry *geometry = m_mesh->geometry();
    for (QAttribute* attribute : geometry->attributes())
    {
        if (attribute->name() == defaultTextureCoordinateAttributeName())
        {
            vData.vTexCoord = extractVertexData<QVector2D, uint>(attribute, idx);
        }
...
    }

    return vData;
}
</code>```

I then have the vertex index, position, and uv texture coordinates. Now, what I need is the RGB data from the uv position for the given vertex. How do I go about getting that data? I am keeping the diffuse material and the QTextureImage containing the diffuse map in memory. I'm sure there's a way to get the RGB value, I just need a little help with how to translate the uv texture coordinate to QTextureImage and get the pixel data.

FOLLOWUP

Using the answer given, I am holding the image in a QImage object, I get the vertex position, followed by texture coordinates. Using the texture coordinates, I am able to get the pixel position and the pixel's color using this small function:

```<code>QColor getPixelColorForTexturePos(QVector2D const& uvPos, QImage* map)
{
    auto x = uvPos.x() * map->width();
    auto y = map->height() - (uvPos.y() * map->height());
    return map->pixelColor((int)x, (int)y);
}
</code>```

答:
The QTextureImage does not hold the image data itself, it just holds information about the texture that was uploaded to OpenGL.

It is possible to get the texture data back with raw OpenGL. There is probably some way to do it using Qt too, but I would not recommend it. Copying data between GPU and CPU is slow, so better to avoid it if not necessary.

I would recommend to keep the texture loaded in a QImage, then you can easily query to pixel colors using pixel(..) or pixelColor(..) methods. It may seem wasteful to have it loaded twice, but if you need to access the pixel data from CPU, there is no better way.

Body:
I am developing an application using Qt3D's Scene3D components. I have loaded a mesh obj into the Scene3D and applying a PNG image as diffuse map via QDiffuseMapMaterial. Great so far, object renders with map correct.

Now, I need to get the RGB properties for a picked vertex using a QPickEvent. I aquire a few vertex properties like so:

ESEctoPoint ES3DAnalysisEntity::getVertexDataFromIndex(quint32 idx)
{
    ESEctoPoint vData;
    vData.vIndex = idx;

    const QGeometry *geometry = m_mesh->geometry();
    for (QAttribute* attribute : geometry->attributes())
    {
        if (attribute->name() == defaultTextureCoordinateAttributeName())
        {
            vData.vTexCoord = extractVertexData<QVector2D, uint>(attribute, idx);
        }
...
    }

    return vData;
}

I then have the vertex index, position, and uv texture coordinates. Now, what I need is the RGB data from the uv position for the given vertex. How do I go about getting that data? I am keeping the diffuse material and the QTextureImage containing the diffuse map in memory. I'm sure there's a way to get the RGB value, I just need a little help with how to translate the uv texture coordinate to QTextureImage and get the pixel data.

FOLLOWUP

Using the answer given, I am holding the image in a QImage object, I get the vertex position, followed by texture coordinates. Using the texture coordinates, I am able to get the pixel position and the pixel's color using this small function:

QColor getPixelColorForTexturePos(QVector2D const& uvPos, QImage* map)
{
    auto x = uvPos.x() * map->width();
    auto y = map->height() - (uvPos.y() * map->height());
    return map->pixelColor((int)x, (int)y);
}


问:
Wordpress wp-admin fatal error
I have just switched my website's hosting and it is giving me error in opening the wordpress admin panel page. Can any body help me out. Thankyou

Fatal error: Uncaught Error: Call to undefined function eregi() in
  /home/atifchat/public_html/pakistanivoicechat.com/wp-content/plugins/google-bot-bling/google-bot-bling.php:59
  Stack trace: #0
  /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/class-wp-hook.php(298):
  thisismyurl_google_bot_bling_init_code('') #1
  /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/class-wp-hook.php(323):
  WP_Hook->apply_filters(NULL, Array) #2
  /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/plugin.php(453):
  WP_Hook->do_action(Array) #3
  /home/atifchat/public_html/pakistanivoicechat.com/wp-settings.php(448):
  do_action('init') #4
  /home/atifchat/public_html/pakistanivoicechat.com/wp-config.php(104):
  require_once('/home/atifchat/...') #5
  /home/atifchat/public_html/pakistanivoicechat.com/wp-load.php(37):
  require_once('/home/atifchat/...') #6
  /home/atifchat/public_html/pakistanivoicechat.com/wp-admin/admin.php(31):
  require_once('/home/atifchat/...') #7
  /home/atifchat/public_html/pakistanivoicechat.com/wp-admin/in in
  /home/atifchat/public_html/pakistanivoicechat.com/wp-content/plugins/google-bot-bling/google-bot-bling.php
  on line 59

答:
The eregi() function, actually, the entire ereg_* family of functions was removed entirely in PHP 7.x. According to your error log, you have a voice chat plugin still using those functions.

```<code>Stack trace: #0 /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/class-wp-hook.php
</code>```

Suggestion: Contact plugin developer and ask them to update.

Title: Wordpress wp-admin fatal error

Body:
The eregi() function, actually, the entire ereg_* family of functions was removed entirely in PHP 7.x. According to your error log, you have a voice chat plugin still using those functions.

Stack trace: #0 /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/class-wp-hook.php

Suggestion: Contact plugin developer and ask them to update.


问:
Host Styles Applied to Component in Angular2
I am currently in the process of creating a custom form component for my Angular component and am running into some styling issues.

I'd like for my input to be able to take variable widths and for them to be controlled by the host component.

For example: <my-input class="input"> would have a corresponding class as such:

```<code>.input {
    width: 250px;
}
</code>```

For some reason, if I do this, the rules are just ignored and not applied to my component.

I've seen others wrap their components in what seems like unnecessary divs and then styling those parent divs so that the content inside fits. I don't want to write wrappers just for styling purposes when a CSS rule would suffice.

Would doing this involve using :host ?
Also, how about, host-context(.input) and then applying the classes inside of the consumers CSS ?

答:
I would advice against using ::ng-deep since the Angular team is planning on deprecating it.

If you want to style something within your component from whatever component is hosting yours I suggest you create a host-binding/input and then use that value to bind to your component using the style-directive.

Body:
I am currently in the process of creating a custom form component for my Angular component and am running into some styling issues.

I'd like for my input to be able to take variable widths and for them to be controlled by the host component.

For example: <my-input class="input"> would have a corresponding class as such:

.input {
    width: 250px;
}

For some reason, if I do this, the rules are just ignored and not applied to my component.

I've seen others wrap their components in what seems like unnecessary divs and then styling those parent divs so that the content inside fits. I don't want to write wrappers just for styling purposes when a CSS rule would suffice.

Would doing this involve using :host ?
Also, how about, host-context(.input) and then applying the classes inside of the consumers CSS ?


问:
Is there any way to revert changes from a specific file to the latest commit?
I just did add>commit>push and everything worked fine. Then made many changes and made some more pushes. But now one file is buggy and I need to revert only that file to the latest commit not the whole project. How can I do that without losing rest of my changes? </p>

答:
I think you misunderstand what git reset does. There are several ways to use this command. If you have made some changes and do not want to commit them, you can do git rest --hard HEAD to throw away all the changes. This does not change any of your existing commit history. It only changes the contents of the current working directory.

If you want to revert the local copy back to the latest commit but still save the changes you have made in order to reference them later, you can use git stash. Later git stash pop or git stash apply will restore the most recent stash.


问:
Converting socket.io data to JSON in Swift
I'm writing a socket.io client and I'm having trouble getting the emitted data into any usable format.

My handler is:

```<code>socket.on("foriEvent") { data, ack in
    print(data)
}
</code>```

which prints:

```<code>[
   {
      "foriEvent":{
         "eventType":"location",
         "state":"moving",
         "latitude":"60.4413407",
         "longitude":"22.2476208",
         "accuracy":"20",
         "ts":1510653600189
      }
   }
]
</code>```

I have a Struct that "looks" like that data, and I would like to use something like this where the from object is of type Data.

```<code>let decoder = JSONDecoder()
let foriEvent = try decoder.decode(ForiEvent.self, from: data)
</code>```

Currently I'm using the following to get a Data object, but when I send it to decoder.decode, I get the following error message:

```<code>return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
</code>```

```<code>error trying to convert data to JSON typeMismatch(Swift.Dictionary<Swift.String, Any>,
Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
</code>```

Could it be my struct? What should it look like? The Struct looks like this right now:

```<code>struct ForiEvent : Codable {
    var eventType: String?
    var state : String?
    var latitude: String?
    var longitude : String?
    var accuracy : String?
    var timeStamp : CLong?
}

struct ForiData : Codable {
    var foriEvent : ForiEvent?
}
</code>```

答:
I use swiftyjson for this. It does a great job.

You haven't defined what type the data is but if it is a string which it looks like it is from the print command that you have then you can do this.

```<code>    guard let dataFromString = data[0].data(using: String.Encoding.utf8, allowLossyConversion: false) else {return}
    var swiftyJson:JSON!
    do {
        swiftyJson = try JSON(data: dataFromString)
    } catch {
        print("Error JSON: \(error)")
    }
</code>```

This will give you the data in JSON format which you can very easily parse using swiftyjson into the custom type you have outlined above. The reason that Codable might not be working is because your JSON is returned as an array of JSON.

Try this

```<code>let tempVar = swiftyJson["foriEvent"]["eventType"].string
print("test \(tempVar)")
</code>```

Body:
I'm writing a socket.io client and I'm having trouble getting the emitted data into any usable format.

My handler is:

socket.on("foriEvent") { data, ack in
    print(data)
}

which prints:

[
   {
      "foriEvent":{
         "eventType":"location",
         "state":"moving",
         "latitude":"60.4413407",
         "longitude":"22.2476208",
         "accuracy":"20",
         "ts":1510653600189
      }
   }
]

I have a Struct that "looks" like that data, and I would like to use something like this where the from object is of type Data.

let decoder = JSONDecoder()
let foriEvent = try decoder.decode(ForiEvent.self, from: data)

Currently I'm using the following to get a Data object, but when I send it to decoder.decode, I get the following error message:

return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)

error trying to convert data to JSON typeMismatch(Swift.Dictionary<Swift.String, Any>,
Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

Could it be my struct? What should it look like? The Struct looks like this right now:

struct ForiEvent : Codable {
    var eventType: String?
    var state : String?
    var latitude: String?
    var longitude : String?
    var accuracy : String?
    var timeStamp : CLong?
}

struct ForiData : Codable {
    var foriEvent : ForiEvent?
}

Body:
I use swiftyjson for this. It does a great job.

You haven't defined what type the data is but if it is a string which it looks like it is from the print command that you have then you can do this.

    guard let dataFromString = data[0].data(using: String.Encoding.utf8, allowLossyConversion: false) else {return}
    var swiftyJson:JSON!
    do {
        swiftyJson = try JSON(data: dataFromString)
    } catch {
        print("Error JSON: \(error)")
    }

This will give you the data in JSON format which you can very easily parse using swiftyjson into the custom type you have outlined above. The reason that Codable might not be working is because your JSON is returned as an array of JSON.

Try this

let tempVar = swiftyJson["foriEvent"]["eventType"].string
print("test \(tempVar)")


问:
raspberry pi controlling relay, led on relay lights up but NO switch not closing
I hear no switching sounds from relay.

I connected

JD-VCC to Pin2 (5V)

GND to Pin6 (Ground)

IN1 to pin7 (Gpio4)

VCC to Pin1 (3V)

Connected 240V DC to NO and COM.

gpio export 4 out lets the led on the relay lighten in red.

What is going wrong?

This project shall replace and old viessmann alogue time switch by a switch controlled by pi. .

Is my setup and wiring correct? I am sorry this is my first pi project. Can someone please double check the setup and wiring?

This is the old clock case:

答: I can't see your images, so forgive me, but is it possible your relay takes 5v to close the switch? Have you tried just using plain wires to a 5v source to see if it's your relay or your pi?</p>


问:
Issues with embedding IronPython 2 in a C# web application
First Some Background (incase it helps):

My application is a Web-based framework recently upgraded to v3.5 of the .Net Framework but does not use a Master Pages / User Controls system.  It's more akin to the MVC pattern (although much older) and outputs pure HTML down the response stream from Templates.  The Python expressions allow some rules and template variations to be achieved.

The old way

When embedding the IronPython 1.x engine in C#, we were able to do code such as:

```<code>PythonEngine pe = new PythonEngine();
Assembly a = Assembly.LoadFile("path to assembly");
pe.LoadAssembly(a);
pe.Import("Script");
</code>```

there is no Import() method in ipy 2.0 and the ImportModule() method doesn't seem to work the same way.  The Import() alleviated the need to put a line in every python script we write, such as:

```<code>from MyAssembly import MyClass
</code>```

the fact that MyClass is full of static methods, means that calls to MyClass.MyMethod() work really well.  I can't just instansiate an object and assign it to a variable in scope as the assembly that MyClass is contained in is dynamically loaded at runtime.

Now to the issue

I have sorted out all the other parts of the integration of IronPython 2.0 but would prefer not to require my implementers to type "from MyAssembly import MyClass" at the top of every script they write (just seems silly when it was not necessary in ipy 1.x) and likely to be a support issue for a while too.

And finally the question

Has anyone had this issue and resolved it? Am I doing things the wrong way for the DLR? or am I missing something obvious?

I'm not sure of the detail required for someone to help, but I hope this is enough.

答:
Once the assembly's loaded, you can execute the import in the Scope you're using to run the script:

```<code>ScriptEngine engine = Python.CreateEngine();
engine.Runtime.LoadAssembly(a);
string code = "from MyAssembly import MyClass";
ScriptSource source = engine.CreateScriptSourceFromString(code, "<import>", SourceCodeKind.Statements);
CompiledCode c = source.Compile();

Scope scope = engine.CreateScope();
c.Execute(scope);

// then run your script in the same scope
</code>```

We do something similar in our product.

(Hopefully this is valid C# - I actually tried it in IronPython itself, because it was more convenient.)

OwnerDisplayName: kolosan

Body:
First Some Background (incase it helps):

My application is a Web-based framework recently upgraded to v3.5 of the .Net Framework but does not use a Master Pages / User Controls system.  It's more akin to the MVC pattern (although much older) and outputs pure HTML down the response stream from Templates.  The Python expressions allow some rules and template variations to be achieved.

The old way

When embedding the IronPython 1.x engine in C#, we were able to do code such as:

PythonEngine pe = new PythonEngine();
Assembly a = Assembly.LoadFile("path to assembly");
pe.LoadAssembly(a);
pe.Import("Script");

there is no Import() method in ipy 2.0 and the ImportModule() method doesn't seem to work the same way.  The Import() alleviated the need to put a line in every python script we write, such as:

from MyAssembly import MyClass

the fact that MyClass is full of static methods, means that calls to MyClass.MyMethod() work really well.  I can't just instansiate an object and assign it to a variable in scope as the assembly that MyClass is contained in is dynamically loaded at runtime.

Now to the issue

I have sorted out all the other parts of the integration of IronPython 2.0 but would prefer not to require my implementers to type "from MyAssembly import MyClass" at the top of every script they write (just seems silly when it was not necessary in ipy 1.x) and likely to be a support issue for a while too.

And finally the question

Has anyone had this issue and resolved it? Am I doing things the wrong way for the DLR? or am I missing something obvious?

I'm not sure of the detail required for someone to help, but I hope this is enough.

Body:
Once the assembly's loaded, you can execute the import in the Scope you're using to run the script:

ScriptEngine engine = Python.CreateEngine();
engine.Runtime.LoadAssembly(a);
string code = "from MyAssembly import MyClass";
ScriptSource source = engine.CreateScriptSourceFromString(code, "<import>", SourceCodeKind.Statements);
CompiledCode c = source.Compile();

Scope scope = engine.CreateScope();
c.Execute(scope);

// then run your script in the same scope

We do something similar in our product.

(Hopefully this is valid C# - I actually tried it in IronPython itself, because it was more convenient.)

OwnerDisplayName: wilberforce


问:
Extending a class that implements Serializable
If I extend a class that implements Serializable, do I need that class to also implement Serializable?

For instance if I have,

```<code>public class classToBeExtended implements Serializable
</code>```

Then will this suffice?

```<code>public class classThatWillExtend extends classToExtended
</code>```

Or do I need to do this?

```<code>public class classThatWillExtend extends classToExtended implements Serializable
</code>```

答:
Per Javadoc:

All subtypes of a serializable class are themselves serializable

Body:
If I extend a class that implements Serializable, do I need that class to also implement Serializable?

For instance if I have,

public class classToBeExtended implements Serializable

Then will this suffice?

public class classThatWillExtend extends classToExtended

Or do I need to do this?

public class classThatWillExtend extends classToExtended implements Serializable


问:
Trouble Uncompressing Zip and then parsing CSV with Google Apps Script
Trying to create a Google Apps Script that reads emails from a specific email address and copy the contents of a CSV file into a Google sheet.

Problem is sometimes the files come in as zip attachments.    I'm trying to work logic into the script to uncompress the zip if it's a zip attachment and then post the data to the Google sheet.

Currently getting the following error message:  Cannot find function getDataAsString in object Blob.

Any ideas / recommendations for getting this to work with potential zip files would be great.

You can find my full code below:

```<code>function myFunction() {
    var threads = GmailApp.search("from:testemail@example.com");
    var message = threads[0].getMessages()[0];
    var attachment = message.getAttachments()[0];
    Logger.log(attachment.getContentType());
    // Is the attachment a CSV file
    if (attachment.getContentType() === "text/csv") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
      Logger.log("Found a CSV file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
    if (attachment.getContentType() === "application/zip") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var files = Utilities.unzip(attachment);
      Logger.log(files);
        var newDriveFile = DriveApp.createFile(files[0]);
        var csvData = Utilities.parseCsv(files.getDataAsString(), ",");
        Logger.log("Found a ZIP file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
}
</code>```

答:
Utilities.unzip will return array of blobs. So you need to refer the particular blob inside the array of blobs. Just modify the below code snippet.

```<code>var files = Utilities.unzip(attachment)[0];
</code>```

Also, it is safe to mention the charset so that special characters are displayed properly.

```<code>var csvData = Utilities.parseCsv(attachment.getDataAsString('ISO-8859-1'), ",");
</code>```

Entire Function:

```<code>function exportData() {
    var threads = GmailApp.search("from:testemail@example.com");
    var message = threads[0].getMessages()[0];
    var attachment = message.getAttachments()[0];
    Logger.log(attachment.getContentType());
    // Is the attachment a CSV file
    if (attachment.getContentType() === "text/csv") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var csvData = Utilities.parseCsv(attachment.getDataAsString('ISO-8859-1'), ",");
      Logger.log("Found a CSV file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
    if (attachment.getContentType() === "application/zip") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var files = Utilities.unzip(attachment)[0];
        var csvData = Utilities.parseCsv(files.getDataAsString('ISO-8859-1'), ",");
        Logger.log("Found a ZIP file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
}
</code>```

Body:
Trying to create a Google Apps Script that reads emails from a specific email address and copy the contents of a CSV file into a Google sheet.

Problem is sometimes the files come in as zip attachments.    I'm trying to work logic into the script to uncompress the zip if it's a zip attachment and then post the data to the Google sheet.

Currently getting the following error message:  Cannot find function getDataAsString in object Blob.

Any ideas / recommendations for getting this to work with potential zip files would be great.

You can find my full code below:

function myFunction() {
    var threads = GmailApp.search("from:testemail@example.com");
    var message = threads[0].getMessages()[0];
    var attachment = message.getAttachments()[0];
    Logger.log(attachment.getContentType());
    // Is the attachment a CSV file
    if (attachment.getContentType() === "text/csv") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
      Logger.log("Found a CSV file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
    if (attachment.getContentType() === "application/zip") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var files = Utilities.unzip(attachment);
      Logger.log(files);
        var newDriveFile = DriveApp.createFile(files[0]);
        var csvData = Utilities.parseCsv(files.getDataAsString(), ",");
        Logger.log("Found a ZIP file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
}

Body:
Utilities.unzip will return array of blobs. So you need to refer the particular blob inside the array of blobs. Just modify the below code snippet.

var files = Utilities.unzip(attachment)[0];

Also, it is safe to mention the charset so that special characters are displayed properly.

var csvData = Utilities.parseCsv(attachment.getDataAsString('ISO-8859-1'), ",");

Entire Function:

function exportData() {
    var threads = GmailApp.search("from:testemail@example.com");
    var message = threads[0].getMessages()[0];
    var attachment = message.getAttachments()[0];
    Logger.log(attachment.getContentType());
    // Is the attachment a CSV file
    if (attachment.getContentType() === "text/csv") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var csvData = Utilities.parseCsv(attachment.getDataAsString('ISO-8859-1'), ",");
      Logger.log("Found a CSV file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
    if (attachment.getContentType() === "application/zip") {
        var sheet = SpreadsheetApp.getActiveSheet();
        var files = Utilities.unzip(attachment)[0];
        var csvData = Utilities.parseCsv(files.getDataAsString('ISO-8859-1'), ",");
        Logger.log("Found a ZIP file");
        // Remember to clear the content of the sheet before importing new data
        sheet.clearContents().clearFormats();
        sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
}


问:
Customizing Crawlera Ban Rules For Scrapy
I'm in the process of updating a (formerly) working website crawler. It appears the website I have been crawling has introduced stricter ban rules, so I have begun to use Crawlera as an attempt to circumvent this issue.

The problem I'm having currently is that the target website is using a non-standard banning approach of doing a 302 to a standard html page. Crawlera is not detecting this as a ban and immediately stops the crawl. Is there any way I can customize what Crawlera detects as a ban, or will I need to look into another approach?

答:
I think you can ask them to insert that rule into their system and also depending on your plan, they should offer you a way to customize your own rules (still, you can ask their support, I am not completely sure).

I would say that is your best bet, if not, I would recommend creating your own Downloader Middlewares to retry when that redirect happens. What crawlera does when they get a ban is to retry n more times (you can set that also on the headers), so you'll have to set retries to 0 and handle those yourself depending on what response you get.


问:
How to query vsts artifacts with tags
we would like to query artefacts with tags to trigger parallel deployments. How should we do that? Is there an UI or do we have to use the API ?</p>

答: There is no UI for this, you're going to be looking at the VSTS Build Rest API to build this.</p>

Title: How to query vsts artifacts with tags