问:
Jqgrid treegrid Data format
my surroundings：jqgrid 5.1 ，php 5.3

my data：

```<code>{
"values": [
    {
        "id": "1",
        "mac": "64:09:80:57:A6:EE",
        "username": "WIFI-DQ",
        "company": "Xiaomi Communications Co Ltd",
        "isLeaf": false,
        "expanded": true,
        "level":0,
        "p_id": "0"
    },
    {
        "id": "2",
        "mac": "F0:B4:29:5A:B5:0F",
        "username": "1001",
        "company": "Tenda Technology Co., Ltd.",
        "isLeaf": false,
        "expanded": true,
        "level":0,
        "p_id": "0"
    },
    {
        "id": "3",
        "mac": "64:09:80:57:A6:EF",
        "username": "WIFI-DQ_5G",
        "company": "TP-LINK TECHNOLOGIES CO.,LTD.",
        "isLeaf": false,
        "expanded": true,
        "level":0,
        "p_id": "0"
    },
    {
        "id": "4",
        "mac": "00:1C:BF:8B:DF:8E",
        "username": "QCL16",
        "company": "Intel Corporate",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "2"
    },
    {
        "id": "5",
        "mac": "98:2F:3C:07:56:36",
        "username": "admin23",
        "company": "Xiaomi Communications Co Ltd",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "2"
    },
    {
        "id": "6",
        "mac": "34:80:B3:FC:3F:0B",
        "username": "Iphone",
        "company": "Iphone",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "2"
    },
    {
        "id": "7",
        "mac": "35:85:B3:DC:3F:0B",
        "username": "Lenovo PC",
        "company": "Iphone",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "3"
    }
],
"start": 0,
"limit": 15,
"end": 15,
"pageNumber": 1,
"totalSize": 7,
"totalPages": 1
</code>```

}

my html：

```<code>$('#tree').jqGrid({
            "url":"wifi.json",
            "styleUI" : 'Bootstrap',
            "colModel":[
                {
                    "name":"id",
                    "index":"id",
                    "sorttype":"int",
                    "key":true,
                    "hidden":true,
                    "width":50
                },{
                    "name":"username",
                    "index":"username",
                    "sorttype":"string",
                    "label":"Name",
                    "width":170,
                    formatter: function (value, grid, rows, state) {
                        return "test："+value;
                    }
                },{
                    "name":"mac",
                    "index":"mac",
                    "sorttype":"string",
                    "hidden":false,
                    "width":50
                }
            ],
            "width":"600",
            "hoverrows":false,
            "viewrecords":false,
            "gridview":true,
            "height":"auto",
            "loadonce":true,
            "rowNum":100,
            "scrollrows":true,
            // enable tree grid
            "treeGrid":true,
            // which column is expandable
            "ExpandColumn":"username",//点击那一列触发展开，收缩操作
            // datatype
            "treedatatype":"json",
            "treeIcons":{plus:'glyphicon-triangle-right',minus:'glyphicon-triangle-bottom',leaf:''},//plus：折叠起来的图标，minus：展开的图标,leaf：没有子节点了的图标
            // the model used
            "treeGridModel":"adjacency",
            "tree_root_level":0,
            // configuration of the data comming from server
            "treeReader":{
                //"left_field":"id",
                //"right_field":"id",
                "level_field":"level",//当前菜单的级别1级菜单，2级菜单....
                "parent_id_field": "p_id",//数据里面的父级节点的名称
                //"leaf_field":"isLeaf",
                "expanded_field":"expanded",//是否展开子节点
                //"loaded":"loaded",
                "icon_field":"icon"
            },
            jsonReader: {
                root: "values",
                repeatitems : false
            },
            "sortorder":"asc",
            "datatype":"json"
        });
</code>```

I have a question，Whether the data needs to be sorted in order to show it？
Test time, the results show is chaos, please, how to modify this?
enter image description here

答:
It's important to understand that the current implementation of old jqGrid, commercial Guriddo jqGrid JS (which you use currently) and free jqGrid suppose specific order of items in the input data. The nodes or leafs have to follow its parent node.

The items with ids from 4 till 6 contains the property "p_id": "2". It means that one have to move the items to place there directly after the item "id": "2" (between the item "id": "2" and the item "id": "3"). It should fix the problem, which you describes.

Title: Jqgrid treegrid Data format

Body:
my surroundings：jqgrid 5.1 ，php 5.3

my data：

{
"values": [
    {
        "id": "1",
        "mac": "64:09:80:57:A6:EE",
        "username": "WIFI-DQ",
        "company": "Xiaomi Communications Co Ltd",
        "isLeaf": false,
        "expanded": true,
        "level":0,
        "p_id": "0"
    },
    {
        "id": "2",
        "mac": "F0:B4:29:5A:B5:0F",
        "username": "1001",
        "company": "Tenda Technology Co., Ltd.",
        "isLeaf": false,
        "expanded": true,
        "level":0,
        "p_id": "0"
    },
    {
        "id": "3",
        "mac": "64:09:80:57:A6:EF",
        "username": "WIFI-DQ_5G",
        "company": "TP-LINK TECHNOLOGIES CO.,LTD.",
        "isLeaf": false,
        "expanded": true,
        "level":0,
        "p_id": "0"
    },
    {
        "id": "4",
        "mac": "00:1C:BF:8B:DF:8E",
        "username": "QCL16",
        "company": "Intel Corporate",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "2"
    },
    {
        "id": "5",
        "mac": "98:2F:3C:07:56:36",
        "username": "admin23",
        "company": "Xiaomi Communications Co Ltd",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "2"
    },
    {
        "id": "6",
        "mac": "34:80:B3:FC:3F:0B",
        "username": "Iphone",
        "company": "Iphone",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "2"
    },
    {
        "id": "7",
        "mac": "35:85:B3:DC:3F:0B",
        "username": "Lenovo PC",
        "company": "Iphone",
        "isLeaf": true,
        "expanded": true,
        "level":1,
        "p_id": "3"
    }
],
"start": 0,
"limit": 15,
"end": 15,
"pageNumber": 1,
"totalSize": 7,
"totalPages": 1

}

my html：

$('#tree').jqGrid({
            "url":"wifi.json",
            "styleUI" : 'Bootstrap',
            "colModel":[
                {
                    "name":"id",
                    "index":"id",
                    "sorttype":"int",
                    "key":true,
                    "hidden":true,
                    "width":50
                },{
                    "name":"username",
                    "index":"username",
                    "sorttype":"string",
                    "label":"Name",
                    "width":170,
                    formatter: function (value, grid, rows, state) {
                        return "test："+value;
                    }
                },{
                    "name":"mac",
                    "index":"mac",
                    "sorttype":"string",
                    "hidden":false,
                    "width":50
                }
            ],
            "width":"600",
            "hoverrows":false,
            "viewrecords":false,
            "gridview":true,
            "height":"auto",
            "loadonce":true,
            "rowNum":100,
            "scrollrows":true,
            // enable tree grid
            "treeGrid":true,
            // which column is expandable
            "ExpandColumn":"username",//点击那一列触发展开，收缩操作
            // datatype
            "treedatatype":"json",
            "treeIcons":{plus:'glyphicon-triangle-right',minus:'glyphicon-triangle-bottom',leaf:''},//plus：折叠起来的图标，minus：展开的图标,leaf：没有子节点了的图标
            // the model used
            "treeGridModel":"adjacency",
            "tree_root_level":0,
            // configuration of the data comming from server
            "treeReader":{
                //"left_field":"id",
                //"right_field":"id",
                "level_field":"level",//当前菜单的级别1级菜单，2级菜单....
                "parent_id_field": "p_id",//数据里面的父级节点的名称
                //"leaf_field":"isLeaf",
                "expanded_field":"expanded",//是否展开子节点
                //"loaded":"loaded",
                "icon_field":"icon"
            },
            jsonReader: {
                root: "values",
                repeatitems : false
            },
            "sortorder":"asc",
            "datatype":"json"
        });

I have a question，Whether the data needs to be sorted in order to show it？
Test time, the results show is chaos, please, how to modify this?
enter image description here


来源: stackexchange

问:
Finding all numbers in a array with top frequency?
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

```<code>8 => 2
1 => 2
9 => 2
</code>```

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

```<code>    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }
</code>```

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

```<code>    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }
</code>```

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

答:
I believe this to be the simplest optimal (O(n), for this problem) answer. As in many other answers, it calculates frequency for all integers. Unlike others, it does not need a second pass to find the most frequent result, and in particular does not perform a sort-by-frequency, which is overkill if you only need "the most frequent". Also, short code is easier to debug.

```<code>   public static ArrayList<Integer> mostFrequent(int [] numbers) {
        HashMap<Integer, Integer> frequencies = new HashMap<>();
        ArrayList<Integer> mostFrequent = new ArrayList<>();
        int greatestFrequency = 0;
        for (int n : numbers) {

            // build number -> frequency of number map
            int f = frequencies.getOrDefault(n, 0) + 1;
            frequencies.put(n, f);

            if (f > greatestFrequency) {
                // this number is more frequent than all others:
                //  it is now the sole, most frequent, number: no ties
                mostFrequent.clear();
                greatestFrequency = f;
            }
            if (f == greatestFrequency) {
                // this number is as frequent as the most frequent:
                //  add it to the list of numbers tied for this privilege
                mostFrequent.add(n);
            }
        }

        // print out the final list of numbers that are tied for "most frequent"
        for (int n : mostFrequent) {
            System.out.println(n + " => " + greatestFrequency);
        }
    }
</code>```

