问:
MasterPage Load Theme
on asp.net C#,
i want to change the theme when page is load, this action requiers PreInit Event, Which Masterpage dont have. what is the solution for that issue?

thanks,

答:
Aside from an Module, you could consider having all your pages inherit from a base page that defines PreInit and sets the theme accordingly.

Edit for comment.

There isn't all that much to it, just make sure the pages you create inherit from a class similar to the BasePage class below instead of the default Page class and you should be set.

```<code>public class BasePage : Page
{
  public BasePage()
  {
    this.PreInit += new EventHandler(BasePage_PreInit);
  }

  protected void BasePage_PreInit(object sender, EventArgs e)
  {
    this.Page.Theme = theme; //Garner from appropriate resource
  }
}
</code>```

Hope that helps.

Title: MasterPage Load Theme

Body:
Aside from an Module, you could consider having all your pages inherit from a base page that defines PreInit and sets the theme accordingly.

Edit for comment.

There isn't all that much to it, just make sure the pages you create inherit from a class similar to the BasePage class below instead of the default Page class and you should be set.

public class BasePage : Page
{
  public BasePage()
  {
    this.PreInit += new EventHandler(BasePage_PreInit);
  }

  protected void BasePage_PreInit(object sender, EventArgs e)
  {
    this.Page.Theme = theme; //Garner from appropriate resource
  }
}

Hope that helps.


来源: stackexchange

问:
How to find if excel column has a sequence?
How to find if excel column contains the sequence i am looking for?

for example column 1 contains A B C D A B B C D A B and i would like to find if the column contains A B and would like to know the row number in which it starts from. similar to the example here.

I found a solution from the website http://www.get-digital-help.com/2014/10/28/find-a-sequence/? but it doesn't seem to work.

答:
This is a great question -- essentially, how do we use MATCH for 2 criteria, not just one. We can do this via array formulas. In essence, we're going to make a new array, that concatenates each possible combination of sequential entries (so in the example, it would look like AB,BC,CD,DA,AB,BB,BC...). Then we can search that as need be for 'AB'.

The formula looks like this:

```<code>=MATCH("A"&"B",A1:A100&A2:A101,0)
</code>```

Or more generally:

```<code>=MATCH([Criteria 1]&[Criteria 2],[Data 1st val]:[Data last val]&[Data 2nd val]:[Data last + 1 val],0)
</code>```

A very important note: after writing in the formula, do not press Enter, press Ctrl+Shift+Enter. This tells Excel to treat it as an array formula. If done correctly, you should see curly braces around the formula.

ContentLicense: CC BY-SA 3.0

Body:
This is a great question -- essentially, how do we use MATCH for 2 criteria, not just one. We can do this via array formulas. In essence, we're going to make a new array, that concatenates each possible combination of sequential entries (so in the example, it would look like AB,BC,CD,DA,AB,BB,BC...). Then we can search that as need be for 'AB'.

The formula looks like this:

=MATCH("A"&"B",A1:A100&A2:A101,0)

Or more generally:

=MATCH([Criteria 1]&[Criteria 2],[Data 1st val]:[Data last val]&[Data 2nd val]:[Data last + 1 val],0)

A very important note: after writing in the formula, do not press Enter, press Ctrl+Shift+Enter. This tells Excel to treat it as an array formula. If done correctly, you should see curly braces around the formula.


问:
Perl exit code 17920 on sendmail
i have the problem with my software on my server with plesk.
I send one email from perl script but system return  the following error:

```<code>error closing /usr/lib/sendmail:  (exit 17920)
</code>```

why recive this error?
In the maillog i recive this error:

```<code>Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: handlers_stderr: PASS
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: PASS during call 'limit-out' handler
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: Unable to rename '/usr/local/psa/handlers/spool/messageEFbeQO' file: Permission denied
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: System error (/usr/local/psa/handlers/spool/messageEFbeQO): No such file or directory
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7710]: Unable to open temporary file `/usr/local/psa/handlers/spool/messageEFbeQO' (2): No such file or directory
</code>```

and i not have idea where the problem.
i hope have said all information.

答:
This might be caused by selinux (if it's enabled on your server). You can check that by issuing the command bellow:

```<code>sestatus
</code>```

If the output says permissive or disabled then selinux is not the issue.

Also this link might help you in fixing your mail problem on your plesk server:
https://support.plesk.com/hc/en-us/articles/213947085-Mail-server-does-not-work-How-to-repair-the-mail-server-configuration

Title: Perl exit code 17920 on sendmail

Body:
i have the problem with my software on my server with plesk.
I send one email from perl script but system return  the following error:

error closing /usr/lib/sendmail:  (exit 17920)

why recive this error?
In the maillog i recive this error:

Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: handlers_stderr: PASS
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: PASS during call 'limit-out' handler
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: Unable to rename '/usr/local/psa/handlers/spool/messageEFbeQO' file: Permission denied
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7708]: System error (/usr/local/psa/handlers/spool/messageEFbeQO): No such file or directory
Jun 29 11:23:57 ip-xxx-xx-xx-xxx journal: plesk sendmail[7710]: Unable to open temporary file `/usr/local/psa/handlers/spool/messageEFbeQO' (2): No such file or directory

and i not have idea where the problem.
i hope have said all information.

