问:
Update XML nodes when there are multiple matches in MySQL
I need to remove nodes from XML.

I try to use UpdateXML function.

For example removing node C:

```<code>SELECT UpdateXML('<A><B>b_value<C>c_value1</C></B></A>', '/A/B/C', '')
</code>```

Result:

```<code>'<A><B>b_value</B></A>'
</code>```

But when in XML there are multiples matches, function returns the original xml:

```<code>SELECT UpdateXML('<A><B>b_value<C>c_value1</C><C>c_value2</C></B></A>', '/A/B/C', '')
</code>```

Result:

```<code>'<A><B>b_value<C>c_value1</C><C>c_value2</C></B></A>'
</code>```

But I need to get such result:

```<code>'<A><B>b_value</B></A>'
</code>```

How I can remove all nodes when there are multiple matches.

答:
12.11 XML Functions :: UpdateXML

...

If no expression matching xpath_expr is found, or if multiple matches
  are found, the function returns the original xml_target XML fragment. ...

...

A possible workaround is to use a stored procedure:

DELIMITER //

CREATE PROCEDURE `sp_update_xml`(
  `xml` TEXT,
  `path` TEXT
)
BEGIN
  DECLARE `current_item` BIGINT UNSIGNED
    DEFAULT ExtractValue(`xml`,
                         CONCAT('COUNT(', `path`, ')')
                        );
  WHILE `current_item` > 0 DO
    SET `xml` := UpdateXML(`xml`,
                           CONCAT(`path`, '[', `current_item`, ']'),
                           ''
                          ),
        `current_item` := `current_item` - 1;
  END WHILE;
  SELECT `xml`;
END//

DELIMITER ;

CALL `sp_update_xml`(@`xml`, '/A/B/C');
```

See db-fiddle.

Body:
I need to remove nodes from XML.

I try to use UpdateXML function.

For example removing node C:

SELECT UpdateXML('b_value<C>c_value1</C>', '/A/B/C', '')

Result:

'b_value'

But when in XML there are multiples matches, function returns the original xml:

SELECT UpdateXML('b_value<C>c_value1</C><C>c_value2</C>', '/A/B/C', '')

Result:

'b_value<C>c_value1</C><C>c_value2</C>'

But I need to get such result:

'b_value'

How I can remove all nodes when there are multiple matches.

Body:
12.11 XML Functions :: UpdateXML

...

If no expression matching xpath_expr is found, or if multiple matches
  are found, the function returns the original xml_target XML fragment. ...

...

A possible workaround is to use a stored procedure:

DELIMITER //

CREATE PROCEDURE `sp_update_xml`(
  `xml` TEXT,
  `path` TEXT
)
BEGIN
  DECLARE `current_item` BIGINT UNSIGNED
    DEFAULT ExtractValue(`xml`,
                         CONCAT('COUNT(', `path`, ')')
                        );
  WHILE `current_item` > 0 DO
    SET `xml` := UpdateXML(`xml`,
                           CONCAT(`path`, '[', `current_item`, ']'),
                           ''
                          ),
        `current_item` := `current_item` - 1;
  END WHILE;
  SELECT `xml`;
END//

DELIMITER ;

CALL `sp_update_xml`(@`xml`, '/A/B/C');

See db-fiddle.


来源: stackexchange

答:
try using  sum  of the quantity  divided  by number of days </p>

```<code>select sum(quantity) /( datediff(max(zaman), min(zaman))) as quantity

FROM report WHERE DATE(zaman) BETWEEN ? AND ?
</code>```

ContentLicense: CC BY-SA 3.0

Title: MySql Average and Group By Usage

Body:
Report Table

+----+-------------------+--------+---------------------+
| id | mac_address       |quantity| zaman               |
+----+-------------------+--------+---------------------+
| 12 | 26-C0-B7-1E-7A-8C |   001  | 2017-12-07 10:22:09 |
| 14 | 26-C0-B7-1E-7A-8C |   001  | 2017-12-07 10:28:44 |
| 15 | 26-C0-B7-1E-7A-8D |   001  | 2017-12-07 10:44:54 |
| 19 | 26-C0-B7-1E-7A-AC |   001  | 2017-12-08 10:11:00 |
| 20 | 26-C0-B7-1E-7A-AD |   002  | 2017-12-08 10:32:12 |
| 24 | 26-C0-B7-1E-7A-8D |   001  | 2017-12-09 10:29:54 |
| 25 | 26-C0-B7-1E-7A-8E |   002  | 2017-12-09 10:39:11 |

I want to find average of quantity between days according to this equation:

Sum of quantity(9)/Number of day(3) = 3

So far I have this query:

SELECT ROUND(AVG(quantity),2) AS quantity, DATE(zaman) as DateOnly
FROM report WHERE DATE(zaman) BETWEEN ? AND ?
GROUP BY DateOnly

How can I achieve this?

Body:
try using  sum  of the quantity  divided  by number of days

select sum(quantity) /( datediff(max(zaman), min(zaman))) as quantity

FROM report WHERE DATE(zaman) BETWEEN ? AND ?


问:
How do I display local image in markdown?
Does anyone know how to display a local image in markdown? I don't want to set up a webserver for that.

I try the following in markdown, but it doesn't work:

![image](files/Users/jzhang/Desktop/Isolated.png)

答:
To add an image in markdown file the .md file and the image should be in the same directory. As in my case my .md file was in doc folder so i also moved the image into the same folder. After that write the following syntax in .md file

```<code>![alt text](filename)
</code>```

like ![Car Image](car.png)

This has worked for me.

ContentLicense: CC BY-SA 4.0

Body:
To add an image in markdown file the .md file and the image should be in the same directory. As in my case my .md file was in doc folder so i also moved the image into the same folder. After that write the following syntax in .md file

![alt text](filename)

like ![Car Image](car.png)

This has worked for me.


问:
crop image without disturbing aspect ratio
** In image processing, while cropping images, aspect ratio is maintained on any site or app.

Even uploading images as profile photo on whatsApp and Facebook, we cant edit both height and width separately

Why we cant edit the way we want **

答:
Almost all image editing programs have an option to control whether aspect ratio is constrained or not while cropping. Sometimes one wants to guarantee the same aspect ratio and sometimes one wants to crop to a different one for a specific purpose. In fine art printing, crops are usually unconstrained to either match a specific paper size or to make sure the edges hit exactly where the photographer wants them to. (Resizing without preserving aspect ratio is almost never useful on photographs.)

For creating a profile photo, the desired aspect ratio constraint would be the one the site prefers or imposes, not the original one for the image. This immediately creates user confusion if the target ratio is not the one of the uploaded photo because most users do not understand the constraint and would wonder why they can't just use their entire photo.

It might be useful to have the UI that guides people to crop to the aspect ratio the site prefers, but most sites are somewhat imprecise about the entire concept anyway. (E.g. Facebook's profile photo layout has changed a number of times over the years. When I worked on the Photos team there, effort was being put into trying to automatically generate crops of photos so they could be display in a variety of places with different aspect ratios due to design choices. That this would enrage any serious photographer was not a significant concern to those working on the feature.)

It also takes a moderate amount of design and programming to do the UI for this and thus it doesn't get done that often. But most likely the reason is because it confuses users. Instagram would be an exception as it heavily pushes toward square aspect ratio and its large user base has very much embraced this. The UI very much steers one to crop to a square.


问:
How to use DateDiff in calculated field in access
I am trying to get "No of days late" in a particular table in MS access. I am trying to use calculated data type.

I have [ActualReturnDate] and [ReturnDate] in the same table (both are Date/Time) and I want to save difference between two columns in a calculated field.

I am using following expression:

```<code>DateDiff("d", [ActualReturnDate] , [ReturnDate] )
</code>```

But no matter what i do I get error saying "The expression X cannot be used in a calculated column."

So does that mean I cannot use DateDiff in Calculated field? If not how should I do it?

答:
You can just add and substract dates.

Just use [ActualReturnDate] - [ReturnDate] as the expression to calculate the difference. If both fields are defined as date/time, the result should be the same, only include the time part as decimal.

If you want only whole days, you can wrap the result in Int()

Body:
I am trying to get "No of days late" in a particular table in MS access. I am trying to use calculated data type.

I have [ActualReturnDate] and [ReturnDate] in the same table (both are Date/Time) and I want to save difference between two columns in a calculated field.

I am using following expression:

DateDiff("d", [ActualReturnDate] , [ReturnDate] )

But no matter what i do I get error saying "The expression X cannot be used in a calculated column."

So does that mean I cannot use DateDiff in Calculated field? If not how should I do it?


问:
Distribute elements evenly (adding ints values to array of int values)
Say I have an array of Ints and all elements equal zero. It'd look something like this:

```<code>let arr: [Int] =  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

There are 11 elements in this array in total. I want three of the elements in this array to be the number one. I want these one values to be distributed evenly throughout the array so that it looks something like this:

```<code>[0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]
</code>```

I want to be able to add however many one's and distribute them evenly (or as close to evenly as possible) no matter how many total elements there are. How could I do this?

Note: For anyone wondering why I need this, I have a collection of strings that when joined together make up a large body of text. Think of the zeroes as the pieces of text and think of the ones as advertisements I am adding in between the text. I wanted to distribute these ads as evenly as possible. I figured this would be a simple way of expressing what I needed.

答:
Maybe you can try this.

```<code>var arr: [Int] =  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let distribution = arr.count / 3 // 3 is the number of 1s
for (index, value) in arr.enumerated() {
    arr[index] = (index + 1) % distribution == 0 ? 1 : value
}

print(arr) // [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]
</code>```

Assuming that the value distribution > 1

Body:
Say I have an array of Ints and all elements equal zero. It'd look something like this:

let arr: [Int] =  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

