问:
Windows bat: How to loop files in sub directories
I need to use a bat named process.bat to process all of jpg files in some sub directories.

```<code>dir
 |---subdir1
 |     |-----a.jpg
 |     |-----b.jpg
 |
 |---subdir2
       |-----c.jpg
       |-----d.jpg

process.bat dir/subdir1/a.jpg dir/subdir1/b.jpg
process.bat dir/subdir2/c.jpg dir/subdir2/d.jpg
</code>```

In Linux, I can make such a script:

```<code>find $1 -type d | while read dir; do
    files=("$dir"/*.jpg)
    if [ ${#files[@]} -gt 0 ]; then
        if ! [[ $files =~ \* ]]; then
            process.bat "${files[@]}"
        fi
    fi
done
</code>```

But I don't know how to do the same thing in Windows.

I've known how to loop files in Windows bat: for /r %%i in (*) do echo %%i

答:
dir should be an absolut path:

```<code>> tree . /F
C:\TEST\DIR
├───subdir1
│       a.jpg
│       b.jpg
│
├───subdir2
│       c.jpg
│       d.jpg
│
└───subdir3
</code>```

```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
For /d %%A in (C:\Test\dir\*) Do (
  Set "Files="
  For %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
  If defined Files echo process.bat !Files!
)
</code>```

Sample output with echo :

```<code>process.bat  "C:\Test\dir\subdir1\a.jpg" "C:\Test\dir\subdir1\b.jpg"
process.bat  "C:\Test\dir\subdir2\c.jpg" "C:\Test\dir\subdir2\d.jpg"
</code>```

Body:
I need to use a bat named process.bat to process all of jpg files in some sub directories.

dir
 |---subdir1
 |     |-----a.jpg
 |     |-----b.jpg
 |
 |---subdir2
       |-----c.jpg
       |-----d.jpg

process.bat dir/subdir1/a.jpg dir/subdir1/b.jpg
process.bat dir/subdir2/c.jpg dir/subdir2/d.jpg

In Linux, I can make such a script:

find $1 -type d | while read dir; do
    files=("$dir"/*.jpg)
    if [ ${#files[@]} -gt 0 ]; then
        if ! [[ $files =~ \* ]]; then
            process.bat "${files[@]}"
        fi
    fi
done

But I don't know how to do the same thing in Windows.

I've known how to loop files in Windows bat: for /r %%i in (*) do echo %%i

Body:
dir should be an absolut path:

> tree . /F
C:\TEST\DIR
├───subdir1
│       a.jpg
│       b.jpg
│
├───subdir2
│       c.jpg
│       d.jpg
│
└───subdir3

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
For /d %%A in (C:\Test\dir\*) Do (
  Set "Files="
  For %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
  If defined Files echo process.bat !Files!
)

Sample output with echo :

process.bat  "C:\Test\dir\subdir1\a.jpg" "C:\Test\dir\subdir1\b.jpg"
process.bat  "C:\Test\dir\subdir2\c.jpg" "C:\Test\dir\subdir2\d.jpg"


来源: stackexchange

问:
Strange behavior with input type="hidden" and prop("checked", true)
I stumbled upon this by accident, and I'm wondering if its a bug or intended behaviour. I set a checked on an input type="hidden" which I thought was not possible. But depending on the used jQuery selector this field is then returned or not returned.

HTML:

```<code><form>
  <div>Checkbox: <input class="test" type="checkbox" name="check" value="1" /></div>
  <div>Hidden: <input class="test" type="hidden" name="check" value="1" /></div>
  <div><input id="button" type="button" value="run test" /></div>
  <div>Results:</div>
  <div id="resultA"><strong>$('.test:checked')</strong><br /></div>
  <div id="resultB"><strong>$('.test:checked[value=1]')</strong><br /></div>
  <div id="resultC"><strong>$('.test:checked[value="1"]')</strong><br /></div>
</form>
</code>```

jQuery:

```<code>$(function() {
  $('#button').click(function() {
    $('.test').prop('checked', true);

    $('.test:checked').each(function() {
      $('#resultA').append($(this).attr('type') + ' - checked<br />');
    });

    $('.test:checked[value=1]').each(function() {
      $('#resultB').append($(this).attr('type') + ' - checked<br />');
    });

    $('.test:checked[value="1"]').each(function() {
      $('#resultC').append($(this).attr('type') + ' - checked<br />');
    });
  });
});
</code>```

Above example as a JSFiddle: https://jsfiddle.net/m5fatj8q/6/

ResultA: only returns the checkbox.

ResultB: returns both the checkbox and hiddden field!

ResultC: only returns the checkbox.

My questing is:

Why does resultB return the hidden field? And is this a bug or intended behaviour?

答:
The attribute selector [value=1] is not valid; the value you're matching against in an attribute selector either has to be a string (denoted with quotes, as per your 3rd option) or a CSS identifier which

cannot start with a digit.

That's why the behaviour differs between 2 and 3.

The reason it then differs between 1 and 2 must be down to a bug in Sizzle, the selector engine that jQuery uses internally, not correctly handling invalid selectors.  If you instead use querySelectorAll, you get

'.test:checked[value=1]' is not a valid selector.

I'm by no means an expert in the Sizzle source code, but I think the issue is a combination of their definition of an attribute:

```<code>// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
</code>```

and here:

```<code>// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
</code>```

which would appear to just use the value given, no matter whether it was quoted or not.  This is then compounded by the check for :checked:

```<code>return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
</code>```

Which seems to only look to make sure it's an <input> element, and not specifically a checkbox or radio button.

ContentLicense: CC BY-SA 3.0

Body:
I stumbled upon this by accident, and I'm wondering if its a bug or intended behaviour. I set a checked on an input type="hidden" which I thought was not possible. But depending on the used jQuery selector this field is then returned or not returned.

HTML:

<form>

Checkbox: <input class="test" type="checkbox" name="check" value="1" />

Hidden: <input class="test" type="hidden" name="check" value="1" />

<input id="button" type="button" value="run test" />

Results:

$('.test:checked')

$('.test:checked[value=1]')

$('.test:checked[value="1"]')

</form>

jQuery:

$(function() {
  $('#button').click(function() {
    $('.test').prop('checked', true);

    $('.test:checked').each(function() {
      $('#resultA').append($(this).attr('type') + ' - checked
');
    });

    $('.test:checked[value=1]').each(function() {
      $('#resultB').append($(this).attr('type') + ' - checked
');
    });

    $('.test:checked[value="1"]').each(function() {
      $('#resultC').append($(this).attr('type') + ' - checked
');
    });
  });
});

Above example as a JSFiddle: https://jsfiddle.net/m5fatj8q/6/

ResultA: only returns the checkbox.

ResultB: returns both the checkbox and hiddden field!

ResultC: only returns the checkbox.

My questing is:

Why does resultB return the hidden field? And is this a bug or intended behaviour?

Body:
The attribute selector [value=1] is not valid; the value you're matching against in an attribute selector either has to be a string (denoted with quotes, as per your 3rd option) or a CSS identifier which

cannot start with a digit.

That's why the behaviour differs between 2 and 3.

The reason it then differs between 1 and 2 must be down to a bug in Sizzle, the selector engine that jQuery uses internally, not correctly handling invalid selectors.  If you instead use querySelectorAll, you get

'.test:checked[value=1]' is not a valid selector.

I'm by no means an expert in the Sizzle source code, but I think the issue is a combination of their definition of an attribute:

// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"

and here:

// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );

which would appear to just use the value given, no matter whether it was quoted or not.  This is then compounded by the check for :checked:

return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);

Which seems to only look to make sure it's an <input> element, and not specifically a checkbox or radio button.


问:
Office 365 Javascript Add-In - Speech Synthesis
I'm currently working on a Word Add-In using the Office Tools for Visual Studio, which I want to implement TTS into.  As it is a web app, is it possible to use a Web speech API such as SpeechSynthesis, rather than a thirdparty solution?

I imagine this would work for platforms such as Word Online, but would it be possible for the desktop app?

答:
You'll run into issues on the Windows versions of Word. Under the covers the new app platform use Internet Explorer as their engine (on windows, safari for mac/ipad).  Per the mozilla documentation there is no support for the speech synth api in internet explorer.

https://developer.mozilla.org/en-US/docs/Web/API/Window/speechSynthesis


问:
How to create an API to select functions with arguments
I am trying to build an API that will allow me to pick different methods of extraction and comparison. Each method has its own set of parameters. What would be the most pythonic and cleanest way to do something like this:</p>

```<code>class ThisObject(object):
    def __init__(self, input_file, extraction_method, analyses_method):
        self.input_file = input_file

        extracted_info = extraction_method(input_file, **parameters1**)
        analyzed_info = analyses_method(extracted_info)

this_object = ThisObject(input_file='~/some_file',
                         extraction_method=extraction_method.get_first_name(**parameters**),
                         analyses_method=analyses_method.get_percent_matrix(**parameters**)
                         )
</code>```

答: I think you are looking for arbitrary argument lists.</p>

Body:
I am trying to build an API that will allow me to pick different methods of extraction and comparison. Each method has its own set of parameters. What would be the most pythonic and cleanest way to do something like this:

class ThisObject(object):
    def __init__(self, input_file, extraction_method, analyses_method):
        self.input_file = input_file

        extracted_info = extraction_method(input_file, **parameters1**)
        analyzed_info = analyses_method(extracted_info)

this_object = ThisObject(input_file='~/some_file',
                         extraction_method=extraction_method.get_first_name(**parameters**),
                         analyses_method=analyses_method.get_percent_matrix(**parameters**)
                         )


问:
Convert character 'A' to 'B' if I add 1
Suppose you have one character/string, "A".

What do you write to convert it to 'B' if add 1 to 'A'. If I add '2' it should be converted to 'C' and so on...

答:
Maybe something like?:</p>

```<code>array = ('a'..'z').to_a
p array[array.index('a'.downcase) + 1].upcase
</code>```

Title: Convert character 'A' to 'B' if I add 1

Body:
Maybe something like?:

array = ('a'..'z').to_a
p array[array.index('a'.downcase) + 1].upcase


问:
Modal window comment editing module (editable text)
I want to make, that during the ediditing comment action, I have modal window with comment text written inside textarea, and it is editable without deleting all text with clicking. I tried just to put value inside textarea or placing it in placeholder. But both options are wrong and doesnt work.
Can someone take a look on this code and give me an advice, how should I take for it.

editComment.html

```<code><div class="modal-header">
    <h3 class="modal-title" id="modal-title">Edytuj komentarz</h3>
</div>
<div class="modal-body" id="modal-body">
    <div class="row">
        <div class="col-sm-12">
            <div class="row">
                <div class="col-sm-12 form-group">
                    <label>Treść</label>

                    <textarea class="form-control input-sm"
                              name="description"
                              ng-maxlength="512"
                              ng-model="$ctrl.selected"
                              rows="6">{{comment.value()}}</textarea>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button class="btn btn-raised btn-primary"
            type="button"
            ng-disabled="!$ctrl.selected"
            ng-click="$ctrl.ok()">Zapisz
    </button>
    <button class="btn btn-raised btn-warning"
            type="button"
            ng-click="$ctrl.cancel()">Anuluj
    </button>
</div>
</code>```

editComment.js

```<code>(function() {
    'use strict';

    angular.module('settlerApplication').controller('EditCommentCtrl', function($uibModalInstance) {

        var $ctrl = this;

        $ctrl.ok = function() {
            $uibModalInstance.close($ctrl.selected);
        };

        $ctrl.cancel = function() {
            $uibModalInstance.dismiss('cancel');
        };

    });

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

答:
I'm not sure to understand what you are trying to achieve. But anyway : if you want to init your textarea's ng-model with $ctrl.foo (comment.value() in your case, from what I understood), you should either :

In the controller, init your $ctrl.selected variable with this value :

```<code>$ctrl.selected = $ctrl.foo;
</code>```

Or, in your template, use ng-init :

```<code><textarea class="form-control input-sm"
          ng-init="$ctrl.selected = $ctrl.foo"
          name="description"
          ng-maxlength="512"
          ng-model="$ctrl.selected"
          rows="6"></textarea>
</code>```

Body:
I want to make, that during the ediditing comment action, I have modal window with comment text written inside textarea, and it is editable without deleting all text with clicking. I tried just to put value inside textarea or placing it in placeholder. But both options are wrong and doesnt work.
Can someone take a look on this code and give me an advice, how should I take for it.

editComment.html

Edytuj komentarz

                    Treść

                    <textarea class="form-control input-sm"
                              name="description"
                              ng-maxlength="512"
                              ng-model="$ctrl.selected"
                              rows="6">{{comment.value()}}</textarea>

    <button class="btn btn-raised btn-primary"
            type="button"
            ng-disabled="!$ctrl.selected"
            ng-click="$ctrl.ok()">Zapisz
    </button>
    <button class="btn btn-raised btn-warning"
            type="button"
            ng-click="$ctrl.cancel()">Anuluj
    </button>

editComment.js

(function() {
    'use strict';

    angular.module('settlerApplication').controller('EditCommentCtrl', function($uibModalInstance) {

        var $ctrl = this;

        $ctrl.ok = function() {
            $uibModalInstance.close($ctrl.selected);
        };

        $ctrl.cancel = function() {
            $uibModalInstance.dismiss('cancel');
        };

    });

})();

Body:
I'm not sure to understand what you are trying to achieve. But anyway : if you want to init your textarea's ng-model with $ctrl.foo (comment.value() in your case, from what I understood), you should either :

In the controller, init your $ctrl.selected variable with this value :

$ctrl.selected = $ctrl.foo;

Or, in your template, use ng-init :

<textarea class="form-control input-sm"
          ng-init="$ctrl.selected = $ctrl.foo"
          name="description"
          ng-maxlength="512"
          ng-model="$ctrl.selected"
          rows="6"></textarea>


问:
Strange sum problem

Possible Duplicate:

  Elegant workaround for JavaScript floating point number problem

```<code>var sum = 0;
$('[id$=percentOfTotalEditor]').each(
    function () {
        var igEditor = $find(this.id);
        var value = igEditor.get_value();
        sum += value;
    }
);
</code>```

Then you'll see the magic:

sum == 1.1, value == 0.1. But after sum += value, sum == 1.2000000000000001

WTF!?

答: Numbers in javascript are stored as floating points - there will be some degree of imprecision - please see linked article, or search this site for floating point arithmetic for many explanations.</p>

ContentLicense: CC BY-SA 2.5

Title: Strange sum problem

Body:
Possible Duplicate:

  Elegant workaround for JavaScript floating point number problem

var sum = 0;
$('[id$=percentOfTotalEditor]').each(
    function () {
        var igEditor = $find(this.id);
        var value = igEditor.get_value();
        sum += value;
    }
);

Then you'll see the magic:

sum == 1.1, value == 0.1. But after sum += value, sum == 1.2000000000000001

WTF!?


问:
Rolling a dice and calculating frequency
my goal is to create a dice rolling simulator where the users enters, "number of rolls, "sides on die", and amount of trials. Part of my code (the lower half about error and such are used from an class example). I need help on getting the relative frequency and experimental probability. Also the professor noted that to receive the same numbers as his, the random number generator uses the integer 237. Thank you.

```<code>import random

# Sets the number of faces on the dice we are rolling
# Set to 6 for a 6-sided dice, 20 for a 20-sided dice, etc
NumberOfFaces = int(input("How many sides?:"))

face = [] # create a list
# Set the number of elements in the list
for x in range(0, NumberOfFaces):
  face.append(0)

NumberOfRolls = int(input("How many rolls?:"))

for y in range(0, NumberOfRolls):
  # roll the dice with randrange, and then add one to that element of the list
  face[random.randrange(0, NumberOfFaces)] += 1

numberOfTrials = int(input('How many trials? Enter:'))

# print out how many times each face came up
for z in range(0, NumberOfFaces):
    frequency = (("%d: %d") % (z+1,face[z]))
    #print(frequency)

relativeFrequency = [0, 0]
probability = [0,0]
error = [0,0]
for i in range(2, len(frequency)):
   relativeFrequency.append(frequency/numberOfTrials)
   probability.append(min(i-1,13-i)/36)
   error.append(abs(probability[i]-relativeFrequency[i]))
# end for

#print(relativeFrequency)
#print(probability)
#print(error)
print()

# print results
f1 = "{0:<10}{1:<22}{2:<22}{3:<22}"
f2 = 71*"-"
f3 = "{0:>3}       {1:<22.15f}{2:<22.15f}{3:<.15f}"
print(f1.format("Sum","Relative Frequency","Probability","Error"))
print(f2)
for i in range(2, len(frequency)):
   print(f3.format(i, relativeFrequency[i], probability[i], error[i]))
#end for
print()
</code>```

My desired output

```<code>Enter the number of dice: -1
The number of dice must be at least 1
Please enter the number of dice: 4
Enter the number of sides on each die: 1
The number of sides on each die must be at least 2
Please enter the number of sides on each die: 7
Enter the number of trials to perform: -1
The number of trials must be at least 1
Please enter the number of trials to perform: 10000
Sum Frequency Relative Frequency Experimental Probability
----------------------------------------------------------------------
 4 6 0.00060 0.06 %
 5 18 0.00180 0.18 %
 6 52 0.00520 0.52 %
 7 83 0.00830 0.83 %
 8 166 0.01660 1.66 %
 9 273 0.02730 2.73 %
 10 346 0.03460 3.46 %
 11 469 0.04690 4.69 %
 12 630 0.06300 6.30 %
 13 738 0.07380 7.38 %
 14 836 0.08360 8.36 %
 15 930 0.09300 9.30 %
 16 930 0.09300 9.30 %
 17 985 0.09850 9.85 %
 18 844 0.08440 8.44 %
 19 737 0.07370 7.37 %
 20 589 0.05890 5.89 %
 21 526 0.05260 5.26 %
 22 326 0.03260 3.26 %
 23 238 0.02380 2.38 %
 24 124 0.01240 1.24 %
 25 86 0.00860 0.86 %
 26 49 0.00490 0.49 %
 27 13 0.00130 0.13 %
 28 6 0.00060 0.06 %
</code>```

Here is a link to the picture for accurate look of it

Desired Output

答:
You need to understand the difference between "expected" and "observed". If the random number generator is supposedly uniform, we expect each die to be fair. Assuming more than one die and the results added, expected distribution is a bell curve. The formula is given by our mathematical cousins, here

https://math.stackexchange.com/questions/1010729/when-rolling-multiple-dice-what-is-the-average-value-if-you-only-keep-the-highe

It's a bit tricker than elementary maths, but not all that complicated.

To test if the trial is fair, you need to do a chi-squared tested between observed and expected results.

Body:
my goal is to create a dice rolling simulator where the users enters, "number of rolls, "sides on die", and amount of trials. Part of my code (the lower half about error and such are used from an class example). I need help on getting the relative frequency and experimental probability. Also the professor noted that to receive the same numbers as his, the random number generator uses the integer 237. Thank you.

import random

# Sets the number of faces on the dice we are rolling
# Set to 6 for a 6-sided dice, 20 for a 20-sided dice, etc
NumberOfFaces = int(input("How many sides?:"))

face = [] # create a list
# Set the number of elements in the list
for x in range(0, NumberOfFaces):
  face.append(0)

NumberOfRolls = int(input("How many rolls?:"))

for y in range(0, NumberOfRolls):
  # roll the dice with randrange, and then add one to that element of the list
  face[random.randrange(0, NumberOfFaces)] += 1

numberOfTrials = int(input('How many trials? Enter:'))

# print out how many times each face came up
for z in range(0, NumberOfFaces):
    frequency = (("%d: %d") % (z+1,face[z]))
    #print(frequency)

relativeFrequency = [0, 0]
probability = [0,0]
error = [0,0]
for i in range(2, len(frequency)):
   relativeFrequency.append(frequency/numberOfTrials)
   probability.append(min(i-1,13-i)/36)
   error.append(abs(probability[i]-relativeFrequency[i]))
# end for

#print(relativeFrequency)
#print(probability)
#print(error)
print()

# print results
f1 = "{0:<10}{1:<22}{2:<22}{3:<22}"
f2 = 71*"-"
f3 = "{0:>3}       {1:<22.15f}{2:<22.15f}{3:<.15f}"
print(f1.format("Sum","Relative Frequency","Probability","Error"))
print(f2)
for i in range(2, len(frequency)):
   print(f3.format(i, relativeFrequency[i], probability[i], error[i]))
#end for
print()

My desired output

Enter the number of dice: -1
The number of dice must be at least 1
Please enter the number of dice: 4
Enter the number of sides on each die: 1
The number of sides on each die must be at least 2
Please enter the number of sides on each die: 7
Enter the number of trials to perform: -1
The number of trials must be at least 1
Please enter the number of trials to perform: 10000
Sum Frequency Relative Frequency Experimental Probability
----------------------------------------------------------------------
 4 6 0.00060 0.06 %
 5 18 0.00180 0.18 %
 6 52 0.00520 0.52 %
 7 83 0.00830 0.83 %
 8 166 0.01660 1.66 %
 9 273 0.02730 2.73 %
 10 346 0.03460 3.46 %
 11 469 0.04690 4.69 %
 12 630 0.06300 6.30 %
 13 738 0.07380 7.38 %
 14 836 0.08360 8.36 %
 15 930 0.09300 9.30 %
 16 930 0.09300 9.30 %
 17 985 0.09850 9.85 %
 18 844 0.08440 8.44 %
 19 737 0.07370 7.37 %
 20 589 0.05890 5.89 %
 21 526 0.05260 5.26 %
 22 326 0.03260 3.26 %
 23 238 0.02380 2.38 %
 24 124 0.01240 1.24 %
 25 86 0.00860 0.86 %
 26 49 0.00490 0.49 %
 27 13 0.00130 0.13 %
 28 6 0.00060 0.06 %

Here is a link to the picture for accurate look of it

Desired Output


问:
Is V() a utility function in Visual Basic?
I'm trying to reverse engineer a calculator made with visual basic. The original author has this function called on a lot of variables that looks like:

```<code>V(Offset)
V(CPX)
V(CAng)
</code>```

I can't find this anywhere in any of the functions that he wrote. But I also don't think this is a utility function in visual basic. Does anyone know what this means?

My best guess is that this is converting the units of the numbers it is called on to a format that is compatible with other numbers.

答: As mentioned by GSerg above, V is not a utility function.</p>

Body:
I'm trying to reverse engineer a calculator made with visual basic. The original author has this function called on a lot of variables that looks like:

V(Offset)
V(CPX)
V(CAng)

I can't find this anywhere in any of the functions that he wrote. But I also don't think this is a utility function in visual basic. Does anyone know what this means?

My best guess is that this is converting the units of the numbers it is called on to a format that is compatible with other numbers.


问:
Extracting vertices from scenekit
I'm having a problem with understanding scenekit geometery.

I have the default cube from Blender, and I export as collada (DAE), and can bring it into scenekit.... all good.

Now I want to see the vertices for the cube.  In the DAE I can see the following for the "Cube-mesh-positions-array",

"1 1 -1 1 -1 -1 -1 -0.9999998 -1 -0.9999997 1 -1 1 0.9999995 1 0.9999994 -1.000001 1 -1 -0.9999997 1 -1 1 1"

Now what I'd like to do in scenekit, is get the vertices back, using something like the following:

```<code>SCNGeometrySource *vertexBuffer = [[cubeNode.geometry geometrySourcesForSemantic:SCNGeometrySourceSemanticVertex] objectAtIndex:0];
</code>```

If I process the vertexBuffer (I've tried numerous methods of looking at the data), it doesn't seem correct.

Can somebody explain what "SCNGeometrySourceSemanticVertex" is giving me, and how to extract the vertex data properly?  What I'd like to see is:

```<code>X = "float"
Y = "float"
Z = "float"
</code>```

Also I was investigating the following class / methods, which looked promising (some good data values here), but the data from gmpe appears empty, is anybody able to explain what the data property of "SCNGeometryElement" contains?

```<code>SCNGeometryElement *gmpe = [theCurrentNode.geometry geometryElementAtIndex:0];
</code>```

Thanks, assistance much appreciated,

D

答:
With swift 3.1 you can extract vertices from SCNGeometry in a much faster and shorter way:

```<code>func vertices(node:SCNNode) -> [SCNVector3] {
    let vertexSources = node.geometry?.getGeometrySources(for: SCNGeometrySource.Semantic.vertex)
    if let vertexSource = vertexSources?.first {
        let count = vertexSource.data.count / MemoryLayout<SCNVector3>.size
        return vertexSource.data.withUnsafeBytes {
            [SCNVector3](UnsafeBufferPointer<SCNVector3>(start: $0, count: count))
        }
    }
    return []
}
</code>```

...
Today i've noted that on osx this not going to work correct. This happens because on iOS SCNVector3 build with Float and on osx CGFloat (only apple good do smth simple so suffering). So I had to tweak the code for osx but this not gonna work as fast as on iOS.

```<code>func vertices() -> [SCNVector3] {

        let vertexSources = sources(for: SCNGeometrySource.Semantic.vertex)

        if let vertexSource = vertexSources.first {

        let count = vertexSource.vectorCount * 3
        let values = vertexSource.data.withUnsafeBytes {
            [Float](UnsafeBufferPointer<Float>(start: $0, count: count))
        }

        var vectors = [SCNVector3]()
        for i in 0..<vertexSource.vectorCount {
            let offset = i * 3
            vectors.append(SCNVector3Make(
                CGFloat(values[offset]),
                CGFloat(values[offset + 1]),
                CGFloat(values[offset + 2])
            ))
        }

        return vectors
    }
    return []
}
</code>```

Title: Extracting vertices from scenekit

Body:
I'm having a problem with understanding scenekit geometery.

I have the default cube from Blender, and I export as collada (DAE), and can bring it into scenekit.... all good.

Now I want to see the vertices for the cube.  In the DAE I can see the following for the "Cube-mesh-positions-array",

"1 1 -1 1 -1 -1 -1 -0.9999998 -1 -0.9999997 1 -1 1 0.9999995 1 0.9999994 -1.000001 1 -1 -0.9999997 1 -1 1 1"

Now what I'd like to do in scenekit, is get the vertices back, using something like the following:

SCNGeometrySource *vertexBuffer = [[cubeNode.geometry geometrySourcesForSemantic:SCNGeometrySourceSemanticVertex] objectAtIndex:0];

If I process the vertexBuffer (I've tried numerous methods of looking at the data), it doesn't seem correct.

Can somebody explain what "SCNGeometrySourceSemanticVertex" is giving me, and how to extract the vertex data properly?  What I'd like to see is:

X = "float"
Y = "float"
Z = "float"

Also I was investigating the following class / methods, which looked promising (some good data values here), but the data from gmpe appears empty, is anybody able to explain what the data property of "SCNGeometryElement" contains?

SCNGeometryElement *gmpe = [theCurrentNode.geometry geometryElementAtIndex:0];

Thanks, assistance much appreciated,

D

Body:
With swift 3.1 you can extract vertices from SCNGeometry in a much faster and shorter way:

func vertices(node:SCNNode) -> [SCNVector3] {
    let vertexSources = node.geometry?.getGeometrySources(for: SCNGeometrySource.Semantic.vertex)
    if let vertexSource = vertexSources?.first {
        let count = vertexSource.data.count / MemoryLayout<SCNVector3>.size
        return vertexSource.data.withUnsafeBytes {
            [SCNVector3](UnsafeBufferPointer<SCNVector3>(start: $0, count: count))
        }
    }
    return []
}

...
Today i've noted that on osx this not going to work correct. This happens because on iOS SCNVector3 build with Float and on osx CGFloat (only apple good do smth simple so suffering). So I had to tweak the code for osx but this not gonna work as fast as on iOS.

func vertices() -> [SCNVector3] {

        let vertexSources = sources(for: SCNGeometrySource.Semantic.vertex)

        if let vertexSource = vertexSources.first {

        let count = vertexSource.vectorCount * 3
        let values = vertexSource.data.withUnsafeBytes {
            [Float](UnsafeBufferPointer<Float>(start: $0, count: count))
        }

        var vectors = [SCNVector3]()
        for i in 0..<vertexSource.vectorCount {
            let offset = i * 3
            vectors.append(SCNVector3Make(
                CGFloat(values[offset]),
                CGFloat(values[offset + 1]),
                CGFloat(values[offset + 2])
            ))
        }

        return vectors
    }
    return []
}


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
This answer assumes that you're using Oracle.

The way to solve this is to create a resultset that contains all of the numbers in your range, then join to that. The way to do this is to use a recursive query:

```<code>SELECT     LEVEL AS x
FROM       DUAL
CONNECT BY LEVEL <= 999999
</code>```

CONNECT BY is Oracle-specific syntax that tells the query to run recursively as long as the predicate is true. level is a pseudo-column that only exists in queries that use CONNECT BY that indicates the level of recursion. The end result is that this query will run the query against dual 999,999 times, each time being a level deeper in the recursion.

Given this method of generating numbers, plugging it into the query you tried earlier is pretty trivial:

```<code>SELECT MIN (x)
FROM   (SELECT     LEVEL AS x
        FROM       DUAL
        CONNECT BY LEVEL <= 999999)
WHERE  x NOT IN (SELECT ag_trnid
                 FROM   ps_training
                 WHERE  ag_trnid = x)
</code>```

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce

Body:
This answer assumes that you're using Oracle.

The way to solve this is to create a resultset that contains all of the numbers in your range, then join to that. The way to do this is to use a recursive query:

SELECT     LEVEL AS x
FROM       DUAL
CONNECT BY LEVEL <= 999999

CONNECT BY is Oracle-specific syntax that tells the query to run recursively as long as the predicate is true. level is a pseudo-column that only exists in queries that use CONNECT BY that indicates the level of recursion. The end result is that this query will run the query against dual 999,999 times, each time being a level deeper in the recursion.

Given this method of generating numbers, plugging it into the query you tried earlier is pretty trivial:

SELECT MIN (x)
FROM   (SELECT     LEVEL AS x
        FROM       DUAL
        CONNECT BY LEVEL <= 999999)
WHERE  x NOT IN (SELECT ag_trnid
                 FROM   ps_training
                 WHERE  ag_trnid = x)


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
I would do it with a Regex : </p>

```<code>if(s.matches("[0-9]"))
{
    //it's an Integer,
    //execute logic
}
</code>```

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

Body:
I would do it with a Regex :

if(s.matches("[0-9]"))
{
    //it's an Integer,
    //execute logic
}


问:
Why does objective-c not have API availability checking?
Swift 2 have API availability checking.

The compiler will give you an error when using an API too new for your
  minimum target OS

Why can't the objective-c compiler do the equivalent?

I googled objective c API availability checking and only swift 2 results came out so I assume the compiler for objective c can't do that.

答:
Xcode 9.0 brings the runtime availability checking syntax from Swift to Objective-C:

```<code>if (@available(macOS 10.9, *))
{
// call 10.9+ API
}
else
{
// fallback code
}
</code>```

this comes complete with warnings for calling APIs that are newer than your deployment target (if those calls are not wrapped in checks).

finally ;)

Body:
Xcode 9.0 brings the runtime availability checking syntax from Swift to Objective-C:

if (@available(macOS 10.9, *))
{
// call 10.9+ API
}
else
{
// fallback code
}

this comes complete with warnings for calling APIs that are newer than your deployment target (if those calls are not wrapped in checks).

finally ;)


问:
Low level caching in rails 4
I have two models Employee and Organization

```<code>class Employee < ActiveRecord::Base
  belongs_to :organization, touch: true
end

class Organization < ActiveRecord::Base
  has_many :employees
end
</code>```

There is a form which is used to search the employees.

The search query is based on first_name, last_name and emp_id.

I am trying to implement Low-Level Caching

In Employee Controller

```<code>def list_employees
  first_name = params[:employee][:first_name]
  last_name  = params[:employee][:last_name]
  emp_id     = params[:employee][:emp_id]
  @employees = Employee.all_employees(first_name,last_name,emp_id)
end
</code>```

In Employee Model

```<code>def self.all_employees(first_name,last_name,emp_id)
  cache_key = "#{first_name}-#{last_name}-#{emp_id}"
  Rails.cache.fetch("#{cache_key}", expires_in: 5.minutes) do
    Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{emp_id}%")
  end
end
</code>```

But i cant see any difference each time its querying again. I can see data
Rails.cache.fetch("cache_keys") from console even here its querying to employee table.

First time when i query it takes 500ms
Second time same query it takes  490ms (not serving from cache)

Let me know what i am doing wrong.

Thanks in advance

答:
This is what you store as your cached value:

```<code>Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{emp_id}%")
</code>```

This is not a list of employees, this is only information on how to find the employees. So when you later retrieve this object from the cache, you run the query every time, to get the employees.

Run the query when caching, by appending .to_a to that. This will return an array of employees, which is what you want to cache.

Title: Low level caching in rails 4

Body:
I have two models Employee and Organization

class Employee < ActiveRecord::Base
  belongs_to :organization, touch: true
end

class Organization < ActiveRecord::Base
  has_many :employees
end

There is a form which is used to search the employees.

The search query is based on first_name, last_name and emp_id.

I am trying to implement Low-Level Caching

In Employee Controller

def list_employees
  first_name = params[:employee][:first_name]
  last_name  = params[:employee][:last_name]
  emp_id     = params[:employee][:emp_id]
  @employees = Employee.all_employees(first_name,last_name,emp_id)
end

In Employee Model

def self.all_employees(first_name,last_name,emp_id)
  cache_key = "#{first_name}-#{last_name}-#{emp_id}"
  Rails.cache.fetch("#{cache_key}", expires_in: 5.minutes) do
    Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{emp_id}%")
  end
end

But i cant see any difference each time its querying again. I can see data
Rails.cache.fetch("cache_keys") from console even here its querying to employee table.

First time when i query it takes 500ms
Second time same query it takes  490ms (not serving from cache)

Let me know what i am doing wrong.

Thanks in advance

Body:
This is what you store as your cached value:

Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{emp_id}%")

This is not a list of employees, this is only information on how to find the employees. So when you later retrieve this object from the cache, you run the query every time, to get the employees.

Run the query when caching, by appending .to_a to that. This will return an array of employees, which is what you want to cache.


问:
Android Spinner value and text
Hello I have question about android spinner

I have spinner which is populated by array.The array is Country name and Country phone code on every row

Part of the array

```<code><item>355  Albania</item>
<item>213  Algeria</item>
<item>376  Andorra</item>
<item>244  Angola</item>
<item>1264  Anguilla</item>
<item>1268  Antigua and Barbuda</item>
<item>54  Argentina</item>
</code>```

This is my java code for populating the spinner

```<code>final Spinner spnCountry = (Spinner) findViewById(R.id.countries);
ArrayAdapter<CharSequence> adpCountry = ArrayAdapter.createFromResource(
        this, R.array.countries, android.R.layout.simple_spinner_item);
adpCountry
    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountry.setAdapter(adpCountry);
</code>```

I want to show only country code on the box and when the spinner is opened to show country name and code on every row.

Can someone help me how to do that?

答:
Loading the Spinner;

```<code>String[] countries = getResources().getStringArray(R.array.countries);

ArrayAdapter<String> adpCountry = new ArrayAdapter<String>();
for(String country : countries)
{
    String parts = country.split(" ");
    String code = parts[0];

    adpCountry.addItem(code);
}

adpCountry.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountry.setAdapter(adpCountry);
</code>```

Selecting an item;

```<code>spnCountry.setOnItemSelectedListener(new OnItemSelectedListener()
{
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int index, long arg3)
    {
        String country = "";
        String[] countries = getResources().getStringArray(R.array.countries);

        String selected = countries[index];
        String[] parts = selected.split(" ");
        for(String part : parts)
        {
            country += part;
        }

        TextView txtName = findViewById(R.id.country_name);
        txtName.setText(country);
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0){ /* Unused */ }
});
</code>```

(out of heart)

ContentLicense: CC BY-SA 4.0

Title: Android Spinner value and text

Body:
Hello I have question about android spinner

I have spinner which is populated by array.The array is Country name and Country phone code on every row

Part of the array

<item>355  Albania</item>
<item>213  Algeria</item>
<item>376  Andorra</item>
<item>244  Angola</item>
<item>1264  Anguilla</item>
<item>1268  Antigua and Barbuda</item>
<item>54  Argentina</item>

This is my java code for populating the spinner

final Spinner spnCountry = (Spinner) findViewById(R.id.countries);
ArrayAdapter<CharSequence> adpCountry = ArrayAdapter.createFromResource(
        this, R.array.countries, android.R.layout.simple_spinner_item);
adpCountry
    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountry.setAdapter(adpCountry);

I want to show only country code on the box and when the spinner is opened to show country name and code on every row.

Can someone help me how to do that?

Body:
Loading the Spinner;

String[] countries = getResources().getStringArray(R.array.countries);

ArrayAdapter<String> adpCountry = new ArrayAdapter<String>();
for(String country : countries)
{
    String parts = country.split(" ");
    String code = parts[0];

    adpCountry.addItem(code);
}

adpCountry.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountry.setAdapter(adpCountry);

Selecting an item;

spnCountry.setOnItemSelectedListener(new OnItemSelectedListener()
{
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int index, long arg3)
    {
        String country = "";
        String[] countries = getResources().getStringArray(R.array.countries);

        String selected = countries[index];
        String[] parts = selected.split(" ");
        for(String part : parts)
        {
            country += part;
        }

        TextView txtName = findViewById(R.id.country_name);
        txtName.setText(country);
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0){ /* Unused */ }
});

(out of heart)


问:
redirect to an external url with request parameters
I need to redirect user to an external url from my java application whenever a button is clicked.

url: https://example.org?x=12345&y=ab

the parameters to be passed in url has to be calculated dynamically. It will be different for different users.

Could any one provide pointers to it?

I am not sure if HttpClient or HttpUrlConnection will do a redirect from my application to the new url

答:
You can just use the following code line :</p>

```<code>response.setHeader("Location", redirectUrl);
</code>```

Body:
You can just use the following code line :

response.setHeader("Location", redirectUrl);


问:
File output manipulation - ideally in one line
Apologies in advance this is my first post, hope you can understand it etc.

Original File

```<code>cat trail
PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global
    forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