Body:
This might be caused by selinux (if it's enabled on your server). You can check that by issuing the command bellow:

sestatus

If the output says permissive or disabled then selinux is not the issue.

Also this link might help you in fixing your mail problem on your plesk server:
https://support.plesk.com/hc/en-us/articles/213947085-Mail-server-does-not-work-How-to-repair-the-mail-server-configuration


问:
'Double join' nested MySQL query?
as a beginner, I'm struggling with this for a few hours now, any help is much appreciated :D

I have 3 tables:

```<code>threads (id, title)
tags (id, name)
tag_thread (thread_id, tag_id)
</code>```

The following, working code returns the 5 most used tags (names) of the latest 100 threads:

```<code>select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5
</code>```

Question: Given there is a $tagId, how would I have to change to query to filter the results so that only those tags show up, which are connected to threads that use tags with $tagId?

Thank you very much!

答:
If it were me, I would take a slightly different approach to the problem. This should offer faster performance and is easier to read in my opinion:

```<code>SELECT * FROM (
  SELECT ta.name, COUNT(ta.name) AS tag_count
  FROM threads th
  JOIN tag_thread tt
    ON tt.tag_id = th.id
  JOIN tags ta
    ON ta.id = tt.thread_id
  GROUP BY ta.name
  ORDER BY th.id DESC LIMIT 100
)
ORDER BY tag_count DESC LIMIT 5
</code>```

It's generally a good idea to eliminate subselects in joins and aggregates in the ORDER BY clause. If you had an index on ta.name, it would be ignored in your query and a full table scan would be performed regardless.

I saw your pastebin but I'm not entirely convinced I understand what you're trying to do. Please comment below if I misunderstood.

Title: 'Double join' nested MySQL query?

Body:
as a beginner, I'm struggling with this for a few hours now, any help is much appreciated :D

I have 3 tables:

threads (id, title)
tags (id, name)
tag_thread (thread_id, tag_id)

The following, working code returns the 5 most used tags (names) of the latest 100 threads:

select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5

Question: Given there is a $tagId, how would I have to change to query to filter the results so that only those tags show up, which are connected to threads that use tags with $tagId?

Thank you very much!

Body:
If it were me, I would take a slightly different approach to the problem. This should offer faster performance and is easier to read in my opinion:

SELECT * FROM (
  SELECT ta.name, COUNT(ta.name) AS tag_count
  FROM threads th
  JOIN tag_thread tt
    ON tt.tag_id = th.id
  JOIN tags ta
    ON ta.id = tt.thread_id
  GROUP BY ta.name
  ORDER BY th.id DESC LIMIT 100
)
ORDER BY tag_count DESC LIMIT 5

It's generally a good idea to eliminate subselects in joins and aggregates in the ORDER BY clause. If you had an index on ta.name, it would be ignored in your query and a full table scan would be performed regardless.

I saw your pastebin but I'm not entirely convinced I understand what you're trying to do. Please comment below if I misunderstood.


问:
Keybind Shortcuts - Opening other views from MainView - MVVM
I'm creating a bidding program to give customers quotes. I'm using WPF + MVVM

What I would like to do is to be able to create a shortcut (Ctrl+O) from the main page directly to the view that enables me to select which bid I want to open.

I can't imagine it is very difficult, I just seem to be missing something. I've looked for the answer in other threads. It is possible that I have missed it, if I have, please let me know and refer me to where the answer can be found.

答:
Assuming you already have a command you are calling when clicking the button to open the other view you could use an InputBinding

Something like this should do the work

```<code><Window>
    <Window.InputBindings>
        <KeyBinding Command="{Binding OpenSecondViewCommand}"
                    Modifiers="Control"
                    Key="O"/>
    </Window.InputBindings>
 </Window>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Assuming you already have a command you are calling when clicking the button to open the other view you could use an InputBinding

Something like this should do the work

<Window>
    <Window.InputBindings>
        <KeyBinding Command="{Binding OpenSecondViewCommand}"
                    Modifiers="Control"
                    Key="O"/>
    </Window.InputBindings>
 </Window>


问:
Why is disruptor slower with smaller ring buffer?
Following the Disruptor Getting Started Guide, I've built a minimal disruptor with a single producer and single consumer.

Producer

```<code>import com.lmax.disruptor.RingBuffer;

public class LongEventProducer
{
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
    {
        this.ringBuffer = ringBuffer;
    }

    public void onData()
    {
        long sequence = ringBuffer.next();
        try
        {
            LongEvent event = ringBuffer.get(sequence);
        }
        finally
        {
            ringBuffer.publish(sequence);
        }
    }
}
</code>```

Consumer (Notice the consumer does nothing onEvent)

```<code>import com.lmax.disruptor.EventHandler;

public class LongEventHandler implements EventHandler<LongEvent>
{
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
    {}
}
</code>```

My goal was to performance test going around a large ring buffer once versus traversing a smaller ring multiple times.  In each case the total ops (bufferSize X rotations) is the same.  I found was that the ops/sec rate fell drastically as the ring buffer got smaller.

```<code>RingBuffer Size |  Revolutions  | Total Ops   |   Mops/sec

    1048576     |      1        |  1048576    |     50-60

       1024     |      1024     |  1048576    |     8-16

        64      |      16384    |  1048576    |    0.5-0.7

        8       |      131072   |  1048576    |    0.12-0.14
</code>```

Question: what is the reason for the massive degradation of performance when the ring buffer size is reduced but the total iterations is fixed?  This trend is independent of the WaitStrategy and Single vs MultiProducer- the throughput is reduced, but the trend is the same.

Main (notice SingleProducer and BusySpinWaitStrategy)

```<code>import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class LongEventMainJava{
        static double ONEMILLION = 1000000.0;
        static double ONEBILLION = 1000000000.0;

    public static void main(String[] args) throws Exception {
            // Executor that will be used to construct new threads for consumers
            Executor executor = Executors.newCachedThreadPool();

            // TUNABLE PARAMS
            int ringBufferSize = 1048576; // 1024, 64, 8
            int rotations = 1; // 1024, 16384, 131702

            // Construct the Disruptor
            Disruptor disruptor = new Disruptor<>(new LongEventFactory(), ringBufferSize, executor, ProducerType.SINGLE, new BusySpinWaitStrategy());

            // Connect the handler
            disruptor.handleEventsWith(new LongEventHandler());

            // Start the Disruptor, starts all threads running
            disruptor.start();

            // Get the ring buffer from the Disruptor to be used for publishing.
            RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
            LongEventProducer producer = new LongEventProducer(ringBuffer);

            long start = System.nanoTime();
            long totalIterations = rotations * ringBufferSize;
            for (long i = 0; i < totalIterations; i++) {
                producer.onData();
            }
            double duration = (System.nanoTime()-start)/ONEBILLION;
            System.out.println(String.format("Buffersize: %s, rotations: %s, total iterations = %s, duration: %.2f seconds, rate: %.2f Mops/s",
                    ringBufferSize, rotations, totalIterations, duration, totalIterations/(ONEMILLION * duration)));
        }
}
</code>```

And to run, you'll need the trivial Factory code

```<code>import com.lmax.disruptor.EventFactory;

public class LongEventFactory implements EventFactory<LongEvent>
{
    public LongEvent newInstance()
    {
        return new LongEvent();
    }
}
</code>```

Running on core i5-2400, 12GB ram, windows 7

Sample Output

```<code>Buffersize: 1048576, rotations: 1, total iterations = 1048576, duration: 0.02 seconds, rate: 59.03 Mops/s

Buffersize: 64, rotations: 16384, total iterations = 1048576, duration: 2.01 seconds, rate: 0.52 Mops/s
</code>```

答:
Seems like the issue lies in this block of code in lmax\disruptor\SingleProducerSequencer

```<code>if (wrapPoint > cachedGatingSequence || cachedGatingSequence > nextValue)
        {
            cursor.setVolatile(nextValue);  // StoreLoad fence

            long minSequence;
            while (wrapPoint > (minSequence = Util.getMinimumSequence(gatingSequences, nextValue)))
            {
                waitStrategy.signalAllWhenBlocking();
                LockSupport.parkNanos(1L); // TODO: Use waitStrategy to spin?
            }

            this.cachedValue = minSequence;
        }
</code>```

Particularly the call to LockSupport.parkNanos(1L).  This can take up to 15ms on Windows.  When the producer gets to the end of the buffer and is waiting on the consumer, this gets called.

Secondly, when the buffer is small, the false sharing of the RingBuffer is likely occurring.  I surmise both of these effect are in play.

Finally, I was able to speed up the code using JIT with one million calls to onData() before benchmarking.  This got the best case up > 80Mops/sec, but did not remove the degradation with buffer shrinkage.

Body:
Following the Disruptor Getting Started Guide, I've built a minimal disruptor with a single producer and single consumer.

Producer

import com.lmax.disruptor.RingBuffer;

public class LongEventProducer
{
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
    {
        this.ringBuffer = ringBuffer;
    }

    public void onData()
    {
        long sequence = ringBuffer.next();
        try
        {
            LongEvent event = ringBuffer.get(sequence);
        }
        finally
        {
            ringBuffer.publish(sequence);
        }
    }
}

Consumer (Notice the consumer does nothing onEvent)

import com.lmax.disruptor.EventHandler;

public class LongEventHandler implements EventHandler<LongEvent>
{
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
    {}
}

My goal was to performance test going around a large ring buffer once versus traversing a smaller ring multiple times.  In each case the total ops (bufferSize X rotations) is the same.  I found was that the ops/sec rate fell drastically as the ring buffer got smaller.

RingBuffer Size |  Revolutions  | Total Ops   |   Mops/sec

    1048576     |      1        |  1048576    |     50-60

       1024     |      1024     |  1048576    |     8-16

        64      |      16384    |  1048576    |    0.5-0.7

        8       |      131072   |  1048576    |    0.12-0.14

Question: what is the reason for the massive degradation of performance when the ring buffer size is reduced but the total iterations is fixed?  This trend is independent of the WaitStrategy and Single vs MultiProducer- the throughput is reduced, but the trend is the same.

Main (notice SingleProducer and BusySpinWaitStrategy)

import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class LongEventMainJava{
        static double ONEMILLION = 1000000.0;
        static double ONEBILLION = 1000000000.0;

    public static void main(String[] args) throws Exception {
            // Executor that will be used to construct new threads for consumers
            Executor executor = Executors.newCachedThreadPool();

            // TUNABLE PARAMS
            int ringBufferSize = 1048576; // 1024, 64, 8
            int rotations = 1; // 1024, 16384, 131702

            // Construct the Disruptor
            Disruptor disruptor = new Disruptor<>(new LongEventFactory(), ringBufferSize, executor, ProducerType.SINGLE, new BusySpinWaitStrategy());

            // Connect the handler
            disruptor.handleEventsWith(new LongEventHandler());

            // Start the Disruptor, starts all threads running
            disruptor.start();

            // Get the ring buffer from the Disruptor to be used for publishing.
            RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
            LongEventProducer producer = new LongEventProducer(ringBuffer);

            long start = System.nanoTime();
            long totalIterations = rotations * ringBufferSize;
            for (long i = 0; i < totalIterations; i++) {
                producer.onData();
            }
            double duration = (System.nanoTime()-start)/ONEBILLION;
            System.out.println(String.format("Buffersize: %s, rotations: %s, total iterations = %s, duration: %.2f seconds, rate: %.2f Mops/s",
                    ringBufferSize, rotations, totalIterations, duration, totalIterations/(ONEMILLION * duration)));
        }
}

And to run, you'll need the trivial Factory code

import com.lmax.disruptor.EventFactory;

public class LongEventFactory implements EventFactory<LongEvent>
{
    public LongEvent newInstance()
    {
        return new LongEvent();
    }
}

Running on core i5-2400, 12GB ram, windows 7

Sample Output

Buffersize: 1048576, rotations: 1, total iterations = 1048576, duration: 0.02 seconds, rate: 59.03 Mops/s

Buffersize: 64, rotations: 16384, total iterations = 1048576, duration: 2.01 seconds, rate: 0.52 Mops/s

Body:
Seems like the issue lies in this block of code in lmax\disruptor\SingleProducerSequencer

if (wrapPoint > cachedGatingSequence || cachedGatingSequence > nextValue)
        {
            cursor.setVolatile(nextValue);  // StoreLoad fence

            long minSequence;
            while (wrapPoint > (minSequence = Util.getMinimumSequence(gatingSequences, nextValue)))
            {
                waitStrategy.signalAllWhenBlocking();
                LockSupport.parkNanos(1L); // TODO: Use waitStrategy to spin?
            }

            this.cachedValue = minSequence;
        }

Particularly the call to LockSupport.parkNanos(1L).  This can take up to 15ms on Windows.  When the producer gets to the end of the buffer and is waiting on the consumer, this gets called.

Secondly, when the buffer is small, the false sharing of the RingBuffer is likely occurring.  I surmise both of these effect are in play.

Finally, I was able to speed up the code using JIT with one million calls to onData() before benchmarking.  This got the best case up > 80Mops/sec, but did not remove the degradation with buffer shrinkage.


问:
matweb.com: How to get source of page?
I have url like:

http://www.matweb.com/search/DataSheet.aspx?MatGUID=849e2916ab1541be9ff6a17b78f95c82

I want to download source code from that page using this code:

```<code>private static string urlTemplate = @"http://www.matweb.com/search/DataSheet.aspx?MatGUID=";

static string GetSource(string guid)
{
    try
    {
        Uri url = new Uri(urlTemplate + guid);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";

        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        String result = responseStreamReader.ReadToEnd();

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}
</code>```

When I do so I get:

You do not seem to have cookies enabled. MatWeb Requires cookies to be enabled.

Ok, that I understand, so I added lines:

```<code>CookieContainer cc = new CookieContainer();
webRequest.CookieContainer = cc;
</code>```

I got:

Your IP Address has been restricted due to excessive use. The problem may be compounded when an IP address may be shared by many people in a company or through an internet service provider. We apologize for any inconvenience.

I can understand this but I'm not getting this message when I try to visit this page using web browser. What can I do to get the source code? Some cookies or http headers?

答: It looks like you're doing something that the company doesn't like, if you got an "excessive use" response.</p>

ContentLicense: CC BY-SA 2.5

Title: matweb.com: How to get source of page?

Body:
I have url like:

http://www.matweb.com/search/DataSheet.aspx?MatGUID=849e2916ab1541be9ff6a17b78f95c82

I want to download source code from that page using this code:

private static string urlTemplate = @"http://www.matweb.com/search/DataSheet.aspx?MatGUID=";

static string GetSource(string guid)
{
    try
    {
        Uri url = new Uri(urlTemplate + guid);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";

        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        String result = responseStreamReader.ReadToEnd();

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}

When I do so I get:

You do not seem to have cookies enabled. MatWeb Requires cookies to be enabled.

Ok, that I understand, so I added lines:

CookieContainer cc = new CookieContainer();
webRequest.CookieContainer = cc;

I got:

Your IP Address has been restricted due to excessive use. The problem may be compounded when an IP address may be shared by many people in a company or through an internet service provider. We apologize for any inconvenience.

I can understand this but I'm not getting this message when I try to visit this page using web browser. What can I do to get the source code? Some cookies or http headers?


问:
What is the maximum number of event source mappings per AWS Lambda?
I cannot find this limitation listed anywhere in the AWS Documentation for maximum number of event sources to trigger one Lambda.

I have a Lambda which will be triggered by an indefinitely growing number of S3 Buckets. Obviously this will only work if the maximum number of buckets exceeds the maximum number of triggers. Is there a maximium? If so, what is it, and can it be increased?

答: There's a paginated response to http://docs.aws.amazon.com/lambda/latest/dg/API_ListEventSourceMappings.html , and since I can find no info on the lambda limits page, I bet there's no limit (or at least there's some huge number you don't have to practically worry about).</p>


问:
Curator Hierarchy Locking (overlapping locks)
I was able to successfully get lock on /ads/lock/0-test1 and then couldn't get a lock on /ads/lock

How can I solve this?

```<code>InterProcessMutex lock1 = new InterProcessMutex(client, "/ads/lock/0-test1");
if(lock1.acquire(30000, TimeUnit.MILLISECONDS)){
   InterProcessMutex lock2 = new InterProcessMutex(client, "/ads/lock");

   if(lock2.acquire(30000, TimeUnit.MILLISECONDS)) {  //Failing
   ...
   }
}
</code>```

Update: This is the essence of what's happening in this https://github.com/Microsoft/Cluster-Partition-Rebalancer-For-Kafka/ZookeeperBackedAdoptionLogicImpl.java Locks at line 250(detailed path) and 299(Root path) are sequential. So, when another instance tries the lock a detailed path (250), the lock fails as the root path (299) is locked. The logic is valid but the root lock is never obtained

Update 2: I wrote a small program to check whether overlapping locks work and It does.

```<code>public class LockTesting {
    public static final String ROOT_LOCK = "/locks";
    public static final String CHILD_LOCK = ROOT_LOCK+"/child";
    private static CuratorFramework client;

    public static void main(String[] args) throws Exception {

        client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 30));
        client.start();
        InterProcessMutex lock1 = new InterProcessMutex(client, CHILD_LOCK);
        if (lock1.acquire(30000, TimeUnit.MILLISECONDS)) {
            System.out.println("Child Locked");
            InterProcessMutex lock2 = new InterProcessMutex(client, ROOT_LOCK);
            if (lock2.acquire(30000, TimeUnit.MILLISECONDS)) {
                System.out.println("Root Locked");
            }
        }

    }
}
</code>```

答:
While not documented explicitly (but see technote 7), the mechanisms used by curator to create the lock depend on the child nodes of a particular znode path.  The InterProcessMutex is an implementation of the zookeeper lock recipe, whose documentation does include these details.  By trying to use a hierarchical construct like this, you are essentially messing with the internal structure of the lock.

The path to lock should be considered an "object" whose internal znodes are inaccessible and subject to change.

Response to Update

The code in question is indeed an example of this inappropriate use.

Response to Update2

Yes, it can sometimes work.  But it depends on internal details of the InterProcessMutex implementation.  You'll find that with some lock names this will work and with others it will not or you'll have undefined behavior.

Body:
I was able to successfully get lock on /ads/lock/0-test1 and then couldn't get a lock on /ads/lock

How can I solve this?

InterProcessMutex lock1 = new InterProcessMutex(client, "/ads/lock/0-test1");
if(lock1.acquire(30000, TimeUnit.MILLISECONDS)){
   InterProcessMutex lock2 = new InterProcessMutex(client, "/ads/lock");

   if(lock2.acquire(30000, TimeUnit.MILLISECONDS)) {  //Failing
   ...
   }
}

Update: This is the essence of what's happening in this https://github.com/Microsoft/Cluster-Partition-Rebalancer-For-Kafka/ZookeeperBackedAdoptionLogicImpl.java Locks at line 250(detailed path) and 299(Root path) are sequential. So, when another instance tries the lock a detailed path (250), the lock fails as the root path (299) is locked. The logic is valid but the root lock is never obtained

Update 2: I wrote a small program to check whether overlapping locks work and It does.

public class LockTesting {
    public static final String ROOT_LOCK = "/locks";
    public static final String CHILD_LOCK = ROOT_LOCK+"/child";
    private static CuratorFramework client;

    public static void main(String[] args) throws Exception {

        client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 30));
        client.start();
        InterProcessMutex lock1 = new InterProcessMutex(client, CHILD_LOCK);
        if (lock1.acquire(30000, TimeUnit.MILLISECONDS)) {
            System.out.println("Child Locked");
            InterProcessMutex lock2 = new InterProcessMutex(client, ROOT_LOCK);
            if (lock2.acquire(30000, TimeUnit.MILLISECONDS)) {
                System.out.println("Root Locked");
            }
        }

    }
}


问:
NuGet push to TFS Feed publishes nuget as V2 but TFS Build expect to restore V3
I have setup a NuGet Package feed in TFS 2017 Update 1.
The NuGet Source is as following

http://tfsserver:8080/tfs/defaultcollection/_packaging/NuGet-Feed/nuget/v3/index.json

Following the instructions stated when connecting to TFS Package Feed, I added NuGet source locally and also try to publish package(s) to the NuGet Feed with following format as an example:

```<code>nuget.exe  push -Source "NuGet-Feed" -ApiKey INCTX Microsoft.AspNetCore.Http.Abstractions.1.1.2.nupkg
</code>```

The result of executing above command is as following:

```<code>Pushing Microsoft.AspNetCore.Http.Abstractions.1.1.2.nupkg to 'http://tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nug
et/v2/'...
  PUT http://mtrlpqdc2av-053:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v2/
  Accepted http://mtrlpqdc2av-053:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v2/ 1702ms