There are 11 elements in this array in total. I want three of the elements in this array to be the number one. I want these one values to be distributed evenly throughout the array so that it looks something like this:

[0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]

I want to be able to add however many one's and distribute them evenly (or as close to evenly as possible) no matter how many total elements there are. How could I do this?

Note: For anyone wondering why I need this, I have a collection of strings that when joined together make up a large body of text. Think of the zeroes as the pieces of text and think of the ones as advertisements I am adding in between the text. I wanted to distribute these ads as evenly as possible. I figured this would be a simple way of expressing what I needed.

Body:
Maybe you can try this.

var arr: [Int] =  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let distribution = arr.count / 3 // 3 is the number of 1s
for (index, value) in arr.enumerated() {
    arr[index] = (index + 1) % distribution == 0 ? 1 : value
}

print(arr) // [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]

Assuming that the value distribution > 1


问:
why remove "\n","\r","\t" in phalcon？
I found that in the muilti-module which is created by phalcon-tool has these code:

```<code>$application = new Application($di);
echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());
</code>```

Why remove "\n","\r","\t"?

答: This is to replace newlines, line feeds and tabs with a single space so that the application's details can be written to STD_OUT as a single line with no wrapping.</p>

Title: why remove "\n","\r","\t" in phalcon？

Body:
I found that in the muilti-module which is created by phalcon-tool has these code:

$application = new Application($di);
echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());

Why remove "\n","\r","\t"?


问:
Can any one explain me how does the string and number comparison work in javascript?
I have compared some strings and numbers to see the result as true and false

```<code>"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false
</code>```

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

```<code>"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false
</code>```

答:
It is attempting to cast the string to a number.

In the console, if you do

```<code>x = +''
</code>```

then x will be set to 0.  1 > 0 is true.

For all the other ones, if you do something like

```<code>x = +'dfdf'
</code>```

then x will be set to NaN (not a number), and any comparison with it will return false.

Body:
I have compared some strings and numbers to see the result as true and false

"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false

Body:
It is attempting to cast the string to a number.

In the console, if you do

x = +''

then x will be set to 0.  1 > 0 is true.

For all the other ones, if you do something like

x = +'dfdf'

then x will be set to NaN (not a number), and any comparison with it will return false.


问:
Zoom Camera2 Preview using TextureView
i have a Problem with my Preview Zoom for the Camera2 API. I am using a TextureView.

I want to zoom only the preview Stream that was showed in the TextureView.

I want to zoom the Area where i use the Zoom Gesture.

I use the SimpleOnScaleGestureListener!

I added following Code. The zoomingFactor and the x and y Position are right.

```<code> private void updateTextureViewSize(float xPosi,float yPosi, float scale){
        float scaleX = 1.0f;
        float scaleY = 1.0f;

        float mVideoWidth = mCamcontrol.getmPreviewSize().getWidth();
        float mVideoHeight = mCamcontrol.getmPreviewSize().getHeight();

        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        RectF viewRect = new RectF(0, 0, 1440, 2560);
        RectF bufferRect = new RectF(0, 0, mVideoHeight, mVideoWidth);

        bufferRect.offset(xPosi - bufferRect.centerX(), yPosi -    bufferRect.centerY());

         //16:9 faktor
        scaleX = ((mScale * scale) / 9f) * 16f;
        scaleY = ((mScale * scale) / 16f) * 9f;

        Matrix matrix = new Matrix();

        matrix.setRectToRect(bufferRect, viewRect, Matrix.ScaleToFit.FILL);
        scalefactorView.setText(String.valueOf(xPosi) + "  " + String.valueOf(yPosi));

        matrix.setScale(scaleY, scaleX, xPosi, yPosi);
        matrix.postRotate(90 * (rotation - 2), xPosi, yPosi);

        mTextureView.setTransform(matrix);

}
</code>```

Zooming is Right, but not the Position where i Zoom. For Example! When i zoom on the position right/middle i see only the left/top rectangle of the Stream.

I added the following pictures to unterstand the problem.

答:
Thanks to @arin 's answer, I made an improved version.

His code is basically working, but there are 2 problems:

1) Readability - actually I don't know what is going on calculating the Rect zoom

2) In my Android 7.1.1 device, the preview will freeze if the zoom is big to a certain extent. Since I solved this problem with the code below, I am pretty sure it is because the original code allowed over-zooming beyond camera's maximum zoom ratio.

(In fact, I don't know why he needs to apply *10 on the ratio returned by CameraCharacteristics)

Below are my codes: (I do this all inside my custom TextureView, which also stores my Camera2 objects and logics):

Related Member variables:

```<code>protected CameraCharacteristics cameraCharacteristics;
protected CameraCaptureSession captureSession;
protected CaptureRequest.Builder previewRequestBuilder;

//Zooming
protected float fingerSpacing = 0;
protected float zoomLevel = 1f;
protected float maximumZoomLevel;
protected Rect zoom;
</code>```

Right after you get CameraCharacteristics from CameraManager, probably in some initial setup:

```<code>maximumZoomLevel = cameraCharacteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
</code>```

override onTouchEvent:

```<code>@Override
public boolean onTouchEvent(MotionEvent event) {
    try {
        Rect rect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
        if (rect == null) return false;
        float currentFingerSpacing;

        if (event.getPointerCount() == 2) { //Multi touch.
            currentFingerSpacing = getFingerSpacing(event);
            float delta = 0.05f; //Control this value to control the zooming sensibility
            if (fingerSpacing != 0) {
                if (currentFingerSpacing > fingerSpacing) { //Don't over zoom-in
                    if ((maximumZoomLevel - zoomLevel) <= delta) {
                        delta = maximumZoomLevel - zoomLevel;
                    }
                    zoomLevel = zoomLevel + delta;
                } else if (currentFingerSpacing < fingerSpacing){ //Don't over zoom-out
                    if ((zoomLevel - delta) < 1f) {
                        delta = zoomLevel - 1f;
                    }
                    zoomLevel = zoomLevel - delta;
                }
                float ratio = (float) 1 / zoomLevel; //This ratio is the ratio of cropped Rect to Camera's original(Maximum) Rect
                //croppedWidth and croppedHeight are the pixels cropped away, not pixels after cropped
                int croppedWidth = rect.width() - Math.round((float)rect.width() * ratio);
                int croppedHeight = rect.height() - Math.round((float)rect.height() * ratio);
                //Finally, zoom represents the zoomed visible area
                zoom = new Rect(croppedWidth/2, croppedHeight/2,
                        rect.width() - croppedWidth/2, rect.height() - croppedHeight/2);
                previewRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, zoom);
            }
            fingerSpacing = currentFingerSpacing;
        } else { //Single touch point, needs to return true in order to detect one more touch point
            return true;
        }
        captureSession.setRepeatingRequest(previewRequestBuilder.build(), captureCallback, null);
        return true;
    } catch (final Exception e) {
        //Error handling up to you
        return true;
    }
}
</code>```

And the getFingerSpacing method:

```<code>private float getFingerSpacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float) Math.sqrt(x * x + y * y);
}
</code>```

Finally don't forget to set the crop region when you actually take the photo. My code is base on this Camera2Basic, I do this inside the captureStillPicture() method:

```<code>        //Zoom
        if (zoom != null) {
            captureBuilder.set(CaptureRequest.SCALER_CROP_REGION, zoom);
        }
</code>```

Title: Zoom Camera2 Preview using TextureView

Body:
i have a Problem with my Preview Zoom for the Camera2 API. I am using a TextureView.

I want to zoom only the preview Stream that was showed in the TextureView.

I want to zoom the Area where i use the Zoom Gesture.

I use the SimpleOnScaleGestureListener!

I added following Code. The zoomingFactor and the x and y Position are right.

 private void updateTextureViewSize(float xPosi,float yPosi, float scale){
        float scaleX = 1.0f;
        float scaleY = 1.0f;

        float mVideoWidth = mCamcontrol.getmPreviewSize().getWidth();
        float mVideoHeight = mCamcontrol.getmPreviewSize().getHeight();

        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        RectF viewRect = new RectF(0, 0, 1440, 2560);
        RectF bufferRect = new RectF(0, 0, mVideoHeight, mVideoWidth);

        bufferRect.offset(xPosi - bufferRect.centerX(), yPosi -    bufferRect.centerY());

         //16:9 faktor
        scaleX = ((mScale * scale) / 9f) * 16f;
        scaleY = ((mScale * scale) / 16f) * 9f;

        Matrix matrix = new Matrix();

        matrix.setRectToRect(bufferRect, viewRect, Matrix.ScaleToFit.FILL);
        scalefactorView.setText(String.valueOf(xPosi) + "  " + String.valueOf(yPosi));

        matrix.setScale(scaleY, scaleX, xPosi, yPosi);
        matrix.postRotate(90 * (rotation - 2), xPosi, yPosi);

        mTextureView.setTransform(matrix);

}

Zooming is Right, but not the Position where i Zoom. For Example! When i zoom on the position right/middle i see only the left/top rectangle of the Stream.

I added the following pictures to unterstand the problem.

Body:
Thanks to @arin 's answer, I made an improved version.

His code is basically working, but there are 2 problems:

1) Readability - actually I don't know what is going on calculating the Rect zoom

2) In my Android 7.1.1 device, the preview will freeze if the zoom is big to a certain extent. Since I solved this problem with the code below, I am pretty sure it is because the original code allowed over-zooming beyond camera's maximum zoom ratio.

(In fact, I don't know why he needs to apply *10 on the ratio returned by CameraCharacteristics)

Below are my codes: (I do this all inside my custom TextureView, which also stores my Camera2 objects and logics):

Related Member variables:

protected CameraCharacteristics cameraCharacteristics;
protected CameraCaptureSession captureSession;
protected CaptureRequest.Builder previewRequestBuilder;

//Zooming
protected float fingerSpacing = 0;
protected float zoomLevel = 1f;
protected float maximumZoomLevel;
protected Rect zoom;

Right after you get CameraCharacteristics from CameraManager, probably in some initial setup:

maximumZoomLevel = cameraCharacteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);

