问:
How does Twitter extract meaningful subject colors from image pixel data?
Let me first clarify the problem statement. Check out this tweet:

https://twitter.com/jungledragon/status/926894337761345538

Next, click the image itself within the tweet. In the light box that appears, the menu bar below it takes on a meaningful color that is based on the actual pixels in the image itself. Even in this stress test, this is a difficult image given all the light pixels, does it do a fine job in picking an overall color that 1) represents the content of the image 2) is dark/contrasty enough to place white text on it:

I was simultaneously implementing a similar system before I even knew Twitter had this. Check out a preview below:

The examples in the screenshot are optimistic, as there are plenty of situations where the background is too light. Even in seemingly positive examples as seen in my screenshot, most of the time it does not pass the AA or AAA contrast check.

My current approach:

One-time per image, a JS runs that calculates the average color of
all pixels in the image. Note that the average color is not
necessarily a meaningful color, such as in the edge case of the
spider where the average would be close to white.

I store the RGB value in the database

Upon rendering the page (server-side) I dynamically set the
background color of the image's caption using a formula

My formula is to convert the RGB to HSL, and then to manipulate in particular the S and L values. Given them a notch, using min/max values to set a treshold. I've tried countless combinations.

Yet it seems like a never-ending struggle because color darkness and contrast are subject to human perception.

Hence my curiosity on how Twitter seems to have nailed this, in particular two aspects:

Finding a meaningful subject color (not the same as average or dominant color)

Toning that meaningful color in a way that it remains recognizable (hue) yet is contrasty enough to place light text on it, whilst passing at least the AA contrast check.

I've searched around, but cannot find any information on their implementation. Anybody aware of they do it? Or other proven methods to solve this puzzle end-to-end?

答:
I took a peek at Twitter's markup to see what I could find, and, after running a bit of code in the browser's console, it seems like Twitter takes a color average over a flat distribution of pixels in the images and scales each of the RGB channels to values of 64 and below. This provides a pretty fast way to create a high-contrast background for light text while still retaining a reasonable color match. From what I can tell, Twitter doesn't perform any advanced subject-color-detection, but I can't say for sure.

Here's a quick-and-dirty demo I made to validate this theory. The top and left borders that appear around the images initially display the color Twitter uses. After running the snippet, a bottom and right border appears with the calculated color. Requires 9+ for IE users.

function processImage(img)
{
    var imageCanvas = new ImageCanvas(img);
    var tally = new PixelTally();

    for (var y = 0; y < imageCanvas.height; y += config.interval) {
        for (var x = 0; x < imageCanvas.width; x += config.interval) {
            tally.record(imageCanvas.getPixelColor(x, y));
        }
    }

    var average = new ColorAverage(tally);

    img.style.borderRightColor = average.toRGBStyleString();
    img.style.borderBottomColor = average.toRGBStyleString();
}

function ImageCanvas(img)
{
    var canvas = document.createElement('canvas');

    this.context2d = canvas.getContext('2d');
    this.width = canvas.width = img.naturalWidth;
    this.height = canvas.height = img.naturalHeight;

    this.context2d.drawImage(img, 0, 0, this.width, this.height);

    this.getPixelColor = function (x, y) {
        var pixel = this.context2d.getImageData(x, y, 1, 1).data;

        return { red: pixel[0], green: pixel[1], blue: pixel[2] };
    }
}

function PixelTally()
{
    this.totalPixelCount = 0;
    this.colorPixelCount = 0;
    this.red = 0;
    this.green = 0;
    this.blue = 0;
    this.luminosity = 0;

    this.record = function (colors) {
        this.luminosity += this.calculateLuminosity(colors);
        this.totalPixelCount++;

        if (this.isGreyscale(colors)) {
            return;
        }

        this.red += colors.red;
        this.green += colors.green;
        this.blue += colors.blue;

        this.colorPixelCount++;
    };

    this.getAverage = function (colorName) {
        return this[colorName] / this.colorPixelCount;
    };

    this.getLuminosityAverage = function () {
        return this.luminosity / this.totalPixelCount;
    }

    this.getNormalizingDenominator = function () {
        return Math.max(this.red, this.green, this.blue) / this.colorPixelCount;
    };

    this.calculateLuminosity = function (colors) {
        return (colors.red + colors.green + colors.blue) / 3;
    };

    this.isGreyscale = function (colors) {
        return Math.abs(colors.red - colors.green) < config.greyscaleDistance
            && Math.abs(colors.red - colors.blue) < config.greyscaleDistance;
    };
}

function ColorAverage(tally)
{
    var lightness = config.lightness;
    var normal = tally.getNormalizingDenominator();
    var luminosityAverage = tally.getLuminosityAverage();

    // We won't scale the channels up to 64 for darker images:
    if (luminosityAverage < lightness) {
        lightness = luminosityAverage;
    }

    this.red = (tally.getAverage('red') / normal) * lightness
    this.green = (tally.getAverage('green') / normal) * lightness
    this.blue = (tally.getAverage('blue') / normal) * lightness

    this.toRGBStyleString = function () {
        return 'rgb('
            + Math.round(this.red) + ','
            + Math.round(this.green) + ','
            + Math.round(this.blue) + ')';
    };
}

function Configuration()
{
    this.lightness = 64;
    this.interval = 100;
    this.greyscaleDistance = 15;
}

var config = new Configuration();
var indicator = document.getElementById('indicator');