vi and :set list

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global                    $
    forked child process 31522922$
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global                    $
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown $

cat trail | oc -d
0226220                        G   l   o   b   a   l
0226240                                                               \n
0226260                                    f   o   r   k   e   d       c
0226300    h   i   l   d       p   r   o   c   e   s   s       3   1   5
0226320    2   2   9   2   2  \n   P   R   O   C   _   E   x   e   c   u
0226340    t   e                   r   o   o   t                       O
0226360    K                                           M   o   n       J
0226400    u   n       0   5       1   6   :   0   5   :   4   5       2
0226420    0   1   7       a   u   d   i   t
0226440
0226460                    G   l   o   b   a   l
0226500                                                           \n
0226520                                e   u   i   d   :       0       e
0226540    g   i   d   :       0       e   p   r   i   v   :       f   f
0226560    f   f   f   f   f   f   :   f   f   f   f   f   f   f   f
0226600    n   a   m   e       a   u   d   i   t       s   h   u   t   d
0226620    o   w   n      \n
0226625
</code>```

Desired Output

Ideally using some tools that I can pipe the trail file through such as sed/tr/awk etc.

```<code>PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                            Global        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                           Global        euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown
</code>```

or

```<code>PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit       euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown
</code>```

I have manged to just remove the carriage returns and the word Global, but am struggling to just remove the carriage return and /or Global on the lines with Global in.  Thanks in advance.

I have used the following:

```<code>sed 's/Global//g'
tr -d '\n'
</code>```

but was hoping to do it all with sed but couldn't get it to work when trying to remove the carriage returns.

Larger sample of file

```<code>S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 5 filename =
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 3 filename =
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
   euid: 0 egid: 0 epriv: ffffffff:ffffffff name -ksh