override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent event) {
    try {
        Rect rect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
        if (rect == null) return false;
        float currentFingerSpacing;

        if (event.getPointerCount() == 2) { //Multi touch.
            currentFingerSpacing = getFingerSpacing(event);
            float delta = 0.05f; //Control this value to control the zooming sensibility
            if (fingerSpacing != 0) {
                if (currentFingerSpacing > fingerSpacing) { //Don't over zoom-in
                    if ((maximumZoomLevel - zoomLevel) <= delta) {
                        delta = maximumZoomLevel - zoomLevel;
                    }
                    zoomLevel = zoomLevel + delta;
                } else if (currentFingerSpacing < fingerSpacing){ //Don't over zoom-out
                    if ((zoomLevel - delta) < 1f) {
                        delta = zoomLevel - 1f;
                    }
                    zoomLevel = zoomLevel - delta;
                }
                float ratio = (float) 1 / zoomLevel; //This ratio is the ratio of cropped Rect to Camera's original(Maximum) Rect
                //croppedWidth and croppedHeight are the pixels cropped away, not pixels after cropped
                int croppedWidth = rect.width() - Math.round((float)rect.width() * ratio);
                int croppedHeight = rect.height() - Math.round((float)rect.height() * ratio);
                //Finally, zoom represents the zoomed visible area
                zoom = new Rect(croppedWidth/2, croppedHeight/2,
                        rect.width() - croppedWidth/2, rect.height() - croppedHeight/2);
                previewRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, zoom);
            }
            fingerSpacing = currentFingerSpacing;
        } else { //Single touch point, needs to return true in order to detect one more touch point
            return true;
        }
        captureSession.setRepeatingRequest(previewRequestBuilder.build(), captureCallback, null);
        return true;
    } catch (final Exception e) {
        //Error handling up to you
        return true;
    }
}

And the getFingerSpacing method:

private float getFingerSpacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float) Math.sqrt(x * x + y * y);
}

Finally don't forget to set the crop region when you actually take the photo. My code is base on this Camera2Basic, I do this inside the captureStillPicture() method:

        //Zoom
        if (zoom != null) {
            captureBuilder.set(CaptureRequest.SCALER_CROP_REGION, zoom);
        }


问:
How do I sort a bunch of letters and their corresponding frequencies from a string?
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

```<code>def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)
</code>```

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

```<code>pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq
</code>```

And here is an example of my desired output:

```<code>('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)
</code>```

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

答:
Using collections.Counter, string.ascii_lowercase and sorted

```<code>from collections import Counter
from string import ascii_lowercase
s = 'pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq'
sorted([(i.upper(),Counter(s)[i]) for i in ascii_lowercase], key=lambda x:x[1], reverse=True)
</code>```

Or without using collections

```<code>sorted([(i.upper(), s.count(i)) for i in ascii_lowercase], key=lambda x:x[1], reverse=True)
</code>```

Output:

```<code>[('Q', 10),
 ('W', 9),
 ('E', 8),
 ('R', 7),
 ('T', 6),
 ('Y', 5),
 ('U', 4),
 ('I', 3),
 ('O', 2),
 ('P', 1),
 ('A', 0),
 ('B', 0),
 ('C', 0),
 ('D', 0),
 ('F', 0),
 ('G', 0),
 ('H', 0),
 ('J', 0),
 ('K', 0),
 ('L', 0),
 ('M', 0),
 ('N', 0),
 ('S', 0),
 ('V', 0),
 ('X', 0),
 ('Z', 0)]
</code>```

Body:
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq

And here is an example of my desired output:

