问:
ICU Layout sample renders text differently than Microsoft Notepad and Word
I have a bidirectional text

```<code>1002   -ابو ماجد الانصاري
</code>```

Most editors notepad++, notepad etc. show the text as it is shown here. But when I get this text processed through ICU the number is shifted to the right then spaces and hyphen and then Arabic. ICU's sample application layout.exe also shows the number on the right.
I have modified paragraphlayout.cpp and set all possible reordering modes but result is still the same:

Can someone help to configure ICU to provide output as other display engines do.

答:
If I understand correctly, your text 'begins' with the numeric, which is followed by the hyphen and text. Notepad and other editors let you choose the 'writing direction'. If you choose right-to-left, you get the same result as your screenshot,

If you want to maintain left-to-right writing direction, you can set it explicitly

```<code>ubidi_setPara(para, "1002   -ابو ماجد الانصاري", 25, UBIDI_LTR, NULL, pErrorCode);
</code>```

or you can embed a UNICODE flag U+202A (LEFT-TO-RIGHT EMBEDDING) into your string that will enforce this direction. If your code is in C++, you can write something like

```<code>icu::UnicodeString string_to_layout = "\x202a";
string_to_layout += "1002   -ابو ماجد الانصاري";
</code>```

and not you can use string_to_layout as input parameter for renderParagraph() (see http://icu-project.org/apiref/icu4c-latest/ubidi_8h.htm).

Body:
I have a bidirectional text

1002   -ابو ماجد الانصاري

Most editors notepad++, notepad etc. show the text as it is shown here. But when I get this text processed through ICU the number is shifted to the right then spaces and hyphen and then Arabic. ICU's sample application layout.exe also shows the number on the right.
I have modified paragraphlayout.cpp and set all possible reordering modes but result is still the same:

Can someone help to configure ICU to provide output as other display engines do.

Body:
If I understand correctly, your text 'begins' with the numeric, which is followed by the hyphen and text. Notepad and other editors let you choose the 'writing direction'. If you choose right-to-left, you get the same result as your screenshot,

If you want to maintain left-to-right writing direction, you can set it explicitly

ubidi_setPara(para, "1002   -ابو ماجد الانصاري", 25, UBIDI_LTR, NULL, pErrorCode);

or you can embed a UNICODE flag U+202A (LEFT-TO-RIGHT EMBEDDING) into your string that will enforce this direction. If your code is in C++, you can write something like

icu::UnicodeString string_to_layout = "\x202a";
string_to_layout += "1002   -ابو ماجد الانصاري";

and not you can use string_to_layout as input parameter for renderParagraph() (see http://icu-project.org/apiref/icu4c-latest/ubidi_8h.htm).


来源: stackexchange

问:
what does this bash script line of code mean
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

```<code>Path=`echo $line | awk -F '|' '{print $1}'`
</code>```

答:
I think this is just a complicated way to express

```<code> echo ${line%%|*}
</code>```

i.e. write to stdout the part of the content of the variable line which goes up to - but not including - the first vertical bar.

ContentLicense: CC BY-SA 3.0

Body:
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

Path=`echo $line | awk -F '|' '{print $1}'`

Body:
I think this is just a complicated way to express

 echo ${line%%|*}

i.e. write to stdout the part of the content of the variable line which goes up to - but not including - the first vertical bar.


问:
Data providers issue in phpunit
This is my data provider function:

```<code>public function addDataProvider() {
    return [
        [
            [
                'currency' => 'eur',
                'amount' => 800,
            ],
            [
                'currency' => '12312k',
                'amount' => 1201,
            ],
            [
                'currency' => 'DKK',
                'amount' => 1200.01
            ],
            [
                'currency' => 'SEK  ',
                'amount' => 1200.01
            ]
        ],
    ];
}
</code>```

This is my test function:

```<code>/**
 * Test case
 * @covers AmountPerCustomer::checkAmounts()
 * @dataProvider addDataProvider
 */
public function testCheckAmountUsingCurrency($query)
{
        ....
        try {
            $ordersPerCustomer->checkAmounts($query['amount'], $query['currency'], $dateInterval);
            $this->fail("Expected Exception has not been raised.");
        }catch (\Exception $error) {
            $this->assertEquals($error->getMessage(), "Total order amount event given parameters exceed sum {$query['amount']} since {$dateInterval->format('H:i d-m-Y')} from source {$source}");
        }
}
</code>```

I am getting this success mesage: OK (1 test, 1 assertion) , My question why I have only one assertion. I have multiple array values in my provider . What am I doing wrong ?

Thank you!

答:
As an alternative to returning an array of arrays with arguments for the test method from the data provider, you can also use generators and yield an array of arguments instead:

```<code>public function addDataProvider() : \Generator
{
    $queries = [
        [
            'currency' => 'eur',
            'amount' => 800,
        ],
        [
            'currency' => 'dkk',
            'amount' => 1201,
        ],
        [
            'currency' => 'GBP',
            'amount' => 1201,
        ],
        [
            'currency' => 'sek',
            'amount' => 1200.01,
        ],
    ];

    foreach ($queries as $query) {
        yield [
            $query,
        ];
    }
}
</code>```

Then it might be easier to see what is going on, and less array nesting is required.

Note

It might also make more sense for you to use expectException() and expectExceptionMessage() in your test:

```<code>public function testCheckAmountUsingCurrency($query)
{
    // ...

    $this->expectException(\Exception::class);
    $this->expectExceptionMessage(sprintf(
        'Total order amount event given parameters exceed sum %s since %s from source %s',
        $query['amount'],
        $dateInterval->format('H:i d-m-Y'),
        $source
    ));

    $ordersPerCustomer->checkAmounts(
        $query['amount'],
        $query['currency'],
        $dateInterval
    );
}
</code>```

For reference, see

https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions

Title: Data providers issue in phpunit

Body:
This is my data provider function:

public function addDataProvider() {
    return [
        [
            [
                'currency' => 'eur',
                'amount' => 800,
            ],
            [
                'currency' => '12312k',
                'amount' => 1201,
            ],
            [
                'currency' => 'DKK',
                'amount' => 1200.01
            ],
            [
                'currency' => 'SEK  ',
                'amount' => 1200.01
            ]
        ],
    ];
}

This is my test function:

/**
 * Test case
 * @covers AmountPerCustomer::checkAmounts()
 * @dataProvider addDataProvider
 */
public function testCheckAmountUsingCurrency($query)
{
        ....
        try {
            $ordersPerCustomer->checkAmounts($query['amount'], $query['currency'], $dateInterval);
            $this->fail("Expected Exception has not been raised.");
        }catch (\Exception $error) {
            $this->assertEquals($error->getMessage(), "Total order amount event given parameters exceed sum {$query['amount']} since {$dateInterval->format('H:i d-m-Y')} from source {$source}");
        }
}

I am getting this success mesage: OK (1 test, 1 assertion) , My question why I have only one assertion. I have multiple array values in my provider . What am I doing wrong ?

Thank you!

Body:
As an alternative to returning an array of arrays with arguments for the test method from the data provider, you can also use generators and yield an array of arguments instead:

public function addDataProvider() : \Generator
{
    $queries = [
        [
            'currency' => 'eur',
            'amount' => 800,
        ],
        [
            'currency' => 'dkk',
            'amount' => 1201,
        ],
        [
            'currency' => 'GBP',
            'amount' => 1201,
        ],
        [
            'currency' => 'sek',
            'amount' => 1200.01,
        ],
    ];

    foreach ($queries as $query) {
        yield [
            $query,
        ];
    }
}

Then it might be easier to see what is going on, and less array nesting is required.

Note

It might also make more sense for you to use expectException() and expectExceptionMessage() in your test:

public function testCheckAmountUsingCurrency($query)
{
    // ...

    $this->expectException(\Exception::class);
    $this->expectExceptionMessage(sprintf(
        'Total order amount event given parameters exceed sum %s since %s from source %s',
        $query['amount'],
        $dateInterval->format('H:i d-m-Y'),
        $source
    ));

    $ordersPerCustomer->checkAmounts(
        $query['amount'],
        $query['currency'],
        $dateInterval
    );
}

For reference, see

https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions


问:
How to rectify "Document was used before it was defined" using Jslint
I get the following error in jsLint:

'document' was used before it was defined.

Line that causes the error:

```<code>document.cookie = name + "=" + value + expires + "; path=/";
</code>```

I get why this happens, but I would like my code to be compliant.

How do I resolve this?

Thanks.

答:
In cli mode you can use config file:

jslint.conf

```<code>{
    "predef": [
        "module",
        "require",
        "window",
        "document",
        "jQuery",
        "Backbone",
        "Marionette",
        "Modernizr",
        "_",
        "setTimeout",
        "clearTimeout",
        "setInterval",
        "clearInterval"
    ],
    "evil":false,
    "indent":4,
    "vars":true,
    "passfail":false,
    "plusplus":false
}
</code>```

And use jslint with --config jslint.conf parameter.

Body:
I get the following error in jsLint:

'document' was used before it was defined.

Line that causes the error:

document.cookie = name + "=" + value + expires + "; path=/";

I get why this happens, but I would like my code to be compliant.

How do I resolve this?

Thanks.

Body:
In cli mode you can use config file:

jslint.conf

{
    "predef": [
        "module",
        "require",
        "window",
        "document",
        "jQuery",
        "Backbone",
        "Marionette",
        "Modernizr",
        "_",
        "setTimeout",
        "clearTimeout",
        "setInterval",
        "clearInterval"
    ],
    "evil":false,
    "indent":4,
    "vars":true,
    "passfail":false,
    "plusplus":false
}

And use jslint with --config jslint.conf parameter.


问:
sort value not coming where i have used the sort in map
I tried below code
var data =

```<code>[{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);
</code>```

ERROR:TypeError: s.name.sort is not a function.

But expecting the output is ["karthik","ramu", "ravi"]

答:
Try

```<code>var names = data.map(s=>s.name).sort(); //just move the sort out
</code>```

Demo

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
];
//var names = data.map(s=>s.name).sort(); //just move the sort out
var names = data.map(s => s.name).sort((a, b) => a.localeCompare(b)); //used localeCompare instead of simple sort

console.log(names);```

Body:
I tried below code
var data =

[{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);

ERROR:TypeError: s.name.sort is not a function.

But expecting the output is ["karthik","ramu", "ravi"]

Body:
Try

var names = data.map(s=>s.name).sort(); //just move the sort out

Demo

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
];
//var names = data.map(s=>s.name).sort(); //just move the sort out
var names = data.map(s => s.name).sort((a, b) => a.localeCompare(b)); //used localeCompare instead of simple sort

console.log(names);


问:
angularjs ng-click function is not working in directive
I am trying to bind a click function with an element template , defined in directive. Somehow it is not working for unknown reasons and not throwing any error either.

My html

```<code><body>
    <div ng-app="mainApp">
        <div ng-controller="MyController">
             <div id="Container" class="Container">
             <collection collection='testdata'></collection>
             </div>
        </div>
    </div>
</body>
</code>```

My JS

```<code>var mainApp = angular.module("mainApp", [])
mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
    }
})