Your package was pushed.
</code>```

As it shows, the package is published to 'nuget/v2' endpoint.

Running TFS Build with NuGet Restore task: the following command expects
 nuget/V3/ endpoint from the TFS Feed which does not exists.
Note: NuGet restore task in TFS build is customized to use NuGet 4.. version.

GET http://tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.aspnetcore.http.abstractions/1.1.2/microsoft.aspnetcore.http.abstractions.1.1.2.nupkg

The question I guess is why NuGet Push will publish to 'nuget/v2/' endpoint.

TFS Build NuGet Restore Task output:

```<code>2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: URI: http://tfsserver:8080/tfs/defaultcollection/_packaging/INCTX-NuGet-Feed/nuget/v3/index.json
</code>```

2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: Is retry: False

2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: Matched prefix:

2017-07-06T15:58:13.2688422Z CredentialProvider.TeamBuild: This provider only
handles URIs from the build's Team Project Collection

2017-07-06T15:58:13.6125991Z   GET tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.netcore.app/index.json

2017-07-06T15:58:13.6125991Z   GET tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.netcore.app/index.json

2017-07-06T15:58:13.7219799Z   NotFound

Thanks,

Mamrez

答:
You may want to check your nuget.config and reference the following:

https://learn.microsoft.com/en-us/nuget/tools/nuget-exe-cli-reference#push

it says you can either specify it on push or define DefaultPushSource in the config. I might suspect your v2 source is defined as DefaultPushSource in the config.

try: nuget.exe config DefaultPushSource to see what it is set to.

Body:
I have setup a NuGet Package feed in TFS 2017 Update 1.
The NuGet Source is as following

http://tfsserver:8080/tfs/defaultcollection/_packaging/NuGet-Feed/nuget/v3/index.json

Following the instructions stated when connecting to TFS Package Feed, I added NuGet source locally and also try to publish package(s) to the NuGet Feed with following format as an example:

nuget.exe  push -Source "NuGet-Feed" -ApiKey INCTX Microsoft.AspNetCore.Http.Abstractions.1.1.2.nupkg

The result of executing above command is as following:

Pushing Microsoft.AspNetCore.Http.Abstractions.1.1.2.nupkg to 'http://tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nug
et/v2/'...
  PUT http://mtrlpqdc2av-053:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v2/
  Accepted http://mtrlpqdc2av-053:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v2/ 1702ms
Your package was pushed.

As it shows, the package is published to 'nuget/v2' endpoint.

Running TFS Build with NuGet Restore task: the following command expects
 nuget/V3/ endpoint from the TFS Feed which does not exists.
Note: NuGet restore task in TFS build is customized to use NuGet 4.. version.

GET http://tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.aspnetcore.http.abstractions/1.1.2/microsoft.aspnetcore.http.abstractions.1.1.2.nupkg

The question I guess is why NuGet Push will publish to 'nuget/v2/' endpoint.

TFS Build NuGet Restore Task output:

2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: URI: http://tfsserver:8080/tfs/defaultcollection/_packaging/INCTX-NuGet-Feed/nuget/v3/index.json

2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: Is retry: False

2017-07-06T15:58:13.0657118Z CredentialProvider.TeamBuild: Matched prefix:

2017-07-06T15:58:13.2688422Z CredentialProvider.TeamBuild: This provider only
handles URIs from the build's Team Project Collection

2017-07-06T15:58:13.6125991Z   GET tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.netcore.app/index.json

2017-07-06T15:58:13.6125991Z   GET tfsserver:8080/tfs/DefaultCollection/_packaging/23093bd8-41aa-403d-9d3f-5c713b14ce32/nuget/v3/flat2/microsoft.netcore.app/index.json

2017-07-06T15:58:13.7219799Z   NotFound

Thanks,

Mamrez


问:
How to check if the dictionary has only one key with value "1"
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.

Here is the working code which I tried, but want to know if there is any way to optimize the same?

```<code>>>> trmode_data = {'continuous': 1, 'fixed': 1}

>>> new = []
>>> for k, v in trmode_data.items():
...  if v == 1:
...   new.append(k)

>>> if len(new) > 1:
...  print "unexpected"
...
unexpected
</code>```

Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.

答:
Since you know your dict has exactly 2 items, you can use all in combination with a comprehension:

```<code>if all(val==1 for val in trmode_data.values()):
    print('unexpected')
</code>```

Alternatively, a more generic approach would be to use sum:

```<code>if sum(val==1 for val in trmode_data.values()) > 1:
    print('unexpected')