('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

Body:
Using collections.Counter, string.ascii_lowercase and sorted

from collections import Counter
from string import ascii_lowercase
s = 'pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq'
sorted([(i.upper(),Counter(s)[i]) for i in ascii_lowercase], key=lambda x:x[1], reverse=True)

Or without using collections

sorted([(i.upper(), s.count(i)) for i in ascii_lowercase], key=lambda x:x[1], reverse=True)

Output:

[('Q', 10),
 ('W', 9),
 ('E', 8),
 ('R', 7),
 ('T', 6),
 ('Y', 5),
 ('U', 4),
 ('I', 3),
 ('O', 2),
 ('P', 1),
 ('A', 0),
 ('B', 0),
 ('C', 0),
 ('D', 0),
 ('F', 0),
 ('G', 0),
 ('H', 0),
 ('J', 0),
 ('K', 0),
 ('L', 0),
 ('M', 0),
 ('N', 0),
 ('S', 0),
 ('V', 0),
 ('X', 0),
 ('Z', 0)]


问:
Angualr4, Wait after 3 invalid login attempts
I am working on an login form in Angular4. I would like to implement a 30 seconds wait (by disabling button) after entering 3 invalid credentials. After the next 3 invalid attempts, waiting time will just double, 60 seconds, 120 seconds so on and so forth. I initiatialized a counter and decrement it in each invalid form submissions. And used setTimeInterval like:

```<code>initCounter() {
    this.intervalTimer = setInterval(() => {
        let count = this.counter;
        if (count > 0) {
            this.counter = count - 1;
        }
    }, 1000);
}
</code>```

However I couldn't complete this task as expected.

Hope someone can help me.

答:
Finally I could done it like</p>

```<code> setLoginCounter(loginForm) {
      this.loginCounter += 1;
      localStorage.setItem('logCount', this.loginCounter.toString());

      if (this.loginCounter % 3 === 0) {
                this.counter = 30 * (Math.pow(2, (this.loginCounter / 3) - 1));
      }

    }
</code>```

Body:
I am working on an login form in Angular4. I would like to implement a 30 seconds wait (by disabling button) after entering 3 invalid credentials. After the next 3 invalid attempts, waiting time will just double, 60 seconds, 120 seconds so on and so forth. I initiatialized a counter and decrement it in each invalid form submissions. And used setTimeInterval like:

initCounter() {
    this.intervalTimer = setInterval(() => {
        let count = this.counter;
        if (count > 0) {
            this.counter = count - 1;
        }
    }, 1000);
}

However I couldn't complete this task as expected.

Hope someone can help me.

Body:
Finally I could done it like

 setLoginCounter(loginForm) {
      this.loginCounter += 1;
      localStorage.setItem('logCount', this.loginCounter.toString());

      if (this.loginCounter % 3 === 0) {
                this.counter = 30 * (Math.pow(2, (this.loginCounter / 3) - 1));
      }

    }


问:
How split a string in java and assign a hyperlink to each separated value
I am getting the following from DB with the respective id's as shown in the below picture:

I need to separate the location_names with their respective location id's so that I can update each location individually.
Finally I need something like this:

```<code> <a href="updateLocation/1">loc1</a>
 <a href="updateLocation/2">loc2</a>
</code>```

答:
You can create map like this from your data.

```<code>String id = "3,2,1,5,4";
String location = "loc3,loc2,loc1,loc5,loc4";
String[] ids = id.split(",");
String[] locations = location.split(",");

Map<String, String> map = new HashMap<>();

for (int i = 0; i < ids.length; i++) {
    map.put(ids[i], locations[i]);
}
</code>```

By iterating map in jsp you can create link as you want.

Body:
I am getting the following from DB with the respective id's as shown in the below picture:

I need to separate the location_names with their respective location id's so that I can update each location individually.
Finally I need something like this:

 loc1
 loc2

Body:
You can create map like this from your data.

String id = "3,2,1,5,4";
String location = "loc3,loc2,loc1,loc5,loc4";
String[] ids = id.split(",");
String[] locations = location.split(",");

Map<String, String> map = new HashMap<>();

for (int i = 0; i < ids.length; i++) {
    map.put(ids[i], locations[i]);
}

By iterating map in jsp you can create link as you want.


答:
Try this:</p>

```<code>SELECT ROUND((SUM(Quantity)*1.0)/datediff(MAX(Zaman), MIN(Zaman)),0)
FROM report
WHERE zaman BETWEEN ? AND ?
</code>```

Title: MySql Average and Group By Usage

Body:
Report Table

+----+-------------------+--------+---------------------+
| id | mac_address       |quantity| zaman               |
+----+-------------------+--------+---------------------+
| 12 | 26-C0-B7-1E-7A-8C |   001  | 2017-12-07 10:22:09 |
| 14 | 26-C0-B7-1E-7A-8C |   001  | 2017-12-07 10:28:44 |
| 15 | 26-C0-B7-1E-7A-8D |   001  | 2017-12-07 10:44:54 |
| 19 | 26-C0-B7-1E-7A-AC |   001  | 2017-12-08 10:11:00 |
| 20 | 26-C0-B7-1E-7A-AD |   002  | 2017-12-08 10:32:12 |
| 24 | 26-C0-B7-1E-7A-8D |   001  | 2017-12-09 10:29:54 |
| 25 | 26-C0-B7-1E-7A-8E |   002  | 2017-12-09 10:39:11 |

I want to find average of quantity between days according to this equation:

Sum of quantity(9)/Number of day(3) = 3

So far I have this query:

SELECT ROUND(AVG(quantity),2) AS quantity, DATE(zaman) as DateOnly
FROM report WHERE DATE(zaman) BETWEEN ? AND ?
GROUP BY DateOnly

How can I achieve this?

Body:
Try this:

SELECT ROUND((SUM(Quantity)*1.0)/datediff(MAX(Zaman), MIN(Zaman)),0)
FROM report
WHERE zaman BETWEEN ? AND ?


问:
DDD - How does the domain receive client data
I'm planning to refactor a legacy .NET project that I'm maintaining, there are mainly 4 projects involved:

My.Company.Web - The presentation layer. ASP.NET MVC.

My.Company.Service - The service layer, defines service interfaces and contains command handlers. Invoked by the web layer.

My.Company.DTO - The assembly that contains DTO classes for data transfer between the domain and web layers.

My.Company.Domain - The domain layer.

My.Company.Data - The persistence layer.

When user submits a form to update a person's details, the process looks somewhat like this:

Using the submitted data, controller constructs a PersonDetailsDTO which consists of multiple simple fields to hold FirstName, LastName, Age and etc, and a complex type object called AddressDTO that holds address details: var dto = new PersonDetails(...);

Controller calls the service layer with the DTO:

```<code>_personService.UpdateDetails(dto);
</code>```

In the service:

```<code>public void UpdatePerson(PersonDetailsDTO dto)
{
    var person = _personRepository.GetById(dto.PersonId);
    person.Update(dto);
    _personRepository.Update(person);
}
</code>```

In the Person domain:

```<code>public class Person : AggregateRoot
{
    private string FirstName;
    .... // other fields
    private Address Address;

    public void Update(PersonDetailsDTO dto)
    {
        FirstName = dto.FirstName;
        .... // other fields
        Address.Update(dto.AddressDTO); // update the value object - address
    }
}
</code>```

As you can see here, the Person domain references the PersonDetailsDTO. This feels wrong to me as DTOs are means to present the data in the domain to its clients while not exposing the domain itself. and the domain should not be concerned with how it's presented to the clients.

Also IMO the DTOs should live in the My.Company.Service project as it's the service that defines the operation/data transfer contracts.

But then how would the service pass the details on to the domain? Would it have to be a loooong list of parameters: person.Update(firstName, lastName, age, gender, street1, street2, state, postcode...). This certainly looks wrong to me.

Or does the domain have to define yet another set of it's own "DTOs" to receive client data?

I have gone through a LOT of tutorials and SO posts and no one seem to share my concern, so I'm starting to think I'm missing something here, could someone point me to the right direction?

答:
According to the Dependency inversion principle and DDD, the Value objects (the DTOs as you call them: PersonDetailsDTO and Address) should be owned by the Domain. This means that they should reside in the Domain namespace/package/project. And BTW, those Value objects can be used all the way up to the Presentation layer and back.

Secondly, they are not DTOs (Data transfer objects) because there is no expensive remote call involved, but Value objects (cohesive data and possible behavior); read more here how to not use them as an anti-pattern.

Last but not least, you should name your methods with terms from the Ubiquitous language (person.Update does not seem to be from the UL). I'm not saying 100% that is your case because I don't know your domain, I'm just saying that you should pay attention to these important details (naming things).

Body:
I'm planning to refactor a legacy .NET project that I'm maintaining, there are mainly 4 projects involved:

My.Company.Web - The presentation layer. ASP.NET MVC.

My.Company.Service - The service layer, defines service interfaces and contains command handlers. Invoked by the web layer.

My.Company.DTO - The assembly that contains DTO classes for data transfer between the domain and web layers.

My.Company.Domain - The domain layer.

My.Company.Data - The persistence layer.

When user submits a form to update a person's details, the process looks somewhat like this:

Using the submitted data, controller constructs a PersonDetailsDTO which consists of multiple simple fields to hold FirstName, LastName, Age and etc, and a complex type object called AddressDTO that holds address details: var dto = new PersonDetails(...);

Controller calls the service layer with the DTO:

_personService.UpdateDetails(dto);

In the service:

public void UpdatePerson(PersonDetailsDTO dto)
{
    var person = _personRepository.GetById(dto.PersonId);
    person.Update(dto);
    _personRepository.Update(person);
}

In the Person domain:

public class Person : AggregateRoot
{
    private string FirstName;
    .... // other fields
    private Address Address;

    public void Update(PersonDetailsDTO dto)
    {
        FirstName = dto.FirstName;
        .... // other fields
        Address.Update(dto.AddressDTO); // update the value object - address
    }
}

As you can see here, the Person domain references the PersonDetailsDTO. This feels wrong to me as DTOs are means to present the data in the domain to its clients while not exposing the domain itself. and the domain should not be concerned with how it's presented to the clients.

Also IMO the DTOs should live in the My.Company.Service project as it's the service that defines the operation/data transfer contracts.

But then how would the service pass the details on to the domain? Would it have to be a loooong list of parameters: person.Update(firstName, lastName, age, gender, street1, street2, state, postcode...). This certainly looks wrong to me.

Or does the domain have to define yet another set of it's own "DTOs" to receive client data?

I have gone through a LOT of tutorials and SO posts and no one seem to share my concern, so I'm starting to think I'm missing something here, could someone point me to the right direction?


问:
No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

```<code>/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.
</code>```

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

```<code><style name="Base.V26.Widget.AppCompat.Toolbar" parent="Base.V7.Widget.AppCompat.Toolbar">
    <item name="android:touchscreenBlocksFocus">true</item>
    <item name="android:keyboardNavigationCluster">true</item>
</style>
</code>```

We're using the following versions:

```<code>ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"
</code>```

```<code>compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
</code>```

Any ideas?

答:
I also faced this issue you just need to make 2 changes:

File Name : android/build.gradle mention this below code

```<code>subprojects {
   afterEvaluate {
     project -> if (project.hasProperty("android")) {
       android {
        compileSdkVersion 26 buildToolsVersion '26.0.2'
       }
      }
    }
}
</code>```

File Name :android/app/build.gradle
change your compliesdk version and buildToolVersion like this:

```<code>compileSdkVersion 26 buildToolsVersion "26.0.2"
</code>```

and in

```<code>dependencies {
    compile 'com.android.support:appcompat-v7:26.0.2'
}
</code>```

Body:
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

We're using the following versions:

ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"

compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION

Any ideas?

Body:
I also faced this issue you just need to make 2 changes:

File Name : android/build.gradle mention this below code

subprojects {
   afterEvaluate {
     project -> if (project.hasProperty("android")) {
       android {
        compileSdkVersion 26 buildToolsVersion '26.0.2'
       }
      }
    }
}

File Name :android/app/build.gradle
change your compliesdk version and buildToolVersion like this:

compileSdkVersion 26 buildToolsVersion "26.0.2"

and in

dependencies {
    compile 'com.android.support:appcompat-v7:26.0.2'
}


问:
Elasticsearch sorting based on several fields and time condition
I have a little online store application and I would like to sort items based on their active price. So there is a normal price and optionally a discounted price. But the discounted price is valid for a time range only and the index is not updated when discount ends. For example:

```<code>{price: 2.00, discount:{price:1.10, start:2016-08-11, end:2016-09-14}}
</code>```

Is it possible to include such condition on sorting? The goal is to ensure the correct sort order any given time.

Edit: At the moment the ES version is rather old but update to the latest is not an issue.

答:
This is for Elasticsearch 5 and 6 (you didn't mention, as I said, the version and the mapping of that discount field). Also, you need to explicitly pass as a parameter the current date and time in milliseconds whenever you run that query:

```<code>  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": "if (doc['discount.price']!=null && doc['discount.start'].date.getMillis() < params['time'] && doc['discount.end'].date.getMillis() > params['time']) return doc['discount.price'].value; else return doc['price'].value",
        "params": {
          "time": 1512717897000
        }
      },
      "order": "desc"
    }
  }
</code>```

Body:
I have a little online store application and I would like to sort items based on their active price. So there is a normal price and optionally a discounted price. But the discounted price is valid for a time range only and the index is not updated when discount ends. For example:

{price: 2.00, discount:{price:1.10, start:2016-08-11, end:2016-09-14}}

Is it possible to include such condition on sorting? The goal is to ensure the correct sort order any given time.

Edit: At the moment the ES version is rather old but update to the latest is not an issue.

Body:
This is for Elasticsearch 5 and 6 (you didn't mention, as I said, the version and the mapping of that discount field). Also, you need to explicitly pass as a parameter the current date and time in milliseconds whenever you run that query:

  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": "if (doc['discount.price']!=null && doc['discount.start'].date.getMillis() < params['time'] && doc['discount.end'].date.getMillis() > params['time']) return doc['discount.price'].value; else return doc['price'].value",
        "params": {
          "time": 1512717897000
        }
      },
      "order": "desc"
    }
  }


问:
k2 module subtemplate doesn't pick up changes after editing - joomla 3.8.0
I hope some of you joomla enthusiast can help a beginner with a problem.

So I created a subtemplate for a k2 module in the folder templates/my_template/html/mod_k2_content. This folder contains the two subfolders Default (contains the default.php) and Team (contains the team.php).
The team.php file is the default.php file with minor changes. Everything worked fine and i could select the "Team" subtemplates in the joomla backend and it also showed the changes.  Now I tried to edit the team.php in templates/my_template/html/mod_k2_content/Team again and it just doesn't pick up the changes anymore. When I edit the default.php in templates/my_template/html/mod_k2_content/Default it works just fine on the modules that work with the default subtemplate.

But the modules that have the Team subtemplate selected just stay the same, the way they were when i first selected this subtemplate for the modules.

Anybody that already enountered that problem and knows what I'm doing wrong?
I already reselected the team subtemplate several times and made sure I'm connected to the server. I also encluded a bunch of characters in the code to make the changes more visible, to make sure I'd truly notice them if the would be picked up. But nothing.

I'm really grateful if someone can help.

Thank you a lot!

答: Just to be sure: did you disable the caching on the website as well as the caching on your browser?</p>


问:
Normal Mapping doesn't work
For some reason, the following map is not working:

nmap ,u :.g/./t.|s/./=/g<CR>

It was intended that once I typed ,u on a line like this:

```<code>lorem ipsum
</code>```

