问:
How to create the mongodb schema for below Json?
```<code>{
    "_id" : ObjectId("5a0e77f4b7368f14c088f542"),
    "folderName" : "team 4",
    "tag" : "search",
    "ismainFolder" : true,
    "innerFolder" : [
                    {
                       parentfolderId" : null,
                      "ismainFolder" : false,
                      "foldername" : "Onkar 11"
                        "subinnerFolder" : [
                                        {
                                            "parentfolderId" : null,
                                            "ismainFolder" : false,
                                            "foldername" : "Onkar 11"
                                            "thirdSubFolder" : [
                                                        {
                                                            "parentfolderId" : null,
                                                            "ismainFolder" : false,
                                                           "foldername" : "Onkar 11"
                                                        },
                                                        {
                                                             "parentfolderId" : null,
                                                             "ismainFolder" : false,
                                                             "foldername" : "Onkar 11"
                                                        }
                                                    ]
                                        },

                                   ]
                    },
                ]
}
</code>```

I need to create the mongodb schema for below json format so that innerFolder, subinnerFolder, etc (inner folder structure goes nested) so please help me in this ?

答:
Here is an example of schema in Mongoose style.

The only difficulty here is with null value.

One of your possibility is to store it as text,
but consider to do not store null value at all.

```<code>const detailFolder = {
  parentfolderId: { type: String, default: null },
  ismainFolder: Boolean,
  foldername: String
}

const schema = {
  folderName: String,
  tag: String,
  ismainFolder: Boolean,
  innerFolder: [{
    detailFolder,
    subinnerFolder: [{
      detailFolder,
      thirdSubFolder: [ detailFolder ]
    }]
  }]
}
</code>```

Body:
{
    "_id" : ObjectId("5a0e77f4b7368f14c088f542"),
    "folderName" : "team 4",
    "tag" : "search",
    "ismainFolder" : true,
    "innerFolder" : [
                    {
                       parentfolderId" : null,
                      "ismainFolder" : false,
                      "foldername" : "Onkar 11"
                        "subinnerFolder" : [
                                        {
                                            "parentfolderId" : null,
                                            "ismainFolder" : false,
                                            "foldername" : "Onkar 11"
                                            "thirdSubFolder" : [
                                                        {
                                                            "parentfolderId" : null,
                                                            "ismainFolder" : false,
                                                           "foldername" : "Onkar 11"
                                                        },
                                                        {
                                                             "parentfolderId" : null,
                                                             "ismainFolder" : false,
                                                             "foldername" : "Onkar 11"
                                                        }
                                                    ]
                                        },

                                   ]
                    },
                ]
}

I need to create the mongodb schema for below json format so that innerFolder, subinnerFolder, etc (inner folder structure goes nested) so please help me in this ?

Body:
Here is an example of schema in Mongoose style.

The only difficulty here is with null value.

One of your possibility is to store it as text,
but consider to do not store null value at all.

const detailFolder = {
  parentfolderId: { type: String, default: null },
  ismainFolder: Boolean,
  foldername: String
}

const schema = {
  folderName: String,
  tag: String,
  ismainFolder: Boolean,
  innerFolder: [{
    detailFolder,
    subinnerFolder: [{
      detailFolder,
      thirdSubFolder: [ detailFolder ]
    }]
  }]
}


来源: stackexchange

问:
how to set single custom validation message for multiple input field?
```<code>public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    return [
      "skill" => "required|array",
      "skillyear.*" => "required_with:skill|numeric",
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyear.*.required_with'=>"Experience year is required for the selected skill"
];}
</code>```

so, for each field i'm getting message like this
enter image description here
how can I get only one message for all these.

答:
Use simple laravel validation in controller:

```<code>    public function getRequest(Request $request) {

                    $this->validate($request, [
                        'param1' => 'required',
                        'param2' => 'required'
                    ], [
                      'required' => 'Field is required'
                       ], [
                        'param1' => 'field name 1 - message',
                        'param2' => 'field name 2 - message'
                    ]);
</code>```

More: https://laravel.com/docs/5.5/validation

ContentLicense: CC BY-SA 3.0

Body:
public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    return [
      "skill" => "required|array",
      "skillyear.*" => "required_with:skill|numeric",
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyear.*.required_with'=>"Experience year is required for the selected skill"
];}

so, for each field i'm getting message like this
enter image description here
how can I get only one message for all these.

Body:
Use simple laravel validation in controller:

    public function getRequest(Request $request) {

                    $this->validate($request, [
                        'param1' => 'required',
                        'param2' => 'required'
                    ], [
                      'required' => 'Field is required'
                       ], [
                        'param1' => 'field name 1 - message',
                        'param2' => 'field name 2 - message'
                    ]);

More: https://laravel.com/docs/5.5/validation


问:
Reference regex when using find and replace in Notepad++
I use this regex ^.*?\K\d+\.\d+\.\d+ to search for the first date on every line in notepad++. It seems to work just fine.

The text I work with looks something like this:

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017,  Martin Lægland 31.12.2017 Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

The search gives me every 09.09.2017, but not 31.12.2017 on the second line. Which is exactly what I want. I then want to replace all the 09.09.2017s so they becomes *09.09.2017*.

How do I reference ^.*?\K\d+\.\d+\.\d+ in the replace field in notepad++? Earlier I have been able to do this with *\1* in the replace field, where \1 references the regex I've used, but that doesn't seem to work now.

答:
Your previous regex looked like \K(([0-9]{2}).([0-9]{2}).([0-9]{4})) with a capturing group set around the whole pattern. That is why \1 referred to the whole match that was also captured into Group 1.

You may either capture the whole pattern with (...) again and use *\1*, or  use $0 backreference instead of \1:

```<code>^.*?\K\d+\.\d+\.\d+
</code>```

replace with

```<code>*$0*
</code>```

where $0 is the backreference to the whole match.

Body:
Your previous regex looked like \K(([0-9]{2}).([0-9]{2}).([0-9]{4})) with a capturing group set around the whole pattern. That is why \1 referred to the whole match that was also captured into Group 1.

You may either capture the whole pattern with (...) again and use *\1*, or  use $0 backreference instead of \1:

^.*?\K\d+\.\d+\.\d+

replace with

*$0*

where $0 is the backreference to the whole match.


问:
Get Json_encode to a different jQuery page
I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).

Here is my process.php file:

```<code><div id="msg" class="msg">
<?php
    $query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
    $json =  array();
    $result= $conn->query($query);
    while($row = $result->fetch_assoc()){
        $json[]= $row;
    }
    echo json_encode($json);
?>
</div>
</code>```

This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.

Here is my jQuery file:

```<code><script>
 $(document).ready(function(){
  $("button").click(function(){
    var mycontent  = $('div.msg').text();
    console.log(mycontent);
  });
 });
</script>
</code>```

But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?

答:
You need to make AJAX call to the process.php page. Try the following code:</p>

```<code>`<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax( {
            type : 'GET',
            url:'process.php',
            success:function(mycontent) {
                console.log(mycontent);
            }
        });
    });
});
</script>`
</code>```

Body:
I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).

Here is my process.php file:

<?php
    $query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
    $json =  array();
    $result= $conn->query($query);
    while($row = $result->fetch_assoc()){
        $json[]= $row;
    }
    echo json_encode($json);
?>

This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.

Here is my jQuery file:

But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?

Body:
You need to make AJAX call to the process.php page. Try the following code:

`<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax( {
            type : 'GET',
            url:'process.php',
            success:function(mycontent) {
                console.log(mycontent);
            }
        });
    });
});
</script>`


问:
custom button always too big
I am trying to create a custom button with its shape being as similar as possible to the one of the Android default button. The problem is, no matter how much I reduce the height, it doesn't go below a certain value:

image of custom and default button

The text size of both buttons is 14sp. Here the xlm-code for my custom button:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <padding
        android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
    <solid
        android:color="@color/colorBtnActive" />

    <corners android:radius="2dp" />

    <size
        android:height="16dp"/>

</shape>
</code>```

So even if I write <size android:height="50dp"/>, the button looks the same.

Here part of the xlm-file of the activity:

```<code><Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_selector_selected"
    android:text="custom"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:text="default"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.501" />
</code>```

What am I doing wrong? Thank you!

EDIT:
So upon your suggestions I removed the size-tag.Sadly, the button still looks the same. However, I noticed that the buttoms have the same size, the default button just looks smaller: screenshot

How can I achieve this effect?

答:
Android Button has default padding.

When I set android:background="@android:color/holo_blue_bright" in the Button.
It will be the same of custom Button .

```<code> <Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:text="default"
    android:background="@android:color/holo_blue_bright"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.501" />
</code>```

Output

Title: custom button always too big

Body:
I am trying to create a custom button with its shape being as similar as possible to the one of the Android default button. The problem is, no matter how much I reduce the height, it doesn't go below a certain value:

image of custom and default button

The text size of both buttons is 14sp. Here the xlm-code for my custom button:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <padding
        android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
    <solid
        android:color="@color/colorBtnActive" />

    <corners android:radius="2dp" />

    <size
        android:height="16dp"/>

</shape>

So even if I write <size android:height="50dp"/>, the button looks the same.

Here part of the xlm-file of the activity:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_selector_selected"
    android:text="custom"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:text="default"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.501" />

What am I doing wrong? Thank you!

EDIT:
So upon your suggestions I removed the size-tag.Sadly, the button still looks the same. However, I noticed that the buttoms have the same size, the default button just looks smaller: screenshot

How can I achieve this effect?

Body:
Android Button has default padding.

When I set android:background="@android:color/holo_blue_bright" in the Button.
It will be the same of custom Button .

 <Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:text="default"
    android:background="@android:color/holo_blue_bright"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.501" />

Output


问:
Javascript regular expression string-replacement of multi-line strings
With JavaScript regular expression replace, trying to replace anything between  and  tags so that:

```<code><head>
   Multiline foo