mainApp.directive('member', function ($compile) {
    //var NewImg = "<img ng-click=ShowChildren() src=../Images/Plus15.png></img>";
    //var NewChild = "<li>"+NewImg+"<span>{{member.TagName}}</span></li>";
    //var NewChild = "<li><img id=dynamic src=../Images/Plus15.png></img><span>{{member.TagName}}</span></li>";
    var NewChild = "<li><img ng-click=ShowChildren(event) src=../Images/Plus15.png></img><span>{{member.TagName}}</span></li>";
    //var NewChild = "<li>{{member.TagName}}</li>";

    return {
        restrict: "E",
        replace: false,
        scope: {
            member: '='
        },
        template: NewChild,
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {

                element.append("<collection collection='member.children'></collection>");
                $compile(element.contents())(scope.$new())

                //$compile(collectionSt)(scope, function(cloned, scope)   {
                    //element.append(cloned);
                  //});
            }
        }
    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.data = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]
    $scope.testdata = $scope.data[0].children
});

function ShowChildren (event) {
    console.log("in function ShowChildren");
    var src = ($(this).attr('src') === '../Images/Plus15.png')
         ? '../Images/Minus15.png'
         : '../Images/Plus15.png';
     $(this).attr('src', src);
    event.stopImmediatePropagation();
}
</code>```

I noticed that , function ShowChildren executes when in put this in directive  but then it again gives problem in "$(this).attr('src') ". And i want it to be in separate files because i will be moving all codes to different javascript file.

Please help me to resolve this.

答: use ng-click=ShowChildren($event) instead of ng-click=ShowChildren(event) and also your function should defined in the angular scope. like which is answered by @Kaustubh Khare

Body:
I am trying to bind a click function with an element template , defined in directive. Somehow it is not working for unknown reasons and not throwing any error either.

My html

             <collection collection='testdata'></collection>

My JS

var mainApp = angular.module("mainApp", [])
mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: "
<member ng-repeat='member in collection' member='member'></member>
"
    }
})

mainApp.directive('member', function ($compile) {
    //var NewImg = "";
    //var NewChild = "
"+NewImg+"{{member.TagName}}
";
    //var NewChild = "
{{member.TagName}}
";
    var NewChild = "
{{member.TagName}}
";
    //var NewChild = "
{{member.TagName}}
";

    return {
        restrict: "E",
        replace: false,
        scope: {
            member: '='
        },
        template: NewChild,
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {

                element.append("<collection collection='member.children'></collection>");
                $compile(element.contents())(scope.$new())

                //$compile(collectionSt)(scope, function(cloned, scope)   {
                    //element.append(cloned);
                  //});
            }
        }
    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.data = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]
    $scope.testdata = $scope.data[0].children
});

function ShowChildren (event) {
    console.log("in function ShowChildren");
    var src = ($(this).attr('src') === '../Images/Plus15.png')
         ? '../Images/Minus15.png'
         : '../Images/Plus15.png';
     $(this).attr('src', src);
    event.stopImmediatePropagation();
}

I noticed that , function ShowChildren executes when in put this in directive  but then it again gives problem in "$(this).attr('src') ". And i want it to be in separate files because i will be moving all codes to different javascript file.

Please help me to resolve this.


问:
MS SQL: How to create user that has only permission for defined views?
I would like to create a User that only has permission for defined views.

This is how it should work then:
- DB01 => Permission denied
- vView01 => success

At the moment each User has Permission to Views and Datebase or none...

Any Ideas?

Thanks a lot!

Bernhard

答:
Grant user permissions only on views and ownership chaining will allow access to the underlying tables even without permissions on those objects as long as all objects involved have the same owner.

Unfortunately, the is no GRANT syntax to grant permissions on all current and future views such that the user has permissions current and new views. However, this functionality could be accomplished by creating views in a different schema and granting permissions at the schema level:

```<code>GRANT SELECT ON SCHEMA::ViewSchema TO <some-user-or-role>;
</code>```

Otherwise, you'll need to grant permissions on existing views and on each new one after creation. Below is an example script to make quick work for this task.

```<code>DECLARE @GrantScript nvarchar(MAX);

SET @GrantScript = (
    SELECT N'GRANT SELECT ON ' + QUOTENAME(OBJECT_SCHEMA_NAME(object_id))  + '.' + QUOTENAME(name) + N' TO <some-user-or-role>;'
    FROM sys.views
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)');

EXEC sp_executesql @GrantScript;
</code>```

Body:
Grant user permissions only on views and ownership chaining will allow access to the underlying tables even without permissions on those objects as long as all objects involved have the same owner.

Unfortunately, the is no GRANT syntax to grant permissions on all current and future views such that the user has permissions current and new views. However, this functionality could be accomplished by creating views in a different schema and granting permissions at the schema level:

GRANT SELECT ON SCHEMA::ViewSchema TO <some-user-or-role>;

Otherwise, you'll need to grant permissions on existing views and on each new one after creation. Below is an example script to make quick work for this task.

DECLARE @GrantScript nvarchar(MAX);

SET @GrantScript = (
    SELECT N'GRANT SELECT ON ' + QUOTENAME(OBJECT_SCHEMA_NAME(object_id))  + '.' + QUOTENAME(name) + N' TO <some-user-or-role>;'
    FROM sys.views
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)');

EXEC sp_executesql @GrantScript;


答:
Map first and then sort on array of names.

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},      {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},      {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

var names = data.map(s=>s.name);
var sorted = names.sort();
console.log(sorted );```

Title: sort value not coming where i have used the sort in map

ContentLicense: CC BY-SA 4.0


问:
font-awesome icons not showing up in Chrome 61
I've downloaded font-awesome icons in my project and imported font-awesome.min.css as

```<code><link rel="stylesheet" href="resources/font-awesome/css/font-awesome.min.css">
</code>```