It should transform into:

```<code>lorem ipsum
===========
</code>```

The result: I see :.g/./t. in the bottom of the window. Then I tried escaping the |, and now once I use the mapping I simply see :.g/./t.|s/./=/g in the bottom, and nothing happens.

There probably is a better and error-free way to do it, I still a beginner.

Thanks!

答:
You need to escape bar in mapping: either use \|, or <bar>. Now it is parsed as two commands: nmap ,u :.g/./t. and s/./=/g<CR>.

And do not use nmap, use nnoremap.

Update: though escaped variant of your mapping works, I would have written it as either yyp:s/./=/g<CR>, as :call append('.', repeat('=', strdisplaywidth(getline('.'))))<CR> (vim-7.3, best variant) or as :call append('.', repeat('=', len(split(getline('.'), '\zs'))))<CR> (vim-7.2, has just the same problems with tabs and fullwidth characters as yyp... variant, but does not overwrite any registers).

ContentLicense: CC BY-SA 2.5

Title: Normal Mapping doesn't work

Body:
For some reason, the following map is not working:

nmap ,u :.g/./t.|s/./=/g<CR>

It was intended that once I typed ,u on a line like this:

lorem ipsum

It should transform into:

lorem ipsum
===========

The result: I see :.g/./t. in the bottom of the window. Then I tried escaping the |, and now once I use the mapping I simply see :.g/./t.|s/./=/g in the bottom, and nothing happens.

There probably is a better and error-free way to do it, I still a beginner.

Thanks!


问:
CSS How to put 4 divs on each side of a parent div
I wish to include 4 divs inside a parent div in the following manner:

I could use fixed position and set right/left/top/bottom = 0 accordingly for each child div if they were not inside in a div, but right now, I can't figure out how to do this.

答:
Consider utilizing absolute positioning on nested div elements and offsetting their positions, within the containing element, appropriately and as required by declaring top, bottom, left and right properties respectively.

Code Snippet Demonstration

Note:

In the below demonstration, a containing element, with resizing properties, has been wrapped around the element in question, to demonstrate the responsive behaviour of this method.

Resize the element manually by clicking the icon, in the bottom-left corner of the containing element, and dragging vertically or horizontally.

* {
  box-sizing: border-box;
  font-family: arial;
}

.outer {
  border: 3px solid black;
  width: 100%;
  height: 100%;
  position: relative; /* required */
}

.outer-wrapper { /* purely for the sake of responsive demonstration */
  padding: 10px;
  resize: auto;
  overflow: hidden;
  border: 3px dashed gray;
  width: 400px;
  height: 400px;
}

.outer div {
  position: absolute;
  padding: 10px;
  font-weight: bold;
  font-size: 12px;
}

.outer div:nth-child(odd) {
    width: 80%;
    height: 20%;
}

.outer div:nth-child(even) {
    width: 20%;
    height: 80%;
}

.outer div:nth-child(1) {
  background: #ed1c24;
  left: 0;
  top: 0;
}

.outer div:nth-child(2) {
    background: #00a2e8;
    right: 0;
    top: 0;
}

.outer div:nth-child(3) {
    background: #22b14c;
    right: 0;
    bottom: 0;
}