PROC_Create     root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
    forked child process 40763616
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 termdef                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name termdef
</code>```

答:
NOTE: Assuming all input consists of 2-line pairs where the second line of a pair is appended to the end of the first line in the pair.

A couple (simplistic) awk examples to get the ball rolling:

```<code>awk '/^[a-zA-Z]/ {printf $0} /^ / {print $0}' trail
</code>```

-or-

```<code>awk '/^[[:alpha:]]/ {printf $0} /^[[:space:]]/ {print $0}' trail
</code>```

First search pattern is looking for a line that has a letter (lower- or upper-case) in the first postion; if found, use printf to output the entire line but without a carriage return at the end.

Second search pattern is looking for a line that as a space in the first position; if found, use print to output the entire line with a carriage return at the end.

Borrowing RavinderSingh13's getline idea to eliminate second search pattern:

```<code>awk '/^[[:alpha:]]/ {printf $0 ; getline ; print}' trail
</code>```

For each line that starts with a character use printf to output entire line without a carriage return, read next line, print entire line with a carriage return at the end.

Body:
Apologies in advance this is my first post, hope you can understand it etc.

Original File

cat trail
PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global
    forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

vi and :set list

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global                    $
    forked child process 31522922$
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global                    $
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown $

cat trail | oc -d
0226220                        G   l   o   b   a   l
0226240                                                               \n
0226260                                    f   o   r   k   e   d       c
0226300    h   i   l   d       p   r   o   c   e   s   s       3   1   5
0226320    2   2   9   2   2  \n   P   R   O   C   _   E   x   e   c   u
0226340    t   e                   r   o   o   t                       O
0226360    K                                           M   o   n       J
0226400    u   n       0   5       1   6   :   0   5   :   4   5       2
0226420    0   1   7       a   u   d   i   t
0226440
0226460                    G   l   o   b   a   l
0226500                                                           \n
0226520                                e   u   i   d   :       0       e
0226540    g   i   d   :       0       e   p   r   i   v   :       f   f
0226560    f   f   f   f   f   f   :   f   f   f   f   f   f   f   f
0226600    n   a   m   e       a   u   d   i   t       s   h   u   t   d
0226620    o   w   n      \n
0226625

Desired Output

Ideally using some tools that I can pipe the trail file through such as sed/tr/awk etc.

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                            Global        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                           Global        euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

or

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit       euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

I have manged to just remove the carriage returns and the word Global, but am struggling to just remove the carriage return and /or Global on the lines with Global in.  Thanks in advance.

I have used the following:

sed 's/Global//g'
tr -d '\n'

but was hoping to do it all with sed but couldn't get it to work when trying to remove the carriage returns.

Larger sample of file

S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 5 filename =
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 3 filename =
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
   euid: 0 egid: 0 epriv: ffffffff:ffffffff name -ksh
PROC_Create     root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
    forked child process 40763616
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 termdef                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name termdef

Body:
NOTE: Assuming all input consists of 2-line pairs where the second line of a pair is appended to the end of the first line in the pair.

A couple (simplistic) awk examples to get the ball rolling:

awk '/^[a-zA-Z]/ {printf $0} /^ / {print $0}' trail

-or-

awk '/^[[:alpha:]]/ {printf $0} /^[[:space:]]/ {print $0}' trail

First search pattern is looking for a line that has a letter (lower- or upper-case) in the first postion; if found, use printf to output the entire line but without a carriage return at the end.

Second search pattern is looking for a line that as a space in the first position; if found, use print to output the entire line with a carriage return at the end.

Borrowing RavinderSingh13's getline idea to eliminate second search pattern:

awk '/^[[:alpha:]]/ {printf $0 ; getline ; print}' trail

For each line that starts with a character use printf to output entire line without a carriage return, read next line, print entire line with a carriage return at the end.


问:
how to consume hapi.js rest response within a route
The hapi.js server i am running are distributed into two ports.
on port 4000

i am running the following server

var handlebars = require("handlebars");
var Vision =require('vision');
var Inert = require('inert');
var Wreck = require('wreck');
var mongo = require('mongoskin');
var fs = require("fs");
var db = mongo.db("mongodb://localhost:27017/connect_db", {native_parser:true});
var ObjectID = mongo.ObjectID;

// Create a server with a host and port
exports.register = function (server, options , next ) {
//register view engine
server.register(Vision);
server.register(Inert);

server.views({
    engines: {
        'html': handlebars
    },
    relativeTo :__dirname,
    path: 'views',
    isCached: false
   });

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        db.collection("hello_collection").find().toArray(function(err, items) {
           var body = {title: items};
          reply.view('index.html', body);
          db.close();
       });
    }
});
server.route({
    method: 'GET',
    path: '/edit',
    handler: function (request, reply) {
    var params = request.query.id;
    db.collection("hello_collection").find({"_id":ObjectID(params)}).toArray(function(err, items) {

            reply.view('edit.html',items[0]);

                    db.close();
       });;

    }
});

server.route({
    method: 'GET',
    path: '/delete',
    handler: function (request, reply) {
        var params = request.query.id;
 db.collection("hello_collection").remove({ "_id": ObjectID(params)});
        db.close();
        reply().redirect("/");
    }

});

server.route({
    method: 'POST',
    path: '/new_data',
    handler: function (request, reply) {
    var data = request.payload;
     db.collection("hello_collection").insert( { name: data.name, description: data.description, content: data.content  } );

    db.close();
    reply().redirect("/");

    }
});
server.route({
    method: 'POST',
    path: '/edit_data',
    handler: function (request, reply) {
    var data = request.payload;
    db.collection('hello_collection').update({ "_id" : ObjectID(data.id) },{$set: { name : data.name, description : data.description , content : data.content } }
);
    db.close();
    reply().redirect("/");

    }
});

server.route({
  method: "GET",
  path: "/bower_components/{path1}/{path2}",
  handler: function (request, reply) {
    var Path = "./web/bower_components/" + request.params.path1  +"/" + request.params.path2;
    console.log(Path);
    reply.file(Path);
  }
});

  return next();
};

exports.register.attributes = { name: 'web' };```
</div>
</div>
</p>