And used them simply like

```<code><i class="fa fa-user-o" aria-hidden="true"></i>
</code>```

The stylesheet was loaded so there was no problem with the path.

The icons worked fine in Firefox, but didn't show up in Chrome 61 at all,  neither in Win 10 nor Linux, so I guess it has nothing to do with OS.

I don't have any plugin in Chrome that would be conflicting.

I've also tried <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> but nothing changed.

Does anyone know what might cause this problem? Thanks!

答:
Forgot to mention, I'm using Polymer. And here is a solution I found.

install polymer-font-awesome with npm:

npm i polymer-font-awesome

add the following dependency to polymer.json:

"extraDependencies": ["node_modules/polymer-font-awesome/dist/fonts/*"]

import these two files:

<link rel="import" href="node_modules/polymer-font-awesome/dist/font-face.html">

<link rel="import" href="node_modules/polymer-font-awesome/dist/font-awesome.html">

include stlye module:

Clear the cache in Chrome and it worked for me.

Body:
I've downloaded font-awesome icons in my project and imported font-awesome.min.css as

<link rel="stylesheet" href="resources/font-awesome/css/font-awesome.min.css">

And used them simply like

The stylesheet was loaded so there was no problem with the path.

The icons worked fine in Firefox, but didn't show up in Chrome 61 at all,  neither in Win 10 nor Linux, so I guess it has nothing to do with OS.

I don't have any plugin in Chrome that would be conflicting.

I've also tried <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> but nothing changed.

Does anyone know what might cause this problem? Thanks!

Body:
Forgot to mention, I'm using Polymer. And here is a solution I found.

install polymer-font-awesome with npm:

npm i polymer-font-awesome

add the following dependency to polymer.json:

"extraDependencies": ["node_modules/polymer-font-awesome/dist/fonts/*"]

import these two files:

<link rel="import" href="node_modules/polymer-font-awesome/dist/font-face.html">

<link rel="import" href="node_modules/polymer-font-awesome/dist/font-awesome.html">

include stlye module:

<style type="text/css" include="font-awesome"></style>

Clear the cache in Chrome and it worked for me.


问:
Escape of Escape character not accepted (Java and MySQL)
I have a statement for MySQL 5.5.58-0+deb8u1 that looks like this:

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

I try to escape the \ (after ss) with

```<code>string statementEsc = statement.replace('\\', '\\\\');
</code>```

this results in:

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

When trying the query manually, MySQL accepts this query, but the program gives an error

MySQL JDBC Driver Registered
Problem occured at executeUpdate operation : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', `...at line 1
SQL UPDATE operation has been failed: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', ... = '' at line 1.

I don't understand why.

答:
You had a + maybe from copying the code for us.

However this is an excellent opportunity to use a PreparedStatement.

```<code>String sql = "UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', "
        + "`MAINTENANCE_CONTRACT_NR` = ?, `CONTACT1_NAME` = ? WHERE `general`.`uuid` = ?";
try  (PreparedStatement stmt = connection.prepareStatement(sql)) {
    stmt.setInt(1, 5678);
    stmt.setString(2, "ss\\"); // One backslash
    stmt.setString(3, "06f8417b-c865-11e7-9a86-000c2924bf92");
    stmt.executeUpdate();
}
</code>```

By the way = 'null' would assign a string "null" to that field.

Body:
I have a statement for MySQL 5.5.58-0+deb8u1 that looks like this:

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

I try to escape the \ (after ss) with

string statementEsc = statement.replace('\\', '\\\\');

this results in:

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

When trying the query manually, MySQL accepts this query, but the program gives an error

MySQL JDBC Driver Registered
Problem occured at executeUpdate operation : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', `...at line 1
SQL UPDATE operation has been failed: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', ... = '' at line 1.

I don't understand why.

Body:
You had a + maybe from copying the code for us.

However this is an excellent opportunity to use a PreparedStatement.

String sql = "UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', "
        + "`MAINTENANCE_CONTRACT_NR` = ?, `CONTACT1_NAME` = ? WHERE `general`.`uuid` = ?";
try  (PreparedStatement stmt = connection.prepareStatement(sql)) {
    stmt.setInt(1, 5678);
    stmt.setString(2, "ss\\"); // One backslash
    stmt.setString(3, "06f8417b-c865-11e7-9a86-000c2924bf92");
    stmt.executeUpdate();
}

By the way = 'null' would assign a string "null" to that field.


问:
Conflict while getting operating system name on Java 1.6 and Java 1.8?
I running java application and get a conflict on operating system name and build number.

Sample Code (On Java 1.6.0_31)

```<code>System.out.println("OS Name " + System.getProperty("os.name"));
System.out.println("Version "+System.getProperty("os.version"));
</code>```

Output:

```<code>OS Name Windows NT (unknown)
Version 6.2
</code>```

and

Sample Code (On Java 1.8.0_45)

```<code>System.out.println("OS Name " + System.getProperty("os.name"));
System.out.println("Version "+System.getProperty("os.version"));
</code>```

Output:

```<code>OS Name Windows Server 2012 R2
Version 6.3
</code>```

Why i am getting like this can explain?

答:
Think about movie, "back to the future".

If you went back in time to 1800s with a DeLorean, people of that time would call it "a wagon" because it is what they call a cart on 4 wheels, although they would be puzzled a bit because they would not see any horses in front the vehicle.

If you went to 2500s with the same car, people would probably call it "a  vintage car out of the past".

So it is all relative.

The versions of Java, you are using are both outdated. They are trying to name your operating system as best as they can. It is understandable that they fail in precision but we should still applaud their effort to give you a "close enough" description.

EDIT:

Because there was a bug in JDK, which was fixed by this

More info could be found this topic could also be found here

Body:
I running java application and get a conflict on operating system name and build number.

Sample Code (On Java 1.6.0_31)

System.out.println("OS Name " + System.getProperty("os.name"));
System.out.println("Version "+System.getProperty("os.version"));

Output:

OS Name Windows NT (unknown)
Version 6.2

and

Sample Code (On Java 1.8.0_45)

System.out.println("OS Name " + System.getProperty("os.name"));
System.out.println("Version "+System.getProperty("os.version"));

Output:

OS Name Windows Server 2012 R2
Version 6.3

Why i am getting like this can explain?


问:
php_curl does not work when I try and install Magento
I have Apache version 2.2.22 and PHP 5.3.13. When I try to install Magento it just keeps telling me that curl must be loaded. I have tried to troubleshoot the problem but nothing has solved it. I've done the following:

uncomment php_curl.dll in php.ini file (both in php/ext and the apache/bin folders)

When that didn't work I downloaded two versions of php_ curl fix files (5.3.13 and 5.4.3) and used each to replace the original php_curl.dll file in php/ext.
With 5.4.3 I got the error message that "curl failed to start because the side-by-side configuration is incorrect". Now the 5.3.13 version is in the folder but I get two error messages "Program can't start because php5.dll is missing from your computer" and "ext/php_curl.dll - the specified module could not be found'.

Could someone give me further advice, because at this point I'm clueless on what to do next? I am using wampserver 2.2 and Windows 7.

答:
Update your PHP version to 7.0 or higher.
They have fix the php-curl in >7.0 version see the artical php Chang log</p>


问:
Send Custom Error response from serializer in django rest framework?
I want to send a custom response from serializers create view to front-end of my application. I tried rest framework Response tutorials but it does not work. My code is:</p>

```<code>class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        """create a new user"""

        firstname = self.initial_data['first_name']
        lastname = self.initial_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = self.initial_data['username'].lower()

        try:
           customer = User.create(
                name=fullname,
                email=email)

        except Error as e:
            error = {'message': e._message or 'Unknown error'}
            return Response(error,status=status.HTTP_400_BAD_REQUEST)
</code>```

答:
serializers.py

```<code>class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        """create a new user"""

        firstname = validated_data['first_name']
        lastname = validated_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = validated_data['username'].lower()

        try:
           customer = User.objects.create(
                name=fullname,
                email=email)
           return customer

        except Exception as e:
            error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
            raise serializers.ValidationError(error)
</code>```

Body:
I want to send a custom response from serializers create view to front-end of my application. I tried rest framework Response tutorials but it does not work. My code is:

class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        """create a new user"""

        firstname = self.initial_data['first_name']
        lastname = self.initial_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = self.initial_data['username'].lower()

        try:
           customer = User.create(
                name=fullname,
                email=email)

        except Error as e:
            error = {'message': e._message or 'Unknown error'}
            return Response(error,status=status.HTTP_400_BAD_REQUEST)