</code>```

Body:
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.

Here is the working code which I tried, but want to know if there is any way to optimize the same?

>>> trmode_data = {'continuous': 1, 'fixed': 1}

>>> new = []
>>> for k, v in trmode_data.items():
...  if v == 1:
...   new.append(k)

>>> if len(new) > 1:
...  print "unexpected"
...
unexpected

Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.

Body:
Since you know your dict has exactly 2 items, you can use all in combination with a comprehension:

if all(val==1 for val in trmode_data.values()):
    print('unexpected')

Alternatively, a more generic approach would be to use sum:

if sum(val==1 for val in trmode_data.values()) > 1:
    print('unexpected')


问:
Created thread does not run simultaneously with main C#
I have created a thread, but the thread pauses the main process after I start it. The thread loads some images from google, but when the internet connection is lost the user interface is unusable.

This is the thread:

```<code>string searchWord = "car photo";
PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html);
        this.Dispatcher.Invoke(() =>
        {
            if (SearchedImagesUrls.Count > 0)
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = new Uri(SearchedImagesUrls[0]);
                image.EndInit();
                SelectPhotoImage.Source = image;
            }
        });
    }
});

PhotoSearchThread.Start();
</code>```

Well threads should run simultaneously, then why this thread is interrupting other threads?

答:
Invoke is used to run code on the main or UI thread.  Specifically for updating UI elements as those can only be updated by that thread.  Currently you have code that loads the image in the Invoke.  Instead you should only put the part of the code that updates the UI inside of the Invoke.

```<code>PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html);

        if (SearchedImagesUrls.Count > 0)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(SearchedImagesUrls[0]);
            image.EndInit();
            this.Dispatcher.Invoke(() =>
            {
                SelectPhotoImage.Source = image;
            });
        }
    }
});
</code>```

Body:
I have created a thread, but the thread pauses the main process after I start it. The thread loads some images from google, but when the internet connection is lost the user interface is unusable.

This is the thread:

string searchWord = "car photo";
PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html);
        this.Dispatcher.Invoke(() =>
        {
            if (SearchedImagesUrls.Count > 0)
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = new Uri(SearchedImagesUrls[0]);
                image.EndInit();
                SelectPhotoImage.Source = image;
            }
        });
    }
});

PhotoSearchThread.Start();

Well threads should run simultaneously, then why this thread is interrupting other threads?

Body:
Invoke is used to run code on the main or UI thread.  Specifically for updating UI elements as those can only be updated by that thread.  Currently you have code that loads the image in the Invoke.  Instead you should only put the part of the code that updates the UI inside of the Invoke.

PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html);

        if (SearchedImagesUrls.Count > 0)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(SearchedImagesUrls[0]);
            image.EndInit();
            this.Dispatcher.Invoke(() =>
            {
                SelectPhotoImage.Source = image;
            });
        }
    }
});


问:
Why does my url spits out the two // at the end?
I am very new to React so bear with me here. I have this button here:

```<code>let showButton
if (schema.type === 'belongs_to') {
  showButton = (
    <Link to={['collections', 'locks', this.props.collectionName]}>
      <button>Visa</button>
    </Link>
  )
}
</code>```

This button will redirect to this URL: http://localhost:3000/#/collections/locks/ and there is nothing wrong with that, but when I'm adding this: this.props.id which is a legit prop, but the url I get is this: http://localhost:3000/#/collections/locks//. Notice the two // at the end.

My Question

Why does my url spits out the two // at the end? Is it because this.props.id is empty? As I said, I am very new to this. Thankful for all the support!

Code:

I just want to say that I'm maintaining this project, so all of the code is not written by me, therefor I might not know every little line.

However.. The this.props.id if from here:

```<code>class DeleteDocument extends Component {
  constructor(props) {
    super(props)
    this.state = { confirmed: false }
  }
  render() {
    return (
      <div className="DeleteDocument">
        <div className="box">
          <div className="title">
            Är du säker på att du vill ta bort dokumentet?
          </div>
          <label>
            <input
              type="checkbox"
              value={this.state.confirmed}
              onChange={e =>
                this.setState({ confirmed: !this.state.confirmed })}
            />
            Ja, jag är säker
          </label>
          <div className="box" />
        </div>
        <div style={{ marginTop: '20px' }}>
          <button
            disabled={!this.state.confirmed}
            onClick={this.props.deleteDocument}
          >
            Ta bort
          </button>
          <div style={{ padding: '15px', borderBottom: '1px solid #ccc' }}>
            <Link to={'/collections/locks/${this.props.id}'}> HERE IT IS
              <button>Avbryt</button>
            </Link>
          </div>
        </div>
      </div>
    )
  }
}
</code>```

So I made a decision to use the same props because it's working here and the naming of it seemed to suit my use for it (don't know if this makes sense).

答: change {'/collections/locks/${this.props.id}'} to {'/collections/locks/'+ this.props.id}

Body:
I am very new to React so bear with me here. I have this button here:

let showButton
if (schema.type === 'belongs_to') {
  showButton = (
    <Link to={['collections', 'locks', this.props.collectionName]}>
      <button>Visa</button>
    </Link>
  )
}

This button will redirect to this URL: http://localhost:3000/#/collections/locks/ and there is nothing wrong with that, but when I'm adding this: this.props.id which is a legit prop, but the url I get is this: http://localhost:3000/#/collections/locks//. Notice the two // at the end.

My Question

Why does my url spits out the two // at the end? Is it because this.props.id is empty? As I said, I am very new to this. Thankful for all the support!

Code:

I just want to say that I'm maintaining this project, so all of the code is not written by me, therefor I might not know every little line.

However.. The this.props.id if from here:

class DeleteDocument extends Component {
  constructor(props) {
    super(props)
    this.state = { confirmed: false }
  }
  render() {
    return (

            Är du säker på att du vill ta bort dokumentet?

            <input
              type="checkbox"
              value={this.state.confirmed}
              onChange={e =>
                this.setState({ confirmed: !this.state.confirmed })}
            />
            Ja, jag är säker

          <button
            disabled={!this.state.confirmed}
            onClick={this.props.deleteDocument}
          >
            Ta bort
          </button>

            <Link to={'/collections/locks/${this.props.id}'}> HERE IT IS
              <button>Avbryt</button>
            </Link>

    )
  }
}

So I made a decision to use the same props because it's working here and the naming of it seemed to suit my use for it (don't know if this makes sense).


问:
Is there a better way to produce a membership matrix (one-hot array) for an array of cluster assignments in Python?
After running kmeans I can easily get an array with the assigned clusters for ever data point. Now I want to get a membership matrix (one-hot array) which has the different clusters as columns and indicates the cluster assignment by either 1 or 0 in the matrix for each data point.

My code is shown below and it works but I am wondering if there is a more elegant way to do the same.

```<code>km = KMeans(n_clusters=3).fit(data)
membership_matrix = np.stack([np.where(km.labels_ == 0, 1,0),
                              np.where(km.labels_ == 1, 1,0),
                              np.where(km.labels_ == 2, 1,0)]
                              axis = 1)
</code>```

答:
Here's a method that's agnostic to the number of clusters you have (with your method, you'll have to "stack" more things if you have more clusters).

This code sample assumes you have six data points and 3 clusters:

```<code>NUM_DATA_POINTS = 6
NUM_CLUSTERS = 3
clusters = np.array([2,1,2,2,0,1]) # hard-coded as an example, but this is your KMeans output

# create your empty membership matrix
membership = np.zeros((NUM_DATA_POINTS, NUM_CLUSTERS))
membership[np.arange(NUM_DATA_POINTS), clusters] = 1
</code>```

The key feature being used here is 2D array indexing - in the last line of code above, we index into the rows of membership sequentially (np.arange creates an incrementing sequence from 0 to NUM_DATA_POINTS-1) and into the columns of membership using the cluster assignments. Here's the relevant numpy reference.

It would produce the following membership matrix:

```<code>>>> membership
array([[ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.]])
</code>```

Body:
After running kmeans I can easily get an array with the assigned clusters for ever data point. Now I want to get a membership matrix (one-hot array) which has the different clusters as columns and indicates the cluster assignment by either 1 or 0 in the matrix for each data point.

My code is shown below and it works but I am wondering if there is a more elegant way to do the same.

km = KMeans(n_clusters=3).fit(data)
membership_matrix = np.stack([np.where(km.labels_ == 0, 1,0),
                              np.where(km.labels_ == 1, 1,0),
                              np.where(km.labels_ == 2, 1,0)]
                              axis = 1)

Body:
Here's a method that's agnostic to the number of clusters you have (with your method, you'll have to "stack" more things if you have more clusters).

This code sample assumes you have six data points and 3 clusters:

NUM_DATA_POINTS = 6
NUM_CLUSTERS = 3
clusters = np.array([2,1,2,2,0,1]) # hard-coded as an example, but this is your KMeans output

# create your empty membership matrix
membership = np.zeros((NUM_DATA_POINTS, NUM_CLUSTERS))
membership[np.arange(NUM_DATA_POINTS), clusters] = 1

The key feature being used here is 2D array indexing - in the last line of code above, we index into the rows of membership sequentially (np.arange creates an incrementing sequence from 0 to NUM_DATA_POINTS-1) and into the columns of membership using the cluster assignments. Here's the relevant numpy reference.

It would produce the following membership matrix:

>>> membership
array([[ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.]])


问:
SVG text clippath in Firefox
I am using a text clippath to create an SVG displaying text so that I can animate the background to come in for a fun text reveal effect.

It works great in Chrome and Safari but in Firefox there are issues with the clippath.

```<code><svg viewBox="0 0 600 150">

  <!-- Clippath  with text -->
  <clippath id="cp-text">
   <text text-anchor="left"
      x="0"
      y="50%"
      dy=".35em"
      class="text--line"
      >
   hello
   </text>
  </clippath>

  <!-- Group with clippath for text-->
  <g clip-path="url(#cp-text)" class="colortext">
    <!-- Animated shapes inside text -->
    <polyline class="anim-shape" points="559.91 153.84 526.17 -11.62 478.32 -11.62 512.05 150.84 559.91 153.84" style="fill: #4c4870"/>
    <polyline class="anim-shape" points="599.75 149.75 599.92 -0.62 528.07 -0.62 558.75 150.75 599.75 149.75" style="fill: #93d2c4"/>
    <polygon class="anim-shape" points="479.07 -11.62 395.78 -11.62 429.52 153.84 512.8 153.84 479.07 -11.62" style="fill: #f89c2c"/>
  </g>