<p>on the port 5000 i am running the following api response</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var handlebars = require("handlebars");
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/connect_db", {native_parser:true});
var ObjectID = mongo.ObjectID;
exports.register = function (server , options , next){
 server.route({
  method: 'GET',
  path: '/retrieve',
  handler : function(request, reply) {
      if(!request.query.id){

   db.collection("hello_collection").find({}).toArray(function(err, items){

     reply(items);
    db.close();
   });

       }
      else{
    var params = request.query.id;
       db.collection("hello_collection").find({"_id":ObjectID(params)}).toArray(function(err, items) {

                reply(items[0]);

                    db.close();
       });

      }

  }

 });
return next();
};
exports.register.attributes = { name : 'api'};</code>```

my question is, how do i read the data from the url http://localhost:5000/retrieve to the url http://localhost:4000 .
I have tried to use wreck but it is not working

答:
Try request:</p>

```<code>Request("http://localhost:5000/retrieve", function(err, res, body){
   console.log(res.body);
});
</code>```

Body:
The hapi.js server i am running are distributed into two ports.
on port 4000

i am running the following server

var handlebars = require("handlebars");
var Vision =require('vision');
var Inert = require('inert');
var Wreck = require('wreck');
var mongo = require('mongoskin');
var fs = require("fs");
var db = mongo.db("mongodb://localhost:27017/connect_db", {native_parser:true});
var ObjectID = mongo.ObjectID;

// Create a server with a host and port
exports.register = function (server, options , next ) {
//register view engine
server.register(Vision);
server.register(Inert);

server.views({
    engines: {
        'html': handlebars
    },
    relativeTo :__dirname,
    path: 'views',
    isCached: false
   });

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        db.collection("hello_collection").find().toArray(function(err, items) {
           var body = {title: items};
          reply.view('index.html', body);
          db.close();
       });
    }
});
server.route({
    method: 'GET',
    path: '/edit',
    handler: function (request, reply) {
    var params = request.query.id;
    db.collection("hello_collection").find({"_id":ObjectID(params)}).toArray(function(err, items) {

            reply.view('edit.html',items[0]);

                    db.close();
       });;

    }
});

server.route({
    method: 'GET',
    path: '/delete',
    handler: function (request, reply) {
        var params = request.query.id;
 db.collection("hello_collection").remove({ "_id": ObjectID(params)});
        db.close();
        reply().redirect("/");
    }

});

server.route({
    method: 'POST',
    path: '/new_data',
    handler: function (request, reply) {
    var data = request.payload;
     db.collection("hello_collection").insert( { name: data.name, description: data.description, content: data.content  } );

    db.close();
    reply().redirect("/");

    }
});
server.route({
    method: 'POST',
    path: '/edit_data',
    handler: function (request, reply) {
    var data = request.payload;
    db.collection('hello_collection').update({ "_id" : ObjectID(data.id) },{$set: { name : data.name, description : data.description , content : data.content } }
);
    db.close();
    reply().redirect("/");

    }
});

server.route({
  method: "GET",
  path: "/bower_components/{path1}/{path2}",
  handler: function (request, reply) {
    var Path = "./web/bower_components/" + request.params.path1  +"/" + request.params.path2;
    console.log(Path);
    reply.file(Path);
  }
});

  return next();
};

exports.register.attributes = { name: 'web' };

on the port 5000 i am running the following api response

var handlebars = require("handlebars");
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/connect_db", {native_parser:true});
var ObjectID = mongo.ObjectID;
exports.register = function (server , options , next){
 server.route({
  method: 'GET',
  path: '/retrieve',
  handler : function(request, reply) {
      if(!request.query.id){

   db.collection("hello_collection").find({}).toArray(function(err, items){

     reply(items);
    db.close();
   });

       }
      else{
    var params = request.query.id;
       db.collection("hello_collection").find({"_id":ObjectID(params)}).toArray(function(err, items) {

                reply(items[0]);

                    db.close();
       });

      }

  }

 });
return next();
};
exports.register.attributes = { name : 'api'};

my question is, how do i read the data from the url http://localhost:5000/retrieve to the url http://localhost:4000 .
I have tried to use wreck but it is not working

Body:
Try request:

Request("http://localhost:5000/retrieve", function(err, res, body){
   console.log(res.body);
});


问:
PHP save to file script giving errors after upgrade to PHP 7.0
I have rather simple script that is supposed to add new line of string to a file.

```<code>if (isset($_POST["score"]))
{
$myFile = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);