Body:
serializers.py

class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        """create a new user"""

        firstname = validated_data['first_name']
        lastname = validated_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = validated_data['username'].lower()

        try:
           customer = User.objects.create(
                name=fullname,
                email=email)
           return customer

        except Exception as e:
            error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
            raise serializers.ValidationError(error)


问:
Visual studio code extension not working
Hi i have installed Visual Studio Code. i can't download plugins from internal extension manager however, i am able to install it by using files downloaded from marketplace. After installation it shows in installed extensions, (Python and Code-Runner) but doesn't work.
For example not single one shortcut from code-runner works. I tried to reinstall but didn't help. Can someone please advice on this?</p>

答: Guess i have found solution i have just copied folder from .extensions into C:\Program Files\VS Code ....extensions.</p>


问:
Is it possible to make desktop GUI application in .NET Core?
I have been developing Windows Forms programs for few years. I am now looking into .NET Core (including ASP.NET Core MVC). I am searching for the new GUI desktop technology. In Visual Studio 2015 update 3 I can't see any option to make a GUI app in .NET Core.

What am I missing?

答:
tl;dr - I'm not sure that it would be possible for the .NET Core developers to supply a cross-platform GUI framework.

I feel like expecting a cross-platform GUI framework to be bundled into the official tooling (especially an old version of the tooling - you mention that you're running Visual Studio 2015 update 3) for an early version of .NET Core is a little premature.

GUI frameworks are really quite heavy, and dependent on the hardware abstractions already present on the host machine. On Windows, there is generally a single window manager (WM) and desktop environment (DE) used by most users, but on the many different distributions of Linux which are supported, there are any number of possible WMs and DEs - granted most users will either be using X-Server or Wayland in combination with KDE, GNOME or Xfce. But no Linux installation ever is the same.

The fact that the open source community can't really settle on a "standard" setup for a VM and DE means that it would be pretty difficult for the .NET Core developers to create a GUI framework which would work across all platforms and combinations of DEs and WMs.

A lot of folks here have some great suggestions (from use ASP.NET Core to builds a Web application and use a browser to listing a bunch of cross-platform frameworks). If you take a look at some of the mentioned cross platform GUI frameworks listed, you'll see how heavy they are.

However, there is light at the end of the tunnel as Miguel de Icaza showed off Xamarin running naively on Linux and macOS at .NET Conf this year (2017, if you're reading this in the future), so it might be worth trying that when it's ready.

(But you'll need to upgrade from Visual Studio 2015 to Visual Studio 2017 to access the .NET Core 2.0 features.)


问:
getting an error- listen EADDRINUSE :::3000 on windows machine
I've searched a lot and I understand there is some process or server running on port 3000, but how can I stop that and run a new express http server on port 3000. There are few answers which tell it for Unix environment..but how to release the port on windows environment using cmd terminal.
Closing the task using PID also didn't work for me.
Thanks in advance </p>

答:
That's because port 3000 is already busy listening to another process.
so just go to task manager and end that process/ delete all node js related processes.</p>


答:
First you can map over your array so you just have the names in an array, which you can then sort.

Your code would look like the following:

var list = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
];

var sortedNames = list.map(item => {
  return item.name;
}).sort();

console.log(sortedNames)```


答:
Sorry I am little late but you can do it with the following piece of code,</p>

```<code>$var = array($polygons1)
</code>```

Title: how to format dynamically-generated nested array in PHP

Body:
I'm trying to dynamically generate a nested array by pulling polygon data from a database using the Pods Framework, however I'm struggling to get the formatting / syntax right (I'm not an expert when it comes to PHP).

This is my code, where "polygon_latlon" is the field containing pairs of latitude and longitude points within double quotes separated by commas which make up the (irregular) polygons:

$lines = array();

//set find parameters
$params = array(
    'limit' => -1
);
//get pods object
 $maps = pods( 'maps_osexplorer', $params );
//loop through records
 if ( $maps->total() > 0 ) {
 while ( $maps->fetch() ) {

 $polygon1 = $maps->field('polygon_latlon');

 $lines[] = "array($polygon1)";

}

}

 $polygons1 = implode(',', $lines);

Using print_r($lines) outputs in this format:

 Array (
[0] => array(“54.8209937901589 -5.1847118669456265″,”54.82875805834827 -4.873857026861909″,”55.03518041767634 -4.888625345496792″,”55.02735680301253 -5.201071164745328″,”54.8209937901589 -5.1847118669456265”)
[1] => array(“54.73307781328839 -5.107888813651375″,”54.73542913841878 -5.014843407073816″,”54.62773859547211 -5.006866177191955″,”54.63292697997008 -4.790281966946296″,”54.839371033206184 -4.804517368244679″,”54.831783194724316 -5.115474120227528″,”54.73307781328839 -5.107888813651375”)
[2] => array(“54.66161594261056 -4.714709589503054″,”54.66230647443063 -4.683739691903676″,”54.68026002182563 -4.684924716676078″,”54.679569033955396 -4.715908247171228″,”54.66161594261056 -4.714709589503054”)
[3] => array(“54.79285752469713 -4.871307801664465″,”54.799816987439904 -4.560586644307456″,”55.06913330516994 -4.577766586876797″,”55.06210435522974 -4.890565603716853″,”54.79285752469713 -4.871307801664465”)
[4] => array(“54.76588200465172 -4.675046760686505″,”54.767570233715865 -4.597418172482791″,”54.66433060233055 -4.590822213183797″,”54.66967882431423 -4.327495656368091″,”54.93904807902748 -4.34303745757995″,”54.93194793898191 -4.686064981190482″,”54.76588200465172 -4.675046760686505”)
 etc
 etc
);

Using print_r($polygons1) outputs in this format:

 array(“54.8209937901589 -5.1847118669456265″,”54.82875805834827 -4.873857026861909″,”55.03518041767634 -4.888625345496792″,”55.02735680301253 -5.201071164745328″,”54.8209937901589 -5.1847118669456265”),
 array(“54.73307781328839 -5.107888813651375″,”54.73542913841878 -5.014843407073816″,”54.62773859547211 -5.006866177191955″,”54.63292697997008 -4.790281966946296″,”54.839371033206184 -4.804517368244679″,”54.831783194724316 -5.115474120227528″,”54.73307781328839 -5.107888813651375”),
 array(“54.66161594261056 -4.714709589503054″,”54.66230647443063 -4.683739691903676″,”54.68026002182563 -4.684924716676078″,”54.679569033955396 -4.715908247171228″,”54.66161594261056 -4.714709589503054”),
 array(“54.79285752469713 -4.871307801664465″,”54.799816987439904 -4.560586644307456″,”55.06913330516994 -4.577766586876797″,”55.06210435522974 -4.890565603716853″,”54.79285752469713 -4.871307801664465”),
 array(“54.76588200465172 -4.675046760686505″,”54.767570233715865 -4.597418172482791″,”54.66433060233055 -4.590822213183797″,”54.66967882431423 -4.327495656368091″,”54.93904807902748 -4.34303745757995″,”54.93194793898191 -4.686064981190482″,”54.76588200465172 -4.675046760686505”),
 etc
 etc

What I need it to output, but I can't quite find the right code / syntax for, is:

 array(
 array(“54.8209937901589 -5.1847118669456265″,”54.82875805834827 -4.873857026861909″,”55.03518041767634 -4.888625345496792″,”55.02735680301253 -5.201071164745328″,”54.8209937901589 -5.1847118669456265”),
 array(“54.73307781328839 -5.107888813651375″,”54.73542913841878 -5.014843407073816″,”54.62773859547211 -5.006866177191955″,”54.63292697997008 -4.790281966946296″,”54.839371033206184 -4.804517368244679″,”54.831783194724316 -5.115474120227528″,”54.73307781328839 -5.107888813651375”),
 array(“54.66161594261056 -4.714709589503054″,”54.66230647443063 -4.683739691903676″,”54.68026002182563 -4.684924716676078″,”54.679569033955396 -4.715908247171228″,”54.66161594261056 -4.714709589503054”),
 array(“54.79285752469713 -4.871307801664465″,”54.799816987439904 -4.560586644307456″,”55.06913330516994 -4.577766586876797″,”55.06210435522974 -4.890565603716853″,”54.79285752469713 -4.871307801664465”),
 array(“54.76588200465172 -4.675046760686505″,”54.767570233715865 -4.597418172482791″,”54.66433060233055 -4.590822213183797″,”54.66967882431423 -4.327495656368091″,”54.93904807902748 -4.34303745757995″,”54.93194793898191 -4.686064981190482″,”54.76588200465172 -4.675046760686505”),
 etc
 etc
);

i.e. I need the output from print_r($polygons1) nested within another array. How would I achieve this?

Ultimately I don't want to print the nested array but store it as a variable for use in another section of code.

Body:
Sorry I am little late but you can do it with the following piece of code,

$var = array($polygons1)


问:
PHP cronjob on Windows with parameter and pipe
I want to run a PHP file via Task Scheduler on Windows.
Everything runs except a parameter comes in.

This runs:

cmd /C C:\php\php.exe
  "C:\cron\cronrun.php" >>
  "C:\cron\log\cronrun.log" 2>&1

This is not running:

cmd /C C:\php\php.exe
  "C:\cron\cronrun.php" --run >>
  "C:\cron\log\cronrun.log" 2>&1

How can I run a job which includes an argument?

Thanks for help.

-lony

Sources:

Set PHP cron job on windows server 2003

http://richarddingwall.name/2009/01/26/capture-the-output-from-a-scheduled-task/

答:
Try adding -- before the --run like this:

```<code>cmd /C C:\php\php.exe "C:\cron\cronrun.php" -- --run >> "C:\cron\log\cronrun.log" 2>&1
</code>```

The clue is in the usage message:

```<code>$ php --help
Usage: php [options] [-f] <file> [--] [args...]

...

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try adding -- before the --run like this:

cmd /C C:\php\php.exe "C:\cron\cronrun.php" -- --run >> "C:\cron\log\cronrun.log" 2>&1

The clue is in the usage message:

$ php --help
Usage: php [options] [-f] <file> [--] [args...]

...

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin


问:
How to extract the required element using find_all()
I am trying to extract the authors' names in the amazon page. The problem is, there are so many tags with same class and there are no other attributes to identify the exact element. Now i want to extract the author name. It is present in the second span tag.

by
Arthur Conan Doyle
```
</div>
</div>
</p>

<p>As we can, there is a same class for both span tags. I want the second span tag.And more over, the a tag is not present in all blocks. So i have to use only span tag to extract the author name. How could i get the author name?</p>

<p>I am using BeautifulSoup and selenium.My code is:</p>

```        soup=BeautifulSoup(self.driver.page_source,"html.parser")
    titles=soup.find_all("h2",{"class":"a-size-medium s-inline s-access-title a-text-normal"})
    authors=soup.find_all("span",{"class":"a-size-small a-color-secondary"})
    for value in range(len(titles)):
        d={}
        d["Title"]=titles[value].text
        d["Author"]=authors[value+2].text
        title.append(d)
```

答:
Find the above "div" element for that "span". then extract the entire text of the div tag.As u observe, there will be a "by" substring in every block of code. Use it to split the text and copy it to the d["Author"] part. If "by" is not present, check before copying it to dictionary using if condition. If u copy directly, then u may get Array out of Bound exception. So use if.

Here is the code:

```<code>temp = authors[value].text
temp1 = temp.split("by")
#print(temp[1])
if temp1[0]!=temp:
    d["Author"] = temp1[1]
else:
    d["Author"] = "None"
</code>```

Body:
I am trying to extract the authors' names in the amazon page. The problem is, there are so many tags with same class and there are no other attributes to identify the exact element. Now i want to extract the author name. It is present in the second span tag.

by
Arthur Conan Doyle

As we can, there is a same class for both span tags. I want the second span tag.And more over, the a tag is not present in all blocks. So i have to use only span tag to extract the author name. How could i get the author name?

I am using BeautifulSoup and selenium.My code is:

        soup=BeautifulSoup(self.driver.page_source,"html.parser")
    titles=soup.find_all("h2",{"class":"a-size-medium s-inline s-access-title a-text-normal"})
    authors=soup.find_all("span",{"class":"a-size-small a-color-secondary"})
    for value in range(len(titles)):
        d={}
        d["Title"]=titles[value].text
        d["Author"]=authors[value+2].text
        title.append(d)

Body:
Find the above "div" element for that "span". then extract the entire text of the div tag.As u observe, there will be a "by" substring in every block of code. Use it to split the text and copy it to the d["Author"] part. If "by" is not present, check before copying it to dictionary using if condition. If u copy directly, then u may get Array out of Bound exception. So use if.

Here is the code:

temp = authors[value].text
temp1 = temp.split("by")
#print(temp[1])
if temp1[0]!=temp:
    d["Author"] = temp1[1]
else:
    d["Author"] = "None"


答:
Refer the following code to get your Names Array -

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

// Names Array Only
var namesArr = data.map(s => s.name).sort((a, b)=> a.localeCompare(b));
document.write('```Names Array ==><br>' + JSON.stringify(namesArr) + '```');```
</div>
</div>
</p>

<p>Also, JSON sorted by name if required - </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 data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
            {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
            {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

// sort JSON by names
data.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});
document.write('```Sorted JSON by names ==>
' + JSON.stringify(data, 0, 4) + '```');</code>```

Body:
Refer the following code to get your Names Array -

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

// Names Array Only
var namesArr = data.map(s => s.name).sort((a, b)=> a.localeCompare(b));
document.write('<pre>Names Array ==><br>' + JSON.stringify(namesArr) + '</pre>');

Also, JSON sorted by name if required -

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
            {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
            {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

// sort JSON by names
data.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});
document.write('<pre>Sorted JSON by names ==><br>' + JSON.stringify(data, 0, 4) + '</pre>');


问:
ThreadPoolExecutor Callbacks?
I have the following code:

```<code>from concurrent.futures import ThreadPoolExecutor

def download_contract_history(self, **kw):
    ThreadPoolExecutor().map(lambda x: x.download_contract_history(**kw), self.instruments.values())
    print("All downloads complete.")
</code>```

It currently prints "All downloads complete" immediately, while the actual download tasks continue asynchronously. How can I get it to print the statement after the threads actually finish?

答:
Being able to do other things at the same time is kind of the point. If you want to wait on completion then you need to check the returned results.

The docs aren't very clear, but they do say:

The returned iterator raises a concurrent.futures.TimeoutError if
  __next__() is called and the result isn’t available after timeout seconds

So it seems that map returns a result iterator, and the results are actual results not futures, so you could do:

```<code>from concurrent.futures import ThreadPoolExecutor

def download_contract_history(self, **kw):
    results = list(
        ThreadPoolExecutor().map(
            lambda x: x.download_contract_history(**kw),
            self.instruments.values()
        )
    )
    print("All downloads complete.")
</code>```

Title: ThreadPoolExecutor Callbacks?

Body:
I have the following code:

from concurrent.futures import ThreadPoolExecutor

def download_contract_history(self, **kw):
    ThreadPoolExecutor().map(lambda x: x.download_contract_history(**kw), self.instruments.values())
    print("All downloads complete.")

It currently prints "All downloads complete" immediately, while the actual download tasks continue asynchronously. How can I get it to print the statement after the threads actually finish?

Body:
Being able to do other things at the same time is kind of the point. If you want to wait on completion then you need to check the returned results.

The docs aren't very clear, but they do say:

The returned iterator raises a concurrent.futures.TimeoutError if
  __next__() is called and the result isn’t available after timeout seconds

So it seems that map returns a result iterator, and the results are actual results not futures, so you could do:

from concurrent.futures import ThreadPoolExecutor

def download_contract_history(self, **kw):
    results = list(
        ThreadPoolExecutor().map(
            lambda x: x.download_contract_history(**kw),
            self.instruments.values()
        )
    )
    print("All downloads complete.")


答:
As I mentioned in the comment above, s.name is a string while you are able to use .sort function only on arrays.

To deal with that issue, you could firstly map given array to get just the name properties and then sort it.

const a = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
   {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
   {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];

const names = a.map((s) => s.name).sort();

console.log(names);```

Body:
I tried below code
var data =

[{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}];
var names = data.map(s=>s.name.sort());
console.log(names);

ERROR:TypeError: s.name.sort is not a function.

But expecting the output is ["karthik","ramu", "ravi"]


问:
Filter First Column Text File (PowerShell)
Newbie to PowerShell.
I want to filter in column 1 where value in a text file equal "Find"

```<code>    Get-Content -Path C:\home\file.csv | Select-String -SimpleMatch "Find"
</code>```

When I ran the above script it returns all records in column 1 that equal "Find" and other columns that have "Find", it should only return column 1 where value is "Find"

Please can you help?

答:
Use Import-csv:

```<code>Import-Csv C:\home\file.csv -Header Col1,Col2,Col3 | Select-Object -Unique Col1 | Select-String -SimpleMatch "Find"
</code>```

Adjust the header columns to the columns you have. I assume you have no headers in the csv. otherwise it would be even easier.

Body:
Newbie to PowerShell.
I want to filter in column 1 where value in a text file equal "Find"

    Get-Content -Path C:\home\file.csv | Select-String -SimpleMatch "Find"

When I ran the above script it returns all records in column 1 that equal "Find" and other columns that have "Find", it should only return column 1 where value is "Find"

Please can you help?

Body:
Use Import-csv:

Import-Csv C:\home\file.csv -Header Col1,Col2,Col3 | Select-Object -Unique Col1 | Select-String -SimpleMatch "Find"

Adjust the header columns to the columns you have. I assume you have no headers in the csv. otherwise it would be even easier.


问:
How to view / open .sof files in linux?
I am trying to open *.sof file by using nedit / gedit , but it couldn't open. It seems that this file is binary file OR encrypted file.

Is there a way to view/open such kind of files in linux ?

答:
The sof file extension is associated with Quartus II, a development environment for Microsoft Windows operating system used to develop apps for FPGAs, SoCs, and CPLDs.

SOF file stands for Altera SRAM Object File that contains the data for configuring all SRAM-based Altera devices supported by the Quartus II software, using the Programmer.

So, .sof file is native to windows World. Wondering how you got that on your Linux System. Coming to your Question I think -

If it is really a .sof file, you can open it on some Windows Machine in Notepad or Wordpad.

It may be the case that file extension is misspelled. In that case you can check for other file extensions such as .cof or .spf or .sod
You can refer to this site for further details.

Title: How to view / open .sof files in linux?


问:
How to use Swift - Autocomplete in textView
I have a textView where user can add comments and mention to other users.
I've build a function which is triggered when the user type the sign "@".
So basically as in Instagram or Facebook when the user types "@" a tableview appears and show the user suggestions.
Here's my function:

```<code>func suggestUser() {
    if let searchText = postTextField.text {
        let words = searchText.components(separatedBy: .whitespacesAndNewlines)
        for var word in words {
            if word.hasPrefix("@") {
                word = word.trimmingCharacters(in: .punctuationCharacters)
                let userToSearch = String(word.dropFirst())
                self.viewContainerForTableView.isHidden = false
                self.suggestedUsers.removeAll()
                self.tableView.reloadData()
                Api.User.queryUsersByMentionName(WithText: userToSearch, completion: { (user) in
                    if !self.suggestedUsers.contains(where: { $0.id == user.id }) {
                        self.suggestedUsers.append(user)
                    }
                    self.tableView.reloadData()
                })
            } else {
                self.viewContainerForTableView.isHidden = true
            }
        }
    }
}
</code>```

I have two issue:
1) When the user clicks on the suggested user in the tableview, how can i remove the text he already typed and add the one he selected?
Let me give you an example:

If a user types @jan in the tableView appears janedoe. When the user click on the suggested name in table view how can i remove jan and add janedoe?

Here's my code for the didSelectRowAt

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let username = suggestedUsers[indexPath.row].username
    let usernameToAppend = username.components(separatedBy: .whitespacesAndNewlines).joined()
     postTextField.text.append("\(usernameToAppend)")
}
</code>```

2) Is there a way to check if an user is already typed in the textView and so not displaying it in the tableview?

Thank you!

答:
After an entire day of trying i Think I've found a solution... Hopefully...

so I have created an extension for my textView:

```<code>extension UITextView {

var currentWord : String? {

    let beginning = beginningOfDocument

    if let start = position(from: beginning, offset: selectedRange.location),
        let end = position(from: start, offset: selectedRange.length) {

        let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)

        if let textRange = textRange {
            return text(in: textRange)
        }
    }
    return nil
  }
}
</code>```

Then in my didSelectRowAt i have:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let username = suggestedUsers[indexPath.row].username
    let usernameToAppend = username.components(separatedBy: .whitespacesAndNewlines).joined()
    let currentWord = postTextField.currentWord
    if currentWord != nil && currentWord != "@"  {
        if let countIndex = currentWord?.count {
            let count = Int(countIndex)
            let startPosition = postTextField.selectedTextRange?.start
            let endPosition = postTextField.position(from: startPosition!, offset: -count)
            postTextField.selectedTextRange = postTextField.textRange(from: startPosition!, to: endPosition!)
            if let range = postTextField.selectedTextRange {
                postTextField.replace(range, withText: usernameToAppend)
            }
        }
    } else if currentWord == "@" {
        if let range = postTextField.selectedTextRange {
            if range.start == range.end {
                postTextField.replace(range, withText: usernameToAppend)
            }
        }
    }
  }
}
</code>```

Body:
I have a textView where user can add comments and mention to other users.
I've build a function which is triggered when the user type the sign "@".
So basically as in Instagram or Facebook when the user types "@" a tableview appears and show the user suggestions.
Here's my function:

func suggestUser() {
    if let searchText = postTextField.text {
        let words = searchText.components(separatedBy: .whitespacesAndNewlines)
        for var word in words {
            if word.hasPrefix("@") {
                word = word.trimmingCharacters(in: .punctuationCharacters)
                let userToSearch = String(word.dropFirst())
                self.viewContainerForTableView.isHidden = false
                self.suggestedUsers.removeAll()
                self.tableView.reloadData()
                Api.User.queryUsersByMentionName(WithText: userToSearch, completion: { (user) in
                    if !self.suggestedUsers.contains(where: { $0.id == user.id }) {
                        self.suggestedUsers.append(user)
                    }
                    self.tableView.reloadData()
                })
            } else {
                self.viewContainerForTableView.isHidden = true
            }
        }
    }
}

I have two issue:
1) When the user clicks on the suggested user in the tableview, how can i remove the text he already typed and add the one he selected?
Let me give you an example:

If a user types @jan in the tableView appears janedoe. When the user click on the suggested name in table view how can i remove jan and add janedoe?

Here's my code for the didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let username = suggestedUsers[indexPath.row].username
    let usernameToAppend = username.components(separatedBy: .whitespacesAndNewlines).joined()
     postTextField.text.append("\(usernameToAppend)")
}

2) Is there a way to check if an user is already typed in the textView and so not displaying it in the tableview?

Thank you!

Body:
After an entire day of trying i Think I've found a solution... Hopefully...

so I have created an extension for my textView:

extension UITextView {

var currentWord : String? {

    let beginning = beginningOfDocument

    if let start = position(from: beginning, offset: selectedRange.location),
        let end = position(from: start, offset: selectedRange.length) {

        let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1)

        if let textRange = textRange {
            return text(in: textRange)
        }
    }
    return nil
  }
}

Then in my didSelectRowAt i have:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let username = suggestedUsers[indexPath.row].username
    let usernameToAppend = username.components(separatedBy: .whitespacesAndNewlines).joined()
    let currentWord = postTextField.currentWord
    if currentWord != nil && currentWord != "@"  {
        if let countIndex = currentWord?.count {
            let count = Int(countIndex)
            let startPosition = postTextField.selectedTextRange?.start
            let endPosition = postTextField.position(from: startPosition!, offset: -count)
            postTextField.selectedTextRange = postTextField.textRange(from: startPosition!, to: endPosition!)
            if let range = postTextField.selectedTextRange {
                postTextField.replace(range, withText: usernameToAppend)
            }
        }
    } else if currentWord == "@" {
        if let range = postTextField.selectedTextRange {
            if range.start == range.end {
                postTextField.replace(range, withText: usernameToAppend)
            }
        }
    }
  }
}


问:
Versions of @angular/compiler-cli and typescript could not be determined
I have installed Angular/cli and then try to run command ng serve then below error is throwing. I have tried lot of thing like uninstall angular/cli, npm cache clean, etc

Versions of @angular/compiler-cli and typescript could not be
  determined. The most common reason for this is a broken npm install.

Please make sure your package.json contains both @angular/compiler-cli
  and typescript in devDependencies, then delete node_modules and
  package-lock.json (if you have one) and run npm install again.

答:
Could you check that your "@angular/compiler" in your dependencies is compatible with angular/cli version.

For example :

```<code>  "devDependencies": {
    "@angular/cli": "1.4.8",
    "@angular/compiler-cli": "4.4.6",
</code>```

is compatible with :

```<code>"@angular/compiler": "4.4.6",
</code>```

Body:
Could you check that your "@angular/compiler" in your dependencies is compatible with angular/cli version.

For example :

  "devDependencies": {
    "@angular/cli": "1.4.8",
    "@angular/compiler-cli": "4.4.6",

is compatible with :

"@angular/compiler": "4.4.6",


问:
Get specific objects from an Array in react-native
I have a static array something like

[apple, banana, orange, lemon, goa, grapes, berry, mango, black grapes]

with no changes in order(order will be fixed). Based on user selection dynamically i am getting two objects like (orange, mango).

Now i need to fetch objects between these two objects i.e.(lemon,goa,grapes,berry) into a different array. Thank you

答:
The Cool Way </p>

<blockquote>
```<code>var fruits = ['apple', 'banana', 'orange', 'lemon', 'goa', 'grapes', 'berry', 'mango', 'black', 'grapes'];
var startingIndex  = fruits.indexOf('orange') + 1;
var endingIndex  = fruits.indexOf('mango');

fruits.splice(startingIndex, endingIndex -  startingIndex);
</code>```
</blockquote>

Body:
The Cool Way

var fruits = ['apple', 'banana', 'orange', 'lemon', 'goa', 'grapes', 'berry', 'mango', 'black', 'grapes'];
var startingIndex  = fruits.indexOf('orange') + 1;
var endingIndex  = fruits.indexOf('mango');

fruits.splice(startingIndex, endingIndex -  startingIndex);


问:
Removing axes lines on chart.js
I have been working with some Chart.js and I have been trying to figure out how to remove the axis lines on a chart.

You can see the grid lines I am trying to remove in this image.

I have managed to remove the grid lines that appear within the chart where the data is represented, but I am having an issue removing these two lines.

You can see the chart.js I have created for the chart below.

```<code>var ctx = document.getElementById("volCause").getContext('2d');
var volCause_Doughnut = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
            labels: <?php echo $cause_label_json?>,
        datasets: [{
            backgroundColor: benefactoGraph_colours,
            data: <?php echo $cause_value_json?>

        }]
    },

    options: {
        maintainAspectRatio: false,
        legend: {
            display: false,
        },
        scales: {
            xAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: 'Volunteer Hours',
                },
                gridLines: {
                    display: false,
                },
            }],

            yAxes: [{
                gridLines: {
                    display: false,

                }
            }]

        }

    }
});
</code>```

Any suggestions would be much appreciated.

答:
You can set display: false in your axis object</p>

```<code>scales: {
  xAxes: [{
    display: false,
    gridLines: {}
  }],
  yAxes: [{
    display: false,
    gridLines: {}
  }]
 }