</svg>
</code>```

I'm using CSS transforms to animate the polgyon shapes on load (scale and translate).

See codepen demo here: https://codepen.io/njpatten/pen/zwEeev

I've tried updating the polgyons inside the svg but it seems to be a problem with the clippath text rendering being delayed.

Any idea what might be the problem in Firefox? Thanks in advance for any suggestions or help!

答:
It seems Firefox requires something to render beside the text mask you have created, while the animated shapes are with scale of 0,1 , it gets some problems.
I added this

```<code><rect x="0" y="0" width="100%" height="100%" fill="transparent" />
</code>```

just before first polygon and seems it now works similar to Chrome.
I think you can work with width and height if you don't want full width and height.

Hope it helps

Title: SVG text clippath in Firefox

Body:
I am using a text clippath to create an SVG displaying text so that I can animate the background to come in for a fun text reveal effect.

It works great in Chrome and Safari but in Firefox there are issues with the clippath.

<svg viewBox="0 0 600 150">

  <clippath id="cp-text">
   <text text-anchor="left"
      x="0"
      y="50%"
      dy=".35em"
      class="text--line"
      >
   hello
   </text>
  </clippath>

  <g clip-path="url(#cp-text)" class="colortext">

    <polyline class="anim-shape" points="559.91 153.84 526.17 -11.62 478.32 -11.62 512.05 150.84 559.91 153.84" style="fill: #4c4870"/>
    <polyline class="anim-shape" points="599.75 149.75 599.92 -0.62 528.07 -0.62 558.75 150.75 599.75 149.75" style="fill: #93d2c4"/>
    <polygon class="anim-shape" points="479.07 -11.62 395.78 -11.62 429.52 153.84 512.8 153.84 479.07 -11.62" style="fill: #f89c2c"/>
  </g>
</svg>

I'm using CSS transforms to animate the polgyon shapes on load (scale and translate).

See codepen demo here: https://codepen.io/njpatten/pen/zwEeev

I've tried updating the polgyons inside the svg but it seems to be a problem with the clippath text rendering being delayed.

Any idea what might be the problem in Firefox? Thanks in advance for any suggestions or help!

Body:
It seems Firefox requires something to render beside the text mask you have created, while the animated shapes are with scale of 0,1 , it gets some problems.
I added this

<rect x="0" y="0" width="100%" height="100%" fill="transparent" />

just before first polygon and seems it now works similar to Chrome.
I think you can work with width and height if you don't want full width and height.

Hope it helps


问:
Keep track of the timer repeatedly in C++
I've a library which accepts a vector of strings as argument & pushes it to a vector of vector of strings (2D vector).
I've a condition that "right from the time 1st row is pushed to the 2D vector the timer should start & for every "X" th milisecond I want to append some special string "FLAG_BORDER" at the end of the vector of string that i receive as argument to library.

LIBRARY CODE

```<code>using namespace std;
vector<vector<sring>> vecOfVecStrs;
MyLibraryFunction(vector<string> vecstr)
{
    if(TimerLimitNOTHit()) // THIS FUNCTION TimerLimitNOTHit() checks if the "X"
                           //    th milisecond is reached or not.
    {
          vecOfVecStrs.push_back(vecstr); // If "X"th ms time poeriod is NOT
                                           // yet reached
    }
    else
    {
         vecstr.push_back("FLAG_BORDER");
         vecOfVecStrs.push_back(vecstr);
    }
</code>```

APPLICATION CODE CALLING LIBRARY FUNCTION::

```<code>int main()
{
    do_something();
    vector<string> vecStr;
    while(vecStr = Get_VecTor_of_strings())
    {
        MyLibraryFunction(vecStr);
    }
</code>```

How do I implement the function TimerLimitNOTHit() here which should
  keep track of the timer "X" milisec across function calls to
  "MyLibraryFunction()" in C++ ?

EDITED: SEEMS LIKE FOUND AN ANSWER. wILL IT WORK ?

```<code>int timeX = 30; //s
bool keepTrack = false;
int ci = 0;
std::vector<int> timeArray;
std::mutex m;

bool keepTracking()
{
    std::unique_lock<std::mutex> lock(m);
    return keepTrack;
}

void GlobalTimer()
{
    while (keepTracking())
    {
        std::this_thread::sleep_for(std::chrono::seconds(timeX));
        timeArray[ci] = 1;
    }
}

 std::thread t1(GlobalTimer);
</code>```

答:
Here is some inspiration, where the function TimerLimitNOTHit returns true if more than X ms has passed since it last returned true.

```<code>int X = ... // #0

bool TimerLimitNOTHit()
{
    static auto start = std::chrono::steady_clock::now(); // #1
    auto now = std::chrono::steady_clock::now();
    if (now - start > std::chrono::milliseconds(X))
    {
        start = now // #2
        return true;
    }
    return false
}
</code>```

#0 Defining the distance in time between two calls to TimerLimitNOTHit that return true.

#1 Initialization depend on your application logic. In this example the function does not return true on the first call, this can changed by initializing start to zero.

#2 start value for the next iteration, again it depends on your application logic. If you want a more steady true you could do some modulo arithmetic.

Let me know if this is not what you were looking for.

Disclaimer

I don't really like the use of static variables, but without a "status" parameter to the function I don't see how it can be avoided.
Furthermore, the use of the global X variable does not fall to my likening neither. The variable X could be changed to a template variable, this better show intent and makes it a compile time constant.

Body:
I've a library which accepts a vector of strings as argument & pushes it to a vector of vector of strings (2D vector).
I've a condition that "right from the time 1st row is pushed to the 2D vector the timer should start & for every "X" th milisecond I want to append some special string "FLAG_BORDER" at the end of the vector of string that i receive as argument to library.

LIBRARY CODE

using namespace std;
vector<vector<sring>> vecOfVecStrs;
MyLibraryFunction(vector<string> vecstr)
{
    if(TimerLimitNOTHit()) // THIS FUNCTION TimerLimitNOTHit() checks if the "X"
                           //    th milisecond is reached or not.
    {
          vecOfVecStrs.push_back(vecstr); // If "X"th ms time poeriod is NOT
                                           // yet reached
    }
    else
    {
         vecstr.push_back("FLAG_BORDER");
         vecOfVecStrs.push_back(vecstr);
    }

APPLICATION CODE CALLING LIBRARY FUNCTION::

int main()
{
    do_something();
    vector<string> vecStr;
    while(vecStr = Get_VecTor_of_strings())
    {
        MyLibraryFunction(vecStr);
    }

How do I implement the function TimerLimitNOTHit() here which should
  keep track of the timer "X" milisec across function calls to
  "MyLibraryFunction()" in C++ ?

EDITED: SEEMS LIKE FOUND AN ANSWER. wILL IT WORK ?

int timeX = 30; //s
bool keepTrack = false;
int ci = 0;
std::vector<int> timeArray;
std::mutex m;

bool keepTracking()
{
    std::unique_lock<std::mutex> lock(m);
    return keepTrack;
}

void GlobalTimer()
{
    while (keepTracking())
    {
        std::this_thread::sleep_for(std::chrono::seconds(timeX));
        timeArray[ci] = 1;
    }
}

 std::thread t1(GlobalTimer);

Body:
Here is some inspiration, where the function TimerLimitNOTHit returns true if more than X ms has passed since it last returned true.

int X = ... // #0

bool TimerLimitNOTHit()
{
    static auto start = std::chrono::steady_clock::now(); // #1
    auto now = std::chrono::steady_clock::now();
    if (now - start > std::chrono::milliseconds(X))
    {
        start = now // #2
        return true;
    }
    return false
}

#0 Defining the distance in time between two calls to TimerLimitNOTHit that return true.

#1 Initialization depend on your application logic. In this example the function does not return true on the first call, this can changed by initializing start to zero.

#2 start value for the next iteration, again it depends on your application logic. If you want a more steady true you could do some modulo arithmetic.

Let me know if this is not what you were looking for.

Disclaimer

I don't really like the use of static variables, but without a "status" parameter to the function I don't see how it can be avoided.
Furthermore, the use of the global X variable does not fall to my likening neither. The variable X could be changed to a template variable, this better show intent and makes it a compile time constant.


问:
CSS targeting elements before image
In my wordpress post I have image and text mixed. I have the following code which targets content right AFTER an image to apply specific css.

```<code>#single-pg p{padding:0 20px; margin-top:0;}

#single-pg img + p{ margin-top:30px; background:red;}

#single-pg img + h1{ background:blue;}

#single-pg img + blockquote{ background:orange;}
</code>```

I want to be able to do similar with content BEFORE an image (ex. apply margin-bottom: 30px to p) but only when its the last element before an image

Targeting its parent I don't think would solve the issue. I just want to target whatever element comes just before the image, I just cannot pre-determine what that is

答:
You can't target a previous element, but as a workaround (if margins is what you want) you could apply the margin to the img if it follows a p

```<code>#single-pg p + img{margin-top:30px;}
</code>```

Title: CSS targeting elements before image

Body:
In my wordpress post I have image and text mixed. I have the following code which targets content right AFTER an image to apply specific css.

#single-pg p{padding:0 20px; margin-top:0;}

#single-pg img + p{ margin-top:30px; background:red;}

#single-pg img + h1{ background:blue;}

#single-pg img + blockquote{ background:orange;}

I want to be able to do similar with content BEFORE an image (ex. apply margin-bottom: 30px to p) but only when its the last element before an image

Targeting its parent I don't think would solve the issue. I just want to target whatever element comes just before the image, I just cannot pre-determine what that is

Body:
You can't target a previous element, but as a workaround (if margins is what you want) you could apply the margin to the img if it follows a p

#single-pg p + img{margin-top:30px;}


问:
Redux-React: error in control flow while dispatchcing a function
Please find my code below as I explain the flow that is currently happening:

First SampleParent calls fetchNames and when called, this populates reports array and returns a json array with 6 objects as of now.
Next, when I loop over the objects in reports array, each time 'fetchDownloadLink' function is called. The function executes till

```<code>fetch(uri, obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);
        }
        return response ;
    })
</code>```

and instead of executing further returns back to SampleParent from where it was called for all 6 objects in the reports array.
Then it enters SampleChild and it renders onClick value as 'undefined'

Then finally the control suddendly seems to go back to 'fetchDownloadLink' function and executes the rest of the function to return the value of report_uri
and finally execution ends!

I dont understand why is this hapenning, I want the entire function to execute in one flow so that it would return the 'report_uri' value to 'onClick' prop of SampleChild

store/index.js

```<code>import C from '../constants'
import appReducer from '../reducers/reducers.js'
import thunkMiddleware  from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux'
export default function configureStore() {
return createStore(
    appReducer,
    applyMiddleware(
        thunkMiddleware))}