</head>
<body>
  Multi line bar
</body>
</code>```

gets replaced into:

```<code><body>
  Multi line bar
</body>
</code>```

and trying with the very basic: /m which doesn't work. It works fine when line breaks are removed from string. No matter what type of line breaks, what's the magic?

答: The problem is that the dot metacharacter doesn't match newlines.  In most regex flavors you can force it to match everything by setting "DOTALL" or "single-line" mode, but JavaScript doesn't support that.  Instead, you have to replace the dot with something that does match everything. The most common idiom is [\s\S] ("any whitespace character or any character that's not whitespace").

ContentLicense: CC BY-SA 2.5

Body:
With JavaScript regular expression replace, trying to replace anything between  and  tags so that:

   Multiline foo

  Multi line bar

gets replaced into:

  Multi line bar

and trying with the very basic: /m which doesn't work. It works fine when line breaks are removed from string. No matter what type of line breaks, what's the magic?


问:
Need Build IVR call flow UI with Drag-Drop element like OpenVBX (Twilio)
Need to create application for desing IVR call flow with drag-drop element UI like OpenVBX(Twilio). I have no advance level knowledge about front-end technologies like CSS and pure JavaScript. I need to this implementation with PHP based project.

Can you please help me out which kind of tool are helpful for this requirement?

答:
Most of the solutions are not opensource and free.

We use the OpenSource/GPL HawHaw (from the HawHaw.de), if you are using the standard VoiceXML language. You can create a portal that will be accessible from the Web / "Wap" / VoiceXML. You can test it on the HTML interface (and ajust your Session/DB/API integration) and play it from the VoiceXML syntax (you need a VoiceXML interpreter as Voximal, Plum, Voxeo...)


问:
Web scraping using Python and Selenium
I am using the following code to submit a form using Python.
When the value entered is correct, it redirects to a new page called http://localhost/a/my.php. How do i check whether the page is redirected using python so that I can know that the values entered where correct.

```<code>from selenium import webdriver

webpage = r"http://localhost/a/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
for i in range(10):
    searchterm = i # edit me
    driver.get(webpage)
    sbox = driver.find_element_by_class_name("txtSearch")
    sbox.send_keys(searchterm)

    submit = driver.find_element_by_class_name("sbtSearch")
    submit.click()