document.addEventListener('DOMContentLoaded', function () {
    document.forms[0].addEventListener('submit', function (event) {
        event.preventDefault();

        config.lightness = Number(this.elements['lightness'].value);
        config.interval = Number(this.elements['interval'].value);
        config.greyscaleDistance = Number(this.elements['greyscale'].value);

        indicator.style.visibility = 'visible';

        setTimeout(function () {
            processImage(document.getElementById('image1'));
            processImage(document.getElementById('image2'));
            processImage(document.getElementById('image3'));
            processImage(document.getElementById('image4'));
            processImage(document.getElementById('image5'));

            indicator.style.visibility = 'hidden';
        }, 50);
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label { display: block; }
img { border-width: 20px; border-style: solid; width: 200px; height: 200px; }
#image1 { border-color: rgb(64, 54, 47) white white rgb(64, 54, 47); }
#image2 { border-color: rgb(46, 64, 17) white white rgb(46, 64, 17); }
#image3 { border-color: rgb(64, 59, 46) white white rgb(64, 59, 46); }
#image4 { border-color: rgb(36, 38, 20) white white rgb(36, 38, 20); }
#image5 { border-color: rgb(45, 53, 64) white white rgb(45, 53, 64); }
#indicator { visibility: hidden; }</code>```

<form id="configuration_form">

        Lightness:
            <input name="lightness" type="number" min="1" max="255" value="64">

        Pixel Sample Interval:
            <input name="interval" type="number" min="1" max="255" value="100">
            (Lower values are slower)

        Greyscale Distance:
            <input name="greyscale" type="number" min="1" max="255" value="15">

        <button type="submit">Run</button> (Wait for images to load first!)

Running...this may take a few moments.

</form>

```

The code ignores white, black, and grey-ish pixels when determining the dominant color from the image which gives us a more vivid saturation despite reducing the brightness of the color. The computed color is pretty close to the original color from Twitter for most of the images.

We can improve this experiment by changing which parts of the image we calculate the average color from. The example above selects pixels uniformly across the whole image, but we can try using only pixels near the edges of the image—so the color blends more seamlessly—or we can try averaging color values from the center of the image to highlight the subject. I'll expand on the code and update this answer later when I have some more time.

Body:
I took a peek at Twitter's markup to see what I could find, and, after running a bit of code in the browser's console, it seems like Twitter takes a color average over a flat distribution of pixels in the images and scales each of the RGB channels to values of 64 and below. This provides a pretty fast way to create a high-contrast background for light text while still retaining a reasonable color match. From what I can tell, Twitter doesn't perform any advanced subject-color-detection, but I can't say for sure.

Here's a quick-and-dirty demo I made to validate this theory. The top and left borders that appear around the images initially display the color Twitter uses. After running the snippet, a bottom and right border appears with the calculated color. Requires 9+ for IE users.

function processImage(img)
{
    var imageCanvas = new ImageCanvas(img);
    var tally = new PixelTally();

    for (var y = 0; y < imageCanvas.height; y += config.interval) {
        for (var x = 0; x < imageCanvas.width; x += config.interval) {
            tally.record(imageCanvas.getPixelColor(x, y));
        }
    }

    var average = new ColorAverage(tally);

    img.style.borderRightColor = average.toRGBStyleString();
    img.style.borderBottomColor = average.toRGBStyleString();
}

function ImageCanvas(img)
{
    var canvas = document.createElement('canvas');

    this.context2d = canvas.getContext('2d');
    this.width = canvas.width = img.naturalWidth;
    this.height = canvas.height = img.naturalHeight;

    this.context2d.drawImage(img, 0, 0, this.width, this.height);

    this.getPixelColor = function (x, y) {
        var pixel = this.context2d.getImageData(x, y, 1, 1).data;

        return { red: pixel[0], green: pixel[1], blue: pixel[2] };
    }
}

function PixelTally()
{
    this.totalPixelCount = 0;
    this.colorPixelCount = 0;
    this.red = 0;
    this.green = 0;
    this.blue = 0;
    this.luminosity = 0;

    this.record = function (colors) {
        this.luminosity += this.calculateLuminosity(colors);
        this.totalPixelCount++;

        if (this.isGreyscale(colors)) {
            return;
        }

        this.red += colors.red;
        this.green += colors.green;
        this.blue += colors.blue;

        this.colorPixelCount++;
    };

    this.getAverage = function (colorName) {
        return this[colorName] / this.colorPixelCount;
    };

    this.getLuminosityAverage = function () {
        return this.luminosity / this.totalPixelCount;
    }

    this.getNormalizingDenominator = function () {
        return Math.max(this.red, this.green, this.blue) / this.colorPixelCount;
    };

    this.calculateLuminosity = function (colors) {
        return (colors.red + colors.green + colors.blue) / 3;
    };

    this.isGreyscale = function (colors) {
        return Math.abs(colors.red - colors.green) < config.greyscaleDistance
            && Math.abs(colors.red - colors.blue) < config.greyscaleDistance;
    };
}

function ColorAverage(tally)
{
    var lightness = config.lightness;
    var normal = tally.getNormalizingDenominator();
    var luminosityAverage = tally.getLuminosityAverage();

    // We won't scale the channels up to 64 for darker images:
    if (luminosityAverage < lightness) {
        lightness = luminosityAverage;
    }

    this.red = (tally.getAverage('red') / normal) * lightness
    this.green = (tally.getAverage('green') / normal) * lightness
    this.blue = (tally.getAverage('blue') / normal) * lightness

    this.toRGBStyleString = function () {
        return 'rgb('
            + Math.round(this.red) + ','
            + Math.round(this.green) + ','
            + Math.round(this.blue) + ')';
    };
}

function Configuration()
{
    this.lightness = 64;
    this.interval = 100;
    this.greyscaleDistance = 15;
}

var config = new Configuration();
var indicator = document.getElementById('indicator');

document.addEventListener('DOMContentLoaded', function () {
    document.forms[0].addEventListener('submit', function (event) {
        event.preventDefault();

        config.lightness = Number(this.elements['lightness'].value);
        config.interval = Number(this.elements['interval'].value);
        config.greyscaleDistance = Number(this.elements['greyscale'].value);

        indicator.style.visibility = 'visible';

        setTimeout(function () {
            processImage(document.getElementById('image1'));
            processImage(document.getElementById('image2'));
            processImage(document.getElementById('image3'));
            processImage(document.getElementById('image4'));
            processImage(document.getElementById('image5'));

            indicator.style.visibility = 'hidden';
        }, 50);
    });
});

label { display: block; }
img { border-width: 20px; border-style: solid; width: 200px; height: 200px; }
#image1 { border-color: rgb(64, 54, 47) white white rgb(64, 54, 47); }
#image2 { border-color: rgb(46, 64, 17) white white rgb(46, 64, 17); }
#image3 { border-color: rgb(64, 59, 46) white white rgb(64, 59, 46); }
#image4 { border-color: rgb(36, 38, 20) white white rgb(36, 38, 20); }
#image5 { border-color: rgb(45, 53, 64) white white rgb(45, 53, 64); }
#indicator { visibility: hidden; }

<form id="configuration_form">
    <p>
        <label>Lightness:
            <input name="lightness" type="number" min="1" max="255" value="64">
        </label>
        <label>Pixel Sample Interval:
            <input name="interval" type="number" min="1" max="255" value="100">
            (Lower values are slower)
        </label>
        <label>Greyscale Distance:
            <input name="greyscale" type="number" min="1" max="255" value="15">
        </label>
        <button type="submit">Run</button> (Wait for images to load first!)
    </p>
    <p id="indicator">Running...this may take a few moments.</p>
</form>

<p>
    <img id="image1" crossorigin="Anonymous" src="https://pbs.twimg.com/media/DNz9fNqWAAAtoGu.jpg:large">
    <img id="image2" crossorigin="Anonymous" src="https://pbs.twimg.com/media/DOdX8AGXUAAYYmq.jpg:large">
    <img id="image3" crossorigin="Anonymous" src="https://pbs.twimg.com/media/DOYp0HQX4AEWcnI.jpg:large">
    <img id="image4" crossorigin="Anonymous" src="https://pbs.twimg.com/media/DOQm1NzXkAEwxG7.jpg:large">
    <img id="image5" crossorigin="Anonymous" src="https://pbs.twimg.com/media/DN6gVnpXUAIxlxw.jpg:large">
</p>

The code ignores white, black, and grey-ish pixels when determining the dominant color from the image which gives us a more vivid saturation despite reducing the brightness of the color. The computed color is pretty close to the original color from Twitter for most of the images.

We can improve this experiment by changing which parts of the image we calculate the average color from. The example above selects pixels uniformly across the whole image, but we can try using only pixels near the edges of the image—so the color blends more seamlessly—or we can try averaging color values from the center of the image to highlight the subject. I'll expand on the code and update this answer later when I have some more time.


来源: stackexchange

问:
Bash addition by the first column, if data in second column is the same
I have a list with delimiters |

```<code>40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2
</code>```

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

```<code>40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11
</code>```

How you can see, we have counted the numbers from first column.

答:
If you need output in same order in which Input_file is there then following awk may help you in same.

```<code>awk -F"|" '!c[$2,$3]++{val++;v[val]=$2$3} {a[$2,$3]+=$1;b[$2,$3]=$2 FS $3;} END{for(j=1;j<=val;j++){print a[v[j]] FS b[v[j]]}}' SUBSEP=""   Input_file
</code>```

Adding a non-one liner form of solution too now.

```<code>awk -F"|" '        ##Making field separator as pipe(|) here for all the lines for Input_file.
!c[$2,$3]++{       ##Checking if array C whose index is $2,$3 is having its first occurrence in array c then do following.
  val++;           ##incrementing variable val value with 1 each time cursor comes here.
  v[val]=$2$3      ##creating an array named v whose index is val and value is $2$3(second field 3rd field).
}                  ##Closing c array block here now.
{
  a[$2,$3]+=$1;    ##creating an array named a whose index is $2 $3 and incrementing its value with 1st field value and add in its same index values to get SUM.
  b[$2,$3]=$2 FS $3;##create array b with index of $2$3 and setting its value to $2 FS $3, where FS is field separator.
}                  ##closing this block here.
END{               ##Starting awk code END bock here.
  for(j=1;j<=val;j++){ ##starting a for loop here from variable named j value 1 to till value of variable val here.
    print a[v[j]] FS b[v[j]] ##printing value of array a whose index is value of array v with index j, and array b with index of array v with index j here.
}}
' SUBSEP="" Input_file       ##Setting SUBSEP to NULL here and mentioning the Input_file name here.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list with delimiters |

40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11

How you can see, we have counted the numbers from first column.

Body:
If you need output in same order in which Input_file is there then following awk may help you in same.

awk -F"|" '!c[$2,$3]++{val++;v[val]=$2$3} {a[$2,$3]+=$1;b[$2,$3]=$2 FS $3;} END{for(j=1;j<=val;j++){print a[v[j]] FS b[v[j]]}}' SUBSEP=""   Input_file

Adding a non-one liner form of solution too now.

awk -F"|" '        ##Making field separator as pipe(|) here for all the lines for Input_file.
!c[$2,$3]++{       ##Checking if array C whose index is $2,$3 is having its first occurrence in array c then do following.
  val++;           ##incrementing variable val value with 1 each time cursor comes here.
  v[val]=$2$3      ##creating an array named v whose index is val and value is $2$3(second field 3rd field).
}                  ##Closing c array block here now.
{
  a[$2,$3]+=$1;    ##creating an array named a whose index is $2 $3 and incrementing its value with 1st field value and add in its same index values to get SUM.
  b[$2,$3]=$2 FS $3;##create array b with index of $2$3 and setting its value to $2 FS $3, where FS is field separator.
}                  ##closing this block here.
END{               ##Starting awk code END bock here.
  for(j=1;j<=val;j++){ ##starting a for loop here from variable named j value 1 to till value of variable val here.
    print a[v[j]] FS b[v[j]] ##printing value of array a whose index is value of array v with index j, and array b with index of array v with index j here.
}}
' SUBSEP="" Input_file       ##Setting SUBSEP to NULL here and mentioning the Input_file name here.


问:
How to save MailMessage with multiple attachment into Sql Server database
I have a requirement where i need to save complete mailmessage object into database. Using below code i am able to save message body and single attachment into database but i can have n number of attachment in my email so how to handle such situation.

```<code> private static void SaveMessage(MailMessage message, byte[] arr)
{
    using (var conn = new SqlConnection("CONNECTION_STRING"))
    {
        using (var cmd = new SqlCommand("INSERT INTO MailSent (Body,Attachment) VALUES(@BODY,@ATTACHMENT)", conn))
        {
            conn.Open();
            var param = new SqlParameter("@BODY", SqlDbType.VarChar)
            {
                Value = message.Body
            };
            var param2 = new SqlParameter("@ATTACHMENT", SqlDbType.Binary)
            {
                Value = arr
            };
            cmd.Parameters.Add(param);
            cmd.Parameters.Add(param2);
            cmd.ExecuteNonQuery();
        }
    }
}
</code>```

Can we have any solution where we can serilize complete mailmessage along with their attachment and then deserlize it again and retrive all information

答:
As a rule of thumb, storing filestreams/files in your db, is considered a bad design choice. Mostly, you would prefer to store the file on a file server, and then just save the URL to the file in your Db.

However, if you must, the attachments should be in a separate table, where the body is the parent table. (IE. there should be a foreign key to the body's primary key, on the attachment table)

This will allow you to link x amounts of attachments to a single row of email body on your DB.

Then you insert the body first, and then all the attachments after in a for loop, with the id of the body.

Once that works, optimize from there.

Body:
I have a requirement where i need to save complete mailmessage object into database. Using below code i am able to save message body and single attachment into database but i can have n number of attachment in my email so how to handle such situation.

 private static void SaveMessage(MailMessage message, byte[] arr)
{
    using (var conn = new SqlConnection("CONNECTION_STRING"))
    {
        using (var cmd = new SqlCommand("INSERT INTO MailSent (Body,Attachment) VALUES(@BODY,@ATTACHMENT)", conn))
        {
            conn.Open();
            var param = new SqlParameter("@BODY", SqlDbType.VarChar)
            {
                Value = message.Body
            };
            var param2 = new SqlParameter("@ATTACHMENT", SqlDbType.Binary)
            {
                Value = arr
            };
            cmd.Parameters.Add(param);
            cmd.Parameters.Add(param2);
            cmd.ExecuteNonQuery();
        }
    }
}

Can we have any solution where we can serilize complete mailmessage along with their attachment and then deserlize it again and retrive all information


问:
Loading dots in Qualtrics
trying to add a in-betweener screen that just has the loading dots animation in Qualtrics. I'm not sure how to add CSS code to one question only. Thanks in advance!</p>

答:
You can add CSS to a question by adding a style tag to the question text in HTML view (the styles will apply to all questions on the page):

```<code>Your question text here.
<style>
/* CSS */
</style>
</code>```

If you need more granularity, you can modify the styles of individual elements using JavaScript.

Title: Loading dots in Qualtrics

Body:
You can add CSS to a question by adding a style tag to the question text in HTML view (the styles will apply to all questions on the page):

Your question text here.
<style>
/* CSS */
</style>

If you need more granularity, you can modify the styles of individual elements using JavaScript.


问:
How to match Java regex in switch case?
I want to write a Java code so that for any word that begins with "Foo", do something and for all that begin with "Bar" do something else.

```<code>for(String str: stringList) {
    switch (str) {
        case Foo*: // do something. then break.

        case Bar*: // do something else. break.
    }
}
</code>```

Now, how do I do this regex matching in java?

答:
You can't do that with a switch statement. Use a if-else-if instead:</p>

```<code>for(String str: stringList) {

    if(str.startsWith("Foo")){
        // do something
    } else if(str.startsWith("Bar")){
        // do something
    }
}
</code>```

Title: How to match Java regex in switch case?

Body:
I want to write a Java code so that for any word that begins with "Foo", do something and for all that begin with "Bar" do something else.

for(String str: stringList) {
    switch (str) {
        case Foo*: // do something. then break.

        case Bar*: // do something else. break.
    }
}

Now, how do I do this regex matching in java?

Body:
You can't do that with a switch statement. Use a if-else-if instead:

for(String str: stringList) {

    if(str.startsWith("Foo")){
        // do something
    } else if(str.startsWith("Bar")){
        // do something
    }
}


问:
Handling messages received by Rabbitmq Client in Android Service
I have an android Service which is running Rabbitmq client and consuming messages from a queue. The client can receive message at any time, so i am starting the service via startService ( not binding methodology ). SO the issue is what kind of communication mechanism i use to communicate from service with the different activities: binding or a notification? Binding wont be that useful as msg recieved could be related to a different activity than the one which is visible .. and Creating a model layer for handling so many different msgs recieved in the queue in  the service is becoming a challenge as well... Any ideas and pointers?</p>

答:
In my case I used EventBus : https://github.com/greenrobot/EventBus

All my activities  extends to an abstractOne wich have the subscribe Method :

```<code>@Subscribe(threadMode = ThreadMode.MAIN)
public void onAlert(MyObject object) {
...
}
</code>```

and in my Service, I'm just posting the message :

```<code>EventBus.getDefault().post(<MyObject>);
</code>```

Body:
In my case I used EventBus : https://github.com/greenrobot/EventBus

All my activities  extends to an abstractOne wich have the subscribe Method :

@Subscribe(threadMode = ThreadMode.MAIN)
public void onAlert(MyObject object) {
...
}

and in my Service, I'm just posting the message :

EventBus.getDefault().post(<MyObject>);


问:
ActiveX DLL locks up main UI thread
I'm struggling with running a function from an ActiveX DLL (compiled from VB6) in a background thread from a C# WinForms application.

Because the VB6 DLL project contains a lot of references to an old library called Sheridan Controls (threed32.ocx), which I'm helpfully informed "doesn't support multi threaded mode", I have to set the Threading Model option to Single Threaded (instead of Apartment Threaded) when compiling the DLL in VB6. So even though I set the ApartmentState property to STA on the C# Thread object from which I invoke the DLL, it still ends up clogging up the UI thread.

I'm not sure what my options are at this point. Refactoring out the Sheridan Controls from the DLL would be a tedious job. Another is just to accept defeat and let the UI hang while the DLL does its work.

I guess my main question is; does anyone know of a way I could (without too much hassle) run the single threaded ActiveX DLL in a separate process/service that could be invoked asynchronously from the main C# thread? Or is there any other option that I'm not aware of?

Solved: Based on the information from user @mnistic, I was able to find a solution. I had to rebuild the ActiveX DLL as an ActiveX EXE, which runs as an out-of-process component. To get it working I had to set "Start Mode" to "Standalone" in project properties. I also set the Instancing parameter on the VB6 class to SingleUse, to ensure that global state would not be shared across instances.

After updating the project reference, I was able to invoke the functions in the library in background threads from my C# application without causing GUI lag.

答:
When it comes to ActiveX, Microsoft differentiates between in-process and out-of-process components. Sometimes when people talk about ActiveX they are referring to in-process components, dll or ocx files that run in the same process as the client that's using them. Typically these components include GUI elements that VB6 made easy to embed within the client application. However, an in-process component must use the client's thread of execution, which in your case was causing the perceived lockup in main thread.

This is what out-of-process components are for. They execute in a separate thread -- separate process as a matter of fact. The drawback is that the communication needs to cross process boundaries, but in your case that's not a concern, and they are relatively easy to set up: https://msdn.microsoft.com/en-us/library/aa262334%28v=vs.60%29.aspx

ContentLicense: CC BY-SA 4.0

Title: ActiveX DLL locks up main UI thread


问:
Why is an element pushed out of view by background image?
I'm making a horizontal scrolling site and encountering an issue where, when using flexbox, my content is pushed out of the page by my background image. Please see my pen:

https://codepen.io/anon/pen/NwgQmG

I'm using three background images that each take up a full page's width and inline-block to create horizontal scrolling.

In addition, I want to add flexbox so that I can create my own grid system on top of each background image. The problem is that when I add flexbox, I must use position: absolute on the first div below my background image so that the background image isn't pushed down to the bottom of the page.

```<code><div id="homeImg" class="background-image-full">
  <div class="container row" style="position: absolute;">
    <div class="container column">
      Hello There!
    </div>
  </div>
</div>
</code>```

Then, when I attempt to add text to a container inside my grid system ("Hello There!"), the text does not show up. It's pushed to the upper left-hand corner, as indicated by inspect.

How can I get my text to show up? Is there a better way to use flexbox where I don't have to also use absolute positioning?

Thanks!

答:
The problem is you set the font-size:0

Change it to some px value as I did it in this Codepen

Also you need to give position:relative to the same class i.e. .surroundContainer.

Which will make your container stick to the current image.

* {
  margin: 0;
}

/*box-sizing will ensure an element stays within a parent width, even if padding or borders are applied.*/

*,
*:after,
*:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

.wrapper {
  height: 100vh;
  background-color: gray;
}

.surroundContainer {
  position: relative;
  height: 100vh;
  white-space: nowrap;
  font-size: 20px;
  color: white;
}

/* IGNORE: this is a class for a plugin */

.scroller {
  /*This scroll-snap functionality only works in Safari*/
  -webkit-scroll-snap-type: mandatory;
  -webkit-scroll-snap-points-x: repeat(100%);
  /*This scroll snap functionality is part of a polyfill
 that enables the functionality in Chrome.*/
  scroll-snap-type: mandatory;
  scroll-snap-destination: 0% 100%;
  scroll-snap-points-x: repeat(100%);
  /*Here, I've set the width to be 100% of the VW
 (the portion of the screen that the viewer sees before scrolling).
 Thus, overflow occurs (because my divs stretch three screens or three VWs, basically)
 and the scroll event from scrollsnap-polyfill.js is triggered.*/
  width: 100vw;
  overflow: auto;
}

.background-image-full {
  height: 100%;
  width: 100%;
  display: inline-block;
  background-size: cover;
  background-repeat: no-repeat;
}

#homeImg {
  background-image: url("https://www.petfinder.com/wp-content/uploads/2012/11/91615172-find-a-lump-on-cats-skin-632x475.jpg");
}

#AboutImg {
  background-image: url("http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg");
}

#CreditImg {
  background-image: url("https://www.bluecross.org.uk/sites/default/files/assets/images/124044lpr.jpg");
}

.container {
  display: flex;
  display: -webkit-flex;
  display: -ms-flexbox;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
}

.row {
  flex-flow: row;
  -webkit-flex-flow: row;
}

.column {
  flex-flow: column;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- This is the wrapper for the entire page -->
<div class="wrapper">
  <!-- This is the div that contains the horizontal scrolling -->
  <div class="surroundContainer scroller">
    <div id="homeImg" class="background-image-full">
      <div class="container" style="position: absolute;">
        <div class="column" style="border:5px solid white; height:300px; width:300px;">
          <p>Hello There!</p>
        </div>
      </div>
    </div>
    <div id="CreditImg" class="background-image-full"></div>
    <div id="AboutImg" class="background-image-full"></div>
  </div>
</div></code>```

Body:
I'm making a horizontal scrolling site and encountering an issue where, when using flexbox, my content is pushed out of the page by my background image. Please see my pen:

https://codepen.io/anon/pen/NwgQmG

I'm using three background images that each take up a full page's width and inline-block to create horizontal scrolling.

In addition, I want to add flexbox so that I can create my own grid system on top of each background image. The problem is that when I add flexbox, I must use position: absolute on the first div below my background image so that the background image isn't pushed down to the bottom of the page.

      Hello There!

Then, when I attempt to add text to a container inside my grid system ("Hello There!"), the text does not show up. It's pushed to the upper left-hand corner, as indicated by inspect.

How can I get my text to show up? Is there a better way to use flexbox where I don't have to also use absolute positioning?

Thanks!

Body:
The problem is you set the font-size:0

Change it to some px value as I did it in this Codepen

Also you need to give position:relative to the same class i.e. .surroundContainer.

Which will make your container stick to the current image.

* {
  margin: 0;
}

/*box-sizing will ensure an element stays within a parent width, even if padding or borders are applied.*/

*,
*:after,
*:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

.wrapper {
  height: 100vh;
  background-color: gray;
}

.surroundContainer {
  position: relative;
  height: 100vh;
  white-space: nowrap;
  font-size: 20px;
  color: white;
}

/* IGNORE: this is a class for a plugin */

.scroller {
  /*This scroll-snap functionality only works in Safari*/
  -webkit-scroll-snap-type: mandatory;
  -webkit-scroll-snap-points-x: repeat(100%);
  /*This scroll snap functionality is part of a polyfill
 that enables the functionality in Chrome.*/
  scroll-snap-type: mandatory;
  scroll-snap-destination: 0% 100%;
  scroll-snap-points-x: repeat(100%);
  /*Here, I've set the width to be 100% of the VW
 (the portion of the screen that the viewer sees before scrolling).
 Thus, overflow occurs (because my divs stretch three screens or three VWs, basically)
 and the scroll event from scrollsnap-polyfill.js is triggered.*/
  width: 100vw;
  overflow: auto;
}

.background-image-full {
  height: 100%;
  width: 100%;
  display: inline-block;
  background-size: cover;
  background-repeat: no-repeat;
}

#homeImg {
  background-image: url("https://www.petfinder.com/wp-content/uploads/2012/11/91615172-find-a-lump-on-cats-skin-632x475.jpg");
}

#AboutImg {
  background-image: url("http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg");
}

#CreditImg {
  background-image: url("https://www.bluecross.org.uk/sites/default/files/assets/images/124044lpr.jpg");
}

.container {
  display: flex;
  display: -webkit-flex;
  display: -ms-flexbox;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
}

.row {
  flex-flow: row;
  -webkit-flex-flow: row;
}

.column {
  flex-flow: column;
}

<!-- This is the wrapper for the entire page -->
<div class="wrapper">
  <!-- This is the div that contains the horizontal scrolling -->
  <div class="surroundContainer scroller">
    <div id="homeImg" class="background-image-full">
      <div class="container" style="position: absolute;">
        <div class="column" style="border:5px solid white; height:300px; width:300px;">
          <p>Hello There!</p>
        </div>
      </div>
    </div>
    <div id="CreditImg" class="background-image-full"></div>
    <div id="AboutImg" class="background-image-full"></div>
  </div>
</div>


问:
af:table filter not keeping filtered value after ppr
Here is my use case :

Filter an ADF table with a column header filter

Then do an action that trigger a PPR on the table

The table is refreshed and the filter disapear. The data isn't filtered anymore.

How can i persist the VC filter when the table is refreshed ?

The table is bind to a view Object with a simple empty view Criteria as filter model :

```<code><af:table value="#{bindings.myVO.collectionModel}"
  var="row"
  rows="#{bindings.myVO.rangeSize}"
  emptyText="#{Traduc_Lib['EmptyData']}"
  fetchSize="#{bindings.myVO.rangeSize}"
  rowBandingInterval="0" rowSelection="single" id="tO"
  styleClass="AFStretchWidth" autoHeightRows="5"
  columnStretching="column:c977" immediate="true"
  selectionListener="#{viewScope.myBean.mySelectionListener}"
  partialTriggers="::s73:cb4"
  contentDelivery="immediate"
  filterModel="#{bindings.myVOQuery.queryDescriptor}"
  queryListener="#{bindings.myVOQuery.processQuery}" varStatus="vs"
  selectedRowKeys="#{bindings.myVO.collectionModel.selectedRow}">
</code>```

答:
If you want to control that you need to utilize the filter facet of the <af:column> tag (https://docs.oracle.com/middleware/12212/adf/tag-reference-faces/tagdoc/af_column.html)

Check this documentation on how to use the facet (http://www.oracle.com/technetwork/developer-tools/adf/learnmore/16-custom-table-filter-169145.pdf)

Once you do that, you will have control over the <af:inputText> or <af:selectOneChoice> and you can retrieve its data back whenever needed.

Body:
Here is my use case :

Filter an ADF table with a column header filter

Then do an action that trigger a PPR on the table

The table is refreshed and the filter disapear. The data isn't filtered anymore.

How can i persist the VC filter when the table is refreshed ?

The table is bind to a view Object with a simple empty view Criteria as filter model :

<af:table value="#{bindings.myVO.collectionModel}"
  var="row"
  rows="#{bindings.myVO.rangeSize}"
  emptyText="#{Traduc_Lib['EmptyData']}"
  fetchSize="#{bindings.myVO.rangeSize}"
  rowBandingInterval="0" rowSelection="single" id="tO"
  styleClass="AFStretchWidth" autoHeightRows="5"
  columnStretching="column:c977" immediate="true"
  selectionListener="#{viewScope.myBean.mySelectionListener}"
  partialTriggers="::s73:cb4"
  contentDelivery="immediate"
  filterModel="#{bindings.myVOQuery.queryDescriptor}"
  queryListener="#{bindings.myVOQuery.processQuery}" varStatus="vs"
  selectedRowKeys="#{bindings.myVO.collectionModel.selectedRow}">


问:
Select div with a text inside in JS
I want to modify a div with a special text inside like this.

```<code><div>
<p>
A global issue
</p>
</div>
</code>```

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

答:
To target the div and set it to display: none you can run either:

```<code>// Pure JS
document.querySelector("div p").style.display = "none"
// w/jQuery
$('div p').hide();
</code>```

If there's more then one div p tags in your HTML, you can also search by text using the following:

```<code>$('div p:contains("A global issue")').css('display', 'none');
</code>```

Title: Select div with a text inside in JS

Body:
I want to modify a div with a special text inside like this.

A global issue

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

Body:
To target the div and set it to display: none you can run either:

// Pure JS
document.querySelector("div p").style.display = "none"
// w/jQuery
$('div p').hide();

If there's more then one div p tags in your HTML, you can also search by text using the following:

$('div p:contains("A global issue")').css('display', 'none');


问:
php, mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables
```<code>    // if the 'id' variable is not set in the URL, we must be creating a new record
    else
    {
            // if the form's submit button is clicked, we need to process the form
            if (isset($_POST['submit']))
            {
                    // get the form data

                            $mtcn = htmlentities($_POST['mtcn'], ENT_QUOTES);
                            $amount = htmlentities($_POST['amount'], ENT_QUOTES);
                            $currency = htmlentities($_POST['currency'], ENT_QUOTES);
                            $sender_name = htmlentities($_POST['sender_name'], ENT_QUOTES);
                            $sender_country = htmlentities($_POST['sender_country'], ENT_QUOTES);
                            $receiver_name = htmlentities($_POST['receiver_name'], ENT_QUOTES);
                            $comment = htmlentities($_POST['comment'], ENT_QUOTES);
                            $support = htmlentities($_POST['support'], ENT_QUOTES);
                            $email = htmlentities($_POST['email'], ENT_QUOTES);

                    // check that mtcn and amount  are both not empty
                    if ($mtcn == '' || $amount == '')
                    {
                            // if they are empty, show an error message and display the form
                            $error = 'ERROR: Please fill in all required fields!';
                            renderForm($mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email, $error);
                    }
                    else
                    {
                            // insert the new record into the database
                            if ($stmt = $mysqli->prepare("INSERT date (mtcn, amount, currency, sender_name, sender_country, receiver_name, comment, support, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"))
                            {
                                    $stmt->bind_param("ss", $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
                                    $stmt->execute();
                                    $stmt->close();
                            }
                            // show an error if the query has an error
                            else
                            {
                                    echo "ERROR: Could not prepare SQL statement.";
                            }

                            // redirec the user
                         //   header("Location: view.php");
                    }

            }
            // if the form hasn't been submitted yet, show the form
            else
            {
                    renderForm();
            }
    }

    // close the mysqli connection
    $mysqli->close();
</code>```

When I run the script I'm getting the error:

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of
  elements in type definition string doesn't match number of bind
  variables in C:\wamp\www\records.php on line 205

Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031):
  No data supplied for parameters in prepared statement in
  C:\wamp\www\records.php on line 206

Any idea how I can fix it ? I counted the parameters from bind_param and they seem fine for me ...

答:
I think you need more 's'-es in this?

```<code> $stmt->bind_param("ss", $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
</code>```

try this (asuming they're all strings)

```<code> $stmt->bind_param("sssssssss", $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
</code>```

Body:
    // if the 'id' variable is not set in the URL, we must be creating a new record
    else
    {
            // if the form's submit button is clicked, we need to process the form
            if (isset($_POST['submit']))
            {
                    // get the form data

                            $mtcn = htmlentities($_POST['mtcn'], ENT_QUOTES);
                            $amount = htmlentities($_POST['amount'], ENT_QUOTES);
                            $currency = htmlentities($_POST['currency'], ENT_QUOTES);
                            $sender_name = htmlentities($_POST['sender_name'], ENT_QUOTES);
                            $sender_country = htmlentities($_POST['sender_country'], ENT_QUOTES);
                            $receiver_name = htmlentities($_POST['receiver_name'], ENT_QUOTES);
                            $comment = htmlentities($_POST['comment'], ENT_QUOTES);
                            $support = htmlentities($_POST['support'], ENT_QUOTES);
                            $email = htmlentities($_POST['email'], ENT_QUOTES);

                    // check that mtcn and amount  are both not empty
                    if ($mtcn == '' || $amount == '')
                    {
                            // if they are empty, show an error message and display the form
                            $error = 'ERROR: Please fill in all required fields!';
                            renderForm($mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email, $error);
                    }
                    else
                    {
                            // insert the new record into the database
                            if ($stmt = $mysqli->prepare("INSERT date (mtcn, amount, currency, sender_name, sender_country, receiver_name, comment, support, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"))
                            {
                                    $stmt->bind_param("ss", $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);
                                    $stmt->execute();
                                    $stmt->close();
                            }
                            // show an error if the query has an error
                            else
                            {
                                    echo "ERROR: Could not prepare SQL statement.";
                            }

                            // redirec the user
                         //   header("Location: view.php");
                    }

            }
            // if the form hasn't been submitted yet, show the form
            else
            {
                    renderForm();
            }
    }

    // close the mysqli connection
    $mysqli->close();

When I run the script I'm getting the error:

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of
  elements in type definition string doesn't match number of bind
  variables in C:\wamp\www\records.php on line 205

Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031):
  No data supplied for parameters in prepared statement in
  C:\wamp\www\records.php on line 206

Any idea how I can fix it ? I counted the parameters from bind_param and they seem fine for me ...

Body:
I think you need more 's'-es in this?

 $stmt->bind_param("ss", $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);

try this (asuming they're all strings)

 $stmt->bind_param("sssssssss", $mtcn, $amount, $currency, $sender_name, $sender_country, $receiver_name, $comment, $support, $email);

ContentLicense: CC BY-SA 2.5


问:
MYSQL 5.6 Command line client for Windows Automatically closing
I need to create and manage connections to database servers using mysql Workbench and Mysql server. I have installed mysql-installer-community-5.6.35.0. But when I open MYSQL command line client, it automatically closes. I have already checked the status in services, it shows running. Any Suggestions as to how can I resolve this issue?

答: It's a known, but weirdly, seemingly unresolved issue when it comes to MySQL. However, it's a bug with your Windows users' privileges most likely. The workaround is to open the Command prompt (cmd), cd into the MySQL installation folder and execute mysql.exe from there.


问:
Debugging/testing facebook messenger bot
For testing purposes I usually put some logs or debugger into my code, probably as everybody does. To test my bot I would like to do the same but is there even a way to test/debug the messenger bot locally, or do I always have to deploy my tests?</p>

答:
Try this out

https://github.com/SonOfSardaar/facebook-send-api-emulator

I wrote that as node application (send api emulation) with angular UI for messenger. this helped me to debug locally.


问:
In Lua, how do you insert into a table with string keys?
In the command

```<code>table.insert(table, data)
</code>```

how can you use that but for the inserts have string keys?

PSEUDO CODE

```<code>tableOfStuff = {cat, pig, hat, lemon}
t = {}
for i=1, #tableOfStuff do
    table.insert(t, key=tableOfStuff[i], data=tableOfStuff[i])
end
</code>```

So I end up with a table...

```<code>t['cat'] == 'cat'
t['dog'] == 'dog'
etc.....
</code>```

EDIT

I think my example confused people... I am asking how to use "insert.table" but insert tings with string keys...

```<code>table.insert(table,data,stringkey)
</code>```

something like this?

答:
Creating One Table

If all you want is to create a table with strings as keys, then check out Table Constructors, you have a couple options.

Option 1:

```<code>t = { key1 = "value1", key2 = "value2" }

--or like this:

t = { ["key1"] = "value1", ["key2"] = "value2" }
</code>```

Option 2: (create an empty table first)

```<code>t = {}

t.key1 = "value1"

--or like this

t["key2"] = "value2"
</code>```

It looks like you want the keys and values to be the same string and that is possible. Just write the same thing for key1 and value1. So t["cat"] = "cat".

Using Two Tables

Based on your example code, it looks like you want to take an existing table of strings and create from that a new table with strings as both the keys and the values. To do that:

```<code>table1 = { "cat", "pig", "hat", "lemon" }
table2 = {}
for i=1, #table1 do
    table2[ table1[i] ] = table1[i]
end

--test
print table2["cat"]
</code>```

Here is a good lesson about tables in Lua: Lua Tables Tutorial

Body:
In the command

table.insert(table, data)

how can you use that but for the inserts have string keys?

PSEUDO CODE

tableOfStuff = {cat, pig, hat, lemon}
t = {}
for i=1, #tableOfStuff do
    table.insert(t, key=tableOfStuff[i], data=tableOfStuff[i])
end

So I end up with a table...

t['cat'] == 'cat'
t['dog'] == 'dog'
etc.....

EDIT

I think my example confused people... I am asking how to use "insert.table" but insert tings with string keys...

table.insert(table,data,stringkey)

something like this?

Body:
Creating One Table

If all you want is to create a table with strings as keys, then check out Table Constructors, you have a couple options.

Option 1:

t = { key1 = "value1", key2 = "value2" }

--or like this:

t = { ["key1"] = "value1", ["key2"] = "value2" }

Option 2: (create an empty table first)

t = {}

t.key1 = "value1"

--or like this

t["key2"] = "value2"

It looks like you want the keys and values to be the same string and that is possible. Just write the same thing for key1 and value1. So t["cat"] = "cat".

Using Two Tables

Based on your example code, it looks like you want to take an existing table of strings and create from that a new table with strings as both the keys and the values. To do that:

table1 = { "cat", "pig", "hat", "lemon" }
table2 = {}
for i=1, #table1 do
    table2[ table1[i] ] = table1[i]
end

--test
print table2["cat"]

Here is a good lesson about tables in Lua: Lua Tables Tutorial


答:
Switch statements require string literals and do not currently accept regex patterns.  But you can easily enough achieve the logic you want just using if and else:

```<code>for (String str: stringList) {
    if (str.matches("Foo.*")) {
        // do something
    }
    else if (str.matches("Bar.*")) {
        // do something else. break.
    }
}
</code>```

We could have used String#startsWith or substring, but I used matches to illustrate that a regex pattern can be used.

Demo

Title: How to match Java regex in switch case?

Body:
Switch statements require string literals and do not currently accept regex patterns.  But you can easily enough achieve the logic you want just using if and else:

for (String str: stringList) {
    if (str.matches("Foo.*")) {
        // do something
    }
    else if (str.matches("Bar.*")) {
        // do something else. break.
    }
}

We could have used String#startsWith or substring, but I used matches to illustrate that a regex pattern can be used.

Demo


问:
Check if a string (char *) can be enumerated
I'm trying to find a way to check if a read-in char * can be represented as a number (with or without decimal places) or not.  Essentially I am asking, if I have a text file containing the following:

```<code>-1.9e-3
e9
1e9
1ee9
-1-.9e3
.9e3
.9.e3
</code>```

It would be able to recognize that line 1, line 3, and line 6 can be "enumerated" into valid numbers, whereas all of the other lines contain erroneous inputs.  I know this could be done with brute force, but there is potentially an unlimited number of possibilities that could be wrong.  It would be much easier if there was a function that read in the entire char * and can just say,  "Yes that string of characters can be represented as an actual number" or "No that string of characters cannot be turned into the number that it intends to be."

And by enumerated I mean that the string (char *) can be the number that it wishes to represent.

答: Just use strtold(), it will tell you if it succeeds, and also give you the converted number.

Body:
I'm trying to find a way to check if a read-in char * can be represented as a number (with or without decimal places) or not.  Essentially I am asking, if I have a text file containing the following:

-1.9e-3
e9
1e9
1ee9
-1-.9e3
.9e3
.9.e3

It would be able to recognize that line 1, line 3, and line 6 can be "enumerated" into valid numbers, whereas all of the other lines contain erroneous inputs.  I know this could be done with brute force, but there is potentially an unlimited number of possibilities that could be wrong.  It would be much easier if there was a function that read in the entire char * and can just say,  "Yes that string of characters can be represented as an actual number" or "No that string of characters cannot be turned into the number that it intends to be."

And by enumerated I mean that the string (char *) can be the number that it wishes to represent.


问:
PHP 5.2.6 executes very slow on IIS 6
I just recently upgraded from PHP 5.2.1 to 5.3.5.  Had problems with my joomla sites, so I downgraded to 5.2.6, but now all my sites are running super slow.  What could be the cause of this in the php ini file?</p>

答:
With PHP 5.2.x you'll never get anywhere near the performance of PHP 5.3 on IIS.. especially on IIS 6. If at all possible, upgrade to IIS7 as soon as possible. I think you can do it for free through the Web Platform Installer (WebPI).

Also, what version of Joomla are you using? I'm pretty sure 1.5 was 5.3-compatible. More importantly, Joomla 1.6 was released last week so you may check out upgrading that too.

Here's some history of the situation:
http://www.slideshare.net/ruslany/php-performance-on-windows

Disclosure: Those slides are from a webcast I hosted with php|architect last year and I've worked with Microsoft and PHP on IIS and getting my Open Source project into WebPI.

Title: PHP 5.2.6 executes very slow on IIS 6


问:
Getting contours in an Order
For handwritten Digit Recognition, I have trained my CNN with MNIST database.

Now, I have to process my input images to the MNIST Format for detecting the digit.

For the following image :

I am using contours to separate 3 and 8, In order to detect and write "38" i need to send 3 first and then 8 to the CNN.

But the order of contours from cv2.findContours() are confusing, which sometimes detects 8 first then 3 making it "83".

How can i get the contours from left to write and similarly up to down ?

答:
What you can do is create bounding rectangles around your two black digits, then from iterate from the left most rectangle and send all contours in that rectangle to your CNN. If you took this as an example and went from top to bottom you would have two seperate rectangles:

Example code from that link:

```<code>contours, hier = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if 200<cv2.contourArea(cnt)<5000:
        cv2.drawContours(img,[cnt],0,(0,255,0),2)
        cv2.drawContours(mask,[cnt],0,255,-1)
</code>```

Then when you have a set of contours you can sort them in order:

```<code>import numpy as np

c = np.load(r"rect.npy")
contours = list(c)

# Example - contours = [(287, 117, 13, 46), (102, 117, 34, 47), (513, 116, 36, 49), (454, 116, 32, 49), (395, 116, 28, 48), (334, 116, 31, 49), (168, 116, 26, 49), (43, 116, 30, 48), (224, 115, 33, 50), (211, 33, 34, 47), ( 45, 33, 13, 46), (514, 32, 32, 49), (455, 32, 31, 49), (396, 32, 29, 48), (275, 32, 28, 48), (156, 32, 26, 49), (91, 32, 30, 48), (333, 31, 33, 50)]

max_width = np.sum(c[::, (0, 2)], axis=1).max()
max_height = np.max(c[::, 3])
nearest = max_height * 1.4

contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0]))

for x, y, w, h in contours:
    print "{:4} {:4} {:4} {:4}".format(x, y, w, h)
</code>```

Taken from - here

Title: Getting contours in an Order

Body:
What you can do is create bounding rectangles around your two black digits, then from iterate from the left most rectangle and send all contours in that rectangle to your CNN. If you took this as an example and went from top to bottom you would have two seperate rectangles:

Example code from that link:

contours, hier = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if 200<cv2.contourArea(cnt)<5000:
        cv2.drawContours(img,[cnt],0,(0,255,0),2)
        cv2.drawContours(mask,[cnt],0,255,-1)

Then when you have a set of contours you can sort them in order:

import numpy as np

c = np.load(r"rect.npy")
contours = list(c)

# Example - contours = [(287, 117, 13, 46), (102, 117, 34, 47), (513, 116, 36, 49), (454, 116, 32, 49), (395, 116, 28, 48), (334, 116, 31, 49), (168, 116, 26, 49), (43, 116, 30, 48), (224, 115, 33, 50), (211, 33, 34, 47), ( 45, 33, 13, 46), (514, 32, 32, 49), (455, 32, 31, 49), (396, 32, 29, 48), (275, 32, 28, 48), (156, 32, 26, 49), (91, 32, 30, 48), (333, 31, 33, 50)]

max_width = np.sum(c[::, (0, 2)], axis=1).max()
max_height = np.max(c[::, 3])
nearest = max_height * 1.4

contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0]))

for x, y, w, h in contours:
    print "{:4} {:4} {:4} {:4}".format(x, y, w, h)

Taken from - here


问:
How to change the colour of a selected WPF DataGrid row header
I have a WPF DataGrid whose row headers get filled with (a small amount of) text, and this works great... until you highlight the row, when the text turns white and is barely visible:

In an attempt to force it to stay black, I set the following code containing both an IsSelected trigger and an explicit DataTemplate with its colour also set.

<DataGrid.RowStyle>

        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Foreground="Black" Text="{Binding}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.RowStyle>
```

Unfortunately, neither of these has any effect. The text remains stubbornly white until the row is deselected.

How can I force this text to remain black (or any other colour) when selected?

答: The style trigger is defined on the row itself instead of the header's template item. Simply move the trigger definition into the header template would do the trick. </p>

Body:
I have a WPF DataGrid whose row headers get filled with (a small amount of) text, and this works great... until you highlight the row, when the text turns white and is barely visible:

In an attempt to force it to stay black, I set the following code containing both an IsSelected trigger and an explicit DataTemplate with its colour also set.

<DataGrid.RowStyle>

        <Setter Property="HeaderTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Foreground="Black" Text="{Binding}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.RowStyle>

Unfortunately, neither of these has any effect. The text remains stubbornly white until the row is deselected.

How can I force this text to remain black (or any other colour) when selected?


问:
How to re-write script of matrix 3D matlab in python
I newbie in python. I have matlab script like below. I want to re-write matrix 3D in matlab script in to python 3.x language. How can I fix it?</p>

```<code>nl=length(res);
ndat=length(per);
phi=atan(1)*4;
amu=phi*4e-7;

for i=1:ndat
  for j=1:nl
     z=sqrt(phi*amu*res(j)/per(i));
     zz(j)=complex(z,z);
     exp0=exp((-2)*zz(j)/res(j)*thi(j));
     exp1=complex(1,0)+exp0;
     exp2=complex(1,0)-exp0;

     %matrix 3D
     ldi(1,1,j)=exp1;
     ldi(1,2,j)=zz(j)*exp2
     ldi(2,1,j)=exp2/zz(j);
     ldi(2,2,j)=exp1;`
  end
end
</code>```

答:
You'll find a self-contained implementation of your code (below), with a few key differences:

Python indexing starts from 0 instead of one

Python indexing uses square brackets instead of round ones

Mathematic functions must be imported from libraries (here math and cmath)

Good luck!

```<code>import math
import cmath

# Data
res = [1, 4, 1, 2, 3]
per = [5, 5, 1, 1, 0.5, 0.6]
thi = [1, 2, 3, 4, 5, 6]
nl = len(res)
ldi = [[[0 for x in range(nl)],[0 for x in range(nl)]], [[0 for x in range(nl)],[0 for x in range(nl)]]]
zz = [0]*nl

nl = len(res)
ndat = len(per)
phi = math.atan(1)*4
amu = phi*4e-7

for i in range(ndat):
  for j in range(nl):
    z = math.sqrt(phi*amu*res[j]/per[i])
    zz[j] = complex(z,z)
    exp0=cmath.exp((-2)*zz[j]/res[j]*thi[j]);
    exp1=complex(1,0)+exp0;
    exp2=complex(1,0)-exp0;

    #- matrix 3D
    ldi[0][0][j]=exp1;
    ldi[0][1][j]=zz[j]*exp2
    ldi[1][0][j]=exp2/zz[j]
    ldi[1][1][j]=exp1
</code>```

Body:
I newbie in python. I have matlab script like below. I want to re-write matrix 3D in matlab script in to python 3.x language. How can I fix it?

nl=length(res);
ndat=length(per);
phi=atan(1)*4;
amu=phi*4e-7;

for i=1:ndat
  for j=1:nl
     z=sqrt(phi*amu*res(j)/per(i));
     zz(j)=complex(z,z);
     exp0=exp((-2)*zz(j)/res(j)*thi(j));
     exp1=complex(1,0)+exp0;
     exp2=complex(1,0)-exp0;

     %matrix 3D
     ldi(1,1,j)=exp1;
     ldi(1,2,j)=zz(j)*exp2
     ldi(2,1,j)=exp2/zz(j);
     ldi(2,2,j)=exp1;`
  end
end

Body:
You'll find a self-contained implementation of your code (below), with a few key differences:

Python indexing starts from 0 instead of one

Python indexing uses square brackets instead of round ones

Mathematic functions must be imported from libraries (here math and cmath)

Good luck!

import math
import cmath

# Data
res = [1, 4, 1, 2, 3]
per = [5, 5, 1, 1, 0.5, 0.6]
thi = [1, 2, 3, 4, 5, 6]
nl = len(res)
ldi = [[[0 for x in range(nl)],[0 for x in range(nl)]], [[0 for x in range(nl)],[0 for x in range(nl)]]]
zz = [0]*nl

nl = len(res)
ndat = len(per)
phi = math.atan(1)*4
amu = phi*4e-7

for i in range(ndat):
  for j in range(nl):
    z = math.sqrt(phi*amu*res[j]/per[i])
    zz[j] = complex(z,z)
    exp0=cmath.exp((-2)*zz[j]/res[j]*thi[j]);
    exp1=complex(1,0)+exp0;
    exp2=complex(1,0)-exp0;

    #- matrix 3D
    ldi[0][0][j]=exp1;
    ldi[0][1][j]=zz[j]*exp2
    ldi[1][0][j]=exp2/zz[j]
    ldi[1][1][j]=exp1


问:
How to set title of navigation bar in storyboard?
I can't solve this despite my best efforts. I also consulted the Apple documentation and several related questions here and still I have a mental block on this.

Using Xcode 6, I embedded a table view controller in a navigation controller and could set the title of the navigation bar in the table view controller, but not in the two view controllers that are connected to the table view via segues.

I did think there was a navigation bar on these two view controllers because after I embedded the table view controller in the navigation controller, it blocked out my topmost textfield in both. I repositioned that so that isn't a problem, but in storyboard I still don't seem to be able to click inside the navigation bar to add a title and now having added a navigation bar manually to test it out, I can see that there is only one navigation bar in document outline.

So do you simply have to set the title of the navigation bar programmatically or with an IBOutlet or some such? Doesn't seem like you can click into it in story board.

答:
None of the answers worked for me.

This worked:

Delete nav connection

Ctrl drag a new nav connection

Make it a show connection

Now you can edit the title

Delete the nav connection again

Create the original nav connection type again

It seems that this is indeed a bug in IB


问:
How to remove a Language Selector Porlet from a page of Liferay 7
I've added a Language Selector portlet to a public page of Liferay 7 but now I've decided to remove it. Unfortunately, there is no remove option on its menu.

You can see the menu image below.

How can I remove it from this page?

Liferay version is: liferay-ce-portal-7.0-ga4

答:
Login with 'Site Admin' role

Control Panel - >  Configuration -> Components page

Aprrox page 3 - > Language Selector -> click -> uncheck "Active" -> Save.

It will remove portlet from Liferay

Now, Go to your Page ( Where 'Language Selector') -> click on 3 dots -> you can see 'Remove' option.

Rollback

Control Panel - >  Configuration -> Components

Aprrox page 3 - > Language Selector -> click -> check "Active" -> Save.


问:
Open multiple links, in random order, by clicking one link
(This is for a client who needs the function for a focus group test)

I am trying to create a link that when clicked will open three tabs to three different urls - each time in random order.

So "Click me" would open example.com, google.com, facebook in three tabs at once, in random order. So first click it might be example.com, google.com, facebook.com - next click might be google.com, facebook.com, example, and so on.

So far I have this code, it selects a random link, but only one of them - I want to open all three at once, but in random order

```<code><script type="text/javascript">
    var urls = [
        "http://example.com",
        'http://google.com',
        'http://facebook.com'
    ];

    function goSomewhere() {
        var url = urls[Math.floor(Math.random()*urls.length)];
        window.location = url; // redirect
    }
</script>

<a href="#" onClick="goSomewhere(); return false;">Start</a>
</code>```

答:
```<code>function goSomewhere() {
 while(urls.length)
    window.open(...urls.splice(Math.floor(Math.random()*urls.length),1),"Test");
}
</code>```

Body:
(This is for a client who needs the function for a focus group test)

I am trying to create a link that when clicked will open three tabs to three different urls - each time in random order.

So "Click me" would open example.com, google.com, facebook in three tabs at once, in random order. So first click it might be example.com, google.com, facebook.com - next click might be google.com, facebook.com, example, and so on.

So far I have this code, it selects a random link, but only one of them - I want to open all three at once, but in random order

Start


问:
Lotusscript : Can I detect picture in rich text field?
I have a problem with my program that because my user like to attach the screen-capture picture into rich-text field

ex.

And my program can not detect them...

Can everyone share your idea ?...

thank you.

答:
Consider using NotesRichTextNavigator for your rich text field. Obtain the navigator via

```<code>Set notesRichTextNavigator  =  notesRichTextItem .CreateNavigator
</code>```

Then for notesRichTextNavigator object, use FindFirstElement and FindNextElement calls to examine rich text field contents for particular element types.

Check the navigator class API reference here: https://www.ibm.com/support/knowledgecenter/en/SSVRGU_9.0.1/basic/H_NOTESRICHTEXTNAVIGATOR_CLASS.html

UPDATE

I have checked some things with Notes Designer and I have to say the following.

Navigator approach described above is not suitable to check for pictures pasted to the rich text field. Standard notes functionality does not allow to check whether a rich-text item contains an embedded picture object.

Neither notesDocument.HasEmbedded nor richtextItem.EmbeddedObjects show contained embedded pictures.

But described way is possible to control file attachments, ole objects and document links according to the API specification.

Please note, if you are working with a notesDocument which was not saved, i.e it is a new document, you should call notesUIDocument.Refresh(true) to pass rich text item from front-end UI document to back-end notesDocument. Otherwise getFirstItem(richTextFieldName) will return Nothing.

Body:
Consider using NotesRichTextNavigator for your rich text field. Obtain the navigator via

Set notesRichTextNavigator  =  notesRichTextItem .CreateNavigator

Then for notesRichTextNavigator object, use FindFirstElement and FindNextElement calls to examine rich text field contents for particular element types.

Check the navigator class API reference here: https://www.ibm.com/support/knowledgecenter/en/SSVRGU_9.0.1/basic/H_NOTESRICHTEXTNAVIGATOR_CLASS.html

UPDATE

I have checked some things with Notes Designer and I have to say the following.

Navigator approach described above is not suitable to check for pictures pasted to the rich text field. Standard notes functionality does not allow to check whether a rich-text item contains an embedded picture object.

Neither notesDocument.HasEmbedded nor richtextItem.EmbeddedObjects show contained embedded pictures.

But described way is possible to control file attachments, ole objects and document links according to the API specification.

Please note, if you are working with a notesDocument which was not saved, i.e it is a new document, you should call notesUIDocument.Refresh(true) to pass rich text item from front-end UI document to back-end notesDocument. Otherwise getFirstItem(richTextFieldName) will return Nothing.


问:
Parallel.Foreach and BulkCopy
I have a C# library which connects to 59 servers of the same database structure and imports data to my local db to the same table. At this moment I am retrieving data server by server in foreach loop:

```<code>foreach (var systemDto in systems)
{
    var sourceConnectionString = _systemService.GetConnectionStringAsync(systemDto.Ip).Result;
    var dbConnectionFactory = new DbConnectionFactory(sourceConnectionString,
        "System.Data.SqlClient");
    var dbContext = new DbContext(dbConnectionFactory);
    var storageRepository = new StorageRepository(dbContext);
    var usedStorage = storageRepository.GetUsedStorageForCurrentMonth();

    var dtUsedStorage = new DataTable();
    dtUsedStorage.Load(usedStorage);
    var dcIp = new DataColumn("IP", typeof(string)) {DefaultValue = systemDto.Ip};
    var dcBatchDateTime = new DataColumn("BatchDateTime", typeof(string))
    {
        DefaultValue = batchDateTime
    };
    dtUsedStorage.Columns.Add(dcIp);
    dtUsedStorage.Columns.Add(dcBatchDateTime);

    using (var blkCopy = new SqlBulkCopy(destinationConnectionString))
    {
        blkCopy.DestinationTableName = "dbo.tbl";
        blkCopy.WriteToServer(dtUsedStorage);
    }
}
</code>```

Because there are many systems to retrieve data, I wonder if it is possible to use Pararel.Foreach loop? Will BulkCopy lock the table during WriteToServer and next WriteToServer will wait until previous will complete?

-- EDIT 1

I've changed Foreach to Parallel.Foreach but I face one problem. Inside this loop I have async method: _systemService.GetConnectionStringAsync(systemDto.Ip)
and this line returns error:

System.NotSupportedException: A second operation started on this
  context before a previous asynchronous operation completed. Use
  'await' to ensure that any asynchronous operations have completed
  before calling another method on this context. Any instance members
  are not guaranteed to be thread safe.

Any ideas how can I handle this?

答:
In general, it will get blocked and will wait until the previous operation complete.

There are some factors that may affect if SqlBulkCopy can be run in parallel or not.

I remember when adding the Parallel feature to my .NET Bulk Operations, I had hard time to make it work correctly in parallel but that worked well when the table has no index (which is likely never the case)

Even when worked, the performance gain was not a lot faster.

Perhaps you will find more information here: MSDN - Importing Data in Parallel with Table Level Locking

Title: Parallel.Foreach and BulkCopy

Body:
I have a C# library which connects to 59 servers of the same database structure and imports data to my local db to the same table. At this moment I am retrieving data server by server in foreach loop:

foreach (var systemDto in systems)
{
    var sourceConnectionString = _systemService.GetConnectionStringAsync(systemDto.Ip).Result;
    var dbConnectionFactory = new DbConnectionFactory(sourceConnectionString,
        "System.Data.SqlClient");
    var dbContext = new DbContext(dbConnectionFactory);
    var storageRepository = new StorageRepository(dbContext);
    var usedStorage = storageRepository.GetUsedStorageForCurrentMonth();

    var dtUsedStorage = new DataTable();
    dtUsedStorage.Load(usedStorage);
    var dcIp = new DataColumn("IP", typeof(string)) {DefaultValue = systemDto.Ip};
    var dcBatchDateTime = new DataColumn("BatchDateTime", typeof(string))
    {
        DefaultValue = batchDateTime
    };
    dtUsedStorage.Columns.Add(dcIp);
    dtUsedStorage.Columns.Add(dcBatchDateTime);

    using (var blkCopy = new SqlBulkCopy(destinationConnectionString))
    {
        blkCopy.DestinationTableName = "dbo.tbl";
        blkCopy.WriteToServer(dtUsedStorage);
    }
}

Because there are many systems to retrieve data, I wonder if it is possible to use Pararel.Foreach loop? Will BulkCopy lock the table during WriteToServer and next WriteToServer will wait until previous will complete?

-- EDIT 1

I've changed Foreach to Parallel.Foreach but I face one problem. Inside this loop I have async method: _systemService.GetConnectionStringAsync(systemDto.Ip)
and this line returns error:

System.NotSupportedException: A second operation started on this
  context before a previous asynchronous operation completed. Use
  'await' to ensure that any asynchronous operations have completed
  before calling another method on this context. Any instance members
  are not guaranteed to be thread safe.

Any ideas how can I handle this?


问:
Migration file don't change Site name and domain
I have this migration file:

```<code>from django.db import migrations
from django.contrib.sites.models import Site as DjangoSite

def change_django_site(apps, schema_editor):
    site = DjangoSite.objects.get(id=1)
    site.delete()

    DjangoSite.objects.get_or_create(id=1, domain='www.xprende.com', name='XPrende')

def create_homepage(apps, schema_editor):
    # Get models
    ContentType = apps.get_model('contenttypes.ContentType')
    Page = apps.get_model('wagtailcore.Page')
    Site = apps.get_model('wagtailcore.Site')
    HomePage = apps.get_model('home.HomePage')

    # Delete the default homepage
    # If migration is run multiple times, it may have already been deleted
    Page.objects.filter(id=2).delete()

    # Create content type for homepage model
    homepage_content_type, __ = ContentType.objects.get_or_create(
        model='homepage', app_label='home')

    # Create a new homepage
    homepage = HomePage.objects.create(
        title="Home",
        draft_title="Home",
        slug='home',
        content_type=homepage_content_type,
        path='00010001',
        depth=2,
        numchild=0,
        url_path='/home/',
    )

    # Create a site with the new homepage set as the root
    Site.objects.create(
        hostname='www.xprende.com', site_name='XPrende', root_page=homepage, is_default_site=True
    )

def remove_homepage(apps, schema_editor):
    # Get models
    ContentType = apps.get_model('contenttypes.ContentType')
    HomePage = apps.get_model('home.HomePage')

    # Delete the default homepage
    # Page and Site objects CASCADE
    HomePage.objects.filter(slug='home', depth=2).delete()

    # Delete content type for homepage model
    ContentType.objects.filter(model='homepage', app_label='home').delete()

class Migration(migrations.Migration):
    dependencies = [
        ('home', '0001_initial'),
        ('sites', '0002_alter_domain_unique'),
    ]

    operations = [
        migrations.RunPython(
            create_homepage,
            remove_homepage,
            change_django_site,
        ),
    ]
</code>```

As you can see i made a function that have to change the django site name and domain. But it doesn't do it, after apply the migrations i get the same default values:

```<code>In [3]: DjangoSite.objects.get(id=1)
Out[3]: <Site: example.com>

In [4]: DjangoSite.objects.get(id=1).name
Out[4]: 'example.com'

In [5]: DjangoSite.objects.get(id=1).domain
Out[5]: 'example.com'

In [6]: DjangoSite.objects.all()
Out[6]: <QuerySet [<Site: example.com>]>
</code>```

I can't understand why, i put the sites migrations as dependencie of this migration file but still it doesn't works.

Can anyone explain me why i have this error?

Thank you.

答:
You have to run change_django_site as separate operation:

```<code>class Migration(migrations.Migration):
    dependencies = [
        ('home', '0001_initial'),
        ('sites', '0002_alter_domain_unique'),
    ]

    operations = [
        migrations.RunPython(change_django_site, reverse_code=migrations.RunPython.noop),
        migrations.RunPython(create_homepage, reverse_code=remove_homepage),
    ]
</code>```

and change_django_site must be

```<code>def change_django_site(apps, schema_editor):
    DjangoSite = apps.get_model('sites', 'Site')
    site = DjangoSite.objects.get_or_create(id=1)
    site.domain='www.xprende.com'
    site.name='XPrende'
    site.save()
</code>```

Body:
I have this migration file:

from django.db import migrations
from django.contrib.sites.models import Site as DjangoSite

def change_django_site(apps, schema_editor):
    site = DjangoSite.objects.get(id=1)
    site.delete()

    DjangoSite.objects.get_or_create(id=1, domain='www.xprende.com', name='XPrende')

def create_homepage(apps, schema_editor):
    # Get models
    ContentType = apps.get_model('contenttypes.ContentType')
    Page = apps.get_model('wagtailcore.Page')
    Site = apps.get_model('wagtailcore.Site')
    HomePage = apps.get_model('home.HomePage')

    # Delete the default homepage
    # If migration is run multiple times, it may have already been deleted
    Page.objects.filter(id=2).delete()

    # Create content type for homepage model
    homepage_content_type, __ = ContentType.objects.get_or_create(
        model='homepage', app_label='home')

    # Create a new homepage
    homepage = HomePage.objects.create(
        title="Home",
        draft_title="Home",
        slug='home',
        content_type=homepage_content_type,
        path='00010001',
        depth=2,
        numchild=0,
        url_path='/home/',
    )

    # Create a site with the new homepage set as the root
    Site.objects.create(
        hostname='www.xprende.com', site_name='XPrende', root_page=homepage, is_default_site=True
    )

def remove_homepage(apps, schema_editor):
    # Get models
    ContentType = apps.get_model('contenttypes.ContentType')
    HomePage = apps.get_model('home.HomePage')

    # Delete the default homepage
    # Page and Site objects CASCADE
    HomePage.objects.filter(slug='home', depth=2).delete()

    # Delete content type for homepage model
    ContentType.objects.filter(model='homepage', app_label='home').delete()

class Migration(migrations.Migration):
    dependencies = [
        ('home', '0001_initial'),
        ('sites', '0002_alter_domain_unique'),
    ]

    operations = [
        migrations.RunPython(
            create_homepage,
            remove_homepage,
            change_django_site,
        ),
    ]

As you can see i made a function that have to change the django site name and domain. But it doesn't do it, after apply the migrations i get the same default values:

In [3]: DjangoSite.objects.get(id=1)
Out[3]: <Site: example.com>

In [4]: DjangoSite.objects.get(id=1).name
Out[4]: 'example.com'

In [5]: DjangoSite.objects.get(id=1).domain
Out[5]: 'example.com'

In [6]: DjangoSite.objects.all()
Out[6]: <QuerySet [<Site: example.com>]>

I can't understand why, i put the sites migrations as dependencie of this migration file but still it doesn't works.

Can anyone explain me why i have this error?

Thank you.

Body:
You have to run change_django_site as separate operation:

class Migration(migrations.Migration):
    dependencies = [
        ('home', '0001_initial'),
        ('sites', '0002_alter_domain_unique'),
    ]

    operations = [
        migrations.RunPython(change_django_site, reverse_code=migrations.RunPython.noop),
        migrations.RunPython(create_homepage, reverse_code=remove_homepage),
    ]

and change_django_site must be

def change_django_site(apps, schema_editor):
    DjangoSite = apps.get_model('sites', 'Site')
    site = DjangoSite.objects.get_or_create(id=1)
    site.domain='www.xprende.com'
    site.name='XPrende'
    site.save()


问:
How can I reference xaml Template from a Converter?
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

```<code>        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>
</code>```

and I have this control using this converter:

```<code><ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>
</code>```

My Converter:

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }
</code>```

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

答:
Put your Templates in the resources of some control, give them x:Keys and call:</p>

```<code>ControlTemplate template = someControl.FindResource("Key") as ControlTemplate;
</code>```

Body:
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>

and I have this control using this converter:

<ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>

My Converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

Body:
Put your Templates in the resources of some control, give them x:Keys and call:

ControlTemplate template = someControl.FindResource("Key") as ControlTemplate;


问:
SQL improvement - UNION?
I have 2 tables: "packages" and "items".

"packages" has the following columns: pack_id | item_id

"items" has the following columns.......:    item_id | type

One package can have multiple items.

UPDATE:

Sample Data and Expected Results:

```<code>pack_id | item_id
1           1
1           2
1           3
2           2
2           1
3           4
3           5
3           6

item_id | type
1           C
2           F
3           Z
4           Z
5           Z
6           Z
</code>```

Expected result:

```<code>pack_id | pack_type
1           Mixed
2           Cool
3           Not Cool
</code>```

My question is:

Is there a better way to query these 2 tables, in order to get a 3rd one, having as columns: "pack_id" and the new column "pack_type"? Those UNIONs seem to add a huge amount of time to the run time.

```<code>    SELECT pack_id, pack_type
    FROM (
      -- CASE 1 - pack_type is 'Cool' - type 'C' or 'F', but not 'Z'
      SELECT  Distinct q1.pack_id, 'Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type <> 'Z') q1
        WHERE q1.type IN ('C','F')

      UNION

      -- CASE 2 - pack_type is 'Not-Cool' - type 'Z', but not 'C' or 'F'
      SELECT  Distinct q2.pack_id, 'Not-Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q2
        WHERE q2.type NOT IN ('C','F')

      UNION

     -- CASE 3 - pack_type is 'Mixed' - type 'Z' and ('C' or 'F')
     SELECT  Distinct q3.pack_id, 'Mixed' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q3
        WHERE q3.type IN ('C','F')
    ) m
</code>```

NOTE: some explication for the multiple comments that point to "A type cannot be Z and also C or F".

I also thought that, but the way I understand the behavior of the query is that if u say "type IN ('C','F')", it will look at each item of type 'C' or 'F' and get the package id that has that item. BUT, a package that has items of type 'C' or 'F' can also have items of type 'Z', hence the inner select, dealing with items of type 'Z' first.

答:
Maybe i have misunderstood something, but isn't this what you actually want:

```<code>SELECT DISTINCT
    pack_id,
    pack_type = CASE WHEN i.type IN ('C','F') THEN 'Cool'
                     WHEN i.type IN ('Z') THEN 'Not-Cool'
                     ELSE 'Mixed' END
FROM  packages p INNER JOIN items i ON p.item_id = i.item_id
</code>```

There are three types: cool or not cool and everything else and you don't want a filter(just unique).

Title: SQL improvement - UNION?

Body:
I have 2 tables: "packages" and "items".

"packages" has the following columns: pack_id | item_id

"items" has the following columns.......:    item_id | type

One package can have multiple items.

UPDATE:

Sample Data and Expected Results:

pack_id | item_id
1           1
1           2
1           3
2           2
2           1
3           4
3           5
3           6

item_id | type
1           C
2           F
3           Z
4           Z
5           Z
6           Z

Expected result:

pack_id | pack_type
1           Mixed
2           Cool
3           Not Cool

My question is:

Is there a better way to query these 2 tables, in order to get a 3rd one, having as columns: "pack_id" and the new column "pack_type"? Those UNIONs seem to add a huge amount of time to the run time.

    SELECT pack_id, pack_type
    FROM (
      -- CASE 1 - pack_type is 'Cool' - type 'C' or 'F', but not 'Z'
      SELECT  Distinct q1.pack_id, 'Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type <> 'Z') q1
        WHERE q1.type IN ('C','F')

      UNION

      -- CASE 2 - pack_type is 'Not-Cool' - type 'Z', but not 'C' or 'F'
      SELECT  Distinct q2.pack_id, 'Not-Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q2
        WHERE q2.type NOT IN ('C','F')

      UNION

     -- CASE 3 - pack_type is 'Mixed' - type 'Z' and ('C' or 'F')
     SELECT  Distinct q3.pack_id, 'Mixed' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q3
        WHERE q3.type IN ('C','F')
    ) m

NOTE: some explication for the multiple comments that point to "A type cannot be Z and also C or F".

I also thought that, but the way I understand the behavior of the query is that if u say "type IN ('C','F')", it will look at each item of type 'C' or 'F' and get the package id that has that item. BUT, a package that has items of type 'C' or 'F' can also have items of type 'Z', hence the inner select, dealing with items of type 'Z' first.

Body:
Maybe i have misunderstood something, but isn't this what you actually want:

SELECT DISTINCT
    pack_id,
    pack_type = CASE WHEN i.type IN ('C','F') THEN 'Cool'
                     WHEN i.type IN ('Z') THEN 'Not-Cool'
                     ELSE 'Mixed' END
FROM  packages p INNER JOIN items i ON p.item_id = i.item_id

There are three types: cool or not cool and everything else and you don't want a filter(just unique).


问:
c# Split string using another string as delimiter and include delimiter as part of the splitted string
I need to split an input string using c# regex.
need to know how to include the delimiter content in the output as given below.

input:

```<code>string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimters = new string[] {"heading1:","heading2:","heading3:"};
</code>```

Expected output:

```<code>outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings
</code>```

What I tried:

```<code>var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);
</code>```

Output I got:

```<code>result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"
</code>```

I couldnt find an API in string.split or in Regex to split as the expect result.

答:
Instead of splitting, I suggest matching which we then can order:

```<code>private static IEnumerable<string> Solution(string source, string[] delimiters) {
  int from = 0;
  int length = 0;

  // Points at which we can split
  var points = delimiters
      .SelectMany(delimiter => Regex
        .Matches(source, delimiter)
        .OfType<Match>()
        .Select(match => match.Index)
        .Select(index => new {
          index = index,
          delimiter = delimiter,
        }))
      .OrderBy(item => item.index)
      .ThenBy(item => Array.IndexOf(delimiters, item.delimiter)); // tie break

  foreach (var point in points) {
    if (point.index >= from + length) {
      // Condition: we don't want the very first empty part
      if (from != 0 || point.index - from != 0)
        yield return source.Substring(from, point.index - from);

      from = point.index;
      length = point.delimiter.Length;
    }
  }

  yield return source.Substring(from);
}
</code>```

Test:

```<code>string content =
  "heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimiters = new string[] {
  "heading1:", "heading2:", "heading3:" };