</code>```

Title: Removing axes lines on chart.js

Body:
I have been working with some Chart.js and I have been trying to figure out how to remove the axis lines on a chart.

You can see the grid lines I am trying to remove in this image.

I have managed to remove the grid lines that appear within the chart where the data is represented, but I am having an issue removing these two lines.

You can see the chart.js I have created for the chart below.

var ctx = document.getElementById("volCause").getContext('2d');
var volCause_Doughnut = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
            labels: <?php echo $cause_label_json?>,
        datasets: [{
            backgroundColor: benefactoGraph_colours,
            data: <?php echo $cause_value_json?>

        }]
    },

    options: {
        maintainAspectRatio: false,
        legend: {
            display: false,
        },
        scales: {
            xAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: 'Volunteer Hours',
                },
                gridLines: {
                    display: false,
                },
            }],

            yAxes: [{
                gridLines: {
                    display: false,

                }
            }]

        }

    }
});

Any suggestions would be much appreciated.

Body:
You can set display: false in your axis object

scales: {
  xAxes: [{
    display: false,
    gridLines: {}
  }],
  yAxes: [{
    display: false,
    gridLines: {}
  }]
 }


问:
Javascript local variable technique
I have a simple question related to one-line programming. First an example:

```<code>function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}
</code>```

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

```<code>function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}
</code>```

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

```<code>function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}
</code>```

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

答:
Your example may be over-complicating a simple operation but the technique you are demonstrating is called method 'chaining'. It's a perfectly valid form and can actually be used to make code more readable when the intermediate results are not needed or meaningful.

My current favorite example of this is the wonderful DateJs:

```<code>var nextTuesday = DateJs.today().next().tuesday();