</code>```

答:
Try using current_url:</p>

```<code>driver.current_url
</code>```

Title: Web scraping using Python and Selenium

Body:
I am using the following code to submit a form using Python.
When the value entered is correct, it redirects to a new page called http://localhost/a/my.php. How do i check whether the page is redirected using python so that I can know that the values entered where correct.

from selenium import webdriver

webpage = r"http://localhost/a/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
for i in range(10):
    searchterm = i # edit me
    driver.get(webpage)
    sbox = driver.find_element_by_class_name("txtSearch")
    sbox.send_keys(searchterm)

    submit = driver.find_element_by_class_name("sbtSearch")
    submit.click()

Body:
Try using current_url:

driver.current_url


问:
vtkRenderingSceneGraphModule.h missing
I am getting the following error when trying to use

```<code>#include <vtkViewNode.h>
</code>```

in my code. I didn't do anything else besides this. I am getting the following error message:

```<code> .../VTK-8.0.1/Rendering/SceneGraph/vtkViewNode.h:29:62: fatal error:vtkRenderingSceneGraphModule.h: No such file or directory
compilation terminated.
</code>```

Everything else i tried so far is working like cylinders or parametric splines. I might be mistaken but if i try searching for "RenderingSceneGraph" on fossies.org there's no match. So to me it seems like it's not part of the VTK 8.0.1 in the first place.

It's needed for several classes according to their documentation. It's strange though since you can't access any information about it.

Any ideas?

答:
Somebody had basically the same problem just the other day: Error C1083 Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory

vtk****Module.h are files generated by CMake when you are configuring the project, that's why you can't find them in a file search of the source code. You have to enable them explicitly, they are among the "advanced" items in the CMake configuration list, then they will be created as you do CMake -> Generate.

It's not clear to me from your comments above whether you are building VTK on your own or if you are using some kind of precompiled package, but in the latter case, I am affraid your package might not be compiled with the vtkRenderingSceneGraph Module and you will have to compile it on your own. Luckily it's not a big problem, you can get some pointers here https://www.vtk.org/Wiki/VTK/Configure_and_Build but in general it's pretty smooth when you use CMake.

Title: vtkRenderingSceneGraphModule.h missing

Body:
I am getting the following error when trying to use

#include <vtkViewNode.h>

in my code. I didn't do anything else besides this. I am getting the following error message:

 .../VTK-8.0.1/Rendering/SceneGraph/vtkViewNode.h:29:62: fatal error:vtkRenderingSceneGraphModule.h: No such file or directory
compilation terminated.

Everything else i tried so far is working like cylinders or parametric splines. I might be mistaken but if i try searching for "RenderingSceneGraph" on fossies.org there's no match. So to me it seems like it's not part of the VTK 8.0.1 in the first place.

It's needed for several classes according to their documentation. It's strange though since you can't access any information about it.

Any ideas?


问:
Access to Excel controls
Is there a way to access to any controls like

those in a Excel sheet from C# (vsto add-in)?

In VBA you can access them without any troubly with a direct call like you do in a winform application. But in C# I didn't found any possibilities.

Thank you for helping

答:
No there is no way, you need to use winforms controls in C#.

VBA controls can only be used in VBA.

Title: Access to Excel controls


问:
Elasticsearch: Nested mapping throws error on search
The snapshots below are self-explanatory but here's what I am trying to do. I have a double nested filed stream.tagging.tag and it's I recreated my index with new mappings. But when I do a search, ES fails to find path for inner nested field.

```<code>nishant-osx:~ nishagar$ curl GET 'localhost:9200/stream_rules/_mappings?pretty'
{
  "stream_rules": {
    "mappings": {
      "stream_rule": {
        "properties": {
          "stream": {
            "type": "nested",
            "properties": {
              "tagging": {
                "type": "nested",
                "properties": {
                  "displayName": {
                    "type": "string"
                  },
                  "tag": {
                    "type": "string",
                    "index": "not_analyzed",
                    "store": true
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

nishant-osx:~ nishagar$ CURL 'localhost:9200/stream_rules/_search' -d '{
>     "query": {
>         "nested" : {
>             "path" : "stream",
>             "query" : {
>                 "nested": {
>                     "path": "tagging",
>                     "query": {
>                         "bool" : {
>                         "must" : { "match" : {"stream.tagging.tag" : "product"} }
>                         }
>                     }
>                 }
>             }
>         }
>     }
> }'
{"error":"SearchPhaseExecutionException[Failed to execute phase [query], all shards failed; shardFailures {[Xh51BRC6SXekokw5jD5IzQ][stream_rules][0]: SearchParseException[[stream_rules][0]...
QueryParsingException[[stream_rules] [nested] failed to find nested object under path [tagging]]; }]","status":400}
</code>```

答:
The nested path in the query is incorrect.</p>

```<code>{
 "query": {
    "nested": {
        "path": "stream",
        "query": {
            "nested": {
                "path": "stream.tagging",
                "query": {
                    "bool": {
                        "must": {
                            "match": {
                                "stream.tagging.tag": "product"
                            }
                        }
                    }
                }
            }
        }
    }
  }
}
</code>```

Body:
The snapshots below are self-explanatory but here's what I am trying to do. I have a double nested filed stream.tagging.tag and it's I recreated my index with new mappings. But when I do a search, ES fails to find path for inner nested field.

nishant-osx:~ nishagar$ curl GET 'localhost:9200/stream_rules/_mappings?pretty'
{
  "stream_rules": {
    "mappings": {
      "stream_rule": {
        "properties": {
          "stream": {
            "type": "nested",
            "properties": {
              "tagging": {
                "type": "nested",
                "properties": {
                  "displayName": {
                    "type": "string"
                  },
                  "tag": {
                    "type": "string",
                    "index": "not_analyzed",
                    "store": true
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

nishant-osx:~ nishagar$ CURL 'localhost:9200/stream_rules/_search' -d '{
>     "query": {
>         "nested" : {
>             "path" : "stream",
>             "query" : {
>                 "nested": {
>                     "path": "tagging",
>                     "query": {
>                         "bool" : {
>                         "must" : { "match" : {"stream.tagging.tag" : "product"} }
>                         }
>                     }
>                 }
>             }
>         }
>     }
> }'
{"error":"SearchPhaseExecutionException[Failed to execute phase [query], all shards failed; shardFailures {[Xh51BRC6SXekokw5jD5IzQ][stream_rules][0]: SearchParseException[[stream_rules][0]...
QueryParsingException[[stream_rules] [nested] failed to find nested object under path [tagging]]; }]","status":400}

Body:
The nested path in the query is incorrect.

{
 "query": {
    "nested": {
        "path": "stream",
        "query": {
            "nested": {
                "path": "stream.tagging",
                "query": {
                    "bool": {
                        "must": {
                            "match": {
                                "stream.tagging.tag": "product"
                            }
                        }
                    }
                }
            }
        }
    }
  }
}


问:
Android notifications: onMessageReceived not called
First of all, it's not because the app is in the background.

The notifications are sent with a data message payload. In the Play console it says the messages are 'Acknowledged', so they're reaching the device. For most users, the onMessageReceived method is called, but for a minority, it isn't. Why would this be?

AndroidManifest:

```<code><service android:name=".push.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>
<service android:name=".push.MyFirebaseMessagingService">
    <intent-filter>
         <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
</code>```

MyFirebaseMessagingService:

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

...
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
...
}
</code>```

答: One of the main reasons why this could be happening is because the particular user has changed his login details or is using a different account when using the app. In this particular case, the particular device token would be receiving the notification, but since he is using a a different account, the notification is not displayed. One way to go around this issue is to clear the user's device token each time the user logs out and saved the newly created one, when a user logs in again. This way the device token is kept updated and the user will receive the notifications.</p>

Body:
First of all, it's not because the app is in the background.

The notifications are sent with a data message payload. In the Play console it says the messages are 'Acknowledged', so they're reaching the device. For most users, the onMessageReceived method is called, but for a minority, it isn't. Why would this be?

AndroidManifest:

<service android:name=".push.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>
<service android:name=".push.MyFirebaseMessagingService">
    <intent-filter>
         <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

MyFirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

...
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
...
}


问:
Accept any name as XML element - JAXB, CXF
I have a XML document, element <elementName> in it and hierarchy set in WSDL file. Generated class (from the WSDL file) maps everything correctly (CXF does it). But what if I need to accept <elementName> with every name? How can I accept any name and have a correct hierarchy? I hope you understand what I'm trying to explain :)

I tried to use @XmlElement(name="") and @XmlElement(name="*"), but that didn't work.

UPDATE:

```<code>@XmlAnyElement
protected Container c;
</code>```

And I want to map every element in the same level in XML on it.

To be specific i want these two examples to be mapped into the same class (Container.class as above):

```<code>... XML hierarchy ...
    <element>
        ... XML content ...
    </element>
</code>```

or

```<code>... XML hierarchy ...
    <elementWithUglyNameaodsafh>
        ... same XML content as above...
    </elementWithUglyNameaodsafh>
</code>```

答:
you should use @XmlAnyElement see information here:

http://jaxb.java.net/tutorial/section_6_2_7_6-Collecting-Unspecified-Elements-XmlAnyElement.html#Collecting%20Unspecified%20Elements:%20XmlAnyElement

for example:

```<code> public class ZooType {
    protected List<Element> animals;
    public ZooType(){
    }

    @XmlAnyElement
    public List<Element> getAnimals(){
        if( animals == null ) animals = new ArrayList<Element>();
        return animals;
    }
    public void setAnimals( List value ){
        animals = value;
    }
}
</code>```

you can later extract the element name and value:

```<code>for( Element el: doc.getZoo().getAnimals() ){
    System.out.println( el.getNodeName() + "->" +
                        el.getTextContent() );
}
</code>```

EDIT:

as a response to the update in the question I can offer a workaround solution.

I am sorry, I have never programmed XML, so there is probably a better way to do the element wrapping and replacement.

The bottom line is: use @XmlAnyElement to get the node... and marshal it to your Container  (whihc also have @XmlRootElement annotation)

```<code>@XmlRootElement
public class Root {

public Container c;

@XmlAnyElement
public void setElements(Element e) throws JAXBException, ParserConfigurationException {
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element container = d.createElement("container");
    d.appendChild(container);
    Node node = d.adoptNode(e.getFirstChild());
    container.appendChild(node);
    c = (Container) JAXBContext.newInstance(Container.class).createUnmarshaller().unmarshal(d);
}

public Element getElements() {
    throw new UnsupportedOperationException();
}
}
</code>```

off-course, this code is ugly and not efficient. I would refactor it before commit.

Body:
I have a XML document, element <elementName> in it and hierarchy set in WSDL file. Generated class (from the WSDL file) maps everything correctly (CXF does it). But what if I need to accept <elementName> with every name? How can I accept any name and have a correct hierarchy? I hope you understand what I'm trying to explain :)

I tried to use @XmlElement(name="") and @XmlElement(name="*"), but that didn't work.

UPDATE:

@XmlAnyElement
protected Container c;

And I want to map every element in the same level in XML on it.

To be specific i want these two examples to be mapped into the same class (Container.class as above):

... XML hierarchy ...
    <element>
        ... XML content ...
    </element>

or

... XML hierarchy ...
    <elementWithUglyNameaodsafh>
        ... same XML content as above...
    </elementWithUglyNameaodsafh>

Body:
you should use @XmlAnyElement see information here:

http://jaxb.java.net/tutorial/section_6_2_7_6-Collecting-Unspecified-Elements-XmlAnyElement.html#Collecting%20Unspecified%20Elements:%20XmlAnyElement

for example:

 public class ZooType {
    protected List<Element> animals;
    public ZooType(){
    }

    @XmlAnyElement
    public List<Element> getAnimals(){
        if( animals == null ) animals = new ArrayList<Element>();
        return animals;
    }
    public void setAnimals( List value ){
        animals = value;
    }
}

you can later extract the element name and value:

for( Element el: doc.getZoo().getAnimals() ){
    System.out.println( el.getNodeName() + "->" +
                        el.getTextContent() );
}

EDIT:

as a response to the update in the question I can offer a workaround solution.

I am sorry, I have never programmed XML, so there is probably a better way to do the element wrapping and replacement.

The bottom line is: use @XmlAnyElement to get the node... and marshal it to your Container  (whihc also have @XmlRootElement annotation)

@XmlRootElement
public class Root {

public Container c;

@XmlAnyElement
public void setElements(Element e) throws JAXBException, ParserConfigurationException {
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element container = d.createElement("container");
    d.appendChild(container);
    Node node = d.adoptNode(e.getFirstChild());
    container.appendChild(node);
    c = (Container) JAXBContext.newInstance(Container.class).createUnmarshaller().unmarshal(d);
}

public Element getElements() {
    throw new UnsupportedOperationException();
}
}

off-course, this code is ugly and not efficient. I would refactor it before commit.


问:
Drop database before anything
I have seen many answer to this question but any of these work for me and I don't know why.

So I want to delete all data in my database before running the tests and after add some. This is what I've done so far :

```<code>const db = require('../models');

describe('Setup database for testing', () => {
    before('Sync and create data', done => {
        db.sequelize
            .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
            .then(() => {
                db.User.sync({force: true});
            })

            // Create everything the tests need here
            .then(() => {
                db.User.create({username: 'foo', password: 'secret', email: 'foo@local.dev'});
            })

            .then(() => {
                db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, {raw: true});
            })
            .then(() => {
                done();
            });
    });
});
</code>```

When I run mocha on my test folder, I have no errors, nothing telling me the before hook is running (even the test title doesn't show). But the file is running because when I write dummy code in it, I have the errors.

答:
You need at least one test within the describe for the before hook to run. </p>

```<code>  describe('Setup database for testing', () => {
    before('Sync and create data', done => {
        db.sequelize
            .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
            .then(() => {
                db.User.sync({force: true});
            })

            // Create everything the tests need here
            .then(() => {
                db.User.create({username: 'foo', password: 'secret', email: 'foo@local.dev'});
            })

            .then(() => {
                db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, {raw: true});
            })
            .then(() => {
                done();
            });
    });

    //add a test for the before hook to run
    it("runs", function () {
        console.log("test");
    });
});
</code>```

Title: Drop database before anything

Body:
I have seen many answer to this question but any of these work for me and I don't know why.

So I want to delete all data in my database before running the tests and after add some. This is what I've done so far :

const db = require('../models');

describe('Setup database for testing', () => {
    before('Sync and create data', done => {
        db.sequelize
            .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
            .then(() => {
                db.User.sync({force: true});
            })

            // Create everything the tests need here
            .then(() => {
                db.User.create({username: 'foo', password: 'secret', email: 'foo@local.dev'});
            })

            .then(() => {
                db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, {raw: true});
            })
            .then(() => {
                done();
            });
    });
});

When I run mocha on my test folder, I have no errors, nothing telling me the before hook is running (even the test title doesn't show). But the file is running because when I write dummy code in it, I have the errors.

Body:
You need at least one test within the describe for the before hook to run.

  describe('Setup database for testing', () => {
    before('Sync and create data', done => {
        db.sequelize
            .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
            .then(() => {
                db.User.sync({force: true});
            })

            // Create everything the tests need here
            .then(() => {
                db.User.create({username: 'foo', password: 'secret', email: 'foo@local.dev'});
            })

            .then(() => {
                db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, {raw: true});
            })
            .then(() => {
                done();
            });
    });

    //add a test for the before hook to run
    it("runs", function () {
        console.log("test");
    });
});


问:
Why is it possible to use Lambda Expressions in Thread class?
Im learning Lambda Expressions and I know it is possible to use them for example in the Runnable functional interface and in Thread class.

I tried to create my own:

```<code>package tests;

public interface Blabla
{
    public void doStuff();
}
</code>```

And this simple test compiled:

```<code>Blabla bla = () -> System.out.println("Lol");
</code>```

Then I tried to make a class like Thread

```<code>package tests;

public class Dodo implements Blabla
{
    public void doStuff()
    {
        // TODO Auto-generated method stub

    }
}
</code>```

And this doesnt compile:

```<code> Dodo dodo = () -> System.out.println("LoL");
</code>```

And I cant find anywhere explaining how to create a class which allows the use of lambda expressions.

How can Thread allow the use of Lambda Expressions while not being an Interface?

答:
A lambda expression is just a short form for writing an anonymous class, by using lambda expression we can declare methods wherever we want them without any name.

The sole purpose of writing an anonymous class object is to override its method and provide our own functionality but for that single method, we always need to declare the class. With lambda expression, we can eliminate the declaration of the anonymous class and we can simply provide the definition of the method.

For example we use below code to create a thread

```<code>Runnable runnable = new Runnable() {
  @Override
  public void run() {
  System.out.println("Running thread using anonymous class");
  }
};
Thread t = new Thread(runnable);
</code>```

But with lambda expression we can easily say

```<code>Runnable runnable = () -> System.out.println("Running thread using lambda expression");
Thread t = new Thread(runnable);
</code>```

Or

```<code>Thread t = new Thread(() -> System.out.println("Running thread using lambda expression"));
</code>```

So by writing Runnable runnable = () -> System.out.println("Running thread using lambda expression"); we told Java to create an anonymous object of type Runnable and provided the body for the run() method.

Lambda expression only works on functional interfaces (an interface which have only one method in it) because we are providing the body for the method on the fly. So if an interface have more than one method and we are are allowed to create a lambda on it then how compiler will identify to which method this provided method body belongs.

Th differences between Lambda Expression and Anonymous class are as follows

An anonymous class object creates a separate class file after compilation which increases the size jar while after compilation Lambda expression becomes invokedynamic which dynamic language implementation.

We can use this keyword to represent the current class in lambda expression while in the case of anonymous class this keyword represents that particular anonymous class.

In the case of Lambda expression, we need to provide the function body only while in the case of anonymous class we need to write the redundant class definition.

You can read more on Java Lambda Expression Explained with Example.

Body:
Im learning Lambda Expressions and I know it is possible to use them for example in the Runnable functional interface and in Thread class.

I tried to create my own:

package tests;

public interface Blabla
{
    public void doStuff();
}

And this simple test compiled:

Blabla bla = () -> System.out.println("Lol");

Then I tried to make a class like Thread

package tests;

public class Dodo implements Blabla
{
    public void doStuff()
    {
        // TODO Auto-generated method stub

    }
}

And this doesnt compile:

 Dodo dodo = () -> System.out.println("LoL");

And I cant find anywhere explaining how to create a class which allows the use of lambda expressions.

How can Thread allow the use of Lambda Expressions while not being an Interface?

Body:
A lambda expression is just a short form for writing an anonymous class, by using lambda expression we can declare methods wherever we want them without any name.

The sole purpose of writing an anonymous class object is to override its method and provide our own functionality but for that single method, we always need to declare the class. With lambda expression, we can eliminate the declaration of the anonymous class and we can simply provide the definition of the method.

For example we use below code to create a thread

Runnable runnable = new Runnable() {
  @Override
  public void run() {
  System.out.println("Running thread using anonymous class");
  }
};
Thread t = new Thread(runnable);

But with lambda expression we can easily say

Runnable runnable = () -> System.out.println("Running thread using lambda expression");
Thread t = new Thread(runnable);

Or

Thread t = new Thread(() -> System.out.println("Running thread using lambda expression"));

So by writing Runnable runnable = () -> System.out.println("Running thread using lambda expression"); we told Java to create an anonymous object of type Runnable and provided the body for the run() method.

Lambda expression only works on functional interfaces (an interface which have only one method in it) because we are providing the body for the method on the fly. So if an interface have more than one method and we are are allowed to create a lambda on it then how compiler will identify to which method this provided method body belongs.

Th differences between Lambda Expression and Anonymous class are as follows

An anonymous class object creates a separate class file after compilation which increases the size jar while after compilation Lambda expression becomes invokedynamic which dynamic language implementation.

We can use this keyword to represent the current class in lambda expression while in the case of anonymous class this keyword represents that particular anonymous class.

In the case of Lambda expression, we need to provide the function body only while in the case of anonymous class we need to write the redundant class definition.

You can read more on Java Lambda Expression Explained with Example.


问:
Beeline cannot connect to HiveServe2 with NOSASL authentication mode ( old client )
This question is common here, there are several flavors of it. In this scenario, I set up an HiveServer2 with no authentication ( NOSASL ) which is working from Python, where I'm using Impyla library to connect.
When I connect using beeline, there is no way to get a working connection.

Beeline ends with:

```<code> beeline> !connect jdbc:hive2://127.0.0.1:10000/default/hive
 Error: Could not open client transport with JDBC Uri: jdbc:hive2://127.0.0.1:10000/default/hive: null (state=08S01,code=0)
</code>```

In HiveServer2 logs I have:

```<code>17/11/16 20:59:35 [HiveServer2-Handler-Pool: Thread-34]: ERROR server.TThreadPoolServer: Thrift error occurred during processing of message.
org.apache.thrift.protocol.TProtocolException: Missing version in readMessageBegin, old client?
    at org.apache.thrift.protocol.TBinaryProtocol.readMessageBegin(TBinaryProtocol.java:228)
    at org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:27)
    at org.apache.hive.service.auth.TSetIpAddressProcessor.process(TSetIpAddressProcessor.java:56)
    at org.apache.thrift.server.TThreadPoolServer$WorkerProcess.run(TThreadPoolServer.java:285)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Any ideas?

答:
Finally, I found the solution.

```<code>!connect jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl
</code>```

Using this I'm able to connect to HiveServer2.
Also, I'm using HiveServer2 for development, so I started the processes under root and all the file system tree belongs to root. Due to this option, I need to use the root user when login to HiveServer2 using beeline:

```<code>Connecting to jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl
Enter username for jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl: root
Enter password for jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl:
Connected to: Apache Hive (version 1.2.2)
</code>```

I did not need to provide the password since there is no authentication at all. Now I'm able to create databases and tables.

This "Comparing Beeline to the Hive CLI" has been a valid reference to solve this problem.

Body:
This question is common here, there are several flavors of it. In this scenario, I set up an HiveServer2 with no authentication ( NOSASL ) which is working from Python, where I'm using Impyla library to connect.
When I connect using beeline, there is no way to get a working connection.

Beeline ends with:

 beeline> !connect jdbc:hive2://127.0.0.1:10000/default/hive
 Error: Could not open client transport with JDBC Uri: jdbc:hive2://127.0.0.1:10000/default/hive: null (state=08S01,code=0)

In HiveServer2 logs I have:

17/11/16 20:59:35 [HiveServer2-Handler-Pool: Thread-34]: ERROR server.TThreadPoolServer: Thrift error occurred during processing of message.
org.apache.thrift.protocol.TProtocolException: Missing version in readMessageBegin, old client?
    at org.apache.thrift.protocol.TBinaryProtocol.readMessageBegin(TBinaryProtocol.java:228)
    at org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:27)
    at org.apache.hive.service.auth.TSetIpAddressProcessor.process(TSetIpAddressProcessor.java:56)
    at org.apache.thrift.server.TThreadPoolServer$WorkerProcess.run(TThreadPoolServer.java:285)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Any ideas?

Body:
Finally, I found the solution.

!connect jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl

Using this I'm able to connect to HiveServer2.
Also, I'm using HiveServer2 for development, so I started the processes under root and all the file system tree belongs to root. Due to this option, I need to use the root user when login to HiveServer2 using beeline:

Connecting to jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl
Enter username for jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl: root
Enter password for jdbc:hive2://127.0.0.1:10000/default/;auth=noSasl:
Connected to: Apache Hive (version 1.2.2)

I did not need to provide the password since there is no authentication at all. Now I'm able to create databases and tables.

This "Comparing Beeline to the Hive CLI" has been a valid reference to solve this problem.


问:
fwrite, fread - problems with fread
I have following code:

```<code>int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
    }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}
</code>```

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working

答:
Your first question seem to have already been answered by Simone & Dewfy.

For your second question about how to write structure values into the file, you will have to write member by member.

Please check fprintf. You can probably use it for writing different data types.

Title: fwrite, fread - problems with fread

Body:
I have following code:

int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
    }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working


问:
Can't bind to 'formGroup' since it isn't a known property of 'form'

The situation

I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works.

The Angular version

Angular 2.0.0 RC5

The error

Can't bind to 'formGroup' since it isn't a known property of 'form'

The code

The view

<form [formGroup]="newTaskForm" (submit)="createNewTask()">

      Name
      <input type="text" name="name" required>

   <button type="submit" class="btn btn-default">Submit</button>
</form>
```
<h3>The controller</h3>
```import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';

@Component({
    selector: 'task-add',
    templateUrl: 'app/task-add.component.html'

})
export class TaskAddComponent {

    newTaskForm: FormGroup;

    constructor(fb: FormBuilder)
    {
        this.newTaskForm = fb.group({
            name: ["", Validators.required]
        });
    }

    createNewTask()
    {
        console.log(this.newTaskForm.value)
    }
}
```
<h3>The ngModule</h3>
```import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { routing }        from './app.routing';
import { AppComponent }  from './app.component';
import { TaskService } from './task.service'

@NgModule({
    imports: [
        BrowserModule,
        routing,
        FormsModule
    ],
    declarations: [ AppComponent ],
    providers: [
        TaskService
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }
```

The question

Why am I getting that error? Am I missing something?

答:
Can't bind to 'formGroup' since it isn't a known property of 'form'

means that you try to bind a property using angular ([prop]) but angular cant find anything he knows for that element (in this case form).

this can happen by not using the right module (missing an import somewhere in the way) and sometimes just cause a typo like:

[formsGroup], with s after form

ContentLicense: CC BY-SA 4.0

Body:
The situation

I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works.

The Angular version

Angular 2.0.0 RC5

The error

Can't bind to 'formGroup' since it isn't a known property of 'form'

The code

The view

<form [formGroup]="newTaskForm" (submit)="createNewTask()">

      Name
      <input type="text" name="name" required>

   <button type="submit" class="btn btn-default">Submit</button>
</form>

The controller

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';

@Component({
    selector: 'task-add',
    templateUrl: 'app/task-add.component.html'

})
export class TaskAddComponent {

    newTaskForm: FormGroup;

    constructor(fb: FormBuilder)
    {
        this.newTaskForm = fb.group({
            name: ["", Validators.required]
        });
    }

    createNewTask()
    {
        console.log(this.newTaskForm.value)
    }
}

The ngModule

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { routing }        from './app.routing';
import { AppComponent }  from './app.component';
import { TaskService } from './task.service'

@NgModule({
    imports: [
        BrowserModule,
        routing,
        FormsModule
    ],
    declarations: [ AppComponent ],
    providers: [
        TaskService
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

The question

Why am I getting that error? Am I missing something?


问:
How to check if two tables are structurally same?
I have two tables in a SQL Server database. I want to check if these two tables are structurally same. I used UNION/ EXCEPT operator to check this and found that these two tables are not identical.

Here are my questions:

How do we know if two tables are the same in structure?

If they are not same, how do we get the details of differences? If a column is missing in one table how do we get the name of the missing column?

If there is a data type mismatch between a column in these two tables, can we get the name of the column with different data type?

答:
If you are using Sql Server Management Studio, right click on table name

script table as > CREATE

and you get DDL of the table, this is just a practical way to see the table as it was created. Then of course, as everybody already said, information_schema has all the info you need.


问:
Why does my number of transactions isn't exactly the same between my default channel grouping and my custom channel grouping ?
I've a simple question and everything is in the title : Why does my number of transactions isn't exactly the same between my default channel grouping and my custom channel grouping ?

Even if the discrepancies if very limited I would like to know why...

I guess it's because of sampling or something like this... but I can't find any officiel statement about this...

Thanks !

答:
It could be because of sampling data in Google Analytics.

It also could because there are on or more filters in your custom channel grouping.

Maybe you have different attribution models in your channel


答:
locate an element that only exists after the new DOM is loaded.  If you can find it, you are on the new page.

```<code>try:
    driver.find_element_by_class_name("txtSearch")
    print("redirected to new page")
except NoSuchElementException:
    print("oops, no redirect happened")
</code>```

Title: Web scraping using Python and Selenium

Body:
locate an element that only exists after the new DOM is loaded.  If you can find it, you are on the new page.

try:
    driver.find_element_by_class_name("txtSearch")
    print("redirected to new page")
except NoSuchElementException:
    print("oops, no redirect happened")


问:
string split using regex and get data on both side
I am trying to parse  a string as below but not able to get expected output
In value pair there can be {} or [] or () and they may contain \n and = both

Please check key 4

3=dkjashd\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}\n5=112

here output has to be

3=dkjashd

4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}

5=112

As above key gives wrong result with "\h*\R\s*(?=\d*=)" and \s+(?=\d{1,2}=) both

```<code>        String req="1=A  \n2=B\n3={AAAAAA}\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA} \n5=AAAAAA \n6=[10]\n7=[]\n8=[10,11]\n99=0";

        String []str=req.split("\\d{1,2}=");
        Arrays.stream(str).forEach(data-> System.out.println("Data :"+ data));
</code>```

Result:

Data : Data :A

Data :B

Data :{AAAAAA}

Data :{AAAAAA

  Data :45=45  AAAAAA    AAAAAA}

Data :AAAAAA

Data :[10]

Data :[]

Data :[10,11]

Data :0

Expected :

Data :1=A

Data :2=B

Data :3={AAAAAA}

Data :4={AAAAAA 45=45  AAAAAA    AAAAAA}

Data :5=AAAAAA

Data :6=[10]

Data :7=[]

Data :8=[10,11]

Data :99=0

Can anyone help over it.

答:
You can use this regex with a looahead:

```<code>String [] strarr = req.split(
   "\\h*\\n+\\h*(?=\\d{1,2}=(?![^{}]*})(?![^()]*\\))(?![^\\]\\[]*]))");
Arrays.stream(strarr).forEach(data-> System.out.println("Data : "+ data));
</code>```

Regex \\h*\\n+\\h*(?=\\d{1,2}=(?![^{}]*})) splits on 1+ new lines surrounded by 0+ horizontal whitespaces that must be followed by 1 or 2 digits and = symbol.

Negative lookahead-1 (?![^{}]*}) asserts that we don't look for \d{1,2}= inside {...} .

Negative lookahead-2 (?![^()]*\)) asserts that we don't look for \d{1,2}= inside (...) .

Negative lookahead-3 (?![^\[\]]*]) asserts that we don't look for \d{1,2}= inside [...] .

(this is assuming you don't have escaped brackets)

You may also use:

```<code>Arrays.stream(strarr).forEach(data-> System.out.println("Data : "+data.replace("\n", "")));
</code>```

if you don't want newline in output.

Output:

```<code>Data : 1=A
Data : 2=B
Data : 3={AAAAAA}
Data : 4={AAAAAA  AAAAAA   AAAAAA}
Data : 5=AAAAAA
Data : 6=[10]
Data : 7=[]
Data : 8=[10,11]
Data : 99=0
</code>```

Body:
I am trying to parse  a string as below but not able to get expected output
In value pair there can be {} or [] or () and they may contain \n and = both

Please check key 4

3=dkjashd\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}\n5=112

here output has to be

3=dkjashd

4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}

5=112

As above key gives wrong result with "\h*\R\s*(?=\d*=)" and \s+(?=\d{1,2}=) both

        String req="1=A  \n2=B\n3={AAAAAA}\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA} \n5=AAAAAA \n6=[10]\n7=[]\n8=[10,11]\n99=0";

        String []str=req.split("\\d{1,2}=");
        Arrays.stream(str).forEach(data-> System.out.println("Data :"+ data));

Result:

Data : Data :A

Data :B

Data :{AAAAAA}

Data :{AAAAAA

  Data :45=45  AAAAAA    AAAAAA}

Data :AAAAAA

Data :[10]

Data :[]

Data :[10,11]

Data :0

Expected :

Data :1=A

Data :2=B

Data :3={AAAAAA}

Data :4={AAAAAA 45=45  AAAAAA    AAAAAA}

Data :5=AAAAAA

Data :6=[10]

Data :7=[]

Data :8=[10,11]

Data :99=0

Can anyone help over it.

Body:
You can use this regex with a looahead:

String [] strarr = req.split(
   "\\h*\\n+\\h*(?=\\d{1,2}=(?![^{}]*})(?![^()]*\\))(?![^\\]\\[]*]))");
Arrays.stream(strarr).forEach(data-> System.out.println("Data : "+ data));

Regex \\h*\\n+\\h*(?=\\d{1,2}=(?![^{}]*})) splits on 1+ new lines surrounded by 0+ horizontal whitespaces that must be followed by 1 or 2 digits and = symbol.