</code>```

Main_Root.js

```<code>import React, { Component } from 'react'
import { Provider } from 'react-redux'
import configureStore from '../store/index.js'
import SampleParent from './containers/SampleParent'
const store = configureStore()
export default class Root extends Component {
render() {return (<div><Provider store={store}><SampleParent /></Provider></div>)}}
</code>```

SampleParent.js

```<code>import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchReport, fetchDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {super(props)}
componentDidMount() {this.props.fetchNames();}
render() {return (<div>
            <ul id="myUL">
                {this.props.reports.map((report) => (
                    <li><SampleChild
                            key={report.id}
                            label={report.label}
                            onClick={this.props.fetchDownloadLink("http://sample"+report.uri+".pdf")}
                        /></li>))}</ul></div>)}}
function mapStateToProps(state) {
const { reports } = state
return {reports}}
const mapDispatchToProps = dispatch => {
return {fetchDownloadLink: url => dispatch(fetchDownloadable(url)),
    fetchNames: () => dispatch(fetchReport())}}
export default connect(mapStateToProps , mapDispatchToProps)(SampleParent)
</code>```

SampleChild.js

```<code>import React, { Component } from 'react'
export default class SampleChild extends Component {
render() {const { key, label, onClick } = this.props
    return (<span className="inside_SampleChild" id={label}>
        {label}
        <a onClick={onClick}>Click me for pdf download!</img></a>
        </span>)}}
</code>```

fetchDownlodable function in action.js

```<code>export const fetchDownloadable = (uri) => dispatch => {
var obj = {method: 'GET',
    headers: {'Authorization': 'Basic ***=','Accept': 'application/json'},
    'credentials': 'include'};
fetch(uri, obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);}
        return response ;})
    .then((response) => response)
    .then(resourceLookup => {
        dispatch({
            type: C.FETCH_DOWNLOADABLE,
            report_uri: resourceLookup.url})
    }).
catch(error => {
    console.log("There was this  error" + error);});}
</code>```

reducer.js

```<code>import C from '../constants'
import { combineReducers } from 'redux'
export const links = (state=null, action) => (action.type === C.FETCH_DOWNLOADABLE) ? action.report_uri : state
export const reports = (state=[], action) => {
switch(action.type) {
    case C.FETCH_REPORTS : return action.reports
    default : return state}}
const rootReducer = combineReducers({ reports, links})
export default rootReducer
</code>```

Thanks in advance!

答:
When passing a function to a child to be used on onClick, invoking it will actually fire it right away, instead of giving it to the child as an onclick function.

Ex:

```<code><ChildComponent onClick={somefunc} />
</code>```

is fine

```<code><ChildComponent onClick={somefunc("foo")} />
</code>```

will fire the somefunc function and return the result of it to the child

If you meant to invoke this function on onClick, and bind it to something, you can do this:

```<code><ChildComponent onClick={() => somefunc("foo")} />
</code>```

This will pass it as a parameterless function to the child that can be triggered as this.props.onClick from the child

In your case, according to your comment, you are trying to send a string down to the child-component. A string cant be used as an onClick value, that has to be a function. If you use my last example above, that will send a function which again triggers somefunc, or in your example, the download.

Body:
Please find my code below as I explain the flow that is currently happening:

First SampleParent calls fetchNames and when called, this populates reports array and returns a json array with 6 objects as of now.
Next, when I loop over the objects in reports array, each time 'fetchDownloadLink' function is called. The function executes till

fetch(uri, obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);
        }
        return response ;
    })

and instead of executing further returns back to SampleParent from where it was called for all 6 objects in the reports array.
Then it enters SampleChild and it renders onClick value as 'undefined'

Then finally the control suddendly seems to go back to 'fetchDownloadLink' function and executes the rest of the function to return the value of report_uri
and finally execution ends!

I dont understand why is this hapenning, I want the entire function to execute in one flow so that it would return the 'report_uri' value to 'onClick' prop of SampleChild

store/index.js

import C from '../constants'
import appReducer from '../reducers/reducers.js'
import thunkMiddleware  from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux'
export default function configureStore() {
return createStore(
    appReducer,
    applyMiddleware(
        thunkMiddleware))}

Main_Root.js

import React, { Component } from 'react'
import { Provider } from 'react-redux'
import configureStore from '../store/index.js'
import SampleParent from './containers/SampleParent'
const store = configureStore()
export default class Root extends Component {
render() {return (
<Provider store={store}><SampleParent /></Provider>
)}}

SampleParent.js

import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchReport, fetchDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {super(props)}
componentDidMount() {this.props.fetchNames();}
render() {return (

                {this.props.reports.map((report) => (

<SampleChild
                            key={report.id}
                            label={report.label}
                            onClick={this.props.fetchDownloadLink("http://sample"+report.uri+".pdf")}
                        />
))}

)}}
function mapStateToProps(state) {
const { reports } = state
return {reports}}
const mapDispatchToProps = dispatch => {
return {fetchDownloadLink: url => dispatch(fetchDownloadable(url)),
    fetchNames: () => dispatch(fetchReport())}}
export default connect(mapStateToProps , mapDispatchToProps)(SampleParent)

SampleChild.js

import React, { Component } from 'react'
export default class SampleChild extends Component {
render() {const { key, label, onClick } = this.props
    return (
        {label}
        Click me for pdf download!
        )}}

fetchDownlodable function in action.js

export const fetchDownloadable = (uri) => dispatch => {
var obj = {method: 'GET',
    headers: {'Authorization': 'Basic ***=','Accept': 'application/json'},
    'credentials': 'include'};
fetch(uri, obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);}
        return response ;})
    .then((response) => response)
    .then(resourceLookup => {
        dispatch({
            type: C.FETCH_DOWNLOADABLE,
            report_uri: resourceLookup.url})
    }).
catch(error => {
    console.log("There was this  error" + error);});}

reducer.js

import C from '../constants'
import { combineReducers } from 'redux'
export const links = (state=null, action) => (action.type === C.FETCH_DOWNLOADABLE) ? action.report_uri : state
export const reports = (state=[], action) => {
switch(action.type) {
    case C.FETCH_REPORTS : return action.reports
    default : return state}}
const rootReducer = combineReducers({ reports, links})
export default rootReducer

Thanks in advance!

Body:
When passing a function to a child to be used on onClick, invoking it will actually fire it right away, instead of giving it to the child as an onclick function.

Ex:

<ChildComponent onClick={somefunc} />

is fine

<ChildComponent onClick={somefunc("foo")} />

will fire the somefunc function and return the result of it to the child

If you meant to invoke this function on onClick, and bind it to something, you can do this:

<ChildComponent onClick={() => somefunc("foo")} />

This will pass it as a parameterless function to the child that can be triggered as this.props.onClick from the child

In your case, according to your comment, you are trying to send a string down to the child-component. A string cant be used as an onClick value, that has to be a function. If you use my last example above, that will send a function which again triggers somefunc, or in your example, the download.


问:
Sequence of indices of tuple elements satifying predicate in Hana
Is there a concise way to get a sequence of indices of tuple elements which satisfy a predicate in Hana?

Here's the code I wrote for that using just the standard library:

```<code>template <template<typename> typename Pred, typename Tuple>
class get_indices_of {
  static constexpr size_t size = std::tuple_size<Tuple>::value;
  template <size_t I, size_t... II> struct impl {
    using type = std::conditional_t<
      Pred<std::tuple_element_t<I,Tuple>>::value,
      typename impl<I+1, II..., I>::type,
      typename impl<I+1, II...>::type >;
  };
  template <size_t... II> struct impl<size,II...> {
    using type = std::index_sequence<II...>;
  };
public:
  using type = typename impl<0>::type;
};
template <template<typename> typename Pred, typename Tuple>
using get_indices_of_t = typename get_indices_of<Pred,Tuple>::type;
</code>```

Usage example:

```<code>using types = std::tuple<std::string,int,double,char>;
using ints = get_indices_of_t<std::is_integral,types>;
</code>```

The type of ints is now std::index_sequence<1ul, 3ul>.

答:
I'd guess something like this:

```<code>constexpr auto get_indices_of = [](auto tuple, auto predicate){
    constexpr auto indices = to<tuple_tag>(range_c<std::size_t, 0, size(tuple)>);
    return filter(indices, [=](auto i){ return predicate(tuple[i]); });
};
</code>```

The only awkward part there is getting the indices, since range_c itself isn't a MonadPlus. Your actual example, using this function, is:

```<code>constexpr auto types = make_tuple(
    type_c<std::string>, type_c<int>, type_c<double>, type_c<char>);
constexpr auto ints = get_indices_of(types, trait<std::is_integral>);
</code>```

Body:
Is there a concise way to get a sequence of indices of tuple elements which satisfy a predicate in Hana?

Here's the code I wrote for that using just the standard library:

template <template<typename> typename Pred, typename Tuple>
class get_indices_of {
  static constexpr size_t size = std::tuple_size<Tuple>::value;
  template <size_t I, size_t... II> struct impl {
    using type = std::conditional_t<
      Pred<std::tuple_element_t>::value,
      typename impl::type,
      typename impl::type >;
  };
  template <size_t... II> struct impl<size,II...> {
    using type = std::index_sequence<II...>;
  };
public:
  using type = typename impl<0>::type;
};
template <template<typename> typename Pred, typename Tuple>
using get_indices_of_t = typename get_indices_of<Pred,Tuple>::type;

Usage example:

using types = std::tuple<std::string,int,double,char>;
using ints = get_indices_of_t<std::is_integral,types>;

The type of ints is now std::index_sequence<1ul, 3ul>.

Body:
I'd guess something like this:

constexpr auto get_indices_of = [](auto tuple, auto predicate){
    constexpr auto indices = to<tuple_tag>(range_c<std::size_t, 0, size(tuple)>);
    return filter(indices, [=](auto i){ return predicate(tuple[i]); });
};

The only awkward part there is getting the indices, since range_c itself isn't a MonadPlus. Your actual example, using this function, is:

constexpr auto types = make_tuple(
    type_c<std::string>, type_c<int>, type_c<double>, type_c<char>);
constexpr auto ints = get_indices_of(types, trait<std::is_integral>);


问:
jQuery not doing what I want it to do
I'm having trouble with a little jQuery, and thought someone in the community could help me out? So, my markup is as follows:

```<code><div class="left">
    <ul id="editing-nav">
        <li><a class="active testforso" href="#TestForSO">Test For SO</a></li>
        <li><a class="testforso2" href="#TestForSO2">Test For SO2</a></li>
        ...and so on.
    </ul>