var aBitLater = DateJs.now().addHours(1).addMinutes(30);
</code>```

Sure, it's syntactic sugar and could be written more verbosely as separate statements, but with careful method nameing you can actually cause this to read like English.

GC / Memory management is not affected by this style, parameters to functions are cleaned up just as any other. In fact it may actually be safer since the parameters immediately go out of scope after the function calls return and there is no need to create local vars for values just to pass them to the next function call.

Your example may be a little contrived but if you use it where it makes sense, it's a useful pattern.

Title: Javascript local variable technique

Body:
I have a simple question related to one-line programming. First an example:

function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

Body:
Your example may be over-complicating a simple operation but the technique you are demonstrating is called method 'chaining'. It's a perfectly valid form and can actually be used to make code more readable when the intermediate results are not needed or meaningful.

My current favorite example of this is the wonderful DateJs:

var nextTuesday = DateJs.today().next().tuesday();

var aBitLater = DateJs.now().addHours(1).addMinutes(30);

Sure, it's syntactic sugar and could be written more verbosely as separate statements, but with careful method nameing you can actually cause this to read like English.

GC / Memory management is not affected by this style, parameters to functions are cleaned up just as any other. In fact it may actually be safer since the parameters immediately go out of scope after the function calls return and there is no need to create local vars for values just to pass them to the next function call.

Your example may be a little contrived but if you use it where it makes sense, it's a useful pattern.

OwnerDisplayName: tweakt


问:
Creating a side-scrolling website
I am trying to create a website that scrolls horizontally with a fixed character in the centre, similar to http://www.rleonardi.com/interactive-resume/.

When trying to change the css to resize the images it doesnt affect the website and I dont know if I need to use the position:fixed to fix the character in the centre.

background

floor

character

```<code>    <html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <title>Your title</title>
    <link   rel="stylesheet"    href="css/styles.css">