Negative lookahead-1 (?![^{}]*}) asserts that we don't look for \d{1,2}= inside {...} .

Negative lookahead-2 (?![^()]*\)) asserts that we don't look for \d{1,2}= inside (...) .

Negative lookahead-3 (?![^\[\]]*]) asserts that we don't look for \d{1,2}= inside [...] .

(this is assuming you don't have escaped brackets)

You may also use:

Arrays.stream(strarr).forEach(data-> System.out.println("Data : "+data.replace("\n", "")));

if you don't want newline in output.

Output:

Data : 1=A
Data : 2=B
Data : 3={AAAAAA}
Data : 4={AAAAAA  AAAAAA   AAAAAA}
Data : 5=AAAAAA
Data : 6=[10]
Data : 7=[]
Data : 8=[10,11]
Data : 99=0


问:
FaceBook query using FQL
While fetching:
https://api.facebook.com/method/fql.query?query=Select+page_id,page_url,name,pic,website,type,location,fan_count,phone+from+page+where+name%20%20=%22SPA%22
i am getting all exact match results with "SPA"
But how to get other which will match "sp" as well. Like when we use like operator in fql i am getting problem.
Please suggest me with solution</p>

答:
Hence there is no LIKE operator in FQL, you will have to use other alternative.
I hope this link will suggest you some way:

Does facebook fql contain the sql like operator?

Title: FaceBook query using FQL


问:
How do I add cover image to a mp3 file using mutagen in Python?
The code below doesnt seem to update the artwork of the mp3 file.
Code:-

```<code>from mutagen.id3 import ID3, APIC
audio = ID3(musicFilename)
with open(coverFilename, 'rb') as albumart:
    print albumart.read()
    audio['APIC'] = APIC(
        encoding=3,
        mime='image/jpeg',
        type=3, desc=u'Cover',
        data=albumart.read()
        )
audio.save()
</code>```

After running the script, the cover of the mp3 file remain empty.

答:
The problem is your code is that you did print albumart.read(), this will make the cursor of the reader to the end of the file, now when you read it again it will be empty. Your solution is right, just remove the print command. this is my tested solution.

```<code>from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error

audio = MP3('example.mp3', ID3=ID3)
audio.tags.add(
    APIC(
        encoding=3, # 3 is for utf-8
        mime='image/png', # image/jpeg or image/png
        type=3, # 3 is for the cover image
        desc=u'Cover',
        data=open('example.png').read()
    )
)
</code>```

Body:
The code below doesnt seem to update the artwork of the mp3 file.
Code:-

from mutagen.id3 import ID3, APIC
audio = ID3(musicFilename)
with open(coverFilename, 'rb') as albumart:
    print albumart.read()
    audio['APIC'] = APIC(
        encoding=3,
        mime='image/jpeg',
        type=3, desc=u'Cover',
        data=albumart.read()
        )
audio.save()

After running the script, the cover of the mp3 file remain empty.

Body:
The problem is your code is that you did print albumart.read(), this will make the cursor of the reader to the end of the file, now when you read it again it will be empty. Your solution is right, just remove the print command. this is my tested solution.

from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error

audio = MP3('example.mp3', ID3=ID3)
audio.tags.add(
    APIC(
        encoding=3, # 3 is for utf-8
        mime='image/png', # image/jpeg or image/png
        type=3, # 3 is for the cover image
        desc=u'Cover',
        data=open('example.png').read()
    )
)


问:
Add my own query parameters to django admin
I have a model that uses latitude and longitude fields for location. One of the queries that I want to run using query params is search around a specific radius. I have the queryset read and I override it:

```<code>queryset = super().get_queryset(request)
if 'radius' in request.GET:
    queryset = queryset.in_distance(request.GET['radius'], fields=['location__latitude',location__longitude'], points=[lat, lon])
return queryset
</code>```

When calling my admin page with /admin/dal/listing?radius=50 I get redirected to the admin without the query string.

Followed Django's code and found this:

```<code># At this point, all the parameters used by the various ListFilters
# have been removed from lookup_params, which now only contains other
# parameters passed via the query string. We now loop through the
# remaining parameters both to ensure that all the parameters are valid
# fields and to determine if at least one of them needs distinct(). If
# the lookup parameters aren't real fields, then bail out.
try:
    for key, value in lookup_params.items():
        lookup_params[key] = prepare_lookup_value(key, value)
        use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key)
    return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist as e:
    six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2])
</code>```

In a nutshell because the query string is not a known field django gracefully panics and redirect a not filter admin page.

What can I do ?

答:
You should pop custome parameters from request. Try this:</p>

```<code>def get_queryset(self, request):
    queryset = super().get_queryset(request)
    request.GET = request.GET.copy()
    radius = request.GET.pop('radius', None)
    if radius:
        queryset = queryset.in_distance(
            radius[0], fields=['location__latitude', 'location__longitude'],
            points=[lat, lon])
    return queryset
</code>```

Body:
I have a model that uses latitude and longitude fields for location. One of the queries that I want to run using query params is search around a specific radius. I have the queryset read and I override it:

queryset = super().get_queryset(request)
if 'radius' in request.GET:
    queryset = queryset.in_distance(request.GET['radius'], fields=['location__latitude',location__longitude'], points=[lat, lon])
return queryset

When calling my admin page with /admin/dal/listing?radius=50 I get redirected to the admin without the query string.

Followed Django's code and found this:

# At this point, all the parameters used by the various ListFilters
# have been removed from lookup_params, which now only contains other
# parameters passed via the query string. We now loop through the
# remaining parameters both to ensure that all the parameters are valid
# fields and to determine if at least one of them needs distinct(). If
# the lookup parameters aren't real fields, then bail out.
try:
    for key, value in lookup_params.items():
        lookup_params[key] = prepare_lookup_value(key, value)
        use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key)
    return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist as e:
    six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2])