.outer div:nth-child(4) {
    background: #b97a57;
    left: 0;
    bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer-wrapper">
  <div class="outer">
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
    <div>Div 4</div>
  </div>
</div>  </code>```

Body:
Consider utilizing absolute positioning on nested div elements and offsetting their positions, within the containing element, appropriately and as required by declaring top, bottom, left and right properties respectively.

Code Snippet Demonstration

Note:

In the below demonstration, a containing element, with resizing properties, has been wrapped around the element in question, to demonstrate the responsive behaviour of this method.

Resize the element manually by clicking the icon, in the bottom-left corner of the containing element, and dragging vertically or horizontally.

* {
  box-sizing: border-box;
  font-family: arial;
}

.outer {
  border: 3px solid black;
  width: 100%;
  height: 100%;
  position: relative; /* required */
}

.outer-wrapper { /* purely for the sake of responsive demonstration */
  padding: 10px;
  resize: auto;
  overflow: hidden;
  border: 3px dashed gray;
  width: 400px;
  height: 400px;
}

.outer div {
  position: absolute;
  padding: 10px;
  font-weight: bold;
  font-size: 12px;
}

.outer div:nth-child(odd) {
    width: 80%;
    height: 20%;
}

.outer div:nth-child(even) {
    width: 20%;
    height: 80%;
}

.outer div:nth-child(1) {
  background: #ed1c24;
  left: 0;
  top: 0;
}

.outer div:nth-child(2) {
    background: #00a2e8;
    right: 0;
    top: 0;
}

.outer div:nth-child(3) {
    background: #22b14c;
    right: 0;
    bottom: 0;
}

.outer div:nth-child(4) {
    background: #b97a57;
    left: 0;
    bottom: 0;
}

<div class="outer-wrapper">
  <div class="outer">
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
    <div>Div 4</div>
  </div>
</div>


问:
CKFinder 3: Moving Resized Image to a destination folder
I am using CKFinder 3 intergrated with CKEditor. Now, after resizing an Image and clicking on Choose Resized, I want to move/copy the resized image to another folder using javascript. I am able to get upto the following code.

```<code>    CKFinder.start({
                onInit: function (finder) {
                     finder.on('file:choose:resizedImage', function (event) {
                        var file = event.data.file;
                        var resizedData = file.get('imageResizeData');
                        var resized = file.get('imageResizeData').get('resized');

                        // Need help here to move the resized image to another folder.

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

NOTE: I am using ASP.NET Connector.

答:
You can use command:send request to send CopyFiles request:
https://docs-old.ckeditor.com/ckfinder3/#!/api/CKFinder.Application-request-command_send

Parameters taken by CopyFiles can be found here:
https://docs-old.ckeditor.com/ckfinder3-net/commands.html#command_copyfiles

Body:
I am using CKFinder 3 intergrated with CKEditor. Now, after resizing an Image and clicking on Choose Resized, I want to move/copy the resized image to another folder using javascript. I am able to get upto the following code.

    CKFinder.start({
                onInit: function (finder) {
                     finder.on('file:choose:resizedImage', function (event) {
                        var file = event.data.file;
                        var resizedData = file.get('imageResizeData');
                        var resized = file.get('imageResizeData').get('resized');

                        // Need help here to move the resized image to another folder.

                     });
                 }
    });

NOTE: I am using ASP.NET Connector.


问:
An invalid value was provided for the parameter 'deviceNumber' while registering multiple devices
I did it before, i.e., registered multiple devices (iPads) just by uploading a text file containing UDIDs and names, and it worked fine, but today I get this error: "An invalid value was provided for the parameter 'deviceNumber'".
I have 70 empty slots, and am trying to add 10 devices.

What is device number? There is no such a thing in the sample files they provide, just device id and name.

答:
I think this is a bug/incorrect example in Apple's importing mechanism.

Today I tried to import my devices in a plist file (example was brought from the developer center, "Download sample files" link, multiple-device-upload-ios.deviceids file) and got the same error.

To eliminate worries about duplicates/malformed plist, I simplified the plist to contain only 1 device, uploaded it, the error remained the same.

The solution was to use a file format as described in multiple-device-upload-ios.txt file:

```<code>Device ID   Device Name
A123456789012345678901234567890123456789    NAME1
B123456789012345678901234567890123456789    NAME2
</code>```

Worked like a charm.

P.S.: Notice the tabs between Device ID and Device Name and between actual numbers and a names. In a name, you may use whitespaces.

Body:
I think this is a bug/incorrect example in Apple's importing mechanism.

Today I tried to import my devices in a plist file (example was brought from the developer center, "Download sample files" link, multiple-device-upload-ios.deviceids file) and got the same error.

To eliminate worries about duplicates/malformed plist, I simplified the plist to contain only 1 device, uploaded it, the error remained the same.

The solution was to use a file format as described in multiple-device-upload-ios.txt file:

Device ID   Device Name
A123456789012345678901234567890123456789    NAME1
B123456789012345678901234567890123456789    NAME2

Worked like a charm.

P.S.: Notice the tabs between Device ID and Device Name and between actual numbers and a names. In a name, you may use whitespaces.


问:
Getting a Linux terminal output of a CLI tool and displaying in Web page

I am trying to create a web application using python which has a HTML form and the form data is used as a command line input to start an application. I know how to initiate the CLI tool from web app, but want a way to get the output of the CLI tool from Linux terminal real time and show it in the web application.

The CLI tool will run for a day and the terminal output will change in real time. Is there a way to display the changing Linux terminal output in to the web application. Information about any web terminal or way to get and store the real-time screen output of a linux application will be helpful.

When ever the screen O/P of the application running in linux changes then the web application should also be updated with the change.

Any python lib or tools will be useful and easy to Integrate?

答:
A quick solution I would do (without any libraries or stuff):

invoke your CLI program and set it up to continuously output to a file on the server. Make sure you know the file name.

use Ajax calls to fetch the output to the client. OR (if you are in for hard stuff) use a webSocket to output to the client.


问:
i need a complex sql query to get employee history
I have one employee shift table which contains an employee id, shit and date.
actually i have daily inserting shifts for all employees. the table is looing like below one

```<code>Employee id       Shift      Date
----------------------------------
1                   G        2017-11-01
1                   G        2017-11-02
1                  NG        2017-11-03
1                  NG        2017-11-04
1                   G        2017-11-05
1                   G        2017-11-06
1                   G        2017-11-07
1                   G        2017-11-08
</code>```

I need output like below

```<code>Employee Id     Shift   From Date     To Date
1                 G     2017-11-01    2017-11-02
1                NG     2017-11-03    2017-11-04
1                 G     2017-11-05    2017-11-08
</code>```

Thanks in advance. please help to write a easy login without using loops.

答:
```<code>create table #merchant_comm(tid nvarchar(20), preval nvarchar(20), curval nvarchar(20), nextval nvarchar(20), datetimerequest datetime, nextdate datetime)

truncate table #merchant_comm

insert into #merchant_comm select * from (select tid,LAG(communication_mode) over (order by datetimerequest) preval, communication_mode curval, LEAD(communication_mode) over (order by datetimerequest) nextval,datetimerequest,LEAD(datetimerequest) over (order by datetimerequest) nextdate
from MRLPOSNET_MSCRM.dbo.Pos_RL_communication_mode_Merchant_Detail
where tid = '3734200M') as a
where preval <> nextval or nextval is null or preval is null  order by datetimerequest

  with CTE as (
  select tid,
case when preval is null then 1 when preval = curval then 0 when preval <> curval then 1 end as flag,
curval as comm_mode, datetimerequest as from_date, lead(datetimerequest) over(order by datetimerequest) as to_date
from #merchant_comm )

 select * from CTE where flag = 1
</code>```

Body:
I have one employee shift table which contains an employee id, shit and date.
actually i have daily inserting shifts for all employees. the table is looing like below one

Employee id       Shift      Date
----------------------------------
1                   G        2017-11-01
1                   G        2017-11-02
1                  NG        2017-11-03
1                  NG        2017-11-04
1                   G        2017-11-05
1                   G        2017-11-06
1                   G        2017-11-07
1                   G        2017-11-08

I need output like below

Employee Id     Shift   From Date     To Date
1                 G     2017-11-01    2017-11-02
1                NG     2017-11-03    2017-11-04
1                 G     2017-11-05    2017-11-08

Thanks in advance. please help to write a easy login without using loops.


问:
How do i get the text from a xml.dom.minidom Dom Element?
How do I get the text value of the title element?
Is this even possible with a Dom Element?
Will I have to parse out the text by hand?</p>

```<code>#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import re
import urllib.request
from xml.dom import minidom

def download(url):
    with urllib.request.urlopen(url) as res:
        return res.read().decode('latin-1')

class RSSFeed(object):
    def __init__(self, url):
        self.url = url
        self.raw_xml = download(url)
        self.dom = minidom.parseString(self.raw_xml)
        self.links = self.dom.getElementsByTagName('link')

    def entries(self):
        ret = {}
        for element in self.dom.getElementsByTagName('entry'):
            title = element.getElementsByTagName('title')[0]
            print(title.toprettyxml())

    def __str__(self):
        return self.dom.toprettyxml()

feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=500'
feed = RSSFeed(feed_url)
dom = feed.dom
print(feedHow totries())
</code>```

答:
The canonical way to determine the node value (i.e. text content) of any XML element is to

get the node value of all the text nodes it contains, including the nested ones

trim them

join them with a space

Minidom inexplicably does not implement this procedure, so if you must use minidom, you need to do it yourself.

So we need a few helper functions.

One to get all the descendant nodes that fulfill a certain condition, like being a text node.

One to get their values and join them

One that gets the first element of a certain name from a node, for convenience.

Let's collect them in a module.

```<code># minidom_helpers.py

def get_descendant_nodes(context_node, predicate):
    if not context_node:
        yield None
    for child in context_node.childNodes:
        if predicate(child):
            yield child
        yield from get_descendant_nodes(child, predicate)

def get_text_value(context_node, default=None):
    texts_nodes = get_descendant_nodes(context_node, lambda n: n.nodeType == n.TEXT_NODE)
    text_value = ' '.join([str.strip(t.nodeValue) for t in texts_nodes])
    return text_value if text_value else default

def get_first_child(context_node, element_name):
    elems = context_node.getElementsByTagName(element_name)
    return elems[0] if elems else None
</code>```

Now we can do

```<code>import re
import urllib.request
from xml.dom import minidom
from minidom_helpers import *

class RSSFeed(object):
    def __init__(self, url):
        self.url = url
        self.dom = minidom.parse(urllib.request.urlopen(url))
        self.links = self.dom.getElementsByTagName('link')

    def entries(self):
        for entry in self.dom.getElementsByTagName('entry'):
            yield {
                "title":  get_text_value(get_first_child(entry, 'title'))
            }

    def __str__(self):
        return self.dom.toprettyxml()

feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=500'
feed = RSSFeed(feed_url)

for entry in feed.entries():
    print(entry)
</code>```

A general note on parsing XML. Try to get into the habit of thinking of XML as binary data, instead of text.

XML parsers implement a complex mechanism of figuring out the file encoding automatically. It's not necessary and not smart to circumvent that mechanism by trying to decode the file or HTTP response into a string yourself ahead of time:

```<code># BAD CODE, DO NOT USE
def download(url):
    with urllib.request.urlopen(url) as res:
        return res.read().decode('latin-1')

raw_xml = download(url)
dom = minidom.parseString(self.raw_xml)
</code>```

The above makes hard-coded (and in your case: wrong) assumptions about the file encoding and will break when the server decides to start sending the file in UTF-16 for some reason.

If you think of XML as binary data instead of text, it gets both a lot easier and a lot more robust.

```<code>dom = minidom.parse(urllib.request.urlopen(url))
</code>```

The XML parser will sniff the bytes and decide what encoding they are in.

This is also true for reading XML from files. Instead of

```<code># BAD CODE, DO NOT USE
with open(path, 'r', encoding='latin-1') as fp:
    dom = minidom.parseString(fp.read())
</code>```

Use

```<code>with open(path, 'rb') as fp:
    dom = minidom.parse(fp)
</code>```

or simply

```<code>dom = minidom.parse(path)
</code>```

Body:
How do I get the text value of the title element?
Is this even possible with a Dom Element?
Will I have to parse out the text by hand?

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import re
import urllib.request
from xml.dom import minidom

def download(url):
    with urllib.request.urlopen(url) as res:
        return res.read().decode('latin-1')

class RSSFeed(object):
    def __init__(self, url):
        self.url = url
        self.raw_xml = download(url)
        self.dom = minidom.parseString(self.raw_xml)
        self.links = self.dom.getElementsByTagName('link')

    def entries(self):
        ret = {}
        for element in self.dom.getElementsByTagName('entry'):
            title = element.getElementsByTagName('title')[0]
            print(title.toprettyxml())

    def __str__(self):
        return self.dom.toprettyxml()

feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=500'
feed = RSSFeed(feed_url)
dom = feed.dom
print(feedHow totries())

Body:
The canonical way to determine the node value (i.e. text content) of any XML element is to

get the node value of all the text nodes it contains, including the nested ones

trim them

join them with a space

Minidom inexplicably does not implement this procedure, so if you must use minidom, you need to do it yourself.

So we need a few helper functions.

One to get all the descendant nodes that fulfill a certain condition, like being a text node.

One to get their values and join them

One that gets the first element of a certain name from a node, for convenience.

Let's collect them in a module.

# minidom_helpers.py

def get_descendant_nodes(context_node, predicate):
    if not context_node:
        yield None
    for child in context_node.childNodes:
        if predicate(child):
            yield child
        yield from get_descendant_nodes(child, predicate)

def get_text_value(context_node, default=None):
    texts_nodes = get_descendant_nodes(context_node, lambda n: n.nodeType == n.TEXT_NODE)
    text_value = ' '.join([str.strip(t.nodeValue) for t in texts_nodes])
    return text_value if text_value else default

def get_first_child(context_node, element_name):
    elems = context_node.getElementsByTagName(element_name)
    return elems[0] if elems else None

Now we can do

import re
import urllib.request
from xml.dom import minidom
from minidom_helpers import *

class RSSFeed(object):
    def __init__(self, url):
        self.url = url
        self.dom = minidom.parse(urllib.request.urlopen(url))
        self.links = self.dom.getElementsByTagName('link')

    def entries(self):
        for entry in self.dom.getElementsByTagName('entry'):
            yield {
                "title":  get_text_value(get_first_child(entry, 'title'))
            }

    def __str__(self):
        return self.dom.toprettyxml()

feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=500'
feed = RSSFeed(feed_url)

for entry in feed.entries():
    print(entry)

A general note on parsing XML. Try to get into the habit of thinking of XML as binary data, instead of text.

XML parsers implement a complex mechanism of figuring out the file encoding automatically. It's not necessary and not smart to circumvent that mechanism by trying to decode the file or HTTP response into a string yourself ahead of time:

# BAD CODE, DO NOT USE
def download(url):
    with urllib.request.urlopen(url) as res:
        return res.read().decode('latin-1')

raw_xml = download(url)
dom = minidom.parseString(self.raw_xml)

The above makes hard-coded (and in your case: wrong) assumptions about the file encoding and will break when the server decides to start sending the file in UTF-16 for some reason.

If you think of XML as binary data instead of text, it gets both a lot easier and a lot more robust.

dom = minidom.parse(urllib.request.urlopen(url))

The XML parser will sniff the bytes and decide what encoding they are in.

This is also true for reading XML from files. Instead of

# BAD CODE, DO NOT USE
with open(path, 'r', encoding='latin-1') as fp:
    dom = minidom.parseString(fp.read())

Use

with open(path, 'rb') as fp:
    dom = minidom.parse(fp)

or simply

dom = minidom.parse(path)


问:
One-liner Algorithm to Combine Arrays into Arrays of All Possible Value Combinations?
Not quite sure I have the question fully formed, but what I'm trying to do is basically this:

```<code># where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]
</code>```

The order of the array is always the same, so the reverse of each, such as [b, a], are not included in the result.

What is this called and what's an efficient way to implement this?

I see Array#permutation, but that's not quite it...

This would hopefully work for any number of arrays and values: combine(*arrays)

Thanks!

Update

Here's a better example of what I'm looking for:

This (x | y).combination(x.length).to_a produces the following:

```<code>x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]]
</code>```

The actual result I'm looking for is this:

```<code>=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]
</code>```

Or if it were a longer array:

```<code>x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]
</code>```

Any ideas?

答:
```<code>(x | y ).combination(x.length).to_a
</code>```

Body:
Not quite sure I have the question fully formed, but what I'm trying to do is basically this:

# where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]

The order of the array is always the same, so the reverse of each, such as [b, a], are not included in the result.

What is this called and what's an efficient way to implement this?

I see Array#permutation, but that's not quite it...

This would hopefully work for any number of arrays and values: combine(*arrays)

Thanks!

Update

Here's a better example of what I'm looking for:

This (x | y).combination(x.length).to_a produces the following:

x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]]

The actual result I'm looking for is this:

=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]

Or if it were a longer array:

x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]

Any ideas?

Body: (x | y ).combination(x.length).to_a


问:
Grails minimum value fetch
I am working to fetch the minimum value from a table in Grails where the vehicleid and the type is given

there are many values associated from that vehicleid and type i need to fetch the minimum date associated with that vehicleid . I have tried this but it is not working for the startDate param.

```<code>List vehicleDate= Table.createCriteria().list() {
   and{
      eq('vehicleid',vehicleIDGiven)
      eq('type',type)
      min("startDate")
   }
}
</code>```

what could be the query like

答:
If you just need to fetch the minimum value, you could use a projection as documented here.

Not tested, but your criteria should look something like this:

```<code>def result = Table.createCriteria().list() {
    and{
        eq('vehicleid',vehicleIDGiven)
        eq('type',type)
    }
    projections {
        min("startDate")
   }
}

println "Minimum start date is ${result[0]}"
</code>```

Title: Grails minimum value fetch

Body:
I am working to fetch the minimum value from a table in Grails where the vehicleid and the type is given

there are many values associated from that vehicleid and type i need to fetch the minimum date associated with that vehicleid . I have tried this but it is not working for the startDate param.

List vehicleDate= Table.createCriteria().list() {
   and{
      eq('vehicleid',vehicleIDGiven)
      eq('type',type)
      min("startDate")
   }
}

what could be the query like

Body:
If you just need to fetch the minimum value, you could use a projection as documented here.

Not tested, but your criteria should look something like this:

def result = Table.createCriteria().list() {
    and{
        eq('vehicleid',vehicleIDGiven)
        eq('type',type)
    }
    projections {
        min("startDate")
   }
}

println "Minimum start date is ${result[0]}"


问:
Convert react-barcode to pdf format to print
I'm trying to print generated barcode but it prints as [object, object] tried using JSON.stringify and all other sources that i got but didn't work. Could someone suggest what is the best way to do this.</p>

```<code>    var printWindow = window.open('', '', 'height=400,width=800');
    printWindow.document.write('<html><head><title>DIV
         Contents</title>');
    printWindow.document.write('</head><body >');
    for(var i=0; i<selectedRows.length;i++){
        printWindow.document.write(
            <Barcode
            value="Rakesh"//{this.state.value}
            width="2"
            height="100"
            format="CODE128"
            displayValue=""
            fontOptions=""
            font="monospace"
            textAlign="center"
            textPosition="bottom"
            textMargin="2"
            fontSize="20"
            background="#ffffff"
            lineColor="#000000"
            margin="10"
            marginTop=""
            marginBottom=""
            marginLeft=""
            marginRight=""
        />
        );
    }
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    // printWindow.print();
</code>```

答:
Depending on the version of React you're using, you want to wrap that component in a React.renderToString, React.renderComponent, or a ReactDOMServer.renderToString call. Of course, this also means that you need to make sure React/ReactDOMServer is within the scope of the popup window generator. See also this answer.

```<code>var ReactDOMServer = require('react-dom/server');
// ...

ReactDOMServer.renderToString(<Barcode
        value="Rakesh"// {this.state.value}
        width="2"
        height="100"
        format="CODE128"
        displayValue=""
        fontOptions=""
        font="monospace"
        textAlign="center"
        textPosition="bottom"
        textMargin="2"
        fontSize="20"
        background="#ffffff"
        lineColor="#000000"
        margin="10"
        marginTop=""
        marginBottom=""
        marginLeft=""
        marginRight=""
    />
 )
</code>```

Body:
I'm trying to print generated barcode but it prints as [object, object] tried using JSON.stringify and all other sources that i got but didn't work. Could someone suggest what is the best way to do this.

    var printWindow = window.open('', '', 'height=400,width=800');
    printWindow.document.write('<title>DIV
         Contents</title>');
    printWindow.document.write('');
    for(var i=0; i<selectedRows.length;i++){
        printWindow.document.write(
            <Barcode
            value="Rakesh"//{this.state.value}
            width="2"
            height="100"
            format="CODE128"
            displayValue=""
            fontOptions=""
            font="monospace"
            textAlign="center"
            textPosition="bottom"
            textMargin="2"
            fontSize="20"
            background="#ffffff"
            lineColor="#000000"
            margin="10"
            marginTop=""
            marginBottom=""
            marginLeft=""
            marginRight=""
        />
        );
    }
    printWindow.document.write('');
    printWindow.document.close();
    // printWindow.print();

Body:
Depending on the version of React you're using, you want to wrap that component in a React.renderToString, React.renderComponent, or a ReactDOMServer.renderToString call. Of course, this also means that you need to make sure React/ReactDOMServer is within the scope of the popup window generator. See also this answer.

var ReactDOMServer = require('react-dom/server');
// ...

ReactDOMServer.renderToString(<Barcode
        value="Rakesh"// {this.state.value}
        width="2"
        height="100"
        format="CODE128"
        displayValue=""
        fontOptions=""
        font="monospace"
        textAlign="center"
        textPosition="bottom"
        textMargin="2"
        fontSize="20"
        background="#ffffff"
        lineColor="#000000"
        margin="10"
        marginTop=""
        marginBottom=""
        marginLeft=""
        marginRight=""
    />
 )


问:
How to increase volume of node-chrome-debug using docker compose?
I want to increase the volume of the chrome node so that it does not crashes , one way to achieve is -

```<code>$ docker run -d -p 4444:4444 --shm-size 2g selenium/node-chrome-debug
</code>```

But how do i write this in a docker compose file.

Thank you

答:
Something like this =)    </p>

```<code>version: "2.0"
    services:
      app:
        image: selenium/node-chrome-debug
        ports:
          - "4444:4444"
        shm_size: "2g"
</code>```

Body:
I want to increase the volume of the chrome node so that it does not crashes , one way to achieve is -

$ docker run -d -p 4444:4444 --shm-size 2g selenium/node-chrome-debug

But how do i write this in a docker compose file.

Thank you

Body:
Something like this =)

version: "2.0"
    services:
      app:
        image: selenium/node-chrome-debug
        ports:
          - "4444:4444"
        shm_size: "2g"


问:
C++ cross-compiler from Windows to Linux
Are there any user friendly tools out there to cross-compile from Windows to Linux?</p>

答:
Your best bet is to use a cross platform IDE like Code::Blocks that can import MSVC projects, and generate a Makefile for Linux, which you can then run on a Linux (with even the same program if you so wish).

So your work flow would then look something like the following:

```<code>Code, Compile, and debug on MSVC -> import into Code::Blocks & generate Makefile
-> test compile and debug with GCC
-> copy to Linux with Code::Blocks -> test compile & debug on Linux
</code>```

It's a little obtuse, probably, but at least Code::Blocks takes care of a lot of those small details with things like Makefiles, and what not.

Body:
Your best bet is to use a cross platform IDE like Code::Blocks that can import MSVC projects, and generate a Makefile for Linux, which you can then run on a Linux (with even the same program if you so wish).

So your work flow would then look something like the following:

Code, Compile, and debug on MSVC -> import into Code::Blocks & generate Makefile
-> test compile and debug with GCC
-> copy to Linux with Code::Blocks -> test compile & debug on Linux

It's a little obtuse, probably, but at least Code::Blocks takes care of a lot of those small details with things like Makefiles, and what not.


问:
Mystery how google makes borders half as thick but still set to 1 pixel
Its a mystery to me how the 1px borders around the cells of this table are very thin, but if I copy the exact style:

```<code>border-right: solid 1px #E0E0E0;
border-bottom: solid 1px #E0E0E0;
</code>```

It looks twice as thick. I cant see anything thats causing these borders to look nicer and sharper. Why are they thinner?

EDIT:
We worked out that google has somehow made the 1px border to 0.5px, it doesnt matter how, you can just set it:

```<code>border: 0.5px solid #ccc;
</code>```

I have a small screen laptop with very high resolution (high pixel density), so I can see the difference between the half and one pixel borders here: https://jsfiddle.net/pd9hkd4j/2/

Most people in tech / gaming spheres do have a full HD screen / monitor, but also have a larger screen and therefore slightly lower pixel density, so their monitor does not render 0.5px and 1px differently.

It may be that Google has not intentionally tried to have a thinner border, and its just a circumstance of a minority of screens.

答:
It is a very bright border-color on a white background. Maybe you try to set the border-color to a different background-color? panther is correct with his comment, 1px is 1px, but with some optical tricks, you can make the border appear thinner, than it actually is.

Take a quick look at the example below: Both
 at the top contain a
 with the same border-color and thickness. But the one on the black background seems to be much thicker, since the contrast between the border and the background is very high.

On the bottom there is a white background with some different borders, and you will probably notice, that the lighter ones look thinner, than the dark ones. It is just an optical trick, Google is using to play with the appearance :-)