</head>

    <body>

       <background><img src="Photos/Backgroundclear%20.png" alt= "Background"/> </background>

       <character><img src="Photos/Character.png" alt= "Background image"/> </character>

       <div><floor><img src="Photos/floor.png" alt= "Background image"/> </floor> </div>

    </body>
</code>```

and css:

```<code>body{
    background-color: $primarycolour;
    max-width: 8000px;
    max-height: auto;

}

background{
    max-height: auto;
    max-width: 100%;

}

character{
    max-height: 20px;
    margin: auto;

}
</code>```

答:
For a complex project like this you're really going to have to wrap your head around the positioning of elements and how fixed/relative and absolute positioning work. This should set you on the right track. In this case I used chrome inspector to have a look at the example that you are trying to replicate and I can see that the character has position: absolute. Here's some css with the character resized. Hope it helps!

```<code>body{
    background-color: $primarycolour;
    max-width: 8000px;
    max-height: auto;

}

background{
    max-height: auto;
    max-width: 100%;

}

character{
    max-height: 20px;
    margin: auto;

}
background img {
    width: 100%;
}
floor img {
    width: 100%;
    position: fixed;
    bottom: 0;
}
character img {
    position: absolute;
    width: 200px;
    bottom: 140px;
    left: calc(50% - 100px);
}
</code>```

Title: Creating a side-scrolling website

Body:
I am trying to create a website that scrolls horizontally with a fixed character in the centre, similar to http://www.rleonardi.com/interactive-resume/.

When trying to change the css to resize the images it doesnt affect the website and I dont know if I need to use the position:fixed to fix the character in the centre.

background

floor

character

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <title>Your title</title>
    <link   rel="stylesheet"    href="css/styles.css">

       <background> </background>

       <character> </character>

<floor> </floor>

and css:

body{
    background-color: $primarycolour;
    max-width: 8000px;
    max-height: auto;

}

background{
    max-height: auto;
    max-width: 100%;

}

character{
    max-height: 20px;
    margin: auto;

}

Body:
For a complex project like this you're really going to have to wrap your head around the positioning of elements and how fixed/relative and absolute positioning work. This should set you on the right track. In this case I used chrome inspector to have a look at the example that you are trying to replicate and I can see that the character has position: absolute. Here's some css with the character resized. Hope it helps!

body{
    background-color: $primarycolour;
    max-width: 8000px;
    max-height: auto;

}

background{
    max-height: auto;
    max-width: 100%;

}

character{
    max-height: 20px;
    margin: auto;

}
background img {
    width: 100%;
}
floor img {
    width: 100%;
    position: fixed;
    bottom: 0;
}
character img {
    position: absolute;
    width: 200px;
    bottom: 140px;
    left: calc(50% - 100px);
}


问:
The below SQL query takes around 6-7 min to execute and it will return ~ 5,833,135 rows, can any help me resolve it performance
The below SQL query takes around 6-7 min to execute and it will return ~ 5,833,135 rows, can any help me resolve it performance

SQL

```<code>select
    min(aml.id) as id,
    aml.name as name,
    round(sum(aml.debit),2) as debit,
    round(sum(aml.credit),2) as credit,
    round(sum(aml.balance),2) as balance,
    aml.account_id as account_id,
    aml.move_id as move_id,
    aml.payment_id as payment_id,
    aml.statement_id as statement_id,
    aml.journal_id as journal_id,
    aml.date as date,
    aml.company_id as company_id,
    aml.invoice_id as invoice_id,
    aml.partner_id as partner_id,
    aml.company_currency_id as company_currency_id