$File = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$Handle = fopen($File, 'w');
$Data = $_POST["score"]."\n".$theData;
fwrite($Handle, $Data);
fclose($Handle);
}
</code>```

After upgrading to PHP 7.0 I get errors:

```<code>fread() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 7
fclose() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 8
</code>```

Could anyone explain why this error shows up and how it can be fixed? What is it with PHP 7.0 that caused it suddenly to stop working?

答:
```<code>//First, see if the file exists
if (!is_file($myFile))
{
    die("<b>404 File not found!</b>");
}
</code>```

Or you can try to use The SplFileObject class - an object oriented interface for a file.

Body:
I have rather simple script that is supposed to add new line of string to a file.

if (isset($_POST["score"]))
{
$myFile = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);

$File = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$Handle = fopen($File, 'w');
$Data = $_POST["score"]."\n".$theData;
fwrite($Handle, $Data);
fclose($Handle);
}

After upgrading to PHP 7.0 I get errors:

fread() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 7
fclose() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 8

Could anyone explain why this error shows up and how it can be fixed? What is it with PHP 7.0 that caused it suddenly to stop working?

Body:
//First, see if the file exists
if (!is_file($myFile))
{
    die("<b>404 File not found!</b>");
}

Or you can try to use The SplFileObject class - an object oriented interface for a file.


问:
Feign Client with Spring Boot: RequestParam.value() was empty on parameter 0
I created a simple Feign Client with Spring Boot like this:

```<code>@FeignClient("spring-cloud-eureka-client")
public interface GreetingClient {
    @RequestMapping("/greeting")
    String greeting(@RequestParam String name);
}
</code>```

But when I try just to start an application I get an error:

```<code>java.lang.IllegalStateException: RequestParam.value() was empty on parameter 0
</code>```

First I didn't understand what is the reason and googled a lot but didn't find an answer. Almost excidentely I figured out that it works if to write request param name explicitly:

```<code>@RequestParam("name") String name
</code>```

So my question: is it a bug or could it be configured to not write request params names explicitly?

答:
Both Spring MVC and Spring cloud feign are using the same ParameterNameDiscoverer - named DefaultParameterNameDiscoverer to find parameter name. It tries to find the parameter names with the following step.

First, it uses StandardReflectionParameterNameDiscoverer. It tries to find the variable name with reflection. It is only possible when your classes are compiled with -parameters.

Second, if it fails, it uses LocalVariableTableParameterNameDiscoverer. It tries to find the variable name from the debugging info in the class file with ASM libraries.

The difference between Spring MVC and Feign occurs here. Feign uses above annotations (like @RequestParam) on methods of Java interfaces. But, we use these on methods of Java classes when using Spring MVC. Unfortunately, javac compiler omits the debug information of parameter name from class file for java interfaces. That's why feign fails to find parameter name without -parameter.

Namely, if you compile your code with -parameters, both Spring MVC and Feign will succeed to acquire parameter names. But if you compile without -parameters, only Spring MVC will succeed.

As a result, it's not a bug. it's a limitation of Feign at this moment as I think.

Body:
I created a simple Feign Client with Spring Boot like this:

@FeignClient("spring-cloud-eureka-client")
public interface GreetingClient {
    @RequestMapping("/greeting")
    String greeting(@RequestParam String name);
}

But when I try just to start an application I get an error:

java.lang.IllegalStateException: RequestParam.value() was empty on parameter 0

First I didn't understand what is the reason and googled a lot but didn't find an answer. Almost excidentely I figured out that it works if to write request param name explicitly:

@RequestParam("name") String name

So my question: is it a bug or could it be configured to not write request params names explicitly?


问:
web_reg_save_param_regexp not extracting data
I've just started working with Loadrunner and I wanted to extract some data from a response.I used the  web_reg_save_param_regexp() function to extract some data but would get the error -

Error -35049: No match found for the requested parameter "UserDetails". Check whether the requested regular expression exists in the response data     [MsgId: MERR-35049]

This is just the part of the response data that i need to be extracted.

{"name":"Alice Duval","id":"59"},{"name":"Amadi Aswad","id":"73"},{"name":"Andrew Daley","id":"50"},{"name":"Andrew Keller","id":"89"},

The regular expression I'm using is,
{\"name\":\"(\w+\s+\w+)\"\,\"id\":\"(\d+)\"}
This expression works,I think its the usage thats causing the problem.

```<code>web_reg_save_param_regexp("ParamName=UserDetails",

"RegExp=\{\"name\"\:\"(\w+\s+\w+)\"\,\"id\"\:\"(\d+)\"\}",
SEARCH_FILTERS,
"Scope=Body",
"RequestUrl=*/onboarding/viewTaskTypes*",
"GROUP=1",
 LAST);
 web_url("viewTaskTypes",       "URL=http://peguser.trials621.orangehrmlive.com/onboarding/viewTaskTypes",
        "Resource=0",
        "RecContentType=text/html",         "Referer=http://peguser.trials621.orangehrmlive.com/onboarding/viewTaskTypes",
        "Snapshot=t176.inf",
        "Mode=HTTP",
        LAST);