Note that null is only returned for empty lists. Throwing an exception could also be valid. With little work, this code would accept any Iterable<Number>, but this would make it somewhat harder to understand. I doubt that the OP wants to use it in a production system.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

8 => 2
1 => 2
9 => 2

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

Body:
I believe this to be the simplest optimal (O(n), for this problem) answer. As in many other answers, it calculates frequency for all integers. Unlike others, it does not need a second pass to find the most frequent result, and in particular does not perform a sort-by-frequency, which is overkill if you only need "the most frequent". Also, short code is easier to debug.

   public static ArrayList<Integer> mostFrequent(int [] numbers) {
        HashMap<Integer, Integer> frequencies = new HashMap<>();
        ArrayList<Integer> mostFrequent = new ArrayList<>();
        int greatestFrequency = 0;
        for (int n : numbers) {

            // build number -> frequency of number map
            int f = frequencies.getOrDefault(n, 0) + 1;
            frequencies.put(n, f);

            if (f > greatestFrequency) {
                // this number is more frequent than all others:
                //  it is now the sole, most frequent, number: no ties
                mostFrequent.clear();
                greatestFrequency = f;
            }
            if (f == greatestFrequency) {
                // this number is as frequent as the most frequent:
                //  add it to the list of numbers tied for this privilege
                mostFrequent.add(n);
            }
        }

        // print out the final list of numbers that are tied for "most frequent"
        for (int n : mostFrequent) {
            System.out.println(n + " => " + greatestFrequency);
        }
    }

Note that null is only returned for empty lists. Throwing an exception could also be valid. With little work, this code would accept any Iterable<Number>, but this would make it somewhat harder to understand. I doubt that the OP wants to use it in a production system.


问:
Selenium - ScrollIntoView - hiding element behind header/footer
Problem : ScrollIntoView hiding element behind header/footer . My application is having header/footer .

Tried following solutions :

1) ScrollIntoView(true) , it hiding web element behind header if element is up and tried to scroll from bottom .

2) Sending true/false  , it works , but I don't know exact location of element , so cant use every time to tell framework scroll down/up towards element .

3) Directly clicked ( taken action ) on element , chrome automatically scroll to visibility , but header is present that's why it hiding behind that .

Please let me know is there any single code that will make a element visible even it header/footer present .Looking solution is c# and using chrome browser .

答:
You can do that using Actions API.

Check whether element is present.

Move to element using Actions class.

Check element is visible.

If element is visible then perform action on element.

```<code>By element = By.id("element_id");
if(driver.findElements(element).size()>0){
    Actions action = new Actions(driver);
    action.moveToElement(driver.findElement(element).perform();
    if(driver.findElement(element).isDisplayed()){
        driver.findElement(element).click();
    }
}
</code>```

Body:
You can do that using Actions API.

Check whether element is present.

Move to element using Actions class.

Check element is visible.

If element is visible then perform action on element.