from
    account_move_line aml
    left join account_account acc on (acc.id = aml.account_id)
    left join account_move am on (am.id = aml.move_id)
    left join account_payment ap on (ap.id = aml.payment_id)
    left join account_bank_statement abs on (abs.id = aml.statement_id)
    left join account_journal aj on (aj.id = aml.journal_id)
    left join res_company comp on (comp.id = aml.company_id)
    left join account_invoice ai on (ai.id = aml.invoice_id)
    left join res_partner resp on (resp.id = aml.partner_id)
    left join res_currency rc on (rc.id = aml.company_currency_id)
group by
    aml.name,
    aml.debit,
    aml.credit,
    aml.balance,
    aml.account_id,
    aml.move_id,
    aml.payment_id,
    aml.statement_id,
    aml.journal_id,
    aml.date,
    aml.company_id,
    aml.invoice_id,
    aml.partner_id,
    aml.company_currency_id
</code>```

答:
You are only selecting from one table, which is the first the series of left joins.

I wonder if this does what you want:

```<code>select min(aml.id) as id,
       aml.name as name,
       round(sum(aml.debit), 2) as debit,
       round(sum(aml.credit), 2) as credit,
       round(sum(aml.balance), 2) as balance,
       aml.account_id as account_id,
       aml.move_id as move_id,
       aml.payment_id as payment_id,
       aml.statement_id as statement_id,
       aml.journal_id as journal_id,
       aml.date as date,
       aml.company_id as company_id,
       aml.invoice_id as invoice_id,
       aml.partner_id as partner_id,
       aml.company_currency_id as company_currency_id
from account_move_line aml
group by aml.name, aml.debit, aml.credit, aml.balance,
         aml.account_id, aml.move_id, aml.payment_id,
         aml.statement_id, aml.journal_id, aml.date,
         aml.company_id,  aml.invoice_id, aml.partner_id,
         aml.company_currency_id;
</code>```

You are then aggregating by so many columns that I wonder if aggregation is even necessary.

Body:
The below SQL query takes around 6-7 min to execute and it will return ~ 5,833,135 rows, can any help me resolve it performance

SQL

select
    min(aml.id) as id,
    aml.name as name,
    round(sum(aml.debit),2) as debit,
    round(sum(aml.credit),2) as credit,
    round(sum(aml.balance),2) as balance,
    aml.account_id as account_id,
    aml.move_id as move_id,
    aml.payment_id as payment_id,
    aml.statement_id as statement_id,
    aml.journal_id as journal_id,
    aml.date as date,
    aml.company_id as company_id,
    aml.invoice_id as invoice_id,
    aml.partner_id as partner_id,
    aml.company_currency_id as company_currency_id
from
    account_move_line aml
    left join account_account acc on (acc.id = aml.account_id)
    left join account_move am on (am.id = aml.move_id)
    left join account_payment ap on (ap.id = aml.payment_id)
    left join account_bank_statement abs on (abs.id = aml.statement_id)
    left join account_journal aj on (aj.id = aml.journal_id)
    left join res_company comp on (comp.id = aml.company_id)
    left join account_invoice ai on (ai.id = aml.invoice_id)
    left join res_partner resp on (resp.id = aml.partner_id)
    left join res_currency rc on (rc.id = aml.company_currency_id)
group by
    aml.name,
    aml.debit,
    aml.credit,
    aml.balance,
    aml.account_id,
    aml.move_id,
    aml.payment_id,
    aml.statement_id,
    aml.journal_id,
    aml.date,
    aml.company_id,
    aml.invoice_id,
    aml.partner_id,
    aml.company_currency_id

Body:
You are only selecting from one table, which is the first the series of left joins.

I wonder if this does what you want:

select min(aml.id) as id,
       aml.name as name,
       round(sum(aml.debit), 2) as debit,
       round(sum(aml.credit), 2) as credit,
       round(sum(aml.balance), 2) as balance,
       aml.account_id as account_id,
       aml.move_id as move_id,
       aml.payment_id as payment_id,
       aml.statement_id as statement_id,
       aml.journal_id as journal_id,
       aml.date as date,
       aml.company_id as company_id,
       aml.invoice_id as invoice_id,
       aml.partner_id as partner_id,
       aml.company_currency_id as company_currency_id
from account_move_line aml
group by aml.name, aml.debit, aml.credit, aml.balance,
         aml.account_id, aml.move_id, aml.payment_id,
         aml.statement_id, aml.journal_id, aml.date,
         aml.company_id,  aml.invoice_id, aml.partner_id,
         aml.company_currency_id;

You are then aggregating by so many columns that I wonder if aggregation is even necessary.


问:
Verbatim Match with sed
I have a list of pairs of URLs - I want to find all occurrences of the first element of the pair and replace them with the second. I'm trying to use sed for this but sed escapes characters in my URL. Is there a way to make sed find these URLs (without changing my pairs)?

Here's my code:

```<code>while read -r NAME
do
    ARG1=`echo "$NAME" | awk '{print $1}'`
    ARG2=`echo "$NAME" | awk '{print $2}'`
    echo "$ARG1"
    echo "$ARG2"
    sed -i "s@$ARG1@$ARG2@g" file
done < pagetable
</code>```

pagetable has the pairs of URLS, and I'm doing the find and replace in 'file'. Since my URLs have special characters, sed isn't interpreting them verbatim.

答:
Replace the metacharacters in the search pattern (\ * ^ $ . /) and in the replacement string (& /) before invoking sed. This assumes that the script is run by Bash.

```<code>ARG1="${ARG1//\\/\\\\}"
ARG1="${ARG1//\*/\\\*}"
ARG1="${ARG1//\//\\/}"
for mc in \^ \$ \.; do ARG1="${ARG1//$mc/\\$mc}"; done
ARG2="${ARG2//\\/\\\\}"
ARG2="${ARG2//\//\\/}"
ARG2="${ARG2//&/\\&}"
sed -i "s/$ARG1/$ARG2/g" file
</code>```

Title: Verbatim Match with sed

Body:
I have a list of pairs of URLs - I want to find all occurrences of the first element of the pair and replace them with the second. I'm trying to use sed for this but sed escapes characters in my URL. Is there a way to make sed find these URLs (without changing my pairs)?

Here's my code:

while read -r NAME
do
    ARG1=`echo "$NAME" | awk '{print $1}'`
    ARG2=`echo "$NAME" | awk '{print $2}'`
    echo "$ARG1"
    echo "$ARG2"
    sed -i "s@$ARG1@$ARG2@g" file
done < pagetable

pagetable has the pairs of URLS, and I'm doing the find and replace in 'file'. Since my URLs have special characters, sed isn't interpreting them verbatim.

Body:
Replace the metacharacters in the search pattern (\ * ^ $ . /) and in the replacement string (& /) before invoking sed. This assumes that the script is run by Bash.

ARG1="${ARG1//\\/\\\\}"
ARG1="${ARG1//\*/\\\*}"
ARG1="${ARG1//\//\\/}"
for mc in \^ \$ \.; do ARG1="${ARG1//$mc/\\$mc}"; done
ARG2="${ARG2//\\/\\\\}"
ARG2="${ARG2//\//\\/}"
ARG2="${ARG2//&/\\&}"
sed -i "s/$ARG1/$ARG2/g" file