Edit:

It turned out, that o0o0o0o0o actually has a high DPI Display, which is able to display "half pixels" since 1px width is not necessarily equal to one pixel of the display on high DPI Settings. So you actually can set the border width to a float value, but it obviously will only be visible to users with higher DPI Displays. A "regular" Monitor will show it as 1px, since its not possible to display half pixels (which also is kind of obvious ;) )

.wrapper {
  float: left;
  width: 30%;
  height: 300px;
  padding: 30px;
}

.black {
  background: black;
}

.white {
  background: white;
}

.border {
  border: solid 1px #E0E0E0;
  padding: 10px;
}

.bottom {
  clear: both;
  background: white;
  width: 60%;
  padding: 60px;
  height: 200px;
}

.bottom div {
  margin-bottom: 30px;
}

.border-10 {
  border-bottom: 1px solid #efefef;
}

.border-30 {
  border-bottom: 1px solid #ccc;
}

.border-50 {
  border-bottom: 1px solid #a0a0a0;
}

.border-70 {
  border-bottom: 1px solid #707070;
}
.border-90 {
  border-bottom: 1px solid #383838;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper black">
  <div class="border">
    Lorem Ipsum
  </div>
</div>
<div class="wrapper white">
  <div class="border">
    Lorem Ipsum
  </div>
</div>
<div class="bottom">
  <div class="border-10"></div>
  <div class="border-30"></div>
  <div class="border-50"></div>
  <div class="border-70"></div>
  <div class="border-90"></div>
</div></code>```

Body:
Its a mystery to me how the 1px borders around the cells of this table are very thin, but if I copy the exact style:

border-right: solid 1px #E0E0E0;
border-bottom: solid 1px #E0E0E0;

It looks twice as thick. I cant see anything thats causing these borders to look nicer and sharper. Why are they thinner?

EDIT:
We worked out that google has somehow made the 1px border to 0.5px, it doesnt matter how, you can just set it:

border: 0.5px solid #ccc;

I have a small screen laptop with very high resolution (high pixel density), so I can see the difference between the half and one pixel borders here: https://jsfiddle.net/pd9hkd4j/2/

Most people in tech / gaming spheres do have a full HD screen / monitor, but also have a larger screen and therefore slightly lower pixel density, so their monitor does not render 0.5px and 1px differently.

It may be that Google has not intentionally tried to have a thinner border, and its just a circumstance of a minority of screens.

Body:
It is a very bright border-color on a white background. Maybe you try to set the border-color to a different background-color? panther is correct with his comment, 1px is 1px, but with some optical tricks, you can make the border appear thinner, than it actually is.

Take a quick look at the example below: Both <div> at the top contain a <div> with the same border-color and thickness. But the one on the black background seems to be much thicker, since the contrast between the border and the background is very high.

On the bottom there is a white background with some different borders, and you will probably notice, that the lighter ones look thinner, than the dark ones. It is just an optical trick, Google is using to play with the appearance :-)

Edit:

It turned out, that o0o0o0o0o actually has a high DPI Display, which is able to display "half pixels" since 1px width is not necessarily equal to one pixel of the display on high DPI Settings. So you actually can set the border width to a float value, but it obviously will only be visible to users with higher DPI Displays. A "regular" Monitor will show it as 1px, since its not possible to display half pixels (which also is kind of obvious ;) )

.wrapper {
  float: left;
  width: 30%;
  height: 300px;
  padding: 30px;
}

.black {
  background: black;
}

.white {
  background: white;
}

.border {
  border: solid 1px #E0E0E0;
  padding: 10px;
}

.bottom {
  clear: both;
  background: white;
  width: 60%;
  padding: 60px;
  height: 200px;
}

.bottom div {
  margin-bottom: 30px;
}

.border-10 {
  border-bottom: 1px solid #efefef;
}

.border-30 {
  border-bottom: 1px solid #ccc;
}

.border-50 {
  border-bottom: 1px solid #a0a0a0;
}

.border-70 {
  border-bottom: 1px solid #707070;
}
.border-90 {
  border-bottom: 1px solid #383838;
}

<div class="wrapper black">
  <div class="border">
    Lorem Ipsum
  </div>
</div>
<div class="wrapper white">
  <div class="border">
    Lorem Ipsum
  </div>
</div>
<div class="bottom">
  <div class="border-10"></div>
  <div class="border-30"></div>
  <div class="border-50"></div>
  <div class="border-70"></div>
  <div class="border-90"></div>
</div>


问:
How to add active class to selected list item
Hi I'm trying to add class to the selectedlList item & also add class if I scroll to the specific div. for example of scroll on div#six number six(6) in the menu should also have class active.</p>

<p>[see my code and demo here][1] </p>

```<code>  [1]: https://codepen.io/GoPerov/pen/aZmVgE
</code>```

答:
Try this code, Here's your updated pen</p>

```<code>$(document).ready(function(){
  $(".page-scroll").click(function(){
     $(".page-scroll").removeClass("active");  //removes current active class
    $(this).addClass("active");   // adds active class to specific click
  })
});
</code>```

Body:
Hi I'm trying to add class to the selectedlList item & also add class if I scroll to the specific div. for example of scroll on div#six number six(6) in the menu should also have class active.

[see my code and demo here][1]

  [1]: https://codepen.io/GoPerov/pen/aZmVgE

Body:
Try this code, Here's your updated pen

$(document).ready(function(){
  $(".page-scroll").click(function(){
     $(".page-scroll").removeClass("active");  //removes current active class
    $(this).addClass("active");   // adds active class to specific click
  })
});


问:
What is the best way to wait for a task to finish with respect to .NET?
This is our async method which executes for a long time in a Task.

```<code>public async Task<int> LongRunningMethod(T p1, T p2, T p3);
</code>```

Some developers in my team use

```<code>Task t = Task.Factory.StartNew(LongRunningMethod(p1,p2,p3));
t.Wait();  //This will suspend main thread and wait for 't' to finish.
</code>```

While some use

```<code>await LongRunningMethod(p1,p2,p3);
// Here too, we simply 'await' till the method finishes.
</code>```

Note: We have a asynchronous task and we want to wait till that task gets completed.

In short, Which one is the best among the above two constructs ?

答:
The point of using Tasks is to execute some Task in parallel from the same context. if you want to start a long running task from a context and just want to wait for the task to finish, both method you showed will work in the same way.

But if you want do any other operation during the execution of the long running task,
you can do as

```<code>Task taskObj = LongRunningMethod();
/// Do some other operations here...
var result = await taskObj;
</code>```

But if need the result from the long running task to do some operation you need to await for the task to complete.
or you can use Task.ContinueWith()

Body:
This is our async method which executes for a long time in a Task.

public async Task<int> LongRunningMethod(T p1, T p2, T p3);

Some developers in my team use

Task t = Task.Factory.StartNew(LongRunningMethod(p1,p2,p3));
t.Wait();  //This will suspend main thread and wait for 't' to finish.

While some use

await LongRunningMethod(p1,p2,p3);
// Here too, we simply 'await' till the method finishes.

Note: We have a asynchronous task and we want to wait till that task gets completed.

In short, Which one is the best among the above two constructs ?

Body:
The point of using Tasks is to execute some Task in parallel from the same context. if you want to start a long running task from a context and just want to wait for the task to finish, both method you showed will work in the same way.

But if you want do any other operation during the execution of the long running task,
you can do as

Task taskObj = LongRunningMethod();
/// Do some other operations here...
var result = await taskObj;

But if need the result from the long running task to do some operation you need to await for the task to complete.
or you can use Task.ContinueWith()


问:
Regex in Python. How to match a string but not in comments?
I want to match any Chinese character in  ""， but not in the comment of Lua, i.e: after --.

For example, in string Tips("中文") -- "注释"，中文 should be matched, but not 注释.

The regex I write is ur'(?

答: You could just capture all Chinese characters between quotes, capture any comment start ´--´ indicators, and then throw away all the matches after that indicator.</p>


问:
Smarty Capitalize throws error: Deprecated: preg_replace(): The /e modifier
capitalize modifier in smarty throws error

```<code>{$payment.first_name|capitalize}
</code>```

The above code throws the following error

Deprecated: preg_replace(): The /e modifier is deprecated, use
  preg_replace_callback instead in
  /home/mysuite/public_html/Demo/yoursite/includes/smarty/libs/plugins/modifier.capitalize.php
  on line 65

答:
You can use the php function ucwords like this.

```<code> {$payment.first_name|ucwords}
</code>```

It might not work for non latin characters (not working on cyrillic) but than you can use some library and define your new function as smarty function.

Body:
capitalize modifier in smarty throws error

{$payment.first_name|capitalize}

The above code throws the following error

Deprecated: preg_replace(): The /e modifier is deprecated, use
  preg_replace_callback instead in
  /home/mysuite/public_html/Demo/yoursite/includes/smarty/libs/plugins/modifier.capitalize.php
  on line 65

Body:
You can use the php function ucwords like this.

 {$payment.first_name|ucwords}

It might not work for non latin characters (not working on cyrillic) but than you can use some library and define your new function as smarty function.


问:
Why does my hand created deb package fails at install with "unable to create" on files?
I made a perl script that creates a deb binary package from scratch.
I created the data, control, etc.
But when I run dpkg -i on my deb package it complains that it is unable to files from data.
Example:
unable to create '.dpkg-new'(while processing ''): No such file or directory.

I have downloaded some .deb packages to look at and they do not use the preinst script to create the directory structure.

I am thinking I am doing something wrong, I consider having to create my own directories in preinst but it does not seem right... perhaps I am missing something?

Do I have to create directories where my files from data will be copied in the preinst sh, or should dpkg do it and I am doing something wrong?

答: In addition to what @Arrowmaster said, check the http://www.debian.org/doc/debian-policy/ for some detailed explanation of the files. After you build the package itself, you can check it with lintian tool to see if there is anything obvious you might have missed.