</div>

<div class="scroll">
    <div class="scrollContainer">
        <div id="testforso">
            ...some content
        </div>
        <div id="testforso2">
            ...some content
        </div>
        ...and so on.
    </div>
</div>
</code>```

So, basically - .left is floated left, and .scroll is on the right side. I am looking for a way so the active nav element (by default, the first one, and then when the user would click another one, it'd assign that element a class of ".active" and remove the previous one's active class)'s co-insiding div has a display:block, while all others hide. I'm doing this inside of fancybox, which makes it a little bit more complicated, but here's what I have now -

```<code>$('#editing-nav li > a').click(function() {
        $('#editing-nav li > a').removeClass('active');
        $(this).addClass('active');
        activeClassID = $(this).attr('class');  // grabs the nav class for the id to show in .scroll
        var divIDToShow = ('.scroll .scrollContainer #') + activeClassID;       // grabs the DOM path & ID of the coinciding div to show
            divIDToShow = divIDToShow.replace(' active', ''); // removes " active" from the class (because before it would have a class of "testforso2 active"; now it just has "testforso".
        $('.scrollContainer div:not(#' + divIDToShow + ')').hide();
        $('.scrollContainer #' + divIDToShow ).show();
    });
</code>```

This works for the first link someone clicks, but not after that. I don't know if I was clear earlier, but the class for the #editing-nav li a co-incides with what div to show inside of .scroll.

Any ideas? I'm not sure why it's doing this... Thank you!

答:
This issue is with your id selector - try this instead

EDIT

Figured out the real issue here - not sure why it works the first time but your divIDToShow variable contains too much information. See here for a cut down version

Title: jQuery not doing what I want it to do

Body:
I'm having trouble with a little jQuery, and thought someone in the community could help me out? So, my markup is as follows:

Test For SO

Test For SO2

        ...and so on.

            ...some content

            ...some content

        ...and so on.

So, basically - .left is floated left, and .scroll is on the right side. I am looking for a way so the active nav element (by default, the first one, and then when the user would click another one, it'd assign that element a class of ".active" and remove the previous one's active class)'s co-insiding div has a display:block, while all others hide. I'm doing this inside of fancybox, which makes it a little bit more complicated, but here's what I have now -

$('#editing-nav li > a').click(function() {
        $('#editing-nav li > a').removeClass('active');
        $(this).addClass('active');
        activeClassID = $(this).attr('class');  // grabs the nav class for the id to show in .scroll
        var divIDToShow = ('.scroll .scrollContainer #') + activeClassID;       // grabs the DOM path & ID of the coinciding div to show
            divIDToShow = divIDToShow.replace(' active', ''); // removes " active" from the class (because before it would have a class of "testforso2 active"; now it just has "testforso".
        $('.scrollContainer div:not(#' + divIDToShow + ')').hide();
        $('.scrollContainer #' + divIDToShow ).show();
    });

This works for the first link someone clicks, but not after that. I don't know if I was clear earlier, but the class for the #editing-nav li a co-incides with what div to show inside of .scroll.

Any ideas? I'm not sure why it's doing this... Thank you!


问:
Meteor scraping, HTTP.post resulting with damaged PDF in response.content
The HTTP.post which I use to scrape a web site for a .PDF file returns a damaged file which is full of 3F characters displayed as question marks.

For example, in a given saved file I have

%PDF-1.4����

instead of

%PDF-1.4\C8\D2\F0\FE

Any ideas what might be the solution to this problem?

答:
Solved the issue with Request (npm install request) and right combination of options. Used Iron router for displaying of the pdf.</p>

```<code>let responseRoute = this.response;
let request = require('request');
request({
    method: "POST",
    url: doc_url,
    headers: headers,
    form: payload,
    body: Buffer,
    encoding: null,
    gzip: true
}, function (error, response, body) {
    responseRoute.writeHead(200, {
        "Content-Type": "application/pdf",
        "Content-Length": body.length,
        "Content-Disposition": "attachment",
    });
    responseRoute.write(body);
    responseRoute.end();
});}, {
    where: "server"
});
</code>```

Body:
Solved the issue with Request (npm install request) and right combination of options. Used Iron router for displaying of the pdf.

let responseRoute = this.response;
let request = require('request');
request({
    method: "POST",
    url: doc_url,
    headers: headers,
    form: payload,
    body: Buffer,
    encoding: null,
    gzip: true
}, function (error, response, body) {
    responseRoute.writeHead(200, {
        "Content-Type": "application/pdf",
        "Content-Length": body.length,
        "Content-Disposition": "attachment",
    });
    responseRoute.write(body);
    responseRoute.end();
});}, {
    where: "server"
});


问:
WPF What is the correct way of using SVG files as icons in WPF
Can someone describe a recommended Step by Step procedure for doing this?

Step1. Convert SVG to XAML... thats easy

Step2. Now what?

答:
Windows 10 build 15063 "Creators Update" natively supports SVG images (though with some gotchas) to UWP/UAP applications targeting Windows 10.

If your application is a WPF app rather than a UWP/UAP, you can still use this API (after jumping through quite a number of hoops): Windows 10 build 17763 "October 2018 Update" introduced the concept of XAML islands (as a "preview" technology but I believe allowed in the app store; in all cases, with Windows 10 build 18362 "May 2019 Update" XAML islands are no longer a preview feature and are fully supported) allowing you to use UWP APIs and controls in your WPF applications.

You need to first add the references to the WinRT APIs, and to use certain Windows 10 APIs that interact with user data or the system (e.g. loading images from disk in a Windows 10 UWP webview or using the toast notification API to show toasts), you also need to associate your WPF application with a package identity, as shown here (immensely easier in Visual Studio 2019). This shouldn't be necessary to use the Windows.UI.Xaml.Media.Imaging.SvgImageSource class, though.

Usage (if you're on UWP or you've followed the directions above and added XAML island support under WPF) is as simple as setting the Source for an <Image /> to the path to the SVG. That is equivalent to using SvgImageSource, as follows:

```<code><Image>
    <Image.Source>
        <SvgImageSource UriSource="Assets/svg/icon.svg" />
    </Image.Source>
</Image>
</code>```

However, SVG images loaded in this way (via XAML) may load jagged/aliased. One workaround is to specify a RasterizePixelHeight or RasterizePixelWidth value that is double+ your actual height/width:

```<code><SvgImageSource RasterizePixelHeight="300" RasterizePixelWidth="300" UriSource="Assets/svg/icon.svg" /> <!-- presuming actual height or width is under 150 -->
</code>```

This can be worked around dynamically by creating a new SvgImageSource in the ImageOpened event for the base image:

```<code>var svgSource = new SvgImageSource(new Uri("ms-appx://" + Icon));
PrayerIcon.ImageOpened += (s, e) =>
{
    var newSource = new SvgImageSource(svgSource.UriSource);
    newSource.RasterizePixelHeight = PrayerIcon.DesiredSize.Height * 2;
    newSource.RasterizePixelWidth = PrayerIcon.DesiredSize.Width * 2;
    PrayerIcon2.Source = newSource;
};
PrayerIcon.Source = svgSource;
</code>```

The aliasing may be hard to see on non high-dpi screens, but here's an attempt to illustrate it.

This is the result of the code above: an Image that uses the initial SvgImageSource, and a second Image below it that uses the SvgImageSource created in the ImageOpened event:

This is a blown up view of the top image:

Whereas this is a blown-up view of the bottom (antialiased, correct) image:

(you'll need to open the images in a new tab and view at full size to appreciate the difference)

Body:
Windows 10 build 15063 "Creators Update" natively supports SVG images (though with some gotchas) to UWP/UAP applications targeting Windows 10.

If your application is a WPF app rather than a UWP/UAP, you can still use this API (after jumping through quite a number of hoops): Windows 10 build 17763 "October 2018 Update" introduced the concept of XAML islands (as a "preview" technology but I believe allowed in the app store; in all cases, with Windows 10 build 18362 "May 2019 Update" XAML islands are no longer a preview feature and are fully supported) allowing you to use UWP APIs and controls in your WPF applications.

You need to first add the references to the WinRT APIs, and to use certain Windows 10 APIs that interact with user data or the system (e.g. loading images from disk in a Windows 10 UWP webview or using the toast notification API to show toasts), you also need to associate your WPF application with a package identity, as shown here (immensely easier in Visual Studio 2019). This shouldn't be necessary to use the Windows.UI.Xaml.Media.Imaging.SvgImageSource class, though.

Usage (if you're on UWP or you've followed the directions above and added XAML island support under WPF) is as simple as setting the Source for an <Image /> to the path to the SVG. That is equivalent to using SvgImageSource, as follows:

<Image>
    <Image.Source>
        <SvgImageSource UriSource="Assets/svg/icon.svg" />
    </Image.Source>
</Image>

However, SVG images loaded in this way (via XAML) may load jagged/aliased. One workaround is to specify a RasterizePixelHeight or RasterizePixelWidth value that is double+ your actual height/width:

<SvgImageSource RasterizePixelHeight="300" RasterizePixelWidth="300" UriSource="Assets/svg/icon.svg" /> <!-- presuming actual height or width is under 150 -->

This can be worked around dynamically by creating a new SvgImageSource in the ImageOpened event for the base image:

var svgSource = new SvgImageSource(new Uri("ms-appx://" + Icon));
PrayerIcon.ImageOpened += (s, e) =>
{
    var newSource = new SvgImageSource(svgSource.UriSource);
    newSource.RasterizePixelHeight = PrayerIcon.DesiredSize.Height * 2;
    newSource.RasterizePixelWidth = PrayerIcon.DesiredSize.Width * 2;
    PrayerIcon2.Source = newSource;
};
PrayerIcon.Source = svgSource;

The aliasing may be hard to see on non high-dpi screens, but here's an attempt to illustrate it.

This is the result of the code above: an Image that uses the initial SvgImageSource, and a second Image below it that uses the SvgImageSource created in the ImageOpened event:

This is a blown up view of the top image:

Whereas this is a blown-up view of the bottom (antialiased, correct) image:

(you'll need to open the images in a new tab and view at full size to appreciate the difference)


问:
How to deploy officeJS addin on office online on-premise server?
I have written a small officeJS addin for excel which run perfectly on desktop excel client. Also office online from onedrive gives an option of installing the addin from the ribbon menu. I want to use this officeJS addin to run on either of the following configuration:

On premise office online server configured with on premise
sharepoint server.

On premise office online server with my own
implementation of wopi host.

How to deploy an officeJS addin on office online on premise server which is preferably managed centrally by the administrator.

Also why is the add-ins option is not available on the office online configured with sharepoint, pfa image:
office online onedrive v/s office online onprem with sharepoint

Thank You

答:
Try this. On a server in the farm, open the SharePoint Management Shell (PowerShell). Run this command:

```<code>Set-OfficeWebAppsFarm - OfficeAddinEnabled:$true
</code>```

You probably have to be logged in as a farm administrator.
There is some documentation here: Set-OfficeWebAppsFarm

Body:
Try this. On a server in the farm, open the SharePoint Management Shell (PowerShell). Run this command:

Set-OfficeWebAppsFarm - OfficeAddinEnabled:$true

You probably have to be logged in as a farm administrator.
There is some documentation here: Set-OfficeWebAppsFarm


问:
Authentication failed to bitbucket
I'm trying to push my project via the https protocol on bitbucket using sourcetree.

But I can't connect to bitbucket with my login and password (which work on the website), I have a fatal error : "Authentication failed".

I read on other posts I can work around the problem using the ssh protocol instead of the https one, so I set up a ssh key following instructions on the source tree faq.
But now I don't know how I can change to the ssh protocol when I want to push my code.
Someone know how I can do this ?
Thank you.

答:
OBSOLETE ANSWER - VERIFIED NOVEMBER 17, 2020

On Mac, I needed to go to Preferences > Accounts, then add a new account as Bitbucket Server and enter my company's bitbucket server URL. Then I had to choose HTTPS as the protocol and enter my username (without @email) and password.

Also I set this new account as the default account by clicking the Set Default... button in the bottom of the Preferences > Account page.

Title: Authentication failed to bitbucket


问:
Android Populate Spinner Content From Another Spinner
I am trying to populate cities by selecting a country from spinner. It should populate second spinner's content based on the first spinner's choice. My strings.xml and MainActivity.java file is like this:

strings.xml

```<code> <!-- Countries -->
<string-array name="country_names">
    <item>Turkey</item>
    <item>Spain</item>