By element = By.id("element_id");
if(driver.findElements(element).size()>0){
    Actions action = new Actions(driver);
    action.moveToElement(driver.findElement(element).perform();
    if(driver.findElement(element).isDisplayed()){
        driver.findElement(element).click();
    }
}


问:
Drools working concurrency drools 5.5.0
How to use drools in an environment where multiple users are working or accessing rules for the same operation.
Considering a drl which contains 5 rules and now these rules are being accessed by multiple users. This is obvious that rules will be stored in knowledgesession. Each time when a request happens system will do i/o and loads dt and drls then a new knowledgesession will be created.
We are going to have more than 1500 rules which will be managed in 150+ dts and 150+ drls.

A sample code lead will be appreciated.

答: The same knowledge session can be used by multiple requests as the the rules remain constant independent of the requests.I have created a KIE session when application loads which is independent of requests made.</p>

Title: Drools working concurrency drools 5.5.0


问:
How to read array in jade file node.js
I have this array set from my route to view

```<code>[ 'dgdgd',
  'gdgdfg',
  'gdgd',
  'dgdg',
  'gdfdg',
  'gdg']
</code>```

In my jade file I wrote

```<code>select#e1.col-md-12.getDb(name='dbname')
    option
    for myset, i in data
        option #{myset}
</code>```

I am completely new to jade. How could I go about doing this?

答:
You should use jade syntax from here </p>

```<code>select#e1.col-md-12.getDb(name='dbname')
    option
  each val, index in data
    option=val
</code>```

Title: How to read array in jade file node.js

Body:
I have this array set from my route to view

[ 'dgdgd',
  'gdgdfg',
  'gdgd',
  'dgdg',
  'gdfdg',
  'gdg']

In my jade file I wrote

select#e1.col-md-12.getDb(name='dbname')
    option
    for myset, i in data
        option #{myset}

I am completely new to jade. How could I go about doing this?

Body:
You should use jade syntax from here

select#e1.col-md-12.getDb(name='dbname')
    option
  each val, index in data
    option=val


问:
how to extract a number from a string if I know when its starting and when its finishing
for example:

I have the following string

```<code>"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"
</code>```

so the number is always between

```<code>theStringBeforeTheNumber{number}theStringAfterTheNumber
</code>```

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like?   val myRgx: Regex = """myRegexGoesHere""".r

答:
If you know the starting and finish string, I think that is better do a substring() because in general the regexp is costly.
For example
substring(indexOf(theStringBeforeTheNumber) + length(theStringBeforeTheNumber) , indexOf(theStringAfterTheNumber))
Also you must consider if the initial and final string are equals because the indexes, in that case you have do some extra calculation.
Hope this help.</p>

Body:
for example:

I have the following string

"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

so the number is always between

theStringBeforeTheNumber{number}theStringAfterTheNumber

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like?   val myRgx: Regex = """myRegexGoesHere""".r


问:
AspNetCore custom TagHelpers not displaying
I am running a AspNetCore application and trying to create a custom TagHelper, its just not rendering. I have read quite a few articles and i think i have everything i need.

project.json

```<code>"Microsoft.AspNetCore.Mvc.TagHelpers": "1.1.3",
</code>```

_ViewImport.cshtml

```<code>@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</code>```

ReverseTextDivTagHelper.cs

The below code i got from an example i was trying

```<code>[HtmlTargetElement("tag-name")]
    public class ReverseTextDivTagHelper : TagHelper
    {
        private string _divData = string.Empty;
        public string DivData
        {
            get
            {
                char[] reversedData = _divData.ToCharArray();
                Array.Reverse(reversedData);
                String sDataReversed = new String(reversedData);
                return AllCaps ? sDataReversed.ToUpper() : sDataReversed;
            }
            set { _divData = value; }
        }

        public bool AllCaps { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.Content.SetContent(DivData);
        }
    }
</code>```

And then in a partial view i am calling it like this

```<code><reverse-text-div all-caps="true" div-data="Jacques"></reverse-text-div>
</code>```

答:
Point 1: [HtmlTargetElement("tag-name")] has to be same as actual HTML tag i.e. reverse-text-div. It should be [HtmlTargetElement("reverse-text-div")]

Point 2: Apply HtmlAttributeName for your properties e.g. [HtmlAttributeName("all-caps")]

Body:
I am running a AspNetCore application and trying to create a custom TagHelper, its just not rendering. I have read quite a few articles and i think i have everything i need.

project.json

"Microsoft.AspNetCore.Mvc.TagHelpers": "1.1.3",

_ViewImport.cshtml

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

ReverseTextDivTagHelper.cs

The below code i got from an example i was trying

[HtmlTargetElement("tag-name")]
    public class ReverseTextDivTagHelper : TagHelper
    {
        private string _divData = string.Empty;
        public string DivData
        {
            get
            {
                char[] reversedData = _divData.ToCharArray();
                Array.Reverse(reversedData);
                String sDataReversed = new String(reversedData);
                return AllCaps ? sDataReversed.ToUpper() : sDataReversed;
            }
            set { _divData = value; }
        }

        public bool AllCaps { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.Content.SetContent(DivData);
        }
    }

And then in a partial view i am calling it like this

<reverse-text-div all-caps="true" div-data="Jacques"></reverse-text-div>


问:
Laravel connection MSSqL server works with cli, but not in browser
After installing the dll's to use with MSSqL server, the command php artisan migrate ran correctly and the tables were made in the db. So I thought the connection would work for this application.

I then used the command php artisan make:auth (which doesn't use the db connection) to scaffold the authentication files.

Now when I try to register anyone I get errors:

PDOExeption (1/2)

Could not find driver

and

PDOExeption (2/2)

Could not find driver (select count(*) from .....

Now I tried to see if using the cli commands still work and both php artisan migrate:rollback and php artisan migrate still work.

Environment:
Windows 7 with xampp installed.
Versions: Laravel 5.4, php 7.1

Not that it matters but here are parts of my .env and database.php files:

```<code>`database.php`
        'sqlsrv' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', '10.0.0.40'),
        'port' => env('DB_PORT', '1433'),
        'database' => env('DB_DATABASE', 'sqlcon'),
        'username' => env('DB_USERNAME', 'sa'),
        'password' => env('DB_PASSWORD', 'test'),
        'charset' => 'utf8',
        'prefix' => '',
    ],

`.env`
DB_CONNECTION=sqlsrv
DB_HOST=10.0.0.40
DB_PORT=1433
DB_DATABASE=sqlcon
DB_USERNAME=sa
DB_PASSWORD=test
</code>```

So how come the cli commands work and the browser don't?

Doesn't laravel use the same config for both cli and browser connections?

Update: added some extra info

C:\xampp\htdocs\sqlcon>php --ini

Configuration File (php.ini) Path: C:\Windows

Loaded Configuration File:         C:\xampp\php\php.ini

Scan for additional .ini files in: (none)

Additional .ini files parsed:      (none)

Used this to show my php configuration and it shows:

Loaded Configuration File C:\xampp\php\php.ini

The php -m command shows:

C:\xampp\htdocs\sqlcon>php -m

[PHP Modules]

bcmath

...(some others)

pdo_mysql

pdo_sqlite

pdo_sqlsrv (this one is enabled)

Phar

...

[Zend Modules]

According to php -m the pdo_sqlsrv is enabled, but I can't find any reference to it in the phpinfo page.

答:
What I thought had fixed the problem

When installing the driver in php.ini I used the following line as this was the name of the file in the extension directory (extension_dir="C:\xampp\php\ext"):

```<code>extension=php_pdo_sqlsrv_71_ts.dll
</code>```

Changing both the name of the file in this directory and the reference to it in the php.ini file and restarting apache solved the problem.

So now the file is php_pdo_sqlsrv.dll and the reference is:

```<code>extension=php_pdo_sqlsrv.dll
</code>```

What actually fixed the problem

Installing this after downloading the dlls and making the change to php.ini.

Don't forget to restart apache.

Body:
After installing the dll's to use with MSSqL server, the command php artisan migrate ran correctly and the tables were made in the db. So I thought the connection would work for this application.

I then used the command php artisan make:auth (which doesn't use the db connection) to scaffold the authentication files.

Now when I try to register anyone I get errors:

PDOExeption (1/2)

Could not find driver

and

PDOExeption (2/2)

Could not find driver (select count(*) from .....

Now I tried to see if using the cli commands still work and both php artisan migrate:rollback and php artisan migrate still work.

Environment:
Windows 7 with xampp installed.
Versions: Laravel 5.4, php 7.1

Not that it matters but here are parts of my .env and database.php files:

`database.php`
        'sqlsrv' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', '10.0.0.40'),
        'port' => env('DB_PORT', '1433'),
        'database' => env('DB_DATABASE', 'sqlcon'),
        'username' => env('DB_USERNAME', 'sa'),
        'password' => env('DB_PASSWORD', 'test'),
        'charset' => 'utf8',
        'prefix' => '',
    ],

`.env`
DB_CONNECTION=sqlsrv
DB_HOST=10.0.0.40
DB_PORT=1433
DB_DATABASE=sqlcon
DB_USERNAME=sa
DB_PASSWORD=test

So how come the cli commands work and the browser don't?

Doesn't laravel use the same config for both cli and browser connections?

Update: added some extra info

C:\xampp\htdocs\sqlcon>php --ini

Configuration File (php.ini) Path: C:\Windows

Loaded Configuration File:         C:\xampp\php\php.ini

Scan for additional .ini files in: (none)

Additional .ini files parsed:      (none)

Used this to show my php configuration and it shows:

Loaded Configuration File C:\xampp\php\php.ini

The php -m command shows:

C:\xampp\htdocs\sqlcon>php -m

[PHP Modules]

bcmath

...(some others)

pdo_mysql

pdo_sqlite

pdo_sqlsrv (this one is enabled)

Phar

...

[Zend Modules]

According to php -m the pdo_sqlsrv is enabled, but I can't find any reference to it in the phpinfo page.

Body:
What I thought had fixed the problem

When installing the driver in php.ini I used the following line as this was the name of the file in the extension directory (extension_dir="C:\xampp\php\ext"):

extension=php_pdo_sqlsrv_71_ts.dll

Changing both the name of the file in this directory and the reference to it in the php.ini file and restarting apache solved the problem.

So now the file is php_pdo_sqlsrv.dll and the reference is:

extension=php_pdo_sqlsrv.dll

What actually fixed the problem

Installing this after downloading the dlls and making the change to php.ini.

Don't forget to restart apache.


问:
Write string with newline to a text file c++
First I don't know if my question already asked but I searched a lot and didn't find a straight forward answer to this question yet.
I want to create a program to read a string wich has newlines \n in it and write the contents back to a text file on SD card with fprintf() function. My compiler is ARM_GCC and I'm using a specific library which only has fprintf() and fwrite() to write a string, so I preferred to only use these functions, but If you think there is another way I would appreciate if you say so.
I can easily use this program to write a string to file:

```<code>void sd_open(string sd_value)
{
  printf("Writing to Sd card...");
  FILE* fd = fopen("/sd/numbers.txt", "w+");
  fprintf(fd, "%s",sd_value.c_str());
  fclose(fd);
  printf("writed this value to sd: %s\r\n", sd_value.c_str());
  printf("Done\n");
}
</code>```

The problem is this code write the values of sd_value to one line only, I tought about using a for loop to search for newline in string and write line by line to a file but I dont know how to implement that.
Thanks.

EDIT...
suppose that sd_value is something like this:

```<code>string sd_value="Hello\nWelcome\nBye"
</code>```

which must be stored as the following to the text file:

```<code>Hello
Welcome
Bye
</code>```

Actually, sd_value is not handling in my program and a user types a value in another application and I receive it as a string. I can tell the user to use \n in his text box to enter a newline but don't know how to treat it as a newline in my code.

答:
There are many easy ways to do what you want but I really need example how the input is taken (sd_value)
What you are saying means that string sd_value contains :HELLO WELCOME BYE ....
and never do a newline

Answers if like what I thought :

Each time you read a string end it with

```<code>*sd_value += "\n";*
</code>```

If you have a lot of lines to process, using stringstream could be more efficient.

ostringstream lines;

lines << "Line 1" << endl;
lines << "Line 2" << endl;

cout << lines.str();   // .str() is a string
```

Body:
First I don't know if my question already asked but I searched a lot and didn't find a straight forward answer to this question yet.
I want to create a program to read a string wich has newlines \n in it and write the contents back to a text file on SD card with fprintf() function. My compiler is ARM_GCC and I'm using a specific library which only has fprintf() and fwrite() to write a string, so I preferred to only use these functions, but If you think there is another way I would appreciate if you say so.
I can easily use this program to write a string to file:

void sd_open(string sd_value)
{
  printf("Writing to Sd card...");
  FILE* fd = fopen("/sd/numbers.txt", "w+");
  fprintf(fd, "%s",sd_value.c_str());
  fclose(fd);
  printf("writed this value to sd: %s\r\n", sd_value.c_str());
  printf("Done\n");
}

The problem is this code write the values of sd_value to one line only, I tought about using a for loop to search for newline in string and write line by line to a file but I dont know how to implement that.
Thanks.

EDIT...
suppose that sd_value is something like this:

string sd_value="Hello\nWelcome\nBye"

which must be stored as the following to the text file:

Hello
Welcome
Bye

Actually, sd_value is not handling in my program and a user types a value in another application and I receive it as a string. I can tell the user to use \n in his text box to enter a newline but don't know how to treat it as a newline in my code.

Body:
There are many easy ways to do what you want but I really need example how the input is taken (sd_value)
What you are saying means that string sd_value contains :HELLO WELCOME BYE ....
and never do a newline

Answers if like what I thought :

Each time you read a string end it with

*sd_value += "\n";*

If you have a lot of lines to process, using stringstream could be more efficient.

ostringstream lines;

lines << "Line 1" << endl;
lines << "Line 2" << endl;

cout << lines.str();   // .str() is a string


问:
Changing connection managers from SQLNCLI11.1 to SQLOLEDB.1?
I've been doing some porting of old SSIS packages from a legacy system into a new system. I was running some tests only to see some kind of error output related to the ODBC connection with Code: 0xC0202009.

The package's two connection managers are both built with SQLNCLI11.1 as the provider.

I believe I can fix the error if I switch that to SQLOLEDB.1. Is there a simple way to do that without having to rebuild the entire package from scratch? Is there an XML file somewhere I can just replace the old value with the new one?

答:
The only way is to open the package (.dtsx) file with a text editor (notepad, notepad++). And search for this property and replace it manually. (.Dtsx file is  an xml file)

But replacing this property may cause other errors if each provider has different properties. So Take a backup of these packages before editing.

Take a look at this question it may help you (check my answer and the others. It will give you an idea on how a dtsx file can be readed outside of visual studio):

Automate Version number Retrieval from .Dtsx files


问:
Cannot access JSON object property in JavaScript
I have a json object

```<code>alert(typeof object)
//Output
Object
</code>```

which returns the following string after

```<code>alert(JSON.stringify(object));

//Output object

[{
"locationId":"8",
"locationTypeId":"0",
"locationTitle":"Alberta Prices",
"locationAddress":"Alberta, Canada",
"locationStatus":"0",
"locationLatitude":"53.9332706",
"locationLongitude":"116.5765035",
"googleLocationId":"ChIJtRkkqIKyCVMRno6bQJpHqbA",
"lastModified":"2017-06-04 03:59:02",
"locationType":"SPORT",
"userId":"4"
}]
</code>```

When I am trying to access any property of the object, I get 'Undefined';

```<code>alert(object.locationId);

//Output
Undefined
</code>```

答:
You can access the locationId value with following statement.

```<code>x = JSON.stringify(object)
x[0].locationId
 8
</code>```

I had tried on chrome console it was working for me. Pop up (alert) box contains 8 value.

Body:
I have a json object

alert(typeof object)
//Output
Object

which returns the following string after

alert(JSON.stringify(object));

//Output object

[{
"locationId":"8",
"locationTypeId":"0",
"locationTitle":"Alberta Prices",
"locationAddress":"Alberta, Canada",
"locationStatus":"0",
"locationLatitude":"53.9332706",
"locationLongitude":"116.5765035",
"googleLocationId":"ChIJtRkkqIKyCVMRno6bQJpHqbA",
"lastModified":"2017-06-04 03:59:02",
"locationType":"SPORT",
"userId":"4"
}]

When I am trying to access any property of the object, I get 'Undefined';

alert(object.locationId);

//Output
Undefined

Body:
You can access the locationId value with following statement.

x = JSON.stringify(object)
x[0].locationId
 8

I had tried on chrome console it was working for me. Pop up (alert) box contains 8 value.


问:
UTF-8 String decoding in Python
In a project I need a PHP and a Python module (Python 3.5.2). As well as a configfile which both modules use. The Python configparser has problems reading special characters from the configfile, like german mutated vowel (ä,ö,ü, e.g.). From the PHP side I use the utf-8 encoding to bypass the problem:

```<code>    utf8_encode ("Köln") //result: KÃ¶ln
</code>```

From the Python side I tried the decode function:

```<code>    "KÃ¶ln".decode("utf-8", "strict")
</code>```

I expected the result "Köln" but just got the result "KÃ¶ln" again.
What do I have do to do to decode my String?

答:
Thanks for all the helpfull answers and comments. I finally ended up with the following solution:

On the PHP side I encode my string with the following command:

```<code>$str = "path/to/file/Köln.jpg";
json_encode ($str, JSON_UNESCAPED_SLASHES);
</code>```

The result is the string "path/to/file/K\u00f6ln.jpg" which is then stored in my config file.
The Python module uses ConfigParser to read the file. The encoded string is then decoded with the following command:

```<code>str.encode('utf8').decode('utf8')
</code>```

The result is again "path/to/file/Köln.jpg".

Title: UTF-8 String decoding in Python

Body:
In a project I need a PHP and a Python module (Python 3.5.2). As well as a configfile which both modules use. The Python configparser has problems reading special characters from the configfile, like german mutated vowel (ä,ö,ü, e.g.). From the PHP side I use the utf-8 encoding to bypass the problem:

    utf8_encode ("Köln") //result: KÃ¶ln

From the Python side I tried the decode function:

    "KÃ¶ln".decode("utf-8", "strict")

I expected the result "Köln" but just got the result "KÃ¶ln" again.
What do I have do to do to decode my String?

Body:
Thanks for all the helpfull answers and comments. I finally ended up with the following solution:

On the PHP side I encode my string with the following command:

$str = "path/to/file/Köln.jpg";
json_encode ($str, JSON_UNESCAPED_SLASHES);

The result is the string "path/to/file/K\u00f6ln.jpg" which is then stored in my config file.
The Python module uses ConfigParser to read the file. The encoded string is then decoded with the following command:

str.encode('utf8').decode('utf8')

The result is again "path/to/file/Köln.jpg".


问:
Is it possible to modify an existing TensorFlow computation graph?
TensorFlow graph is usually built gradually from inputs to outputs, and then executed. Looking at the Python code, the inputs lists of operations are immutable which suggests that the inputs should not be modified. Does that mean that there is no way to update/modify an existing graph?</p>

答:
Yes, tf.Graph are build in an append-only fashion as @mrry puts it.

But there's workaround:

Conceptually you can modify an existing graph by cloning it and perform the modifications needed along the way. As of r1.1, Tensorflow provides a module named tf.contrib.graph_editor which implements the above idea as a set of convinient functions.


问:
Use windows form whilst command prompt is running
What I am working on is a program that runs a command on command prompt and outputs the outcome into the form. But whenever you start the command it locks up the windows form and then you can no longer click anything on the form. This is an issue because I want to add a stop button, please see below for the appropriate code.</p>

```<code>private void Start_Click(object sender, EventArgs e)
    {
        var proc = new Process();
        proc.StartInfo.Arguments = "/C robocopy " + "\"" + source.Text + "\" \"" + Destination.Text + "\" /E /ZB /W:1 /R:3 /MT /A-:SH";
        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.RedirectStandardError = true;
        proc.EnableRaisingEvents = true;
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.UseShellExecute = false;
        // see below for output handler
        proc.ErrorDataReceived += proc_DataReceived;
        proc.OutputDataReceived += proc_DataReceived;

        proc.Start();

        proc.BeginErrorReadLine();
        proc.BeginOutputReadLine();

        proc.WaitForExit();

    }
</code>```

答:
Remove the call to proc.WaitForExit(); as this blocks execution. See [the docs] (https://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforexit(v=vs.110).aspx) about WaitForExit:

Sets the period of time to wait for the associated process to exit, and blocks the current thread of execution until the time has elapsed or the process has exited. To avoid blocking the current thread, use the Exited event.

As stated, if you want to run code after the process has exited use the Exited event. Since your code does not do that you might just skip this step.

Body:
What I am working on is a program that runs a command on command prompt and outputs the outcome into the form. But whenever you start the command it locks up the windows form and then you can no longer click anything on the form. This is an issue because I want to add a stop button, please see below for the appropriate code.

private void Start_Click(object sender, EventArgs e)
    {
        var proc = new Process();
        proc.StartInfo.Arguments = "/C robocopy " + "\"" + source.Text + "\" \"" + Destination.Text + "\" /E /ZB /W:1 /R:3 /MT /A-:SH";
        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.RedirectStandardError = true;
        proc.EnableRaisingEvents = true;
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.UseShellExecute = false;
        // see below for output handler
        proc.ErrorDataReceived += proc_DataReceived;
        proc.OutputDataReceived += proc_DataReceived;

        proc.Start();

        proc.BeginErrorReadLine();
        proc.BeginOutputReadLine();

        proc.WaitForExit();

    }


问:
OneSignal and Gradle error
I dont know where I went wrong, but this keeps me saying

```<code>All com.android.support libraries must use the same exact version
specification (mixing versions can lead to runtime crashes.) Found
versions 25.3.1, 24.0.0. Examples include com.android.support:animated
vector-drawable:25.3.1 and com.android.support:customtabs-v7:24.0.0
</code>```

my build.gradle is

```<code>buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }

    mavenCentral()
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.22.1'
    classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
  }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.jakewharton.hugo'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
  compileSdkVersion 25
  buildToolsVersion '25.0.3'
  defaultConfig {
    applicationId "cosmic.com.fest"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

flavorDimensions "server"

productFlavors {

    local {
        applicationId "cosmic.com.fest.local"
        dimension 'server'
    }

    dev {
        applicationId "cosmic.com.fest"
        dimension 'server'
    }
  }

defaultConfig {
    manifestPlaceholders = [onesignal_app_id: "something",
    onesignal_google_project_number: "something"]
  }
}

def ANDROID_SUPPORT_VERSION = "25.3.1"

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
compile "com.android.support:appcompat-v7:$ANDROID_SUPPORT_VERSION"
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.afollestad.material-dialogs:core:0.8.6.1'
compile 'com.orhanobut:logger:1.15'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile "com.android.support:design:$ANDROID_SUPPORT_VERSION"
compile "com.android.support:support-vector-drawable:$ANDROID_SUPPORT_VERSION"
testCompile 'junit:junit:4.12'
compile 'org.apache.commons:commons-lang3:3.5'
compile "com.android.support:recyclerview-v7:$ANDROID_SUPPORT_VERSION"

compile 'com.google.firebase:firebase-messaging:10.2.6'

compile 'com.onesignal:OneSignal:3.5.6'

// Required for OneSignal, even if you have added FCM.
compile 'com.google.android.gms:play-services-gcm:10.2.6'

// Required for geotagging
compile "com.google.android.gms:play-services-location:10.2.6"

// play-services-analytics is only needed when using 8.1.0 or older.
compile 'com.google.android.gms:play-services-analytics:10.2.6'
}
</code>```

I need to add OneSignal notifications with Firebase to obtain tokens.

When I tried this solution, my appcompat would still complain the same.

答:
Solved it.

Actually I was changing the ANDROID_SUPPORT_VERSION to 24.0.0 which changed all library version. Once I did,

```<code>compile 'com.android.support:appcompat-v7:24.0.0'
</code>```

problem solved.

Title: OneSignal and Gradle error

Body:
I dont know where I went wrong, but this keeps me saying

All com.android.support libraries must use the same exact version
specification (mixing versions can lead to runtime crashes.) Found
versions 25.3.1, 24.0.0. Examples include com.android.support:animated
vector-drawable:25.3.1 and com.android.support:customtabs-v7:24.0.0

my build.gradle is

buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }

    mavenCentral()
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.22.1'
    classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
  }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.jakewharton.hugo'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
  compileSdkVersion 25
  buildToolsVersion '25.0.3'
  defaultConfig {
    applicationId "cosmic.com.fest"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

flavorDimensions "server"

productFlavors {

    local {
        applicationId "cosmic.com.fest.local"
        dimension 'server'
    }

    dev {
        applicationId "cosmic.com.fest"
        dimension 'server'
    }
  }

defaultConfig {
    manifestPlaceholders = [onesignal_app_id: "something",
    onesignal_google_project_number: "something"]
  }
}

def ANDROID_SUPPORT_VERSION = "25.3.1"

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
compile "com.android.support:appcompat-v7:$ANDROID_SUPPORT_VERSION"
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.afollestad.material-dialogs:core:0.8.6.1'
compile 'com.orhanobut:logger:1.15'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile "com.android.support:design:$ANDROID_SUPPORT_VERSION"
compile "com.android.support:support-vector-drawable:$ANDROID_SUPPORT_VERSION"
testCompile 'junit:junit:4.12'
compile 'org.apache.commons:commons-lang3:3.5'
compile "com.android.support:recyclerview-v7:$ANDROID_SUPPORT_VERSION"

compile 'com.google.firebase:firebase-messaging:10.2.6'

compile 'com.onesignal:OneSignal:3.5.6'

// Required for OneSignal, even if you have added FCM.
compile 'com.google.android.gms:play-services-gcm:10.2.6'

// Required for geotagging
compile "com.google.android.gms:play-services-location:10.2.6"

// play-services-analytics is only needed when using 8.1.0 or older.
compile 'com.google.android.gms:play-services-analytics:10.2.6'
}

I need to add OneSignal notifications with Firebase to obtain tokens.

When I tried this solution, my appcompat would still complain the same.

Body:
Solved it.

Actually I was changing the ANDROID_SUPPORT_VERSION to 24.0.0 which changed all library version. Once I did,

compile 'com.android.support:appcompat-v7:24.0.0'

problem solved.


问:
Can't get the browser to read my CSS
Can't work out why this code is not working:

CSS then corresponding HTML:

.intro {
  border: 5px
  border-color: rgb(0,0,255);
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="intro">
   <p>writing</p>
   <p>writing</p>
</div></code>```

No variation seems to work, and I have checked this site, W3C, and seem to be writing the code correctly in the CSS file, but it just is not translating to the browser (Chrome).

答:
You forgot to end one of your CSS lines with a semicolon.

.intro {
 border: 5px;
 border-color: rgb(0,0,255);
 text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="intro">
   <p>writing</p>
   <p>writing</p>
  </div></code>```

Title: Can't get the browser to read my CSS

Body:
Can't work out why this code is not working:

CSS then corresponding HTML:

.intro {
  border: 5px
  border-color: rgb(0,0,255);
  text-align: center;
}

writing

writing

No variation seems to work, and I have checked this site, W3C, and seem to be writing the code correctly in the CSS file, but it just is not translating to the browser (Chrome).

Body:
You forgot to end one of your CSS lines with a semicolon.

.intro {
 border: 5px;
 border-color: rgb(0,0,255);
 text-align: center;
}

<div class="intro">
   <p>writing</p>
   <p>writing</p>
  </div>


问:
What is the naming convention for YARN containers used by Spark?
When running Spark jobs on top of YARN (yarn-cluster mode), YARN creates the workers in containers that have a name that looks something like this: container_e116_1495951495692_11203_01_000105

What is the naming convention for the containers?

Here is my educated guess:

container - Just a constant string, obviously

e116 - No Idea what this is. Maybe something to do with the YARN version.

1495951495692_11203 - The application-id

01 - An attempt counter?

000105 - This is probably just an increment integer.

If there is any concrete information about this (or even a refference to the right place in the code), I'd be glad to hear about it.

In light of the above, when running a Spark job on YARN, How can I know which containers belong to which executor?

答:
You can look at https://hadoop.apache.org/docs/current/api/org/apache/hadoop/yarn/api/records/ContainerId.html

A string representation of containerId. The format is container_eepoch_clusterTimestamp_appId_attemptId_containerId when epoch is larger than 0 (e.g. container_e17_1410901177871_0001_01_000005). epoch is increased when RM restarts or fails over. When epoch is 0, epoch is omitted (e.g. container_1410901177871_0001_01_000005).


问:
quaternion to angle
Alright, so this is how I am doing it:

```<code>float xrot = 0;
float yrot = 0;
float zrot = 0;

Quaternion q = new Quaternion().fromRotationMatrix(player.model.getRotation());
if (q.getW() > 1) {
    q.normalizeLocal();
}

float angle = (float) (2 * Math.acos(q.getW()));
double s = Math.sqrt(1-q.getW()*q.getW());

// test to avoid divide by zero, s is always positive due to sqrt
// if s close to zero then direction of axis not important
if (s < 0.001) {
    // if it is important that axis is normalised then replace with x=1; y=z=0;
    xrot = q.getXf();
    yrot = q.getYf();
    zrot = q.getZf();
    // z = q.getZ();
} else {
    xrot = (float) (q.getXf() / s); // normalise axis
    yrot = (float) (q.getYf() / s);
    zrot = (float) (q.getZf() / s);
}
</code>```

But it doesn't seem to work when I try to put it into use:

```<code>player.model.addTranslation(xrot * player.speed, 0, zrot * player.speed);
</code>```

AddTranslation takes 3 numbers to move my model by than many spaces (x, y, z), but hen I give it the numbers above it doesn't move the model in the direction it has been rotated (on the XZ plane)

Why isn't this working?

Edit: new code, though it's about 45 degrees off now.

```<code>Vector3 move = new Vector3();
move = player.model.getRotation().applyPost(new Vector3(1,0,0), move);
move.multiplyLocal(-player.speed);
player.model.addTranslation(move);
</code>```

答:
xrot, yrot, and zrot define the axis of the rotation specified by the quaternion.  I don't think you want to be using them in your addTranslation() call...in general, that won't have anything to do with the direction of motion.

What I mean by that is: your 3-D object -- let's say for the sake of argument that it's an airplane -- will have a certain preferred direction of motion in its original coordinate
system.  So if the original orientation has the center of mass at the origin, and the
propeller somewhere along the +X axis, the plane wants to fly in the +X direction.

Now you introduce some coordinate transformation that rotates the airplane into some other orientation.  That rotation is described by a rotation matrix, or equivalently, by a
quaternion.  Which way does the plane want to move after the rotation?

You could find
that by taking a unit vector in the +X direction: (1.0, 0.0, 0.0), then applying the
rotation matrix or quaternion to that vector to transform it into the new coordinate
system.  (Then scale it by the speed, as you're doing above.) The X, Y, and Z components
of the transformed, scaled vector give the desired incremental motion along each axis. That transformed vector is generally not going to be the rotation axis of the quaternion, and I think that's probably your problem.

ContentLicense: CC BY-SA 2.5

Title: quaternion to angle

Body:
Alright, so this is how I am doing it:

float xrot = 0;
float yrot = 0;
float zrot = 0;

Quaternion q = new Quaternion().fromRotationMatrix(player.model.getRotation());
if (q.getW() > 1) {
    q.normalizeLocal();
}

float angle = (float) (2 * Math.acos(q.getW()));
double s = Math.sqrt(1-q.getW()*q.getW());

// test to avoid divide by zero, s is always positive due to sqrt
// if s close to zero then direction of axis not important
if (s < 0.001) {
    // if it is important that axis is normalised then replace with x=1; y=z=0;
    xrot = q.getXf();
    yrot = q.getYf();
    zrot = q.getZf();
    // z = q.getZ();
} else {
    xrot = (float) (q.getXf() / s); // normalise axis
    yrot = (float) (q.getYf() / s);
    zrot = (float) (q.getZf() / s);
}

But it doesn't seem to work when I try to put it into use:

player.model.addTranslation(xrot * player.speed, 0, zrot * player.speed);

AddTranslation takes 3 numbers to move my model by than many spaces (x, y, z), but hen I give it the numbers above it doesn't move the model in the direction it has been rotated (on the XZ plane)

Why isn't this working?

Edit: new code, though it's about 45 degrees off now.

Vector3 move = new Vector3();
move = player.model.getRotation().applyPost(new Vector3(1,0,0), move);
move.multiplyLocal(-player.speed);
player.model.addTranslation(move);


问:
R move column to last using dplyr
For a data.frame with n columns, I would like to be able to move a column from any of 1-(n-1) positions, to be the nth column (i.e. a non-last column to be the last column). I would also like to do it using dplyr. I would like to do so without simply typing out the names of all the columns.

For example:

```<code>data<-data.frame(a=1:5, b=6:10, c=11:15)
</code>```

This works, but isn't the dplyr way:

```<code>data[,c(colnames(data)[colnames(data)!='b'],'b')]
</code>```

This is the dplyr way to make column b first:

```<code>data%>%select(b, everything())
</code>```

But this doesn't work to make column b last:

```<code>data%>%select(everything(), b)
</code>```

This works, but requires me to type out all the columns:

```<code>data%>%select(a,c,b)
</code>```

So is there an elegant dplyr way to do this?

Related questions:

move column to first in a data frame

How does one reorder columns in a data frame?

答:
Update:

dplyr::relocate, a new verb introduced in dplyr 1.0.0, is now my preferred solution, since it is explicit about what you are doing, you can continue to pick variables using tidyselect helpers, and you can specify exactly where to put the columns with .before or .after

data %>% relocate(b, .after = last_col())
(same as dule arnaux's update)

Original answer

```<code>data%>%select(-b,everything())
</code>```

will move variable b to the end.

This is because a negative variable in the first position of select elicits a special behavior from select(), which is to insert all the variables. Then it removes b, and then it gets added back with the everything() part.

Explained by Hadley himself: https://github.com/tidyverse/dplyr/issues/2838

Also see this other answer for other examples of how to move some columns to the end and other columns to the beginning:
How does dplyr's select helper function everything() differ from copying?

Title: R move column to last using dplyr

Body:
For a data.frame with n columns, I would like to be able to move a column from any of 1-(n-1) positions, to be the nth column (i.e. a non-last column to be the last column). I would also like to do it using dplyr. I would like to do so without simply typing out the names of all the columns.

For example:

data<-data.frame(a=1:5, b=6:10, c=11:15)

This works, but isn't the dplyr way:

data[,c(colnames(data)[colnames(data)!='b'],'b')]

This is the dplyr way to make column b first:

data%>%select(b, everything())

But this doesn't work to make column b last:

data%>%select(everything(), b)

This works, but requires me to type out all the columns:

data%>%select(a,c,b)

So is there an elegant dplyr way to do this?

Related questions:

move column to first in a data frame

How does one reorder columns in a data frame?

Body:
Update:

dplyr::relocate, a new verb introduced in dplyr 1.0.0, is now my preferred solution, since it is explicit about what you are doing, you can continue to pick variables using tidyselect helpers, and you can specify exactly where to put the columns with .before or .after

data %>% relocate(b, .after = last_col())
(same as dule arnaux's update)

Original answer

data%>%select(-b,everything())

will move variable b to the end.

This is because a negative variable in the first position of select elicits a special behavior from select(), which is to insert all the variables. Then it removes b, and then it gets added back with the everything() part.

Explained by Hadley himself: https://github.com/tidyverse/dplyr/issues/2838

Also see this other answer for other examples of how to move some columns to the end and other columns to the beginning:
How does dplyr's select helper function everything() differ from copying?

ContentLicense: CC BY-SA 4.0


问:
Replace image attributes for lazyload plugin on image elements with specific class
I'm using WordPress and I want to apply lazy load to only certain images. I found here a way to create the data-src attributes and replace the src attribute with the correct image https://wordpress.stackexchange.com/questions/60792/replace-image-attributes-for-lazyload-plugin-data-src. Right now my code applies the lazy load to all the images, and I just want to apply it to the images with the class lazy-load.

This is how my code looks

```<code>// Lazyload Converter
function add_lazyload($content) {

$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$dom = new DOMDocument();
@$dom->loadHTML($content);

$images = [];

foreach ($dom->getElementsByTagName('img') as $node) {
    $images[] = $node;
}

foreach ($images as $node) {
    $fallback = $node->cloneNode(true);

    $oldsrc = $node->getAttribute('src');
    $node->setAttribute('data-src', $oldsrc );
    $newsrc = get_template_directory_uri() . '/assets/placeholders/squares.svg';
    $node->setAttribute('src', $newsrc);

    $oldsrcset = $node->getAttribute('srcset');
    $node->setAttribute('data-srcset', $oldsrcset );
    $newsrcset = '';
    $node->setAttribute('srcset', $newsrcset);

    $noscript = $dom->createElement('noscript', '');
    $node->parentNode->insertBefore($noscript, $node);
    $noscript->appendChild($fallback);
}

$newHtml = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
return $newHtml;
}
add_filter('the_content', 'add_lazyload');
add_filter('post_thumbnail_html', 'add_lazyload');
</code>```

how can I get the element by class instead of using tag?

答:
You can use xpath (with domxpath) for this; xpath is a query language to select nodes from XML/HTML documents.

Unfortunately, selecting elements which have a class that is the stand-alone phrase lazy-load, is a bit convoluted with xpath; it's not as concise as you may perhaps be accustomed to with css-selectors; xpath doesn't have shorthand attribute selectors like @attr~="lazy-load", etc.

Here's an example of how you would select all  elements that have the class lazy-load:

```<code>// create a DOMXPath instance that operates on your DOMDocument instance $dom
$xpath = new DOMXPath( $dom );

// select nodes by some criteria (returns a non-live¹ DOMNodeList)
$images = $xpath->query( '//img[contains(concat(" ", normalize-space(@class), " "), " lazy-load ")]' );

// then apply the same operations to the nodes again as in your last foreach loop
foreach ($images as $node) {
  $fallback = $node->cloneNode(true);
  // etc.
}
</code>```

1) Although not officially documented anywhere (as far as I'm aware), the DOMNodeList returned by DOMXPath is not "live", as opposed to DOMNodeLists returned by DOMDocument, I believe. So, your first foreach() should be unnecessary. But you'd have to give it a try, to be sure.

I would advice against doing any of the following, but if you are sure the only class those  elements will ever have is lazy-load, i.e. the class attribute will always exactly be lazy-load, without any spaces and/or other classes, you could also use this, much simpler, query instead:

```<code>$images = $xpath->query( '//img[@class="lazy-load"]' );
</code>```

or, if the  elements can have multiple classes, but will never have any other classes that contain the phrase lazy-load (like class="thumbnail lazy-loading", for instance) you could use:

```<code>$images = $xpath->query( '//img[contains(@class,"lazy-load")]' );
</code>```

Body:
I'm using WordPress and I want to apply lazy load to only certain images. I found here a way to create the data-src attributes and replace the src attribute with the correct image https://wordpress.stackexchange.com/questions/60792/replace-image-attributes-for-lazyload-plugin-data-src. Right now my code applies the lazy load to all the images, and I just want to apply it to the images with the class lazy-load.

This is how my code looks

// Lazyload Converter
function add_lazyload($content) {

$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$dom = new DOMDocument();
@$dom->loadHTML($content);

$images = [];

foreach ($dom->getElementsByTagName('img') as $node) {
    $images[] = $node;
}

foreach ($images as $node) {
    $fallback = $node->cloneNode(true);

    $oldsrc = $node->getAttribute('src');
    $node->setAttribute('data-src', $oldsrc );
    $newsrc = get_template_directory_uri() . '/assets/placeholders/squares.svg';
    $node->setAttribute('src', $newsrc);

    $oldsrcset = $node->getAttribute('srcset');
    $node->setAttribute('data-srcset', $oldsrcset );
    $newsrcset = '';
    $node->setAttribute('srcset', $newsrcset);

    $noscript = $dom->createElement('noscript', '');
    $node->parentNode->insertBefore($noscript, $node);
    $noscript->appendChild($fallback);
}

$newHtml = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('', '', '', ''), array('', '', '', ''), $dom->saveHTML()));
return $newHtml;
}
add_filter('the_content', 'add_lazyload');
add_filter('post_thumbnail_html', 'add_lazyload');

how can I get the element by class instead of using tag?

Body:
You can use xpath (with domxpath) for this; xpath is a query language to select nodes from XML/HTML documents.

Unfortunately, selecting elements which have a class that is the stand-alone phrase lazy-load, is a bit convoluted with xpath; it's not as concise as you may perhaps be accustomed to with css-selectors; xpath doesn't have shorthand attribute selectors like @attr~="lazy-load", etc.

Here's an example of how you would select all <img> elements that have the class lazy-load:

// create a DOMXPath instance that operates on your DOMDocument instance $dom
$xpath = new DOMXPath( $dom );

// select nodes by some criteria (returns a non-live¹ DOMNodeList)
$images = $xpath->query( '//img[contains(concat(" ", normalize-space(@class), " "), " lazy-load ")]' );

// then apply the same operations to the nodes again as in your last foreach loop
foreach ($images as $node) {
  $fallback = $node->cloneNode(true);
  // etc.
}

1) Although not officially documented anywhere (as far as I'm aware), the DOMNodeList returned by DOMXPath is not "live", as opposed to DOMNodeLists returned by DOMDocument, I believe. So, your first foreach() should be unnecessary. But you'd have to give it a try, to be sure.

I would advice against doing any of the following, but if you are sure the only class those <img> elements will ever have is lazy-load, i.e. the class attribute will always exactly be lazy-load, without any spaces and/or other classes, you could also use this, much simpler, query instead:

$images = $xpath->query( '//img[@class="lazy-load"]' );

or, if the <img> elements can have multiple classes, but will never have any other classes that contain the phrase lazy-load (like class="thumbnail lazy-loading", for instance) you could use:

$images = $xpath->query( '//img[contains(@class,"lazy-load")]' );


问:
SQL Server: Check Upper Case or Lower Case after certain Character
I have data like 'John is my name; Ram is my name; Adam is my name'.

My rule is such that every first letter that comes after ; should be capital letter.

How do I select all values that satisfy the rule?

答:
You might split this with the XML trick like this

```<code>DECLARE @YourString VARCHAR(100)='John is my name; Ram is my name; Adam is my name';
WITH Splitted AS
(
    SELECT CAST('<x>' + REPLACE((SELECT REPLACE(@YourString,'; ','$$SplitHere$$') AS [*] FOR XML PATH('')),'$$SplitHere$$','</x><x>')+ '</x>' AS XML) AS Casted
)
,DerivedTable AS
(
    SELECT  ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS PartNr
           ,x.value(N'text()[1]',N'nvarchar(max)') AS Part
    FROM Splitted
    CROSS APPLY Casted.nodes(N'/x') AS X(x)
)
SELECT PartNr
      ,Part
      ,CASE WHEN ASCII(LEFT(Part,1)) BETWEEN ASCII('A') AND ASCII('Z') THEN 1 ELSE 0 END AS FirstIsCapital
FROM DerivedTable;
</code>```

The result

```<code>Nr  Part            FirstLetterIsCaptial
----------------------------------------
1   John is my name     1
2   Ram is my name      1
3   Adam is my name     1
</code>```

I do not know what your final goal is... Find parts, where the first letter is not capital? Make sure, that your rule is fullfilled?

However:

Best was, to use this to correct your design and place these parts in a 1:n related side table.

Body:
You might split this with the XML trick like this

DECLARE @YourString VARCHAR(100)='John is my name; Ram is my name; Adam is my name';
WITH Splitted AS
(
    SELECT CAST('<x>' + REPLACE((SELECT REPLACE(@YourString,'; ','$$SplitHere$$') AS [*] FOR XML PATH('')),'$$SplitHere$$','</x><x>')+ '</x>' AS XML) AS Casted
)
,DerivedTable AS
(
    SELECT  ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS PartNr
           ,x.value(N'text()[1]',N'nvarchar(max)') AS Part
    FROM Splitted
    CROSS APPLY Casted.nodes(N'/x') AS X(x)
)
SELECT PartNr
      ,Part
      ,CASE WHEN ASCII(LEFT(Part,1)) BETWEEN ASCII('A') AND ASCII('Z') THEN 1 ELSE 0 END AS FirstIsCapital
FROM DerivedTable;

The result

Nr  Part            FirstLetterIsCaptial
----------------------------------------
1   John is my name     1
2   Ram is my name      1
3   Adam is my name     1

I do not know what your final goal is... Find parts, where the first letter is not capital? Make sure, that your rule is fullfilled?

However:

Best was, to use this to correct your design and place these parts in a 1:n related side table.


问:
Make awk keep ending whitespace
I have a file list with two columns. I need to remove the first column and keep a list of filenames. If I happen to have a file that ends with a space, eg "some file ", the space is removed by awk.

Example with file "input" (notice the space at the end of "some file ")

```<code>abc some file
def some other file
</code>```

Running

```<code>cat input | awk '{$1=""; print substr($0, 2)}' > output
</code>```

will produce the file output

```<code>some file
some other file
</code>```

where "some file " is now "some file" resulting in a non existent file when processing the file list.

Any portable solution is appreciated :)

[EDIT] Tried to simplify the example above in order to make it more clear, but in fact there are more columns so some solutions may not apply.

Actual file is an rsync --list-only output:

```<code>drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x      234234 2017/06/04 11:24:19 some file
drwxr-xr-x     1341212 2017/06/04 11:24:19 some other file
</code>```

The column that shows filesizes may expand so removing a fixed amount of trailing characters will lead to errors.

Filenames can indeed contain paths and multiple spaces.

Example test file (keep in mind that filesize may vary, so the second column might increase in size):

```<code>drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x        4096 2017/06/04 11:24:19 another
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites/ de_dust
-rw-r--r--           0 2017/06/04 11:24:19 another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of /the opera
-rw-r--r--           0 2017/06/04 11:24:19 phantom of /the opera/Bohemian Maiden
</code>```

[/EDIT]

答:
A solution with tr and cut :

```<code> tr -s ' ' <inputfile | cut -d' ' -f5-
</code>```

Title: Make awk keep ending whitespace

Body:
I have a file list with two columns. I need to remove the first column and keep a list of filenames. If I happen to have a file that ends with a space, eg "some file ", the space is removed by awk.

Example with file "input" (notice the space at the end of "some file ")

abc some file
def some other file

Running

cat input | awk '{$1=""; print substr($0, 2)}' > output

will produce the file output

some file
some other file

where "some file " is now "some file" resulting in a non existent file when processing the file list.

Any portable solution is appreciated :)

[EDIT] Tried to simplify the example above in order to make it more clear, but in fact there are more columns so some solutions may not apply.

Actual file is an rsync --list-only output:

drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x      234234 2017/06/04 11:24:19 some file
drwxr-xr-x     1341212 2017/06/04 11:24:19 some other file

The column that shows filesizes may expand so removing a fixed amount of trailing characters will lead to errors.

Filenames can indeed contain paths and multiple spaces.

Example test file (keep in mind that filesize may vary, so the second column might increase in size):

drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x        4096 2017/06/04 11:24:19 another
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites/ de_dust
-rw-r--r--           0 2017/06/04 11:24:19 another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of /the opera
-rw-r--r--           0 2017/06/04 11:24:19 phantom of /the opera/Bohemian Maiden

[/EDIT]

Body:
A solution with tr and cut :

 tr -s ' ' <inputfile | cut -d' ' -f5-


问:
ReplaceWith on hidden elements then showing in orginal positions, not in the position of their target
Link:  http://jsfiddle.net/7GGeX/24/

Click on the links in 1,2,3 order and you'll see why I'm confused.

Does using a function inside replaceWith negate the positioning of the replacement?

```<code>$(document).ready(function () {
    $(".click1").click(function () {
        $("#one").replaceWith(function () {
            $('#replace1').show();
        });
        return false;
    });
</code>```

Thanks for the help!

答:
You need to return the value you want to use as the replacement.

```<code>$("#two").replaceWith(function() {
      // return the element
    return $('#replace2').show();
});
</code>```

or don't pass a function:

```<code>$("#two").replaceWith($('#replace2').show());
</code>```

Since you weren't returning anything explicitly, the replace div was being shown, then undefined was returned, effectively replacing the original with nothing.

Body:
Link:  http://jsfiddle.net/7GGeX/24/

Click on the links in 1,2,3 order and you'll see why I'm confused.

Does using a function inside replaceWith negate the positioning of the replacement?

$(document).ready(function () {
    $(".click1").click(function () {
        $("#one").replaceWith(function () {
            $('#replace1').show();
        });
        return false;
    });

Thanks for the help!

Body:
You need to return the value you want to use as the replacement.

$("#two").replaceWith(function() {
      // return the element
    return $('#replace2').show();
});

or don't pass a function:

$("#two").replaceWith($('#replace2').show());

Since you weren't returning anything explicitly, the replace div was being shown, then undefined was returned, effectively replacing the original with nothing.


问:
Getting Build Error " ERROR in NgSemanticModule is not an NgModule " Even after adding dependencies and importing to mail module
I have shared my module , component and package file here , my trying to use click event with ngif but still getting the error.
The error it showing is "ERROR in NgSemanticModule is not an NgModule"
am not able to understand if this error is because of semantic-UI dependency or its happening because am missing something in click event

Can any one help thanks in advance.

```<code>    // app.module.ts
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { CommonModule } from '@angular/common';
    import { AppComponent }   from './app.component';
    import { HomeComponent } from './home/home.component'; //import home components
    import { AboutComponent } from './about/about.component'; //import about component
    import { NgSemanticModule } from 'ng-semantic';
    import { routing }  from './app.routing';

    @NgModule({
    imports:      [ BrowserModule, routing , NgSemanticModule,CommonModule ], //other modules the app depends on
    declarations: [ AppComponent, AboutComponent, HomeComponent ], // declare all derectives and components
    bootstrap : [ AppComponent ] // root component to bootstarp
    })
    export class AppModule { }

//app.component.ts
import { Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})

export class AppComponent {
  isActive:boolean = true;
  isCollapsedMenu() {
    this.isActive = !this.isActive;
  }

}

//package.json

{
  "name": "angularapp",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "ng-semantic": "^1.1.13",
    "ng2-bootstrap": "1.1.16-11",
    "ngx-bootstrap": "^1.7.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.5",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.77",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}
</code>```

答:
Try like this,

```<code>import { NgSemanticModule } from 'ng-semantic/ng-semantic';
</code>```

if you are using angular-cli, try this,

add the following to the file ng-semantic.d.ts in the ng-semantic node package:

```<code>import { NgModule } from '@angular/core';

...

@NgModule({
    declarations: [
        NgSemanticModule
    ]
})
export declare class NgSemanticModule {
}
</code>```

Reference

Body:
I have shared my module , component and package file here , my trying to use click event with ngif but still getting the error.
The error it showing is "ERROR in NgSemanticModule is not an NgModule"
am not able to understand if this error is because of semantic-UI dependency or its happening because am missing something in click event

Can any one help thanks in advance.

    // app.module.ts
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { CommonModule } from '@angular/common';
    import { AppComponent }   from './app.component';
    import { HomeComponent } from './home/home.component'; //import home components
    import { AboutComponent } from './about/about.component'; //import about component
    import { NgSemanticModule } from 'ng-semantic';
    import { routing }  from './app.routing';

    @NgModule({
    imports:      [ BrowserModule, routing , NgSemanticModule,CommonModule ], //other modules the app depends on
    declarations: [ AppComponent, AboutComponent, HomeComponent ], // declare all derectives and components
    bootstrap : [ AppComponent ] // root component to bootstarp
    })
    export class AppModule { }

//app.component.ts
import { Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})

export class AppComponent {
  isActive:boolean = true;
  isCollapsedMenu() {
    this.isActive = !this.isActive;
  }

}

//package.json

{
  "name": "angularapp",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "ng-semantic": "^1.1.13",
    "ng2-bootstrap": "1.1.16-11",
    "ngx-bootstrap": "^1.7.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.5",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.77",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}

Body:
Try like this,

import { NgSemanticModule } from 'ng-semantic/ng-semantic';

if you are using angular-cli, try this,

add the following to the file ng-semantic.d.ts in the ng-semantic node package:

import { NgModule } from '@angular/core';

...

@NgModule({
    declarations: [
        NgSemanticModule
    ]
})
export declare class NgSemanticModule {
}

Reference


问:
Image Button not displaying, On click is working
I am working on Android studio, with an xml that displays a comment like in Facebook. My issue is that one of the buttons, the comment_more_options button, is not showing up in my actual device run, on the emulator provided with Android Studio, but does show up in my xml preview. However, when I click where the button should be, in the app run, the menu that is attached to it displays properly. What am I doing wrong? </p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_gravity="left|center_vertical"
            android:layout_margin="12dp"
            android:layout_weight="0.26"
            app:srcCompat="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:gravity="bottom|left"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginBottom="6dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="2dp"
                android:layout_weight="1"
                android:gravity="top|left"
                android:text="Handle" />

        </LinearLayout>

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="left"
            android:layout_margin="1dp"
            android:layout_weight="0.50"
            android:background="@android:color/transparent"
            android:visibility="visible"
            app:srcCompat="@drawable/ic_more_vert_black_24dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/enter_comment"
        android:textSize="18sp" />

</LinearLayout>
</code>```

答:
Use this instead:

android:src="@drawable/ic_more_vert_black_24dp"

And make sure that your icon's color is not same as the background's.

Body:
I am working on Android studio, with an xml that displays a comment like in Facebook. My issue is that one of the buttons, the comment_more_options button, is not showing up in my actual device run, on the emulator provided with Android Studio, but does show up in my xml preview. However, when I click where the button should be, in the app run, the menu that is attached to it displays properly. What am I doing wrong?

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/comment_profile_picture"
            android:layout_width="40sp"
            android:layout_height="40sp"
            android:layout_gravity="left|center_vertical"
            android:layout_margin="12dp"
            android:layout_weight="0.26"
            app:srcCompat="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/comment_displayName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:gravity="bottom|left"
                android:text="Display Name"
                android:textAppearance="@android:style/TextAppearance.Material.Menu" />

            <TextView
                android:id="@+id/comment_handle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_marginBottom="6dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="2dp"
                android:layout_weight="1"
                android:gravity="top|left"
                android:text="Handle" />

        </LinearLayout>

        <ImageButton
            android:id="@+id/comment_more_options"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_gravity="left"
            android:layout_margin="1dp"
            android:layout_weight="0.50"
            android:background="@android:color/transparent"
            android:visibility="visible"
            app:srcCompat="@drawable/ic_more_vert_black_24dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/comment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/enter_comment"
        android:textSize="18sp" />

</LinearLayout>


问:
Cannot read property 'post' of undefined - Angular 2
Below is the code snippet from my component file

```<code>import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter,Output } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/switchMap';
...
@Injectable()
export class MyComponent {
    constructor (private http: Http) { }
    saveDetails()
    {
        var response:any;
        var body       = customer_details;
        var headers    = new Headers({ 'Content-Type': 'application/json' });
        var options    = new RequestOptions({ headers: headers });
        this.http.post("/user/add-customer-details", body, options)
            .map((res:Response) => res.json()).subscribe(
                data => { response = data},
                err => console.error(err),
                () => {
                    console.log(response);
                }
        );
    }
}
</code>```

There is no compilation error or any other error but
when I am calling the post method it's saying Cannot read property 'post' of undefined so I tried console.log(this.http); right before the post method call, then its showing undefined in the browser console, I tried all the possible solutions but unable to understand why it's not working, please help...

thanks in advance!!!

答:
You need to add the HttpModule to your NgModule for the dependency injection.

You can look it up here https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-providers

The HttpModule is necessary for making HTTP calls. [...]

Body:
Below is the code snippet from my component file

import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter,Output } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/switchMap';
...
@Injectable()
export class MyComponent {
    constructor (private http: Http) { }
    saveDetails()
    {
        var response:any;
        var body       = customer_details;
        var headers    = new Headers({ 'Content-Type': 'application/json' });
        var options    = new RequestOptions({ headers: headers });
        this.http.post("/user/add-customer-details", body, options)
            .map((res:Response) => res.json()).subscribe(
                data => { response = data},
                err => console.error(err),
                () => {
                    console.log(response);
                }
        );
    }
}

There is no compilation error or any other error but
when I am calling the post method it's saying Cannot read property 'post' of undefined so I tried console.log(this.http); right before the post method call, then its showing undefined in the browser console, I tried all the possible solutions but unable to understand why it's not working, please help...

thanks in advance!!!


问:
How to use xkcd together with matplotlib and PyQt
I want to plot a graph in xkcd style in my PyQt application. Since it is not recommended to use pyplot together with the Qt5Agg-backend I am struggling to find a right way to import the xkcd package so that I can use it without pyplot.

The normal way to use the xkcd-package would be

```<code>from matplotlib import pyplot as plt
plt.xkcd()
</code>```

But I am using

```<code>import matplotlib
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
</code>```

So is there a way plotting in xkcd style without using pyplot?

答:
There is no danger in importing pyplot. You may just be recommended not using pyplot for plotting tasks when working with figures inside GUIs. I guess this recommendation is the more valid the less experienced you are. Even using pyplot for plotting tasks in GUIs is in general possible as long as you know what you're doing.

But in any case there is no danger in using plt.xkcd(), since it does not interfere with anything and justs sets the rcParams to follow a certain style.

Body:
I want to plot a graph in xkcd style in my PyQt application. Since it is not recommended to use pyplot together with the Qt5Agg-backend I am struggling to find a right way to import the xkcd package so that I can use it without pyplot.

The normal way to use the xkcd-package would be

from matplotlib import pyplot as plt
plt.xkcd()

But I am using

import matplotlib
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg

So is there a way plotting in xkcd style without using pyplot?


问:
Coming up with a stopping condition in a helper function C++,
i currently need to figure out a stopping condition for a recursive helper function that stops when there is only one number left on the list, or there are no numbers left to try.  The program is to guess the the number 1-100 and progressively correct itself in order to find out the number the person is thinking of, i have a good idea on how to get the numbers in order if the person says it's too high, too low, or if they say the program got it right. however, i do not know how to stop the function if there is only one possible number left to guess, or if the user cheated and there are no numbers left to try. here is what i have for the recursive function so far, and i really do not know where to begin on my current problem stated earlier, thanks for the help in advance :)</p>

```<code>#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

void guessingGame(int size, int low)
{
string answer;
unsigned int median = (low + size) / 2;
cout << "Is your number " << median << " l , y , h? ";
cin >> answer;

if (answer == "l" || answer == "L")
{
    low = median;
    guessingGame(size, low);
}
if (answer == "h" || answer == "H")
{
    size = median;
    guessingGame(size, low);
}
if (answer == "y" || answer == "Y")
{
    cout << "Told ya i'd guess it!\n";
}

  while (answer != "h" && answer != "y" && answer != "l")
{
    cout << "\nPlease enter a valid input: ";
    cin >> answer;
    cin.clear();
    cin.ignore(50, '\n');
    guessingGame(size, low);
}
</code>```

答:
Your code doesn't compile, but I'll consider it as pseudo code and answer your question specifically.

Basically, your stopping condition would be when low is equal to size, and you have only one number remaining. At this point you have two options:

The user will enter 'y', then this is the correct guess and you can return from the function.

The user will enter 'l' or 'h'. In this case, the user is cheating since only one number is remaining and it's not the correct one.

I'd suggest moving the checking for 'y' to the beginning, before the other two checks for 'h' and 'l', then write something as the following:

```<code>if (answer == "y" || answer == "Y")
{
    cout << "Told ya i'd guess it!\n";
}

else if (low == size)
{
    cout << "Not fair! You're cheating.\n";
   // exit the routine.
}

else if (answer == "l" || answer == "L")
{
    low = median;
    guessingGame(size, low);
}
else if (answer == "h" || answer == "H")
{
    size = median;
    guessingGame(size, low);
}
</code>```

If the user doesn't answer with 'y', and you have only one number left, then they're cheating.

Again, your code has problems, but this is just an idea of how the stopping condition would be.

Body:
i currently need to figure out a stopping condition for a recursive helper function that stops when there is only one number left on the list, or there are no numbers left to try.  The program is to guess the the number 1-100 and progressively correct itself in order to find out the number the person is thinking of, i have a good idea on how to get the numbers in order if the person says it's too high, too low, or if they say the program got it right. however, i do not know how to stop the function if there is only one possible number left to guess, or if the user cheated and there are no numbers left to try. here is what i have for the recursive function so far, and i really do not know where to begin on my current problem stated earlier, thanks for the help in advance :)

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

void guessingGame(int size, int low)
{
string answer;
unsigned int median = (low + size) / 2;
cout << "Is your number " << median << " l , y , h? ";
cin >> answer;

if (answer == "l" || answer == "L")
{
    low = median;
    guessingGame(size, low);
}
if (answer == "h" || answer == "H")
{
    size = median;
    guessingGame(size, low);
}
if (answer == "y" || answer == "Y")
{
    cout << "Told ya i'd guess it!\n";
}

  while (answer != "h" && answer != "y" && answer != "l")
{
    cout << "\nPlease enter a valid input: ";
    cin >> answer;
    cin.clear();
    cin.ignore(50, '\n');
    guessingGame(size, low);
}

Body:
Your code doesn't compile, but I'll consider it as pseudo code and answer your question specifically.

Basically, your stopping condition would be when low is equal to size, and you have only one number remaining. At this point you have two options:

The user will enter 'y', then this is the correct guess and you can return from the function.

The user will enter 'l' or 'h'. In this case, the user is cheating since only one number is remaining and it's not the correct one.

I'd suggest moving the checking for 'y' to the beginning, before the other two checks for 'h' and 'l', then write something as the following:

if (answer == "y" || answer == "Y")
{
    cout << "Told ya i'd guess it!\n";
}

else if (low == size)
{
    cout << "Not fair! You're cheating.\n";
   // exit the routine.
}

else if (answer == "l" || answer == "L")
{
    low = median;
    guessingGame(size, low);
}
else if (answer == "h" || answer == "H")
{
    size = median;
    guessingGame(size, low);
}

If the user doesn't answer with 'y', and you have only one number left, then they're cheating.

Again, your code has problems, but this is just an idea of how the stopping condition would be.