In a nutshell because the query string is not a known field django gracefully panics and redirect a not filter admin page.

What can I do ?

Body:
You should pop custome parameters from request. Try this:

def get_queryset(self, request):
    queryset = super().get_queryset(request)
    request.GET = request.GET.copy()
    radius = request.GET.pop('radius', None)
    if radius:
        queryset = queryset.in_distance(
            radius[0], fields=['location__latitude', 'location__longitude'],
            points=[lat, lon])
    return queryset


问:
How to call external javascript function in angular 5?
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

```<code><body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>
</code>```

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

```<code>document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});
</code>```

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

答:
You need to change the order in which you load your JavaSciprt files. Try loading common.js before main......js. Your script tries to access a function from a file that hasn't been loaded yet. Try just switching those two lines of code:

```<code><body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/common.js"></script>
  <script type="text/javascript" src="./assets/js/main.85741bff.js">/script>
</body>
</code>```

Body:
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

  <app-root></app-root>

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

Body:
You need to change the order in which you load your JavaSciprt files. Try loading common.js before main......js. Your script tries to access a function from a file that hasn't been loaded yet. Try just switching those two lines of code:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/common.js"></script>
  <script type="text/javascript" src="./assets/js/main.85741bff.js">/script>
</body>


问:
How to create a Shared Login Service across Multiple Domains?
I'm interested in how to implement a shared cross-domain login system as well as best practices and security precautions to take. If you are familiar with 37Signals, you are probably accustomed to their usage of having a shared universal authentication mechanism whereby you do not have to subsequently login if you use the top level navigation to a different product. I would like to implement something in a similar fashion.