</code>```

答:
I figured it out. You need double backslash where there is a slash in the RegExp and no slash where there is no special character:</p>

```<code>"RegExp={\"name\":\"(\\w+\\s+\\w+)\",\"id\":\"(\\d+)\"}",
</code>```

Body:
I've just started working with Loadrunner and I wanted to extract some data from a response.I used the  web_reg_save_param_regexp() function to extract some data but would get the error -

Error -35049: No match found for the requested parameter "UserDetails". Check whether the requested regular expression exists in the response data     [MsgId: MERR-35049]

This is just the part of the response data that i need to be extracted.

{"name":"Alice Duval","id":"59"},{"name":"Amadi Aswad","id":"73"},{"name":"Andrew Daley","id":"50"},{"name":"Andrew Keller","id":"89"},

The regular expression I'm using is,
{\"name\":\"(\w+\s+\w+)\"\,\"id\":\"(\d+)\"}
This expression works,I think its the usage thats causing the problem.

web_reg_save_param_regexp("ParamName=UserDetails",

"RegExp=\{\"name\"\:\"(\w+\s+\w+)\"\,\"id\"\:\"(\d+)\"\}",
SEARCH_FILTERS,
"Scope=Body",
"RequestUrl=*/onboarding/viewTaskTypes*",
"GROUP=1",
 LAST);
 web_url("viewTaskTypes",       "URL=http://peguser.trials621.orangehrmlive.com/onboarding/viewTaskTypes",
        "Resource=0",
        "RecContentType=text/html",         "Referer=http://peguser.trials621.orangehrmlive.com/onboarding/viewTaskTypes",
        "Snapshot=t176.inf",
        "Mode=HTTP",
        LAST);

Body:
I figured it out. You need double backslash where there is a slash in the RegExp and no slash where there is no special character:

"RegExp={\"name\":\"(\\w+\\s+\\w+)\",\"id\":\"(\\d+)\"}",


问:
Validate input before Jackson in Spring Boot
I've built a REST endpoint using Spring Boot. JSON is posted to the endpoint. Jackson converts the JSON giving me an object.

The JSON look like this:

```<code>{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-02"
}
</code>```

Jackson converts the JSON to an object based on this class:

```<code>public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}
</code>```

This all works fine. The issue I'm having is that I would like to validate the data before Jackson converts the data. For instance if I post

```<code>{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-40"
}
</code>```

Where parameterDateAdjusted is not a valid date (there is no month with 40 days in it). Jackson converts this to 2017-02-09. One way of getting around this is to have a class that is only strings let's call it ParameterDateInput. Validate each filed with Hibernate Validator in the parameterDateInput object and then copy the parameterDateInput object to parameterDate where each field has the correct type (dates are of type Date and not of type String). This to me doesn't look like a very elegant solution. Is there some other way I can solve this? How is data generally validated in Spring Boot when posted as JSON? I like to be able to send back a message to the user/client what is wrong with the data that is being posted.

答:
There is a way to check the dates. setLenient() method

```<code>public static boolean isValidDate(String inDate, String format) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    dateFormat.setLenient(false);
    try {
      dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
      return false;
    }
    return true;
 }
</code>```

Just define own annotation to validate the value

```<code>@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = MyDateFormatCheckValidator.class)
@Documented
public @interface MyDateFormatCheck {
    String pattern();
...
</code>```

and the validator class

```<code>public class MyDateFormatCheckValidator implements ConstraintValidator<MyDateFormatCheck, String> {

    private MyDateFormatCheck check;
    @Override
    public void initialize(MyDateFormatCheck constraintAnnotation) {
        this.check= constraintAnnotation;
    }

    @Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if ( object == null ) {
            return true;
        }

        return isValidDate(object, check.pattern());
    }
}
</code>```

Body:
I've built a REST endpoint using Spring Boot. JSON is posted to the endpoint. Jackson converts the JSON giving me an object.

The JSON look like this:

{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-02"
}

Jackson converts the JSON to an object based on this class:

public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}

This all works fine. The issue I'm having is that I would like to validate the data before Jackson converts the data. For instance if I post

{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-40"
}

Where parameterDateAdjusted is not a valid date (there is no month with 40 days in it). Jackson converts this to 2017-02-09. One way of getting around this is to have a class that is only strings let's call it ParameterDateInput. Validate each filed with Hibernate Validator in the parameterDateInput object and then copy the parameterDateInput object to parameterDate where each field has the correct type (dates are of type Date and not of type String). This to me doesn't look like a very elegant solution. Is there some other way I can solve this? How is data generally validated in Spring Boot when posted as JSON? I like to be able to send back a message to the user/client what is wrong with the data that is being posted.

Body:
There is a way to check the dates. setLenient() method

public static boolean isValidDate(String inDate, String format) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    dateFormat.setLenient(false);
    try {
      dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
      return false;
    }
    return true;
 }

Just define own annotation to validate the value

@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = MyDateFormatCheckValidator.class)
@Documented
public @interface MyDateFormatCheck {
    String pattern();
...

and the validator class

public class MyDateFormatCheckValidator implements ConstraintValidator<MyDateFormatCheck, String> {

    private MyDateFormatCheck check;
    @Override
    public void initialize(MyDateFormatCheck constraintAnnotation) {
        this.check= constraintAnnotation;
    }

    @Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if ( object == null ) {
            return true;
        }

        return isValidDate(object, check.pattern());
    }
}


问:
Create a polygon filled with a tiled image in c#
I'm creating an application which visualises a picture frame as the user designs it.  To create the frame I am drawing 4 polygons which represent the physical bits of wood and using a TextureBrush to fill it.

This works perfectly well for the left and top edges.  However, for the bottom and right edges this method isn't working.  It appears to me that the TextureBrush is tiling from the point (0,0) on the image and not within the polygon I've drawn.  As a result, the tile doesn't line up with the polygon.  By adjusting the size of the image I can get the tile to line up perfectly.

How do I create an arbitrarily positioned polygon and fill it with a tiled image, starting from the point (0,0) within the polygon, not the canvas?

I'm not attached to FillPolygon and TextureBrush if there is a better solution.

Example

答:
I've just found the answer.  I was playing with adding a BoundingBox to the TextureBrush constructor but I kept getting OutOfMemory exceptions and thought it was me not understanding.  Turns out it's a bug in the .NET framework

http://connect.microsoft.com/VisualStudio/feedback/details/90973/texturebrush-constructor-throws-out-of-memory-exception-when-providing-the-bounding-rectangle

The work around is to use a transformation to move the texture

```<code>var brush = new TextureBrush(new Bitmap(imagefile));

Matrix mtx = brush.Transform;
mtx.Translate(xoffset, 0);
brush.Transform = mtx;
</code>```

Body:
I've just found the answer.  I was playing with adding a BoundingBox to the TextureBrush constructor but I kept getting OutOfMemory exceptions and thought it was me not understanding.  Turns out it's a bug in the .NET framework

http://connect.microsoft.com/VisualStudio/feedback/details/90973/texturebrush-constructor-throws-out-of-memory-exception-when-providing-the-bounding-rectangle

The work around is to use a transformation to move the texture

var brush = new TextureBrush(new Bitmap(imagefile));

Matrix mtx = brush.Transform;
mtx.Translate(xoffset, 0);
brush.Transform = mtx;


问:
How to scrape P tags using beautiful soup
I have managed to scrape a website using the findAll function in beautiful soup with H2 / Class / Div tags. (e.g soup.findAll('div', {'class' : 'price'})
But there is one part of the website that has P tags which I'm not sure how to scrape. It has the below

    Listing history

```<code><p class="top">
    <strong>First listed</strong><br>
            800 on