Console.WriteLine(Solution(content, delimiters));
</code>```

Outcome:

```<code>heading1: contents with respect to heading1
heading2: heading2 contents
heading3: heading 3 related contents sample strings
</code>```

In case we split by digits (2nd test)

```<code>Console.WriteLine(Solution(content, new string[] {"[0-9]+"}));
</code>```

We'll get

```<code>heading
1: contents with respect to heading
1 heading
2: heading
2 contents heading
3: heading
3 related contents sample strings
</code>```

Body:
I need to split an input string using c# regex.
need to know how to include the delimiter content in the output as given below.

input:

string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimters = new string[] {"heading1:","heading2:","heading3:"};

Expected output:

outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings

What I tried:

var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);

Output I got:

result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"

I couldnt find an API in string.split or in Regex to split as the expect result.

Body:
Instead of splitting, I suggest matching which we then can order:

private static IEnumerable<string> Solution(string source, string[] delimiters) {
  int from = 0;
  int length = 0;

  // Points at which we can split
  var points = delimiters
      .SelectMany(delimiter => Regex
        .Matches(source, delimiter)
        .OfType<Match>()
        .Select(match => match.Index)
        .Select(index => new {
          index = index,
          delimiter = delimiter,
        }))
      .OrderBy(item => item.index)
      .ThenBy(item => Array.IndexOf(delimiters, item.delimiter)); // tie break

  foreach (var point in points) {
    if (point.index >= from + length) {
      // Condition: we don't want the very first empty part
      if (from != 0 || point.index - from != 0)
        yield return source.Substring(from, point.index - from);

      from = point.index;
      length = point.delimiter.Length;
    }
  }

  yield return source.Substring(from);
}

Test:

string content =
  "heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimiters = new string[] {
  "heading1:", "heading2:", "heading3:" };

Console.WriteLine(Solution(content, delimiters));

Outcome:

heading1: contents with respect to heading1
heading2: heading2 contents
heading3: heading 3 related contents sample strings

In case we split by digits (2nd test)

Console.WriteLine(Solution(content, new string[] {"[0-9]+"}));

We'll get

heading
1: contents with respect to heading
1 heading
2: heading
2 contents heading
3: heading
3 related contents sample strings


问:
Best way to connect Java and Visual Studio 6 C++ via API
We have a web platform written in Java. It will expose certain functionality via some kind of an API - soap, rest or some kind of home-brewed XML. The point is that it'll expose itself via HTTP/s.

There's another stand alone application that was written in C++ (Visual Studio 6) which needs to connect to the aforementioned API. I'm not an expert in C++ so I have hard time recommending something that can accomplish the task. I'm mentioning VS6 as per request of our developer since upgrading is not on a table.

Can someone recommend some library for C++, standard or not, that can simplify API interaction between two applications? If pointed to the right direction, we'll be able to review ourselves to make final decision.

答: We use lmx.</p>

Body: We use lmx.