The closest thing I've found online is the Wikipedia entry on a Central Authentication Service and the response to Cross Domain Login - How to login a user automatically when transfered from one domain to another, which may be slightly different in this case.

I have inspected their session cookies to get a grasp on what they're doing in the process. Initially, each product link has a "goto" uristub, i.e.:

https://MY_COMPANY.campfirenow.com/id/users/[int_identifier]/goto

Using FireCookie and the NET tab in Firebug, I'm able to see the cookies that are set and the redirects that occur in the process. The goto url fires a 302 redirect to:

https://MY_COMPANY.basecamphq.com/login/authenticate?sig=[BASE64_ENCODED_AND_ENCRYPTED_DATA]

The session identifier is recreated, most likely for CSRF purposes. Some of the data in the cookies as well as the GET parameter sig were partially decrypted using base64_decode to the following:

```<code>// sig GET param
array(2) {
  [0]=>
���ף�:@marshal_with_utc_coercionT7�z��<k��kW"
  [1]=>
  string(18) "���k�<kn8�f���to��"
}

// _basecamp_session cookie session param
string(247) {
:_csrf_token"1Sj5D6jCwJKIxkZ6oroy7o/mYUqr4R5Ca34cOPNigqkw=:session_id"%060c0804a5d06dafd1c5b3349815d863"
flashIC:'ActionController::Flash::FlashHash{:
@used{: auth{"
              MY_COMPANY{:
                       user_idi�3
:identity_idi�W����������s�]��:�N[��:
</code>```

߾�����"

The encoding is breaking the code block. Thanks for your help!

答: Use Something Like .NET Passport (IE. Windows Live Id) Or The Way Facebook Has Done It With Their API, Which Can Be Openly Viewed.</p>

Body:
I'm interested in how to implement a shared cross-domain login system as well as best practices and security precautions to take. If you are familiar with 37Signals, you are probably accustomed to their usage of having a shared universal authentication mechanism whereby you do not have to subsequently login if you use the top level navigation to a different product. I would like to implement something in a similar fashion.

The closest thing I've found online is the Wikipedia entry on a Central Authentication Service and the response to Cross Domain Login - How to login a user automatically when transfered from one domain to another, which may be slightly different in this case.

I have inspected their session cookies to get a grasp on what they're doing in the process. Initially, each product link has a "goto" uristub, i.e.:

https://MY_COMPANY.campfirenow.com/id/users/[int_identifier]/goto

Using FireCookie and the NET tab in Firebug, I'm able to see the cookies that are set and the redirects that occur in the process. The goto url fires a 302 redirect to:

https://MY_COMPANY.basecamphq.com/login/authenticate?sig=[BASE64_ENCODED_AND_ENCRYPTED_DATA]

The session identifier is recreated, most likely for CSRF purposes. Some of the data in the cookies as well as the GET parameter sig were partially decrypted using base64_decode to the following:

// sig GET param
array(2) {
  [0]=>
���ף�:@marshal_with_utc_coercionT7�z��<k��kW"
  [1]=>
  string(18) "���k�<kn8�f���to��"
}