</code>```

I want the 800 but the Div Class "Sidebar sbt" has several entries on the website as does the p class = top.
Any help would be appreciated

Thanks

答:
You can find the p tags just as you would any other tag using BeautifulSoup:

```<code>>>> from bs4 import BeautifulSoup as BS
>>> with open('html', 'r') as f:
...     soup = BS(f, "lxml")
...
>>> soup.find_all('p', attrs={'class':'top'})
[<p class="top">
<strong>First listed</strong><br/>
            800 on
</p>]
</code>```

using soup.find_all will produce a ResultSet if there is more than one tag. So from there you would do something like:

```<code>>>> p_tags = soup.find_all('p', attrs={'class':'top'})
>>> for tag in p_tags:
...     tag.get_text()
...
'\nFirst listed\n            800 on\n'
</code>```

Body:
I have managed to scrape a website using the findAll function in beautiful soup with H2 / Class / Div tags. (e.g soup.findAll('div', {'class' : 'price'})
But there is one part of the website that has P tags which I'm not sure how to scrape. It has the below

    Listing history

    First listed

            800 on

I want the 800 but the Div Class "Sidebar sbt" has several entries on the website as does the p class = top.
Any help would be appreciated

Thanks

Body:
You can find the p tags just as you would any other tag using BeautifulSoup:

>>> from bs4 import BeautifulSoup as BS
>>> with open('html', 'r') as f:
...     soup = BS(f, "lxml")
...
>>> soup.find_all('p', attrs={'class':'top'})
[<p class="top">
<strong>First listed</strong><br/>
            800 on
</p>]

using soup.find_all will produce a ResultSet if there is more than one tag. So from there you would do something like:

>>> p_tags = soup.find_all('p', attrs={'class':'top'})
>>> for tag in p_tags:
...     tag.get_text()
...
'\nFirst listed\n            800 on\n'


问:
Stream over a List of Map and collect specific key
This is my List:

```<code>[
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];
</code>```

I want to pluck name values and create another List like this:

```<code>["moe", "larry", "curly"]
</code>```

I've written this code and it works:

```<code>List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}
</code>```

But how to do it in using stream. I've tried this code which doesn't work.

```<code>List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());
</code>```

答:
If list from your iterator has type of Map<String, Object> then I think that the best way to do that task is just invoke method keySet() which will return Set but you can create ArrayList from it in the following way:

```<code>List<String> result = new ArrayList(list.keySet());
</code>```

Body:
This is my List:

[
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];

I want to pluck name values and create another List like this:

["moe", "larry", "curly"]

I've written this code and it works:

List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}

But how to do it in using stream. I've tried this code which doesn't work.

List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());

Body:
If list from your iterator has type of Map<String, Object> then I think that the best way to do that task is just invoke method keySet() which will return Set but you can create ArrayList from it in the following way:

List<String> result = new ArrayList(list.keySet());


问:
How to turn off BIGINT primary keys in Rails 5.1
Rails 5.1 migrations generates BIGINT (instead of Integer) for tables' primary keys (changelog).

Is it possible to disable that somewhere in the config? If so, how to do disable it?

答:
According to pull request, no this is not possible on config level.
But you can, in fact, force id to be integer, like this:

```<code>create_table :users, id: :integer do
</code>```

On the other hand, you must be aware that changes also affected references behavior, so you should be careful with those:

```<code>t.references :orders, type: :integer
</code>```

Seeing as this is too much repeated code, I suggest you write helpers for this, override default methods, or be very radical and fork your database adapter, changing this in it as you like. I'd go with the second option:

Create anonymous modules for Migration[5.0] and ActiveRecord::ConnectionAdapters::TableDefinition

Define create_table, add_reference, add_belongs_to in first one, references and belongs_to in second one (belongs_to ones should be just aliases of references)

In those methods just modify options and call super. Don't forget to handle signatures!

Prepending those modules to their respective classes will handle
everything for you.

You can go even better and do this for their removal counterparts too.

Body:
According to pull request, no this is not possible on config level.
But you can, in fact, force id to be integer, like this:

create_table :users, id: :integer do

On the other hand, you must be aware that changes also affected references behavior, so you should be careful with those:

t.references :orders, type: :integer

Seeing as this is too much repeated code, I suggest you write helpers for this, override default methods, or be very radical and fork your database adapter, changing this in it as you like. I'd go with the second option:

Create anonymous modules for Migration[5.0] and ActiveRecord::ConnectionAdapters::TableDefinition

Define create_table, add_reference, add_belongs_to in first one, references and belongs_to in second one (belongs_to ones should be just aliases of references)

In those methods just modify options and call super. Don't forget to handle signatures!

Prepending those modules to their respective classes will handle
everything for you.

You can go even better and do this for their removal counterparts too.


问:
Unable to copy link when long pressing in UIWebView
The sharing action sheet comes up, I can select Open, Add to Reading List, Copy, Share.. but none of the buttons work. For instance, when I tap copy, Pasteboard does not receive the URL.

The URL is correctly displayed in the action sheet. Any ideas? Perhaps I forgot to implement a delegate or so..?

答:
Please add some code snippets for better understanding of your problem. Also if you are trying to select text in a webview make sure

document.body.style.webkitTouchCallout

is not equal to "none".


问:
What's really happening inside getchar() and printf()? Explain whole process
I was learning from geeksforgeeks and when i saw this, a thought came in my mind that as getchar() and other similar functions returns an int(whether due to failure of program or EOF) then why format specifier used is %c, why not %d(or %i).

```<code>// Example for getchar() in C
#include <stdio.h>
int main()
{
   printf("%c", getchar());
   return 0;
}
</code>```

I know that the character we input in is a character and it is taken by the function getchar() and we are displaying it using %c.

But my problem is what's actually happening inside getchar() and printf() during the whole process, where getchar() is returning that integer, where it is getting stored and how the character we inputted is getting displayed by printf() i.e.what's happening inside printf()?

I did some research on printf() implementation and get to know that printf is part of the C standard library (a.k.a. the libc) and is a variadic function(printf) but i didn't came to know that what is really happening inside this function and how it knows by format specifier that it has to print character or int?

Please help me learning the whole detailed process which is going on.

答:
(I am supposing your computer has an x86-64 processor and runs Linux)

why format specifier used is %c, why not %d(or %i).

Imagine that the corresponding argument (to printf) was 99 (an int). If you use  %c then the letter c (of ASCII code 99) is displayed. If you use %d or %i then 99 is displayed by printf, etc...

printf is, as you noticed, a variadic function. It is implemented using variadic primitives like va_start and va_end which are macros expanded to some builtin known to the compiler. How exactly arguments are passed and results are given (the calling convention) is defined (in some processor & OS specific way) in a document called ABI (application binary interface).

On some C standard library implementations, printf (and related functions, like vfprintf) would ultimately use putc or something related.

Notice that standard I/O functions (those in <stdio.h>) are likely to be provided with the help of some operating system. Read Operating Systems : Three Easy Pieces for more about OSes.

Quite often, the C standard library will use some system calls to interact with the operating system kernel. For Linux these are listed in syscalls(2), but read Advanced Linux Programming. To output some data the write(2) syscall would be used (but the C standard library is generally buffering, see setvbuf(3)).

BTW, for Linux/x86-64 both GNU glibc & musl-libc are free software implementations of the C standard library, and you can study their source code (most of it is coded in C, with a tiny bit of assembly for the system call glue).

But my problem is what's actually happening inside getchar() and printf() during the whole process, where getchar() is returning that integer, where it is getting stored ...?

The ABI defines that the result of an int returning function goes thru register %rax, and getchar (like every other int return function) works that way. See the X86-64 Linux ABI referenced here.

... and how the character we inputted is getting displayed by printf() i.e. what's happening inside printf()?

After many software layers, when the stdout stream gets flushed (e.g. by some call to fflush(3), by a \n newline character, or at exit(3) time, including returning from main into crt0 code), the C standard library will use the  write(2) syscall. The kernel will process it to show something (But details are horribly complex, read first the tty demystified). Actually millions of source code lines are involved (including inside the kernel - read about DRM, inside the display server such as X.Org or Wayland - also some code inside the GPU -, inside the terminal emulator). Linux is free software, so in principle you can study all of it (but that needs more than a lifetime, a typical Linux distribution has about twenty billions lines of source code). See also OSDev wiki which gives some practical information, including about native Intel grapĥics (which are the most primitive graphics today).

PS. You need to spend more than ten years understanding all the details (and I don't).

Body:
I was learning from geeksforgeeks and when i saw this, a thought came in my mind that as getchar() and other similar functions returns an int(whether due to failure of program or EOF) then why format specifier used is %c, why not %d(or %i).

// Example for getchar() in C
#include <stdio.h>
int main()
{
   printf("%c", getchar());
   return 0;
}

I know that the character we input in is a character and it is taken by the function getchar() and we are displaying it using %c.

But my problem is what's actually happening inside getchar() and printf() during the whole process, where getchar() is returning that integer, where it is getting stored and how the character we inputted is getting displayed by printf() i.e.what's happening inside printf()?

I did some research on printf() implementation and get to know that printf is part of the C standard library (a.k.a. the libc) and is a variadic function(printf) but i didn't came to know that what is really happening inside this function and how it knows by format specifier that it has to print character or int?

Please help me learning the whole detailed process which is going on.


问:
Weekly period in Access 2007
Is there a way to define the weekly period I would like to use on a report, Currently Access has the week defined as sun through sat,  I would like to use mon through sun.</p>

答: The Weekday function has an optional parameter to define the start day - is that any use?</p>

OwnerDisplayName: Craig G

Title: Weekly period in Access 2007

LastEditorDisplayName: David Segonds

OwnerDisplayName: Zhaph