</string-array>

<!-- Cities -->
<string-array name="Turkey">
    <item>Istanbul</item>
    <item>Adana</item>
</string-array>

<string-array name="Spain">
    <item>Madrid</item>
    <item>Barcelona</item>
</string-array>
</code>```

MainActivity.java

```<code>    citySpinner = (Spinner) findViewById(R.id.input_city);
    countrySpinner = (Spinner) findViewById(R.id.input_country);

    countryAdapter = ArrayAdapter.createFromResource(this,R.array.country_names,android.R.layout.simple_spinner_item);
    countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    final String[] country = new String[1];
    countrySpinner.setAdapter(countryAdapter);
    countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
        {
            country[0] = adapterView.getItemAtPosition(i).toString();
            Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView)
        {

        }
    });

    cityAdapter = ArrayAdapter.createFromResource(this,R.array.Turkey,android.R.layout.simple_spinner_item);
    cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    citySpinner.setAdapter(cityAdapter);
</code>```

I need to give a variable inside the cityAdapter = ArrayAdapter.createFromResource(...) line instead of writing Turkey or any country name.

I couldn't come up anything useful in the web, this is my last hope :)

答: Inside first spinner's setonitemselected, declare the second spinner and call clicklistener function i.e, second_spinner.setonitemselectedlistener then the two callback methods will be implemented inside the first spinner's setonitemselected method.</p>

Body:
I am trying to populate cities by selecting a country from spinner. It should populate second spinner's content based on the first spinner's choice. My strings.xml and MainActivity.java file is like this:

strings.xml

<string-array name="country_names">
    <item>Turkey</item>
    <item>Spain</item>
</string-array>

<string-array name="Turkey">
    <item>Istanbul</item>
    <item>Adana</item>
</string-array>

<string-array name="Spain">
    <item>Madrid</item>
    <item>Barcelona</item>
</string-array>

MainActivity.java

    citySpinner = (Spinner) findViewById(R.id.input_city);
    countrySpinner = (Spinner) findViewById(R.id.input_country);

    countryAdapter = ArrayAdapter.createFromResource(this,R.array.country_names,android.R.layout.simple_spinner_item);
    countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    final String[] country = new String[1];
    countrySpinner.setAdapter(countryAdapter);
    countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
        {
            country[0] = adapterView.getItemAtPosition(i).toString();
            Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView)
        {

        }
    });

    cityAdapter = ArrayAdapter.createFromResource(this,R.array.Turkey,android.R.layout.simple_spinner_item);
    cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    citySpinner.setAdapter(cityAdapter);

I need to give a variable inside the cityAdapter = ArrayAdapter.createFromResource(...) line instead of writing Turkey or any country name.

I couldn't come up anything useful in the web, this is my last hope :)


问:
Sending mail with a Raspberry Pi hosted apache2/citadel server
I have been running a web server off of my Raspberry Pi for a while now, getting to know HTML/CSS/JS/PHP. I wanted to learn how to send emails with the PHP mail() function from my website with a no-ip.com domain name. From my research, I realized that I needed to use SMTP, so I followed this tutorial to setup a citadel mail server in addition to apache2 on my Pi. I got it "up and running" and I am able to send mail to and from users on the Citadel server, but I am not able to send mail to and from my personal Gmail account.</p>

答: If you are trying to send emails via smtp from google account you have to use googles paraneters for it, and for reciving emails from your host email to gmail well check your spam folder cos without proper registration of your emails domain name in mx record on dns server it will be concidered as spam by google. Hope this helped.</p>


问:
Detect when a node is deleted (or removed from the DOM because a parent was)
I want to detect when a node (nodeX, say) is no longer available, either because it was deleted or because its parent (or its parents parent) was deleted.

So far, all I can think of is to use Mutation Observer to see any deletions on the page, and check if the deleted nodes was nodeX or had nodeX for a descendant.

Is there an easier way?

Please note: as far as I understand, the linked question (that this question "is a duplicate of") asks "how can I detect a [direct] deletion of a node". Mine asks "How can I detect the deletion of a node or its parent (or any other ancestor)".

As far as I understand, this is not straightforward with mutation observers: You need to check every deleted node to see if it was an ancestor.

This is what I seek to confirm or deny.

As far as I understand, that is different from the linked question.

答:
This has been asked before on stack overflow. How to detect element being added/removed from dom element?

If you just want to check whether something exists at a particular point in time, you could obviously do something like:

```<code>if (!document.querySelector(".nonexistent")) {
  console.log("doesn't exist");
}
</code>```

Otherwise Mutation Observers are your only option.

Body:
This has been asked before on stack overflow. How to detect element being added/removed from dom element?

If you just want to check whether something exists at a particular point in time, you could obviously do something like:

if (!document.querySelector(".nonexistent")) {
  console.log("doesn't exist");
}

Otherwise Mutation Observers are your only option.


问:
Removing a usb camera from my Android device does not refresh the list
I have this function that I call every 5 seconds:

```<code>     @NonNull
private ArrayList<LmiVideoCapturerDeviceInfo> getNumberOfCameras() {
    ArrayList<LmiVideoCapturerDeviceInfo> newDevices= new ArrayList<>();
    int numberOfCameras = Camera.getNumberOfCameras();
    Log.i("Refresh devices"," lookForDevicesChangesRunnable refresh devices size is!!!!!!!!!!!!!!!!!!!!!!!!!!!: " + numberOfCameras);
    for (int i = 0; i < numberOfCameras; i++) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(i, info);
        Log.i("Refresh devices", "camera ids are: " + info.toString());
        String facing = "BACK";
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            facing = "FRONT";
        }
        newDevices.add(new LmiVideoCapturerDeviceInfo("Camera " + i, Integer.toString(i), "Camera" + i, facing));
    }
    return newDevices;
}
</code>```

Now I for example at the beginning have 0 cameras, I add a camera in the usb plug, and it will update, and this will return 1, and it will refresh my list.

BUT If I have 1 camera connected, and I remove it, this function will still return 1, for a long time, even though the camera is not there anymore, and if I try to open it, in the app nothing happens, just get the last frame (from when  I removed it). Why isn't my list being updated sooner?
PS: the tv box set I'm using is Android 4.4.2 , so I cannot use Camera2 API, hence why I'm using the CameraAPI

答:
There's no built-in support for webcams in Android, so the manufacturer of your device must have added it.

Unfortunately, since there's no built-in support, it's fairly easy for there to be scenarios that don't work correctly. You're likely hitting one of those. You can try to report the problem to the manufacturer, but whether that'll get the issue resolved anytime soon is hard to say.

Body:
I have this function that I call every 5 seconds:

     @NonNull
private ArrayList<LmiVideoCapturerDeviceInfo> getNumberOfCameras() {
    ArrayList<LmiVideoCapturerDeviceInfo> newDevices= new ArrayList<>();
    int numberOfCameras = Camera.getNumberOfCameras();
    Log.i("Refresh devices"," lookForDevicesChangesRunnable refresh devices size is!!!!!!!!!!!!!!!!!!!!!!!!!!!: " + numberOfCameras);
    for (int i = 0; i < numberOfCameras; i++) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(i, info);
        Log.i("Refresh devices", "camera ids are: " + info.toString());
        String facing = "BACK";
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            facing = "FRONT";
        }
        newDevices.add(new LmiVideoCapturerDeviceInfo("Camera " + i, Integer.toString(i), "Camera" + i, facing));
    }
    return newDevices;
}

Now I for example at the beginning have 0 cameras, I add a camera in the usb plug, and it will update, and this will return 1, and it will refresh my list.

BUT If I have 1 camera connected, and I remove it, this function will still return 1, for a long time, even though the camera is not there anymore, and if I try to open it, in the app nothing happens, just get the last frame (from when  I removed it). Why isn't my list being updated sooner?
PS: the tv box set I'm using is Android 4.4.2 , so I cannot use Camera2 API, hence why I'm using the CameraAPI