// _basecamp_session cookie session param
string(247) {
:_csrf_token"1Sj5D6jCwJKIxkZ6oroy7o/mYUqr4R5Ca34cOPNigqkw=:session_id"%060c0804a5d06dafd1c5b3349815d863"
flashIC:'ActionController::Flash::FlashHash{:
@used{: auth{"
              MY_COMPANY{:
                       user_idi�3
:identity_idi�W����������s�]��:�N[��:

߾�����"

The encoding is breaking the code block. Thanks for your help!


问:
vlookup in pandas between 2 dataframes to create third dataframe
I am wanting to use the equivalent to excel’s vlookup for a new dataframe.  I have 2 dataframes and am trying to v-lookup df1.Column A value against df2.Column A and B and getting Value A.

And the cell beside that is df1.Column A value against df2.Column A and B and getting value B.

Data looks like-

The data is in Columns A and B respectively for both data frames 1 and 2

```<code>Current ouput
    Data frame 1              Dataframe2

      AC1     AC2               AC10                 AC20
    Bus        5              car                      1
    car        3              helicopter               7
    Walking    2              running                  5
</code>```

Desired/Expected output

```<code>           Dataframe [Neu]

NaNa                       NaNa
Car                           1
NaNa                       NaNa
</code>```

I have tried:

```<code>dfz = df1.insert(2, '2A2', df1['AC1'].map(df2.set_index('AC1')['2A2']))
print (dfz)

result = left.join(right, on=['AC2', 'AC1], how='inner')
#left.join(right, lsuffix='_l', rsuffix='_r')

#df1.join(df1.set_index('AC2')['AC1'], on='AC2')
</code>```

I have had some success with:

```<code>df8 = df1['AC3'] = df1.AC1.map(df2.AC10)
print (df8)

df8 = df1['AC4'] = df1.AC1.map(df2.AC20)
print (df8)
</code>```

The exact output is NaN so it's not correct.

Example:

```<code>df1 = pd.read_excel('C:/Users/Desktop/zav.xlsx')

df2 = pd.read_excel('C:/Users/Desktop/zav2.xlsx')

#df3 = pd.merge(df, df2)
df3 = df1.join(df2)
print (df3)

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

df5 = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
                 columns=['a', 'b', 'c', 'd', 'e'])
print(df5)

df8 = df1['AC3'] = df1.AC1.map(df2.AC10)
print (df8)

df8 = df1['AC3'] = df1.AC1.map(df2.AC20)
print (df8)
</code>```

答:
You can check the following code working with map:

```<code>import pandas as pd

df1 = pd.DataFrame([["Bus",5],["car",3],["Walking",2]],columns=["AC1","AC2"])

df2 = pd.DataFrame([["car",1],["helicopter",7],["running", 5]],columns=["AC10","AC20"])

df2 = df2.groupby("AC10").first()

df3= df1.join(df2,on="AC1",how="left").drop("AC2",axis=1)
</code>```

It will output the following:

```<code>       AC1  AC20
0      Bus   NaN
1      car   1.0
2  Walking   NaN
</code>```

Body:
I am wanting to use the equivalent to excel’s vlookup for a new dataframe.  I have 2 dataframes and am trying to v-lookup df1.Column A value against df2.Column A and B and getting Value A.

And the cell beside that is df1.Column A value against df2.Column A and B and getting value B.

Data looks like-

The data is in Columns A and B respectively for both data frames 1 and 2

Current ouput
    Data frame 1              Dataframe2

      AC1     AC2               AC10                 AC20
    Bus        5              car                      1
    car        3              helicopter               7
    Walking    2              running                  5

Desired/Expected output

           Dataframe [Neu]

NaNa                       NaNa
Car                           1
NaNa                       NaNa

I have tried:

dfz = df1.insert(2, '2A2', df1['AC1'].map(df2.set_index('AC1')['2A2']))
print (dfz)

result = left.join(right, on=['AC2', 'AC1], how='inner')
#left.join(right, lsuffix='_l', rsuffix='_r')

#df1.join(df1.set_index('AC2')['AC1'], on='AC2')

I have had some success with:

df8 = df1['AC3'] = df1.AC1.map(df2.AC10)
print (df8)

df8 = df1['AC4'] = df1.AC1.map(df2.AC20)
print (df8)

The exact output is NaN so it's not correct.

Example:

df1 = pd.read_excel('C:/Users/Desktop/zav.xlsx')

df2 = pd.read_excel('C:/Users/Desktop/zav2.xlsx')

#df3 = pd.merge(df, df2)
df3 = df1.join(df2)
print (df3)

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

df5 = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
                 columns=['a', 'b', 'c', 'd', 'e'])
print(df5)

df8 = df1['AC3'] = df1.AC1.map(df2.AC10)
print (df8)

df8 = df1['AC3'] = df1.AC1.map(df2.AC20)
print (df8)

Body:
You can check the following code working with map:

import pandas as pd

df1 = pd.DataFrame([["Bus",5],["car",3],["Walking",2]],columns=["AC1","AC2"])

df2 = pd.DataFrame([["car",1],["helicopter",7],["running", 5]],columns=["AC10","AC20"])

df2 = df2.groupby("AC10").first()

df3= df1.join(df2,on="AC1",how="left").drop("AC2",axis=1)

It will output the following:

       AC1  AC20
0      Bus   NaN
1      car   1.0
2  Walking   NaN


问:
Why my ColumnAttribute are not used when fetching data from a View via SqlQuery with Entity Framework 6.x?
I am struggling to properly fetch data from a SQL view using the DbContext and the entity below:

```<code>public class StagingDbContext : ApplicationDbContext
{
    private const string AssignmentQuery =
        @"SELECT DISTINCT " +
        @"[Region], " +
        @"[Technician], " +
        @"[Email], " +
        @"[On Call Group], " +
        @"[Manager], " +
        @"[Manager Email] " +
        @"FROM [Staging].[dbo].[Assignment] " +
        @"WHERE " +
        @"[Technician] IS NOT NULL AND " +
        @"[Technician] NOT LIKE 'DECOMMISSIONED' " +
        @"AND [Technician] NOT LIKE 'N/A' " +
        @"AND [Technician] NOT LIKE '4242NAH%' " +
        @"AND [Region] IS not Null " +
        @"AND [On Call Group] NOT LIKE 'N/A' " +
        @"AND [On Call Group] NOT LIKE 'Decommisioned'";

    public IEnumerable<Assignment> Assignments => Database.SqlQuery<Assignment>(AssignmentQuery);

    public StagingDbContext ()
        : base(nameof(StagingDbContext ))
    {
    }
}

[Table("Assignment")]
public class Assignment
{
    [Column("Region")]
    public string Region { get; set; }

    [Column("SiteID")]
    public string SiteId { get; set; }

    [Column("Technician")]
    public string Technician { get; set; }

    [Column("Email")]
    public string Email { get; set; }

    [Column("On Call Group")]
    public string OnCallGroup { get; set; }

    [Column("Manager Email")]
    public string ManagerEmail { get; set; }
}
</code>```

My issue arises when it comes to the property names that does not match exactly the ones provided in the query, I thought that the ColumnAttribute was taken in account but apparently this is not really the case.

My current workaround is to basically rename columns in my SQL query ([Column Name] AS ColumnName in order to make them match directly to the property names of my entity (e.g. removing white space characters) but I found it a bit awkward to rewrite the Query exclusively for that particular purpose.

Is there anything that can be done to force the SqlQuery to the names provided by my ColumnAttributes instead of the properties?

[EDIT]
It was more or less already answered somewhere else:

Entity framework Code First - configure mapping for SqlQuery

Entity Framework using Database.SqlQuery() where column names are invalid C# member names

Object Mapping from stored procedure using the columnname attribute in EntityFramework CodeFirst

How to use Entity Framework to map results of a stored procedure to entity with differently named parameters

getting Entity Framework raw query to respect attributes

答:
My current workaround is to basically rename columns in my SQL query ([Column Name] AS ColumnName in order to make them match directly to the property names of my entity (e.g. removing white space characters) but I found it a bit awkward to rewrite the Query exclusively for that particular purpose.

Yes it is really awkward but, as far as I know, this is the only way.

The feature you are seeking (using the mapping configuration for mapping a SqlQuery/Stored Procedure result to entities) does not exist in EF 6.x, and will not be implemented

Body:
I am struggling to properly fetch data from a SQL view using the DbContext and the entity below:

public class StagingDbContext : ApplicationDbContext
{
    private const string AssignmentQuery =
        @"SELECT DISTINCT " +
        @"[Region], " +
        @"[Technician], " +
        @"[Email], " +
        @"[On Call Group], " +
        @"[Manager], " +
        @"[Manager Email] " +
        @"FROM [Staging].[dbo].[Assignment] " +
        @"WHERE " +
        @"[Technician] IS NOT NULL AND " +
        @"[Technician] NOT LIKE 'DECOMMISSIONED' " +
        @"AND [Technician] NOT LIKE 'N/A' " +
        @"AND [Technician] NOT LIKE '4242NAH%' " +
        @"AND [Region] IS not Null " +
        @"AND [On Call Group] NOT LIKE 'N/A' " +
        @"AND [On Call Group] NOT LIKE 'Decommisioned'";

    public IEnumerable<Assignment> Assignments => Database.SqlQuery<Assignment>(AssignmentQuery);

    public StagingDbContext ()
        : base(nameof(StagingDbContext ))
    {
    }
}

[Table("Assignment")]
public class Assignment
{
    [Column("Region")]
    public string Region { get; set; }

    [Column("SiteID")]
    public string SiteId { get; set; }

    [Column("Technician")]
    public string Technician { get; set; }

    [Column("Email")]
    public string Email { get; set; }

    [Column("On Call Group")]
    public string OnCallGroup { get; set; }

    [Column("Manager Email")]
    public string ManagerEmail { get; set; }
}

My issue arises when it comes to the property names that does not match exactly the ones provided in the query, I thought that the ColumnAttribute was taken in account but apparently this is not really the case.

My current workaround is to basically rename columns in my SQL query ([Column Name] AS ColumnName in order to make them match directly to the property names of my entity (e.g. removing white space characters) but I found it a bit awkward to rewrite the Query exclusively for that particular purpose.

Is there anything that can be done to force the SqlQuery to the names provided by my ColumnAttributes instead of the properties?

[EDIT]
It was more or less already answered somewhere else:

Entity framework Code First - configure mapping for SqlQuery

Entity Framework using Database.SqlQuery() where column names are invalid C# member names

Object Mapping from stored procedure using the columnname attribute in EntityFramework CodeFirst

How to use Entity Framework to map results of a stored procedure to entity with differently named parameters

getting Entity Framework raw query to respect attributes


问:
Divide results in two columns depending on the input values? SQL Server
I am using the Nortwind database with SQL Server 2014, I try to make a query to divide the results of the orders in two different years, The format that I want in my query is

```<code>category |anio one | anio two
</code>```

where the years may vary , What I try so far is

```<code>SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;
</code>```

This gives me the totals of each category for a different year, 1996-1997-1998 in column  YEAR(o.OrderDate)

I want to get for example

```<code>CategoryName | 1996 | 1997

Beverages   |53879,20 | 110424,00
Condiments  |19458,30 | 59679,00
....
</code>```

答:
```<code>You can use PIVOT to get your desired Output

BEGIN TRAN
CREATE TABLE #Temp(CategoryName NVARCHAR(50),[Year]INT,TOTAL DECIMAL(15,2))

INSERT INTO #Temp
SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;

SELECT * FROM #Temp
GO
select *
from
(
  select CategoryName, [Year], TOTAL
  from #Temp
) src
pivot
(
  sum(TOTAL)
  for YEAR in ([1996], [1997]
)) piv;

ROLLBACK TRAN
</code>```

Body:
I am using the Nortwind database with SQL Server 2014, I try to make a query to divide the results of the orders in two different years, The format that I want in my query is

category |anio one | anio two

where the years may vary , What I try so far is

SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;

This gives me the totals of each category for a different year, 1996-1997-1998 in column  YEAR(o.OrderDate)

I want to get for example

CategoryName | 1996 | 1997

Beverages   |53879,20 | 110424,00
Condiments  |19458,30 | 59679,00
....


问:
Pass Fluid variable to TypoScript
I want to pass a variable (uid of category) in Fluid to a TypoScript :

```<code> <f:cObject typoscriptObjectPath="lib.testFluid" data="{setting.myvar}/>
</code>```

Then i want to use the var to get all content elements in folder with pid 942 and the category {setting.myvar}

```<code>lib.testFluid = COA
lib.testFluid = CONTENT
lib.testFluid {
table = tt_content
    select {
    pidInList = 942
    where = selected_categories = |
</code>```

}

}

This does not work, it creates an MySql syntax error. I also tried using current = 1 instead of the where clause without success. I looked at post TYPO3: pass variable to typoscript via cObject? and I can recreate it but it does not work with my script. (TYPO3 8)
If i use

```<code>...
    where = selected_categories = 13
....
</code>```

the scrip will succesfully display all CE with category 13. How do i make it work with a var?

答:
I had to solve it once with markers. I couldn't find another simpler way. I give you a very general solution which you may adapt to your needs. For example you could set the pid value via a typoscript setting which is more elegant than to put it in the snippet code. Please try:

```<code><f:cObject typoscriptObjectPath="lib.testFluid" data="{category: setting.myvar, catPid: 942}" currrentValueKey="category" />
</code>```

The related TypoScript snippet:

```<code>lib.testFluid = COA
lib.testFluid {
    10 = LOAD_REGISTER
    10 {
        category.cObject = TEXT
        category.cObject.value.current = 1
        catPid.cObject = TEXT
        catPid.cObject.value.dataWrap = { field: catPid }
    }
    20 = CONTENT
    20 {
        table = tt_content
        select {
            pidInList.cObject = TEXT
            pidInList.cObject.dataWrap = {REGISTER:catPid}
            where = selected_categories=###category###
            markers {
                category.data = REGISTER:category
            }
        }
    }
    30 = RESTORE_REGISTER
}
</code>```

Title: Pass Fluid variable to TypoScript

Body:
I want to pass a variable (uid of category) in Fluid to a TypoScript :

 <f:cObject typoscriptObjectPath="lib.testFluid" data="{setting.myvar}/>

Then i want to use the var to get all content elements in folder with pid 942 and the category {setting.myvar}

lib.testFluid = COA
lib.testFluid = CONTENT
lib.testFluid {
table = tt_content
    select {
    pidInList = 942
    where = selected_categories = |

}

}

This does not work, it creates an MySql syntax error. I also tried using current = 1 instead of the where clause without success. I looked at post TYPO3: pass variable to typoscript via cObject? and I can recreate it but it does not work with my script. (TYPO3 8)
If i use

...
    where = selected_categories = 13
....

the scrip will succesfully display all CE with category 13. How do i make it work with a var?

Body:
I had to solve it once with markers. I couldn't find another simpler way. I give you a very general solution which you may adapt to your needs. For example you could set the pid value via a typoscript setting which is more elegant than to put it in the snippet code. Please try:

<f:cObject typoscriptObjectPath="lib.testFluid" data="{category: setting.myvar, catPid: 942}" currrentValueKey="category" />

The related TypoScript snippet:

lib.testFluid = COA
lib.testFluid {
    10 = LOAD_REGISTER
    10 {
        category.cObject = TEXT
        category.cObject.value.current = 1
        catPid.cObject = TEXT
        catPid.cObject.value.dataWrap = { field: catPid }
    }
    20 = CONTENT
    20 {
        table = tt_content
        select {
            pidInList.cObject = TEXT
            pidInList.cObject.dataWrap = {REGISTER:catPid}
            where = selected_categories=###category###
            markers {
                category.data = REGISTER:category
            }
        }
    }
    30 = RESTORE_REGISTER
}


问:
How to switch the master branch with another branch along with their commits?
I have been working on a project using git. I have two branches master and feature. With the time I added more commits to the feature branch. And the feature branch is 5 commits ahead of master.

Now, I want to make the feature branch 'master'. And the master branch to a normal branch. There is a way to replace master branch with another branch in here using ours merge strategy, but the commits of the previous master are lost because the feature branch overrides them.

Is there a way to switch the master branch and the feature branch without loosing the commits of both branches?

答:
So you want to rename master branch to a normal branch (such as Mybranch) and rename feature branch to master. You can use below commands:

```<code>git branch -m master Mybranch
git branch -m feature master
</code>```

To switch the remote branch based on the new branch name, you can use below commands:

```<code>#Change the remote master same as the new local master branch
git push -u origin master -f
#Push Mybranch to remote
git push -u origin Mybranch
#Delete remote feature branch
git push :feature
</code>```

Body:
So you want to rename master branch to a normal branch (such as Mybranch) and rename feature branch to master. You can use below commands:

git branch -m master Mybranch
git branch -m feature master

To switch the remote branch based on the new branch name, you can use below commands:

#Change the remote master same as the new local master branch
git push -u origin master -f
#Push Mybranch to remote
git push -u origin Mybranch
#Delete remote feature branch
git push :feature


问:
href="tel:xxxxxxxx" not working on mobile
```<code>      <a
          href="tel:+xxxxxxxxxx"
        >CALL 6514 9729
      </a>
</code>```

this code is printing this error on mobile view !

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080

答: it was a CSS issue ! apparently only position relative could make the call work on mobile view. not sure why though!</p>

Body:
      CALL 6514 9729

this code is printing this error on mobile view !

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080


问:
How to conform a class to a protocol in Swift and can protocol methods be overridden?
Is it necessary to use delegates to conform to a protocol? If yes, can anyone write an example code to show the same? Suppose I have a protocol ABC and I want to create a class for mocking the methods of ABC, how can this be done? I don't have very clear concepts of protocols and delegates. Please explain that too.</p>

答:
I can give you an idea of protocols.

Protocol, in general, is a rule that everyone has to follow. When you implement some protocol, example you wrote protocol and put some methods in that protocol as optional and few methods as required. Once protocol implemented whatever that wants to follow the protocol that has to conform that protocol. Once conformed means, they are following it and they have to implmented all the required methods in that.

Now coming to delegates. Delegate helps in following a protocol. You will write a delegate that includes that protocol. When you assign self to delegate you are indirectly saying that this instance is following that protcol and those methods are here. So you will get a call backs to those methods.

Above explanation is given for you to just understand the concept. The more you want to look at it please refer to any article/blog available on net.